howtofixcli 0.4.28 → 0.4.29
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 +13 -13
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
var JP=Object.defineProperty;var u=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Mt=(e,t)=>{for(var n in t)JP(e,n,{get:t[n],enumerable:!0})};function Cd(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*pi-coding-agent[\\/]docs[\\/][^\n]*$/gim,"").replace(/\bpi-coding-agent\b/gi,"the harness").replace(/\n{3,}/g,`
|
|
3
3
|
|
|
4
|
-
`).trim()}var at,Nt,Od,Ld,Go=u(()=>{at="HowToFix",Nt="0.4.
|
|
4
|
+
`).trim()}var at,Nt,Od,Ld,Go=u(()=>{at="HowToFix",Nt="0.4.29",Od=["You are HowToFix, a coding agent. The user wants the actual fix, not a tour of the problem.","Lead with the diagnosis in one or two sentences, then change the code. Prefer the smallest correct change over a rewrite.","When you edit files, say which file and why in a short line. Do not narrate tool calls. Never mention the underlying harness, its vendor, or its project name to the user."].join(`
|
|
5
5
|
`);Ld=["# Project notes","","## What this is","","## Commands","- build:","- test:","","## Conventions","-",""].join(`
|
|
6
6
|
`)});var _d={};Mt(_d,{AGENTS_STORE_DIR:()=>Jr,AGENT_DIR:()=>Ve,CUBENCE_CACHE_PATH:()=>Um,USER_SKILLS_DIR:()=>qm,WORKFLOWS_DIR:()=>Km,pinAgentDir:()=>Gm,projectSkillsDir:()=>hr});import{homedir as YP}from"node:os";import{join as Vr,resolve as XP}from"node:path";function ZP(){let e=(process.env.HOWTOFIX_HOME??process.env.HOME??"").trim();return XP(e||YP())}function hr(e){return Vr(e,".howtofix","skills")}function Gm(){process.env.PI_CODING_AGENT_DIR=Ve}var Ve,qm,Jr,Um,Km,Nn=u(()=>{Ve=process.env.HOWTOFIX_CODING_AGENT_DIR?.trim()||Vr(ZP(),".howtofix","agent"),qm=Vr(Ve,"skills");Jr=Vr(Ve,"agents"),Um=Vr(Ve,"cubence-cache.json"),Km=Vr(Ve,"workflows")});import{closeSync as QP,fsyncSync as eR,openSync as tR,renameSync as Nd,rmSync as Wm,writeSync as nR}from"node:fs";import{dirname as rR,join as oR}from"node:path";function tt(e,t){let n=oR(rR(e),`.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}.tmp`),r=tR(n,"w");try{nR(r,t),eR(r)}finally{QP(r)}try{Nd(n,e)}catch(o){let s=o.code;if(s!=="EPERM"&&s!=="EBUSY"&&s!=="EACCES")throw Wm(n,{force:!0}),o;Wm(e,{force:!0});try{Nd(n,e)}catch(i){throw Wm(n,{force:!0}),i}}}var Hn=u(()=>{});var zd={};Mt(zd,{DEFAULT_CONTEXT_WINDOW:()=>Gd,HOWTOFIX_BASE_URL:()=>Wo,HOWTOFIX_CONSOLE_URL:()=>gi,HOWTOFIX_MODEL_COMPAT:()=>zm,HOWTOFIX_PROVIDERS:()=>Yr,HTTP_IDLE_TIMEOUT_MS:()=>Kd,UNLIMITED_SENTINEL:()=>Bd,applyCompat:()=>xi,checkAccount:()=>yi,checkUsage:()=>Bo,countNewModels:()=>Jm,ensureGatewaySettings:()=>uR,isHowtofixProvider:()=>xr,looksLikeToken:()=>Hm,maskToken:()=>hi,mergeModels:()=>Vm,newProviderEntry:()=>Bm,parseModelIds:()=>Wd,probeModel:()=>Ym,repairGatewayModels:()=>aR});import{existsSync as sR,mkdirSync as iR,readFileSync as qd}from"node:fs";import{join as Ud}from"node:path";function Bm(){return{baseUrl:Wo,api:"openai-completions"}}function aR(e){let t=Ud(e,"models.json"),n;try{n=JSON.parse(qd(t,"utf8"))}catch{return 0}let r=n.providers;if(!r||typeof r!="object")return 0;let o=0;for(let s of Yr){let i=r[s];if(!i||!Array.isArray(i.models))continue;let c=xi(i.models);c.changed!==0&&(i.models=c.models,o+=c.changed)}if(o===0)return 0;try{tt(t,`${JSON.stringify(n,null,2)}
|
|
7
7
|
`)}catch{return 0}return o}function uR(e){let t=Ud(e,"settings.json"),n={};try{let r=qd(t,"utf8"),o=JSON.parse(r);o&&typeof o=="object"&&!Array.isArray(o)&&(n=o)}catch{if(sR(t))return!1}if("httpIdleTimeoutMs"in n)return!1;n.httpIdleTimeoutMs=Kd;try{iR(e,{recursive:!0}),tt(t,`${JSON.stringify(n,null,2)}
|
|
@@ -10,7 +10,7 @@ var JP=Object.defineProperty;var u=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(
|
|
|
10
10
|
`).filter(Boolean).pop()??"";return{ok:!1,message:`the update did not install${/EACCES|EPERM|permission/i.test(o)?" \u2014 npm could not write to its global directory":""}${o?`: ${o}`:""}`}}return{ok:!0,version:e?.version,message:"updated; it takes effect the next time HowToFix starts"}}catch(n){return{ok:!1,message:`the update failed: ${n instanceof Error?n.message:String(n)}`}}finally{rf()}}function yR(e=process.argv[1]){if(!e)return!1;let t=e;try{t=fR(e)}catch{}return t.includes(`${Zm}node_modules${Zm}${zo}${Zm}`)}function bR(e){try{return JSON.parse(dR(e,"utf8")).autoUpdate!==!1}catch{return!0}}var zo,Yd,Xd,Qm,ef,wi=u(()=>{zo="howtofixcli",Yd=5e3,Xd=12e4,Qm=600*1e3;ef=(e,t,n)=>new Promise(r=>{cR(e,t,{cwd:n.cwd,timeout:n.timeoutMs,windowsHide:!0},(o,s,i)=>{let c=o&&typeof o.code=="number"?o.code:o?1:0;r({code:c,stdout:String(s??""),stderr:String(i??"")})})})});var sf={};Mt(sf,{expandFileReferences:()=>tc});import{readFileSync as wR,statSync as IR}from"node:fs";import{isAbsolute as $R,resolve as kR}from"node:path";function tc(e,t){return e.replace(/(^|\s)@([^\s]+)/g,(n,r,o)=>{let s=o.replace(/[),.;:]+$/,""),i=o.slice(s.length),c=$R(s)?s:kR(t,s);try{let p=IR(c);if(!p.isFile()||p.size===0||p.size>TR)return n;let f=wR(c);return f.includes(0)?n:`${r}<file name="${c}">
|
|
11
11
|
${f.toString("utf8").trimEnd()}
|
|
12
12
|
</file>${i}`}catch{return n}})}var TR,nc=u(()=>{TR=64*1024});function ER(e){let t=new WeakSet,n=r=>{if(r===null||typeof r!="object")return r;if(t.has(r))return"[circular]";if(t.add(r),Array.isArray(r))return r.map(n);let o=r,s={};for(let i of Object.keys(o).sort())s[i]=n(o[i]);return s};try{return JSON.stringify(n(e))??""}catch{return""}}function af(e,t){if(vR.has(e))return;let n=`${e}\0${ER(t)}`,r=Ho&&Ho.signature===n?Ho.count+1:1;return Ho={signature:n,count:r},r>=3?{repeats:r}:void 0}function uf(){Ho=void 0}function mf(e,t){return`Refused: ${e} 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 vR,Ho,rc=u(()=>{vR=new Set(["think"])});function cf(e,t){switch(t){case"number":return/^\d+$/.test(e);case"string":return!0;default:return!1}}function PR(e,t,n){let r=t;for(;r<e.length;){let o=e[r];if(!o){r++;continue}if(o==="--")break;if(SR.test(o)){let s=o.includes("="),[i="",...c]=o.split("="),p=n.safeFlags[i];if(!p)return!1;if(p==="none"){if(s)return!1;r++;continue}if(p==="optional"){r++;continue}if(s){if(!cf(c.join("="),p))return!1;r++;continue}let f=e[r+1];if(f===void 0||!cf(f,p))return!1;r+=2;continue}if(n.allowPositional===!1)return!1;r++}return!0}function LR(e){if(!/\$\(|`|\$\{|>|</.test(e)&&!/(?<!&)&(?!&)/.test(e))return e.split(/\|\||&&|;|\|/).map(t=>t.trim()).filter(t=>t.length>0)}function FR(e){let t=e.some(r=>/^cd\b/.test(r)),n=e.some(r=>/^git\b/.test(r));return t&&n}function jR(e){let t=[],n=/'[^']*'|"[^"]*"|\S+/g;for(let r of e.match(n)??[])t.push(r.length>=2&&/^['"]/.test(r)?r.slice(1,-1):r);return t}function DR(e){if(e.length===0)return;let[t="",n=""]=e,r=`${t} ${n}`;if(t==="git"&&n==="config"){let o=e[2];return o==="--get"||o==="--get-all"||o==="--get-regexp"||o==="-l"||o==="--list"?{name:"git config --get",rest:e.slice(3)}:void 0}return t==="git"&&n==="stash"?e[2]==="list"?{name:"git stash list",rest:e.slice(3)}:void 0:t==="git"&&n==="worktree"?e[2]==="list"?{name:"git worktree list",rest:e.slice(3)}:void 0:t==="git"&&lf[`git ${n}`]?{name:`git ${n}`,rest:e.slice(2)}:df[r]?{name:r,rest:e.slice(2)}:{name:t,rest:e.slice(1)}}function NR(e){let t=jR(e),n=DR(t);if(!n)return!1;let{name:r,rest:o}=n;if(_R.has(r)&&o.some(i=>i.includes("$")||i.includes("`")))return!1;let s=lf[r]??OR[r]??df[r];return s?s.dangerous?.(o)?!1:PR(o,0,s):!!(MR.includes(r)||CR.includes(r))}function Ti(e){let t=LR(e);return!t||t.length===0||FR(t)?!1:t.every(NR)}var SR,RR,Ii,$i,oc,ki,sc,pf,AR,lf,MR,OR,df,CR,_R,ic=u(()=>{SR=/^-[a-zA-Z0-9_-]/;RR={"--all":"none","--branches":"none","--tags":"none","--remotes":"none"},Ii={"--oneline":"none","--graph":"none","--decorate":"none","--no-decorate":"none","--date":"string","--relative-date":"none"},$i={"--max-count":"number","-n":"number"},oc={"--stat":"none","--numstat":"none","--shortstat":"none","--name-only":"none","--name-status":"none"},ki={"--color":"none","--no-color":"none"},sc={"--patch":"none","-p":"none","--no-patch":"none","--no-ext-diff":"none","-s":"none"},pf={"--author":"string","--committer":"string","--grep":"string"},AR={"-l":"none","--list":"none","-a":"none","-r":"none","-v":"none","-vv":"none","-i":"none"},lf={"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",...ki}},"git diff":{safeFlags:{...oc,...ki,...sc,"--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:{...Ii,...$i,...oc,...ki,...sc,...pf,...RR,"--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:{...oc,...ki,...sc,...Ii,"--format":"string","--pretty":"string","--abbrev-commit":"none","--no-patch":"none","-q":"none"}},"git shortlog":{safeFlags:{...$i,"-s":"none","--summary":"none","-n":"none","--numbered":"none","-e":"none","--email":"none","-sn":"none","-ns":"none","--all":"none"}},"git reflog":{safeFlags:{...$i,...Ii,...pf,"--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:{...$i,"--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:{...Ii}},"git worktree list":{safeFlags:{"--porcelain":"none","-v":"none","--verbose":"none","-z":"none"}},"git branch":{safeFlags:{...AR,"--merged":"string","--no-merged":"string","--contains":"string","--no-contains":"string","--sort":"string","--format":"string","--points-at":"string","--column":"none"},dangerous:e=>{let t=new Set(["--merged","--no-merged","--contains","--no-contains","--sort","--format","--points-at"]),n=!1;for(let r of e){if(n){n=!1;continue}if(t.has(r)){n=!0;continue}if(!r.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:e=>{let t=new Set(["--contains","--no-contains","--merged","--sort","--points-at"]),n=!1;for(let r of e){if(n){n=!1;continue}if(t.has(r)){n=!0;continue}if(!r.startsWith("-"))return!0}return!1}},"git remote":{safeFlags:{"-v":"none","--verbose":"none"},dangerous:e=>e.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"}}},MR=["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"],OR={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:e=>e.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:e=>e.some(t=>/^-i|^--in-place/.test(t)||/\b[we]\s/.test(t)||/^[we]$/.test(t))},awk:{safeFlags:{"-F":"string","-v":"string","-f":"string"},dangerous:e=>e.some(t=>/\bsystem\s*\(|\|\s*"|>\s*"/.test(t))}},df={"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:{}}},CR=["cd","alias","history","arch","ip addr","ifconfig"];_R=new Set(["echo","printf"])});var wf={};Mt(wf,{APPROVAL_LABELS:()=>vi,APPROVAL_MODES:()=>Xr,MODE_MAX_TIER:()=>ff,TIER_RANK:()=>ac,createPermissionExtension:()=>Vo,criticalCommand:()=>gf,decideToolCall:()=>xf,describeToolCall:()=>yf,formatApprovalPrompt:()=>bf,getApprovalMode:()=>GR,isApprovalMode:()=>qR,isReadOnlyCommand:()=>Ti,resolveTier:()=>uc,setApprovalMode:()=>cc,setApprovalPrompt:()=>pc});function qR(e){return Xr.includes(e)}function uc(e){let t=UR[e];return t||(e.startsWith("mcp__")?"write":"exec")}function gf(e){for(let{pattern:t,reason:n}of KR)if(t.test(e))return n}function cc(e){mc=e}function GR(){return mc}function pc(e){hf=e}function xf(e,t,n){let r=typeof n?.command=="string"?n.command:"";if(t==="bash"||t==="powershell"){let s=gf(r);if(s)return{action:"deny",reason:`Refused in every mode: ${s}.`};if(Ti(r))return{action:"run"}}let o=uc(t);return ac[o]<=ac[ff[e]]?{action:"run"}:{action:"prompt",reason:`this is a ${o}-tier tool`}}function yf(e,t){if(t&&typeof t=="object"){let n=t;if((e==="bash"||e==="powershell")&&typeof n.command=="string")return n.command;if((e==="edit"||e==="write")&&typeof n.path=="string"){let r=Array.isArray(n.edits)?` (${n.edits.length} edits)`:"";return`${n.path}${r}`}try{let r=JSON.stringify(n);if(r&&r!=="{}")return r.length>300?`${r.slice(0,297)}...`:r}catch{}}return e}function bf(e,t,n){let r=[`Allow tool: ${e}`];e.startsWith("mcp__")&&r.push("Origin: MCP server tool"),r.push(`Reason: ${n}`);let o=yf(e,t);return o!==e&&r.push(o),r.join(`
|
|
13
|
-
`)}function Vo(e={}){return t=>{t.on("tool_call",async n=>{let r=af(n.toolName,n.input);if(r)return{block:!0,reason:mf(n.toolName,r.repeats)};let o=mc,s=xf(o,n.toolName,n.input);if(s.action==="run")return;if(s.action==="deny")return{block:!0,reason:s.reason};if(e.interactive===!1)return{block:!0,reason:`Blocked: this is a ${uc(n.toolName)}-tier tool and no UI can approve it here (approval mode: ${o}).`};if(!await hf(`${n.toolName} wants to run`,bf(n.toolName,n.input,s.reason)))return{block:!0,reason:`Blocked by the user (approval mode: ${o}).`}})}}var Xr,vi,ac,ff,UR,KR,mc,hf,Jo=u(()=>{rc();ic();ic();Xr=["suggest","auto-edit","full-auto"],vi={suggest:"suggest: ask before every edit and command","auto-edit":"auto-edit: edits run, commands ask","full-auto":"full-auto: nothing asks"};ac={read:0,write:1,exec:2},ff={suggest:"read","auto-edit":"write","full-auto":"exec"},UR={read:"read",grep:"read",find:"read",ls:"read",think:"read",ask:"read",todo:"read",context:"read",web_search:"read",web_fetch:"read",lsp:"read",workflow:"exec",goal:"read",enter_plan_mode:"read",exit_plan_mode:"read",edit:"write",write:"write",bash:"exec",powershell:"exec",task:"exec"};KR=[{pattern:/\brm\s+(?:-[a-zA-Z]+\s+)*(?:\/|\/\*|~|\$HOME)(?:\s|$)/,reason:"recursive delete of the filesystem root or home"},{pattern:/\bmkfs(?:\.[a-z0-9]+)?\b/,reason:"filesystem format"},{pattern:/\bdd\b[^|;]*\bof=\/dev\/(?:sd|nvme|hd|vd)/,reason:"raw write to a block device"},{pattern:/:\s*\(\s*\)\s*\{.*\}\s*;\s*:/,reason:"fork bomb"},{pattern:/>\s*\/etc\/(?:passwd|shadow|sudoers)/,reason:"overwrite of a system account file"},{pattern:/\b(?:shutdown|reboot|halt|poweroff)\b/,reason:"host shutdown"}];mc="full-auto",hf=async()=>!1});function WR(e){return e.replace(/operating inside pi, a coding agent harness/gi,"operating as HowToFix, a coding agent harness").replace(/^Pi documentation \(read only when the user asks about[^\n]*\):?$/gim,"Harness documentation (internal reference; the user is never told the harness name):").replace(/\bpi itself\b/gi,"the harness itself").replace(/^- When reading pi docs or examples/m,"- When reading harness docs or examples").replace(/^- When working on pi topics/m,"- When working on harness topics").replace(/^- Always read pi \.md files/m,"- Always read the harness .md files").replace(/\bpi packages\b/gi,"harness packages").replace(/\bpi \.md files\b/gi,"harness .md files").replace(/\bpi docs\b/gi,"harness docs").replace(/^-\s*You can inspect PI_\* environment variables/m,"- You can inspect the harness's environment variables")}function zR(e){if(!e)return;let t=!1,n={...e};for(let r of BR){let o=n[r];if(typeof o!="string")continue;let s=WR(o);s!==o&&(n[r]=s,t=!0)}return t?n:void 0}function If(){return e=>{e.on("context_with_system",async t=>{let n=t.messages[0];if(!n||n.role!=="system")return;let r=zR(n.sections);return r?{messages:t.messages.map(s=>s===n?{...n,sections:r}:s)}:void 0})}}var BR,$f=u(()=>{BR=["preamble","rules","docs","addendum"]});import{Type as Zr}from"@earendil-works/pi-ai";import{defineTool as kf}from"@earendil-works/pi-coding-agent";function Tf(e){lc=e}var lc,vf,Ef,dc=u(()=>{vf=kf({name:"think",label:"think",description:"Private scratchpad. The text is not shown to the user. Use it before a non-obvious step.",promptSnippet:"think: private notes, not shown to the user",parameters:Zr.Object({thoughts:Zr.String({description:"Private notes"})}),async execute(){return{content:[{type:"text",text:"noted"}],details:{recorded:!0}}}}),Ef=kf({name:"ask",label:"ask",description:"Ask the user one question and wait for a selected answer. Use this instead of guessing when a choice blocks the task.",promptSnippet:"ask: ask the user to pick one option",parameters:Zr.Object({question:Zr.String(),options:Zr.Array(Zr.String(),{minItems:2})}),async execute(e,t){if(!lc)return{content:[{type:"text",text:"cancelled"}],details:{answer:"cancelled"}};let n=await lc(t.question,t.options);return{content:[{type:"text",text:n}],details:{answer:n}}}})});var sn,yr=u(()=>{sn={assign:0,create:0,clone:0,discard:0,update:0}});function br(e,t,n){return e>=t&&e<=n}function Rf(e){return e===8205}function HR(e){return br(e,55296,56319)}function Sf(e){return br(e,127462,127487)}function Af(e){return br(e,65024,65039)}function Mf(e){return br(e,768,879)||br(e,6832,6911)||br(e,7616,7679)||br(e,65056,65071)}function Ei(e){return e>65535?2:1}function Pf(e,t){for(;t<e.length;){let n=e.codePointAt(t);if(Mf(n)||Af(n))t+=Ei(n);else break}return t}function fc(e,t){let n=e.codePointAt(t),r=t+Ei(n);for(r=Pf(e,r);r<e.length-1&&Rf(e.codePointAt(r));){let o=e.codePointAt(r+1);r+=1+Ei(o),r=Pf(e,r)}return Sf(n)&&r<e.length&&Sf(e.codePointAt(r))&&(r+=Ei(e.codePointAt(r))),r}function Of(e){return e>=768&&(HR(e)||Mf(e)||Af(e)||Rf(e))}function Cf(e){let t=0,n=0;for(;n<e.length;)n=fc(e,n),t++;return t}function VR(e,t){let n=0,r=0;for(;r<e.length;)if(r=fc(e,r),++n>=t)return!0;return!1}function JR(e,t){let n=0,r=0;for(;r<e.length;)if(r=fc(e,r),++n>t)return!1;return!0}function Lf(e,t){if(t===0)return!0;if(e.length<t)return!1;let n=0;for(;;){if(Of(e.charCodeAt(n)))return VR(e,t);if(++n>=t)return!0}}function Ff(e,t){if(e.length<=t)return!0;let n=0;for(;;){if(Of(e.charCodeAt(n)))return JR(e,t);if(++n>t)return!1}}var jf=u(()=>{});var m={};Mt(m,{Counted:()=>pA,Entries:()=>fA,EntriesRegExp:()=>dA,Every:()=>aA,EveryAll:()=>uA,GraphemeCount:()=>oA,HasPropertyKey:()=>lA,IsArray:()=>Xo,IsBigInt:()=>Yo,IsBoolean:()=>Df,IsClassInstance:()=>rA,IsConstructor:()=>XR,IsDeepEqual:()=>xc,IsEqual:()=>ue,IsFunction:()=>_f,IsGreaterEqualThan:()=>qf,IsGreaterThan:()=>eA,IsInteger:()=>gc,IsLessEqualThan:()=>Nf,IsLessThan:()=>tA,IsMaxLength:()=>sA,IsMinLength:()=>iA,IsMultipleOf:()=>nA,IsNull:()=>Pi,IsNumber:()=>Ri,IsObject:()=>Zo,IsObjectNotArray:()=>ZR,IsString:()=>Ai,IsSymbol:()=>QR,IsUndefined:()=>hc,IsUnsafePropertyKey:()=>Kf,IsValueLike:()=>Uf,Keys:()=>Si,ShiftLeft:()=>Mi,Some:()=>mA,SomeAll:()=>cA,Symbols:()=>gA,Values:()=>hA});function Xo(e){return Array.isArray(e)}function Yo(e){return ue(typeof e,"bigint")}function Df(e){return ue(typeof e,"boolean")}function XR(e){if(hc(e)||!_f(e))return!1;let t=Function.prototype.toString.call(e);return!!(/^class\s/.test(t)||/\[native code\]/.test(t))}function _f(e){return ue(typeof e,"function")}function gc(e){return Number.isInteger(e)}function Pi(e){return ue(e,null)}function Ri(e){return Number.isFinite(e)}function ZR(e){return Zo(e)&&!Xo(e)}function Zo(e){return ue(typeof e,"object")&&!Pi(e)}function Ai(e){return ue(typeof e,"string")}function QR(e){return ue(typeof e,"symbol")}function hc(e){return ue(e,void 0)}function ue(e,t){return e===t}function eA(e,t){return e>t}function tA(e,t){return e<t}function Nf(e,t){return e<=t}function qf(e,t){return e>=t}function nA(e,t){if(Yo(e)||Yo(t))return BigInt(e)%BigInt(t)===0n;let n=1e-10;if(!Ri(e)||gc(e)&&1/t%1===0)return!0;let r=e%t;return Math.min(Math.abs(r),Math.abs(r-t),Math.abs(r+t))<n}function rA(e){if(!Zo(e))return!1;let t=globalThis.Object.getPrototypeOf(e);return Pi(t)?!1:ue(typeof t.constructor,"function")&&!(ue(t.constructor,globalThis.Object)||ue(t.constructor.name,"Object"))}function Uf(e){return Yo(e)||Df(e)||Pi(e)||Ri(e)||Ai(e)||hc(e)}function oA(e){return Cf(e)}function sA(e,t){return Ff(e,t)}function iA(e,t){return Lf(e,t)}function aA(e,t,n){return e.every((r,o)=>o<t||n(r,o))}function uA(e,t,n){let r=!0;return e.forEach((o,s)=>{s>=t&&!n(o,s)&&(r=!1)}),r}function mA(e,t){return e.some((n,r)=>t(n,r))}function cA(e,t){let n=!1;return e.forEach((r,o)=>{t(r,o)&&(n=!0)}),n}function pA(e,t){return e.reduce((n,r,o)=>t(r,o)?++n:n,0)}function Mi(e,t,n){return ue(e.length,0)?n():t(e[0],e.slice(1))}function Kf(e){return ue(e,"__proto__")||ue(e,"constructor")||ue(e,"prototype")}function lA(e,t){return Kf(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function dA(e){return Si(e).map(t=>[new RegExp(`^${t}$`),e[t]])}function fA(e){return Object.entries(e)}function Si(e){return Object.getOwnPropertyNames(e)}function gA(e){return Object.getOwnPropertySymbols(e)}function hA(e){return Object.values(e)}function xA(e,t){if(!Zo(t))return!1;let n=Si(e);return ue(n.length,Si(t).length)&&n.every(r=>xc(e[r],t[r]))}function yA(e,t){return Xo(t)&&ue(e.length,t.length)&&e.every((n,r)=>xc(e[r],t[r]))}function xc(e,t){return Xo(e)?yA(e,t):Zo(e)?xA(e,t):ue(e,t)}var Qr=u(()=>{jf()});var Gf=u(()=>{Qr()});var Vn={};Mt(Vn,{IsBigInt64Array:()=>CA,IsBigUint64Array:()=>LA,IsBoolean:()=>wA,IsDate:()=>jA,IsFloat32Array:()=>MA,IsFloat64Array:()=>OA,IsInt16Array:()=>SA,IsInt32Array:()=>RA,IsInt8Array:()=>TA,IsMap:()=>_A,IsNumber:()=>IA,IsRegExp:()=>FA,IsSet:()=>DA,IsString:()=>$A,IsTypeArray:()=>kA,IsUint16Array:()=>PA,IsUint32Array:()=>AA,IsUint8Array:()=>vA,IsUint8ClampedArray:()=>EA});function wA(e){return e instanceof Boolean}function IA(e){return e instanceof Number}function $A(e){return e instanceof String}function kA(e){return globalThis.ArrayBuffer.isView(e)}function TA(e){return e instanceof globalThis.Int8Array}function vA(e){return e instanceof globalThis.Uint8Array}function EA(e){return e instanceof globalThis.Uint8ClampedArray}function SA(e){return e instanceof globalThis.Int16Array}function PA(e){return e instanceof globalThis.Uint16Array}function RA(e){return e instanceof globalThis.Int32Array}function AA(e){return e instanceof globalThis.Uint32Array}function MA(e){return e instanceof globalThis.Float32Array}function OA(e){return e instanceof globalThis.Float64Array}function CA(e){return e instanceof globalThis.BigInt64Array}function LA(e){return e instanceof globalThis.BigUint64Array}function FA(e){return e instanceof globalThis.RegExp}function jA(e){return e instanceof globalThis.Date}function DA(e){return e instanceof globalThis.Set}function _A(e){return e instanceof globalThis.Map}var Wf=u(()=>{});var Bf=u(()=>{Qr()});var O=u(()=>{Gf();Wf();Bf();Qr();Qr()});var an={};Mt(an,{Get:()=>KA,Reset:()=>qA,Set:()=>UA});function qA(){xn.immutableTypes=!1,xn.maxErrors=8,xn.maxInstantiationCount=128,xn.useAcceleration=!0,xn.exactOptionalPropertyTypes=!1,xn.enumerableKind=!1,xn.correctiveParse=!1,xn.unionPrioritySort=!0}function UA(e){for(let t of m.Keys(e)){let n=e[t];n!==void 0&&Object.defineProperty(xn,t,{value:n})}}function KA(){return xn}var xn,zf=u(()=>{O();xn={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0}});var wr=u(()=>{zf()});function Jn(e){return an.Get().immutableTypes?Object.freeze(e):e}var Qo=u(()=>{wr()});function GA(e,t){return sn.assign+=1,Jn({...e,...t})}var Hf=u(()=>{yr();Qo()});function WA(e){return m.HasPropertyKey(e,"~kind")||m.HasPropertyKey(e,"~unsafe")}function BA(e){let t={};for(let n of m.Keys(e)){if(m.IsUnsafePropertyKey(n))continue;let r=Object.getOwnPropertyDescriptor(e,n);r.value=Ir(r.value),m.IsEqual(r.enumerable,!0)?t[n]=r.value:Object.defineProperty(t,n,r)}return t}function zA(e){let t={};for(let n of m.Keys(e))m.IsUnsafePropertyKey(n)||(t[n]=Ir(e[n]));for(let n of m.Symbols(e))t[n]=Ir(e[n]);return t}function HA(e){return m.IsClassInstance(e)?e:WA(e)?BA(e):zA(e)}function VA(e){return e.map(t=>Ir(t))}function JA(e){return e.slice()}function YA(e){return new RegExp(e.source,e.flags)}function XA(e){return new Map(Ir([...e.entries()]))}function ZA(e){return new Set(Ir([...e.values()]))}function Ir(e){return Vn.IsTypeArray(e)?JA(e):Vn.IsRegExp(e)?YA(e):Vn.IsMap(e)?XA(e):Vn.IsSet(e)?ZA(e):m.IsArray(e)?VA(e):m.IsObject(e)?HA(e):e}function es(e){return sn.clone+=1,Ir(e)}var Oi=u(()=>{O();yr()});function QA(e,t){for(let n of Object.keys(t))Object.defineProperty(e,n,{configurable:!0,writable:!0,enumerable:!1,value:t[n]});return e}function Vf(e,t){return{...e,...t}}function eM(e,t,n={}){sn.create+=1;let r=Vf(t,n),o=an.Get().enumerableKind?Vf(r,e):QA(r,e);return Jn(o)}var Jf=u(()=>{wr();yr();Qo()});function tM(e,t){sn.discard+=1;let n={};for(let r of m.Keys(e)){if(t.includes(r))continue;let o=Object.getOwnPropertyDescriptor(e,r);o.value=es(o.value),Object.defineProperty(n,r,o)}return Jn(n)}var Yf=u(()=>{O();yr();Qo();Oi()});function nM(e,t,n){sn.update+=1;let r=an.Get(),o=es(e);for(let s of Object.keys(t))Object.defineProperty(o,s,{configurable:!0,writable:!0,enumerable:r.enumerableKind,value:t[s]});for(let s of Object.keys(n))Object.defineProperty(o,s,{configurable:!0,enumerable:!0,writable:!0,value:n[s]});return Jn(o)}var Xf=u(()=>{wr();yr();Qo();Oi()});var d={};Mt(d,{Assign:()=>GA,Clone:()=>es,Create:()=>eM,Discard:()=>tM,Metrics:()=>sn,Update:()=>nM});var Zf=u(()=>{Hf();Oi();Jf();Yf();yr();Xf()});var S=u(()=>{Zf()});function L(e,t){return m.IsObject(e)&&m.HasPropertyKey(e,"~kind")&&m.IsEqual(e["~kind"],t)}function _e(e){return m.IsObject(e)}var J=u(()=>{O()});function j(e,t,n){return d.Create({"~kind":"Deferred"},{type:"deferred",action:e,parameters:t,options:n},{})}function Yn(e){return L(e,"Deferred")}var ce=u(()=>{S();J()});function rM(e){return d.Update(e,{"~readonly":!0},{})}function ts(e,t){return d.Update(rM(e),{},t)}function Qf(e,t,n,r){let o=T(e,t,n);return ts(o,r)}var Ci=u(()=>{S();q()});function oM(e){return d.Update(e,{"~optional":!0},{})}function ns(e,t){return d.Update(oM(e),{},t)}function eg(e,t,n,r){let o=T(e,t,n);return ns(o,r)}var Li=u(()=>{S();q()});function qt(e,t){return d.Create({"~kind":"Array"},{type:"array",items:e},t)}function ke(e){return L(e,"Array")}function Fi(e){return d.Discard(e,["~kind","type","items"])}var gt=u(()=>{S();J()});function yn(e,t,n={}){return d.Create({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:t},n)}function Ge(e){return L(e,"Constructor")}function tg(e){return d.Discard(e,["~kind","type","parameters","instanceType"])}var Bt=u(()=>{S();J()});function bn(e,t,n={}){return d.Create({"~kind":"Function"},{type:"function",parameters:e,returnType:t},n)}function We(e){return L(e,"Function")}function ng(e){return d.Discard(e,["~kind","type","parameters","returnType"])}var zt=u(()=>{S();J()});function qn(e,t){return d.Create({"~kind":"Ref"},{$ref:e},t)}function Be(e){return L(e,"Ref")}var Ht=u(()=>{S();J()});function Xn(e,t){return d.Create({"~kind":"Generic"},{type:"generic",parameters:e,expression:t})}function eo(e){return L(e,"Generic")}var rs=u(()=>{S();J()});function to(e){return d.Create({"~kind":"Any"},{},e)}function Ee(e){return L(e,"Any")}var $t=u(()=>{S();J()});function ge(e){return d.Create({"~kind":"Never"},{not:{}},e)}function un(e){return L(e,"Never")}var rg,Je=u(()=>{S();J();rg="(?!)"});function wn(e,t={}){return j("AddOptional",[e],t)}function $r(e,t={}){return ns(e,t)}var os=u(()=>{ce();Li()});function og(e){return $r(e)}function ut(e){return _e(e)&&m.HasPropertyKey(e,"~optional")}var Zn=u(()=>{O();J();os()});function sg(e){return m.Keys(e).filter(t=>!ut(e[t]))}function ji(e){return m.Keys(e)}function Di(e){return m.Values(e)}var kr=u(()=>{O();Zn()});function W(e,t={}){let n=sg(e),r=n.length>0?{required:n}:{};return d.Create({"~kind":"Object"},{type:"object",...r,properties:e},t)}function pe(e){return L(e,"Object")}function ig(e){return d.Discard(e,["~kind","type","properties","required"])}var fe=u(()=>{S();J();kr()});function Ye(e){return d.Create({"~kind":"Unknown"},{},e)}function Oe(e){return L(e,"Unknown")}var nt=u(()=>{S();J()});function In(e,t,n){let r=m.Keys(e).reduce((o,s)=>({...o,[s]:d.Update(e[s],{},{$id:s})}),{});return d.Create({"~kind":"Cyclic"},{$defs:r,$ref:t},n)}function rt(e){return L(e,"Cyclic")}var kt=u(()=>{O();S();J()});function ag(e){return d.Update(e,{"~unsafe":null},{})}function _i(e){return m.IsObjectNotArray(e)&&m.HasPropertyKey(e,"~unsafe")&&m.IsNull(e["~unsafe"])}var Ni=u(()=>{O();S()});var $n={};Mt($n,{Match:()=>sM});function sM(e,t){return t[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}var ug=u(()=>{});var no=u(()=>{ug()});function ss(...e){let[t,n]=$n.Match(e,{2:(r,o)=>[r,o,o],1:r=>[r,Ye(),Ye()]});return d.Create({"~kind":"Infer"},{type:"infer",name:t,extends:n},{})}function Ce(e){return L(e,"Infer")}var Vt=u(()=>{no();S();J();nt()});function Tr(e,t,n,r={}){return d.Create({"~kind":"Dependent"},{if:e,then:t,else:n},r)}function Pe(e){return L(e,"Dependent")}function mg(e){return d.Discard(e,["~kind","if","then","else"])}var Ot=u(()=>{S();J()});function cg(e){return m.IsObjectNotArray(e)}function pg(e){return m.Keys(e).filter(n=>isNaN(n)).reduce((n,r)=>[...n,e[r]],[])}var qi=u(()=>{O()});function lg(e){return m.IsString(e)||m.IsNumber(e)}function dg(e,t){let n=cg(e)?pg(e):e;return d.Create({"~kind":"Enum"},{enum:n},t)}function ot(e){return L(e,"Enum")}var mn=u(()=>{O();S();J();qi();qi()});function Tt(e,t={}){return d.Create({"~kind":"Intersect"},{allOf:e},t)}function oe(e){return L(e,"Intersect")}function fg(e){return d.Discard(e,["~kind","allOf"])}var Ne=u(()=>{S();J()});var gg=u(()=>{wr();O()});var hg=u(()=>{gg()});var xg=u(()=>{hg()});function qe(){throw new Error("Unreachable")}var yc=u(()=>{});var kn=u(()=>{yc()});var yg,vU,EU,SU,PU,bg,RU,AU,MU,wg=u(()=>{kn();O();(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(yg||(yg={}));vU=BigInt("14695981039346656037"),[EU,SU]=[BigInt("1099511628211"),BigInt("18446744073709551616")],PU=Array.from({length:256}).map((e,t)=>BigInt(t)),bg=new Float64Array(1),RU=new DataView(bg.buffer),AU=new Uint8Array(bg.buffer),MU=new TextEncoder});var Ig=u(()=>{wg()});var bc=u(()=>{});var $g=u(()=>{bc()});var kg=u(()=>{});var Tg=u(()=>{});var vg=u(()=>{});var Eg=u(()=>{});var Sg=u(()=>{});var Pg=u(()=>{});var Rg=u(()=>{});var Ag=u(()=>{});var Mg=u(()=>{});var Og=u(()=>{});var Cg=u(()=>{});var wc=u(()=>{});var Lg=u(()=>{});var Fg=u(()=>{});var jg=u(()=>{});var Dg=u(()=>{});var _g=u(()=>{});var Ng=u(()=>{});var qg=u(()=>{});var Ug=u(()=>{});var Kg=u(()=>{});var Gg=u(()=>{});var Wg=u(()=>{});var Bg=u(()=>{});var zg=u(()=>{});var Hg=u(()=>{});var Vg=u(()=>{});var Jg=u(()=>{});var Yg=u(()=>{});var Xg=u(()=>{});var Zg=u(()=>{});var Qg=u(()=>{});var eh=u(()=>{});var th=u(()=>{});var nh=u(()=>{});var rh=u(()=>{});var oh=u(()=>{});var sh=u(()=>{$g();kg();Tg();vg();Eg();Sg();bc();Pg();Rg();Ag();Mg();Og();Cg();wc();wc();Lg();Fg();jg();Dg();_g();Ng();qg();Ug();Kg();Gg();Wg();Bg();zg();Hg();Vg();Jg();Yg();Xg();Zg();Qg();eh();th();nh();rh();oh()});var ih=u(()=>{sh()});var is=u(()=>{no();xg();Ig();ih();S();wr()});var uh=u(()=>{is();is();is()});function Ki(e){return new us(e)}function mh(e,t){return Ki(e).Decode(t).Encode(()=>{throw Error("Encode not implemented")})}function ch(e,t){return Ki(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(t)}function Ui(e){return _e(e)&&m.HasPropertyKey(e,"~codec")&&m.IsObject(e["~codec"])&&m.HasPropertyKey(e["~codec"],"encode")&&m.HasPropertyKey(e["~codec"],"decode")}var as,us,Ic=u(()=>{uh();O();J();as=class{constructor(t,n){this.type=t,this.decode=n}Encode(t){let n=this.type,r=Ui(n)?i=>this.decode(n["~codec"].decode(i)):this.decode,o=Ui(n)?i=>n["~codec"].encode(t(i)):t,s={decode:r,encode:o};return d.Update(this.type,{"~codec":s},{})}},us=class{constructor(t){this.type=t}Decode(t){return new as(this.type,t)}}});function ph(e){return ro(e)}function vr(e){return _e(e)&&m.HasPropertyKey(e,"~immutable")}var ms=u(()=>{O();J();cs()});function Tn(e,t={}){return j("AddReadonly",[e],t)}function Er(e,t={}){return ts(e,t)}var ps=u(()=>{ce();Ci()});function lh(e){return Er(e)}function Sr(e){return _e(e)&&m.HasPropertyKey(e,"~readonly")}var ls=u(()=>{O();J();ps()});function mM(e,t){let n=$c(e)?[...e["~refine"],t]:[t];return d.Update(e,{"~refine":n},{})}function dh(...e){let[t,n,r]=$n.Match(e,{3:(o,s,i)=>[o,s,i],2:(o,s)=>[o,s,()=>"Refine Error"]});return mM(t,{check:n,error:r})}function cM(e){return m.IsObjectNotArray(e)&&m.HasPropertyKey(e,"check")&&m.HasPropertyKey(e,"error")&&m.IsFunction(e.check)&&m.IsFunction(e.error)}function $c(e){return _e(e)&&m.HasPropertyKey(e,"~refine")&&m.IsArray(e["~refine"])&&m.Every(e["~refine"],0,t=>cM(t))}var kc=u(()=>{no();S();O();J()});function ds(e){return d.Create({"~kind":"BigInt"},{type:"bigint"},e)}function vn(e){return L(e,"BigInt")}var fh,Pr=u(()=>{S();J();fh="-?(?:0|[1-9][0-9]*)n"});function Gi(e){return d.Create({"~kind":"Boolean"},{type:"boolean"},e)}function Jt(e){return L(e,"Boolean")}var Qn=u(()=>{S();J()});function fs(e){return d.Create({"~kind":"Identifier"},{name:e})}function gh(e){return L(e,"Identifier")}var Tc=u(()=>{S();J()});function Rr(e){return d.Create({"~kind":"Integer"},{type:"integer"},e)}function ht(e){return L(e,"Integer")}var Wi,En=u(()=>{S();J();Wi="-?(?:0|[1-9][0-9]*)"});function pM(e){return m.IsBigInt(e)?"bigint":m.IsBoolean(e)?"boolean":m.IsNumber(e)?"number":m.IsString(e)?"string":(()=>{throw new vc(e)})()}function se(e,t){return d.Create({"~kind":"Literal"},{type:pM(e),const:e},t)}function Bi(e){return m.IsBigInt(e)||m.IsBoolean(e)||m.IsNumber(e)||m.IsString(e)}function hh(e){return le(e)&&m.IsNumber(e.const)}function xh(e){return le(e)&&m.IsString(e.const)}function le(e){return L(e,"Literal")}var vc,Le=u(()=>{S();O();J();vc=class extends Error{constructor(t){super("Invalid Literal value"),Object.defineProperty(this,"cause",{value:{value:t},writable:!1,configurable:!1,enumerable:!1})}}});function oo(e){return d.Create({"~kind":"Null"},{type:"null"},e)}function so(e){return L(e,"Null")}var io=u(()=>{S();J()});function Ct(e){return d.Create({"~kind":"Number"},{type:"number"},e)}function Fe(e){return L(e,"Number")}var zi,xt=u(()=>{S();J();zi="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?"});function ao(e){return d.Create({"~kind":"Symbol"},{type:"symbol"},e)}function er(e){return L(e,"Symbol")}var Ar=u(()=>{S();J()});function Mr(...e){let[t,n,r]=$n.Match(e,{3:(o,s,i)=>[o,s,i],2:(o,s)=>[o,s,s],1:o=>[o,Ye(),Ye()]});return d.Create({"~kind":"Parameter"},{name:t,extends:n,equals:r},{})}function yh(e){return L(e,"Parameter")}var Ec=u(()=>{no();S();J();nt()});function Yt(e){return d.Create({"~kind":"String"},{type:"string"},e)}function yt(e){return L(e,"String")}var Hi,Xt=u(()=>{S();J();Hi=".*"});function X(e,t={}){return d.Create({"~kind":"Union"},{anyOf:e},t)}function F(e){return L(e,"Union")}function bh(e){return d.Discard(e,["~kind","anyOf"])}var Q=u(()=>{S();J()});function gs(e){let t=wh(e);return m.IsEqual(t.length,2)?t[0]:[]}var hs=u(()=>{O();Vi()});function lM(e){return!0}function Ih(e){return m.ShiftLeft(e,(t,n)=>dM(t)?Ih(n):!1,()=>!0)}function $h(e){return m.IsEqual(e.length,0)?!1:Ih(e)}function dM(e){return F(e)?$h(e.anyOf):le(e)?lM(e.const):!1}function Ji(e){return $h(e)}var Yi=u(()=>{O();Le();Q()});function Xi(e){return d.Create({"~kind":"TemplateLiteral"},{type:"string",pattern:e},{})}var Zi=u(()=>{S()});function kh(e,t,n=[]){return m.ShiftLeft(e,(r,o)=>kh(o,t,[...n,`${r}${t}`]),()=>n)}function fM(e,t){return m.IsEqual(e.length,0)?[`${t}`]:kh(e,t)}function Th(e,t,n=[]){return m.ShiftLeft(t,(r,o)=>Th(e,o,[...n,...vh(e,r)]),()=>n)}function vh(e,t){return F(t)?Th(e,t.anyOf):le(t)?fM(e,t.const):qe()}function Eh(e,t){return m.ShiftLeft(t,(n,r)=>Eh(vh(e,n),r),()=>e)}function gM(e){return e.map(t=>se(t))}function hM(e){let t=Eh([],e),n=gM(t);return X(n)}function xM(e){return m.IsEqual(e.length,0)?qe():m.IsEqual(e.length,1)&&le(e[0])?e[0]:hM(e)}function Sc(e){let t=gs(e);return m.IsEqual(t.length,0)?Yt():Ji(t)?xM(t):Xi(e)}function Sh(e){let t=Sc(e);return Re(t)?Yt():t}var Qi=u(()=>{O();kn();Le();Xt();vt();Q();hs();Yi();Zi()});function Et(e,t){let n="object",r={[e]:t};return d.Create({"~kind":"Record"},{type:n,patternProperties:r})}var tr=u(()=>{S()});function Ph(e){return Et(cn,e)}var Rh=u(()=>{Xe();tr()});function Ah(e){return W({true:e,false:e})}var Mh=u(()=>{fe()});function je(e,t={}){let[n,r,o]=[e,e.length,!1];return d.Create({"~kind":"Tuple"},{type:"array",additionalItems:o,items:n,minItems:r},t)}function be(e){return L(e,"Tuple")}function Oh(e){return d.Discard(e,["~kind","type","items","minItems","additionalItems"])}var Ue=u(()=>{S();J()});function yM(e){return d.Discard(e,["~readonly"])}function Pc(e,t){return d.Update(yM(e),{},t)}function Ch(e,t,n,r){let o=T(e,t,n);return Pc(o,r)}var Rc=u(()=>{S();q()});function Lh(e,t={}){return j("RemoveReadonly",[e],t)}function Fh(e,t={}){return Pc(e,t)}var Ac=u(()=>{ce();Rc()});function bM(e){return d.Discard(e,["~optional"])}function Mc(e,t){return d.Update(bM(e),{},t)}function jh(e,t,n,r){let o=T(e,t,n);return Mc(o,r)}var Oc=u(()=>{S();q()});function Dh(e,t={}){return j("RemoveOptional",[e],t)}function ea(e,t={}){return Mc(e,t)}var ta=u(()=>{ce();Oc()});function Cc(e){return e.reduceRight((n,r,o)=>({[o]:r,...n}),{})}function _h(e){let t=Cc(e.items);return W(t)}var Lc=u(()=>{fe()});function Fc(e){return pe(e)||be(e)}function wM(e,t){return Sr(e)?!!Sr(t):!1}function IM(e,t){return ut(e)?!!ut(t):!1}function $M(e,t){let n=wM(e,t),r=IM(e,t),o=Te([e,t]),s=Fh(ea(o));return n&&r?Er($r(s)):n&&!r?Er(s):!n&&r?$r(s):s}function kM(e,t,n){return n in e?n in t?$M(e[n],t[n]):e[n]:n in t?t[n]:ge()}function TM(e,t){return[...new Set([...m.Keys(e),...m.Keys(t)])].reduce((o,s)=>({...o,[s]:kM(e,t,s)}),{})}function Nh(e){return pe(e)?e.properties:be(e)?Cc(e.items):{}}function qh(e,t){let n=Nh(e),r=Nh(t),o=TM(n,r);return W(o)}var jc=u(()=>{O();ls();Zn();fe();Je();Ue();ps();os();Ac();ta();Lc();Y()});function vM(e,t){let n=bs(e,t);return m.IsEqual(n,ys)?e:m.IsEqual(n,na)||m.IsEqual(n,xs)?t:ge()}function EM(e,t){let n=Fc(e),r=Fc(t);return n&&r?qh(e,t):n&&!r?e:!n&&r?t:vM(e,t)}function Uh(e,t){return un(e)||Ee(e)?e:Oe(e)||un(t)||Ee(t)?t:Oe(t)?e:EM(e,t)}var Dc=u(()=>{O();$t();Je();nt();ws();jc()});function SM(e,t){return F(e)||F(t)}function PM(e,t){let n=Zt(e),r=Zt(t);return SM(n,r)?Te([n,r]):Uh(n,r)}function Kh(e,t,n=[]){return m.ShiftLeft(t,(r,o)=>Kh(e,o,[...n,PM(r,e)]),()=>m.IsEqual(n.length,0)?[e]:n)}function Gh(e,t,n=[]){return m.ShiftLeft(e,(r,o)=>Gh(o,t,[...n,...Is([r],t)]),()=>n)}function Is(e,t=[]){return m.ShiftLeft(e,(n,r)=>F(n)?Is(r,Gh(n.anyOf,t)):Is(r,Kh(n,t)),()=>t)}var _c=u(()=>{O();Q();Dc();Y();Y()});function RM(e,t){let n=st({},e,t);return B.IsExtendsTrueLike(n)?[]:[e]}function Wh(e,t,n=[]){return m.ShiftLeft(e,(r,o)=>Wh(o,t,[...n,...RM(r,t)]),()=>n)}function ra(e,t){let n=Zt(e),r=F(n)?n.anyOf:[n],o=Wh(r,t);return St(o)}var Nc=u(()=>{O();Q();Sn();Y();Y()});function pn(e,t,n){let r=Te([e,t]),o=ra(n,e);return St([r,o])}function bt(e,t=[]){return m.ShiftLeft(e,(n,r)=>bt(r,[...t,se(n)]),()=>St(t))}function Te(e){let t=Is(e),n=qc(t);return St(n)}function mt(e){let t=Sh(e);return Zt(t)}function St(e){let t=qc(e);return nr(t)}function Zt(e){return Pe(e)?pn(e.if,e.then,e.else):ot(e)?bt(e.enum):oe(e)?Te(e.allOf):Re(e)?mt(e.pattern):F(e)?St(e.anyOf):e}function nr(e){return m.IsEqual(e.length,1)?e[0]:m.IsEqual(e.length,0)?ge():X(e)}var Y=u(()=>{O();Ot();mn();Ne();Le();Je();vt();Q();_c();Uc();Nc();Qi()});function Bh(e,t){let n=bt(e);return rr(n,t)}var zh=u(()=>{$s();Y()});function Hh(e,t){return Et(or,t)}var Vh=u(()=>{Xe();tr()});function Jh(e,t){let n=Te(e);return rr(n,t)}var Yh=u(()=>{Y();$s()});function Xh(e,t){return m.IsString(e)||m.IsNumber(e)?W({[e]:t}):m.IsEqual(e,!1)?W({false:t}):m.IsEqual(e,!0)?W({true:t}):W({})}var Zh=u(()=>{O();fe()});function Qh(e,t){return Et(uo,t)}var ex=u(()=>{Xe();tr()});function tx(e,t){return m.HasPropertyKey(e,"pattern")&&(m.IsString(e.pattern)||e.pattern instanceof RegExp)?Et(e.pattern.toString(),t):Et(cn,t)}var nx=u(()=>{O();Xe();tr()});function rx(e,t){let n=gs(e);return Ji(n)?rr(mt(e),t):Et(e,t)}var ox=u(()=>{$s();hs();Yi();Y();tr()});function AM(e){return F(e)?mo(e.anyOf):[e]}function mo(e,t=[]){return m.ShiftLeft(e,(n,r)=>mo(r,[...t,...AM(n)]),()=>t)}var oa=u(()=>{O();Q()});function MM(e){return e.some(t=>yt(t)||Fe(t)||ht(t))}function OM(e,t){return m.IsEqual(MM(e),!0)?Et(cn,t):void 0}function CM(e,t){return e.reduce((n,r)=>le(r)&&(m.IsString(r.const)||m.IsNumber(r.const))?{...n,[r.const]:t}:n,{})}function LM(e,t){let n=CM(e,t);return W(n)}function sx(e,t){let n=mo(e),r=OM(n,t);return _e(r)?r:LM(n,t)}var ix=u(()=>{O();J();Le();xt();En();fe();Xt();Xe();oa();tr()});function rr(e,t){return Ee(e)?Ph(t):Jt(e)?Ah(t):ot(e)?Bh(e.enum,t):ht(e)?Hh(e,t):oe(e)?Jh(e.allOf,t):le(e)?Xh(e.const,t):Fe(e)?Qh(e,t):F(e)?sx(e.anyOf,t):yt(e)?tx(e,t):Re(e)?rx(e.pattern,t):W({})}var $s=u(()=>{$t();Qn();mn();Ne();En();Le();xt();fe();Xt();vt();Q();Rh();Mh();zh();Vh();Yh();Zh();ex();nx();ox();ix()});function Kc(e,t,n){return V([e])?d.Update(rr(e,t),{},n):ia(e,t,n)}function ax(e,t,n,r,o){let s=T(e,t,n),i=T(e,t,r);return Kc(s,i,o)}var sa=u(()=>{S();Xe();$s();q()});function ia(e,t,n={}){return j("Record",[e,t],n)}function aa(e,t,n={}){return Kc(e,t,n)}function ux(e,t){return Et(e,t)}function ua(e){return m.IsEqual(e,cn)?Yt():m.IsEqual(e,or)?Rr():m.IsEqual(e,uo)?Ct():Sc(e)}function Qt(e){return m.Keys(e.patternProperties)[0]}function co(e){let t=Qt(e);return ua(t)}function wt(e){return e.patternProperties[Qt(e)]}function it(e){return L(e,"Record")}var or,uo,cn,Xe=u(()=>{S();O();J();En();xt();Xt();ce();Qi();tr();sa();or=`^${Wi}$`,uo=`^${zi}$`,cn=`^${Hi}$`});function Or(e){return d.Create({"~kind":"Rest"},{type:"rest",items:e},{})}function sr(e){return L(e,"Rest")}var po=u(()=>{S();J()});var mx=u(()=>{});function ma(e){return d.Create({"~kind":"This"},{$ref:"#"},e)}function ca(e){return L(e,"This")}var pa=u(()=>{S();J()});function lo(e){return d.Create({"~kind":"Undefined"},{type:"undefined"},e)}function fo(e){return L(e,"Undefined")}var go=u(()=>{S();J()});function la(e){return d.Create({"~kind":"Void"},{type:"void"},e)}function Pn(e){return L(e,"Void")}var Cr=u(()=>{S();J()});var da=u(()=>{Ic();ms();Zn();ls();kc();$t();gt();Pr();Qn();ho();Bt();kt();ce();mn();zt();rs();Tc();Ot();Vt();En();Ne();Le();Je();io();xt();nt();Ar();fe();Ec();kr();Xe();Ht();po();J();mx();Xt();Ar();vt();pa();Ue();go();Q();nt();Ni();Cr()});function jM(e,t){return m.IsEqual(e,"Array")?qt(t[0]):m.IsEqual(e,"Capitalize")?ga(t[0]):m.IsEqual(e,"ConstructorParameters")?wa(t[0]):m.IsEqual(e,"Evaluate")?pb(t[0]):m.IsEqual(e,"Exclude")?Ia(t[0],t[1]):m.IsEqual(e,"Extract")?$a(t[0],t[1]):m.IsEqual(e,"Index")?Es(t[0],t[1]):m.IsEqual(e,"InstanceType")?ka(t[0]):m.IsEqual(e,"Lowercase")?ha(t[0]):m.IsEqual(e,"NonNullable")?Ta(t[0]):m.IsEqual(e,"Omit")?va(t[0],t[1]):m.IsEqual(e,"Parameters")?Ea(t[0]):m.IsEqual(e,"Partial")?Sa(t[0]):m.IsEqual(e,"Pick")?Pa(t[0],t[1]):m.IsEqual(e,"Readonly")?Ra(t[0]):m.IsEqual(e,"KeyOf")?Ss(t[0]):m.IsEqual(e,"Record")?ia(t[0],t[1]):m.IsEqual(e,"Required")?Aa(t[0]):m.IsEqual(e,"ReturnType")?Ma(t[0]):m.IsEqual(e,"Uncapitalize")?xa(t[0]):m.IsEqual(e,"Uppercase")?ya(t[0]):vs(qn(e),t)}function Lr(){throw Error("Unreachable")}function fx(e,t=[]){return m.ShiftLeft(e,(n,r)=>fx(r,[...t,n[1]]),()=>t)}function Un(e){return m.IsEqual(e.length,3)?[e[0],...fx(e[1])]:[]}function gx(e){return Mr(e[0],e[2],e[4])}function hx(e){return Mr(e[0],e[2],e[2])}function xx(e){return Mr(e[0],Ye(),e[2])}function yx(e){return Mr(e,Ye(),Ye())}function bx(e){return Un(e)}function wx(e){return e[1]}function Ix(e){return Un(e)}function $x(e){return e[1]}function kx(e){return jM(e[0],e[1])}function Tx(e){return null}function vx(e){return Yt()}function Ex(e){return Ct()}function Sx(e){return Gi()}function Px(e){return lo()}function Rx(e){return oo()}function Ax(e){return Rr()}function Mx(e){return ds()}function Ox(e){return Ye()}function Cx(e){return to()}function Lx(e){return W({})}function Fx(e){return ge()}function jx(e){return ao()}function Dx(e){return la()}function _x(e){return ma()}function Nx(e){return se(BigInt(e))}function qx(e){return se(m.IsEqual(e,"true"))}function Ux(e){return se(parseFloat(e))}function Kx(e){return se(e)}function Gx(e){return e[1]}function Wx(e){return se(e)}function Bx(e){return m.IsEqual(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function zx(e){return e[1]}function Hx(e){return fa(e)}function Vx(e){return m.IsEqual(e.length,6)?Tr(e[1],e[3],e[5]):Tr(e[1],e[3],Ye())}function Jx(e){return e.length>0}function Yx(e){return e.reduce((t,n)=>m.IsEqual(n.length,3)?[...t,[n[1]]]:[...t,[]],[])}function Xx(e){return m.IsEqual(e.length,6)?[e[1],e[3],e[5]]:[]}function Zx(e){return m.IsArray(e)&&m.IsEqual(e.length,3)?e[1]:e}function Qx(e){return m.IsEqual(e.length,2)?e[1]:[]}function cx(e,t){return t.reduce((n,r)=>{let o=r;return m.IsEqual(o.length,1)?Es(n,o[0]):m.IsEqual(o.length,0)?qt(n):Lr()},e)}function px(e,t){return m.IsEqual(t.length,3)?ba(e,t[0],t[1],t[2]):e}function DM(e,t){return m.IsArray(t)&&m.IsEqual(t.length,0)?e:Oa(e,t)}function ey(e){let[t,n,r,o,s]=e;return DM(px(t?Ss(cx(n,r)):cx(n,r),o),s)}function Gc(e,t){return m.IsEqual(t.length,3)?(()=>{let[n,r,o]=t,s=Gc(r,o);if(m.IsEqual(n,"&"))return oe(s)?Tt([e,...s.allOf]):Tt([e,s]);if(m.IsEqual(n,"|"))return F(s)?X([e,...s.anyOf]):X([e,s]);Lr()})():e}function ty(e){let[t,n]=e;return Gc(t,n)}function ny(e){let[t,n]=e;return Gc(t,n)}function ry(e){return cb(e[1])}function oy(e){return e[1]}function sy(e){return Xn(e[0],e[2])}function iy(e){return m.IsEqual(e.length,4)?ss(e[1],e[3]):m.IsEqual(e.length,2)?ss(e[1],Ye()):Lr()}function ay(e){return`${e}`}function uy(e){return ht(e[3])?or:Fe(e[3])?uo:er(e[3])?cn:yt(e[3])?cn:Lr()}function my(e){return e.length>0}function cy(e){return e.length>0}function py(e){let[t,n,r,o,s]=e;return{[n]:t&&r?Tn(wn(s)):t&&!r?Tn(s):!t&&r?wn(s):s}}function ly(e){return Un(e)}function dy(e){return e.reduce((t,n)=>m.HasPropertyKey(n,or)||m.HasPropertyKey(n,uo)||m.HasPropertyKey(n,cn)?[t[0],d.Assign(t[1],n)]:[d.Assign(t[0],n),t[1]],[{},{}])}function fy(e){return dy(e[1])}function gy(e){let[t,n]=e,r=m.IsEqual(m.Keys(n).length,0)?{}:{patternProperties:n};return W(t,r)}function hy(e){return m.IsEqual(e.length,5)?Tn(wn(e[4])):m.IsEqual(e.length,3)?e[2]:m.IsEqual(e.length,4)?m.IsEqual(e[2],"readonly")?Tn(e[3]):wn(e[3]):Lr()}function xy(e){if(!m.IsArray(e)||!m.IsEqual(e.length,3))return e;let[t,n,r]=e;return t&&r?Tn(wn(n)):t&&!r?Tn(n):!t&&r?wn(n):n}function yy(e){return m.IsEqual(e.length,2)?Or(e[1]):m.IsEqual(e.length,1)?e[0]:Lr()}function by(e){return Un(e)}function wy(e){return je(e[1])}function Iy(e){return Tn(wn(e[4]))}function $y(e){return Tn(e[3])}function ky(e){return wn(e[3])}function Ty(e){return e[2]}function vy(e){return m.IsEqual(e.length,2)?Or(e[1]):m.IsEqual(e.length,1)?e[0]:Lr()}function Ey(e){return Un(e)}function Sy(e){return bn(e[1],e[4])}function Py(e){return yn(e[2],e[5])}function lx(e,t){return m.IsEqual(e,"remove")?Lh(t):m.IsEqual(e,"add")?Tn(t):t}function Ry(e){return m.IsEqual(e.length,2)&&m.IsEqual(e[0],"-")?"remove":m.IsEqual(e.length,2)&&m.IsEqual(e[0],"+")||m.IsEqual(e.length,1)?"add":"none"}function dx(e,t){return m.IsEqual(e,"remove")?Dh(t):m.IsEqual(e,"add")?wn(t):t}function Ay(e){return m.IsEqual(e.length,2)&&m.IsEqual(e[0],"-")?"remove":m.IsEqual(e.length,2)&&m.IsEqual(e[0],"+")||m.IsEqual(e.length,1)?"add":"none"}function My(e){return m.IsEqual(e.length,2)?[e[1]]:[]}function Oy(e){return m.IsArray(e[6])&&m.IsEqual(e[6].length,1)?ks(fs(e[3]),e[5],e[6][0],lx(e[1],dx(e[8],e[10]))):ks(fs(e[3]),e[5],qn(e[3]),lx(e[1],dx(e[8],e[10])))}function Cy(e){return qn(e)}function Ly(e){return BigInt(e)}function Fy(e){return parseFloat(e)}function jy(e){return m.IsEqual(e,"true")}function Dy(e){return null}function _y(e){return{[e[0]]:e[2]}}function Ny(e){return Un(e)}function _M(e){return e.reduce((t,n)=>d.Assign(t,n),{})}function qy(e){return _M(e[1])}function Uy(e){return Un(e)}function Ky(e){return e[1]}function Gy(e){return ds()}function Wy(e){return Yt()}function By(e){return Ct()}function zy(e){return Rr()}function Hy(e){return ge()}function Vy(e){return se(e)}function Jy(e){return X(e[1])}function Yy(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function Xy(e){return[e[0],...e[1]]}function Zy(e){return e[1]}function Qy(e){return Un(e)}function eb(e){return m.IsEqual(e.length,2)?e[1]:[]}function tb(e){let t=e[2],n=e[3],[r,o]=e[4],s=m.IsEqual(m.Keys(o).length,0)?{}:{patternProperties:o};return{[e[1]]:Xn(t,Ts(n,r,s))}}function nb(e){let t=e[2],[n,r]=e[3],o=m.IsEqual(m.Keys(r).length,0)?{}:{patternProperties:r};return{[e[1]]:Ts(t,n,o)}}function rb(e){return{[e[1]]:Xn(e[2],e[4])}}function ob(e){return{[e[1]]:e[3]}}function sb(e){return null}function ib(e){return Un(e)}function ab(e){return e[1]}function ub(e){let[t,n]=[e[0],e[1]];return lb(d.Assign(t,dy(n)[0]))}var mb=u(()=>{S();O();da();xo()});var Kn=u(()=>{Qr()});function Ps(e){return ue(e.length,2)}function te(e,t,n){return Ps(e)?t(e[0],e[1]):n()}var Lt=u(()=>{Kn()});function UM(e,t){return ue(t.indexOf(e),0)?[e,t.slice(e.length)]:[]}function Se(e,t){for(let n=0;n<e.length;n++){let r=UM(e[n],t);if(Ps(r))return r}return[]}var Rn=u(()=>{Lt();Kn()});function Wc(e,t){return Array.from({length:t-e+1},(n,r)=>String.fromCharCode(e+r))}var db,Bc,zc,yo,fb,bo,ir,Ca,gb,La,ct=u(()=>{db=[...Wc(97,122),...Wc(65,90)],Bc="0",zc=Wc(49,57),yo=[Bc,...zc],fb=" ",bo=`
|
|
13
|
+
`)}function Vo(e={}){return t=>{t.on("tool_call",async n=>{let r=af(n.toolName,n.input);if(r)return{block:!0,reason:mf(n.toolName,r.repeats)};let o=mc,s=xf(o,n.toolName,n.input);if(s.action==="run")return;if(s.action==="deny")return{block:!0,reason:s.reason};if(e.interactive===!1)return{block:!0,reason:`Blocked: this is a ${uc(n.toolName)}-tier tool and no UI can approve it here (approval mode: ${o}).`};if(!await hf(`${n.toolName} wants to run`,bf(n.toolName,n.input,s.reason)))return{block:!0,reason:`Blocked by the user (approval mode: ${o}).`}})}}var Xr,vi,ac,ff,UR,KR,mc,hf,Jo=u(()=>{rc();ic();ic();Xr=["suggest","auto-edit","full-auto"],vi={suggest:"suggest: ask before every edit and command","auto-edit":"auto-edit: edits run, commands ask","full-auto":"full-auto: nothing asks"};ac={read:0,write:1,exec:2},ff={suggest:"read","auto-edit":"write","full-auto":"exec"},UR={read:"read",grep:"read",find:"read",ls:"read",think:"read",ask:"read",todo:"read",context:"read",web_search:"read",web_fetch:"read",lsp:"read",workflow:"exec",goal:"read",enter_plan_mode:"read",exit_plan_mode:"read",edit:"write",write:"write",bash:"exec",powershell:"exec",task:"exec"};KR=[{pattern:/\brm\s+(?:-[a-zA-Z]+\s+)*(?:\/|\/\*|~|\$HOME)(?:\s|$)/,reason:"recursive delete of the filesystem root or home"},{pattern:/\bmkfs(?:\.[a-z0-9]+)?\b/,reason:"filesystem format"},{pattern:/\bdd\b[^|;]*\bof=\/dev\/(?:sd|nvme|hd|vd)/,reason:"raw write to a block device"},{pattern:/:\s*\(\s*\)\s*\{.*\}\s*;\s*:/,reason:"fork bomb"},{pattern:/>\s*\/etc\/(?:passwd|shadow|sudoers)/,reason:"overwrite of a system account file"},{pattern:/\b(?:shutdown|reboot|halt|poweroff)\b/,reason:"host shutdown"}];mc="full-auto",hf=async()=>!1});function WR(e){return e.replace(/operating inside pi, a coding agent harness/gi,"operating as HowToFix, a coding agent harness").replace(/^Pi documentation \(read only when the user asks about[^\n]*\):?$/gim,"Harness documentation (internal reference; the user is never told the harness name):").replace(/\bpi itself\b/gi,"the harness itself").replace(/^- When reading pi docs or examples/m,"- When reading harness docs or examples").replace(/^- When working on pi topics/m,"- When working on harness topics").replace(/^- Always read pi \.md files/m,"- Always read the harness .md files").replace(/\bpi packages\b/gi,"harness packages").replace(/\bpi \.md files\b/gi,"harness .md files").replace(/\bpi docs\b/gi,"harness docs").replace(/^-\s*You can inspect PI_\* environment variables/m,"- You can inspect the harness's environment variables")}function zR(e){if(!e)return;let t=!1,n={...e};for(let r of BR){let o=n[r];if(typeof o!="string")continue;let s=WR(o);s!==o&&(n[r]=s,t=!0)}return t?n:void 0}function If(){return e=>{e.on("context_with_system",async t=>{let n=t.messages[0];if(!n||n.role!=="system")return;let r=zR(n.sections);return r?{messages:t.messages.map(s=>s===n?{...n,sections:r}:s)}:void 0})}}var BR,$f=u(()=>{BR=["preamble","rules","docs","addendum"]});import{Type as Zr}from"@earendil-works/pi-ai";import{defineTool as kf}from"@earendil-works/pi-coding-agent";function Tf(e){lc=e}var lc,vf,Ef,dc=u(()=>{vf=kf({name:"think",label:"think",description:"Private scratchpad. The text is not shown to the user. Use it before a non-obvious step.",promptSnippet:"think: private notes, not shown to the user",parameters:Zr.Object({thoughts:Zr.String({description:"Private notes"})}),async execute(){return{content:[{type:"text",text:"noted"}],details:{recorded:!0}}}}),Ef=kf({name:"ask",label:"ask",description:"Ask the user one question and wait for a selected answer. Use this instead of guessing when a choice blocks the task.",promptSnippet:"ask: ask the user to pick one option",parameters:Zr.Object({question:Zr.String(),options:Zr.Array(Zr.String(),{minItems:2})}),async execute(e,t){if(!lc)return{content:[{type:"text",text:"cancelled"}],details:{answer:"cancelled"}};let n=await lc(t.question,t.options);return{content:[{type:"text",text:n}],details:{answer:n}}}})});var sn,yr=u(()=>{sn={assign:0,create:0,clone:0,discard:0,update:0}});function br(e,t,n){return e>=t&&e<=n}function Rf(e){return e===8205}function HR(e){return br(e,55296,56319)}function Sf(e){return br(e,127462,127487)}function Af(e){return br(e,65024,65039)}function Mf(e){return br(e,768,879)||br(e,6832,6911)||br(e,7616,7679)||br(e,65056,65071)}function Ei(e){return e>65535?2:1}function Pf(e,t){for(;t<e.length;){let n=e.codePointAt(t);if(Mf(n)||Af(n))t+=Ei(n);else break}return t}function fc(e,t){let n=e.codePointAt(t),r=t+Ei(n);for(r=Pf(e,r);r<e.length-1&&Rf(e.codePointAt(r));){let o=e.codePointAt(r+1);r+=1+Ei(o),r=Pf(e,r)}return Sf(n)&&r<e.length&&Sf(e.codePointAt(r))&&(r+=Ei(e.codePointAt(r))),r}function Of(e){return e>=768&&(HR(e)||Mf(e)||Af(e)||Rf(e))}function Cf(e){let t=0,n=0;for(;n<e.length;)n=fc(e,n),t++;return t}function VR(e,t){let n=0,r=0;for(;r<e.length;)if(r=fc(e,r),++n>=t)return!0;return!1}function JR(e,t){let n=0,r=0;for(;r<e.length;)if(r=fc(e,r),++n>t)return!1;return!0}function Lf(e,t){if(t===0)return!0;if(e.length<t)return!1;let n=0;for(;;){if(Of(e.charCodeAt(n)))return VR(e,t);if(++n>=t)return!0}}function Ff(e,t){if(e.length<=t)return!0;let n=0;for(;;){if(Of(e.charCodeAt(n)))return JR(e,t);if(++n>t)return!1}}var jf=u(()=>{});var m={};Mt(m,{Counted:()=>pA,Entries:()=>fA,EntriesRegExp:()=>dA,Every:()=>aA,EveryAll:()=>uA,GraphemeCount:()=>oA,HasPropertyKey:()=>lA,IsArray:()=>Xo,IsBigInt:()=>Yo,IsBoolean:()=>Df,IsClassInstance:()=>rA,IsConstructor:()=>XR,IsDeepEqual:()=>xc,IsEqual:()=>ue,IsFunction:()=>_f,IsGreaterEqualThan:()=>qf,IsGreaterThan:()=>eA,IsInteger:()=>gc,IsLessEqualThan:()=>Nf,IsLessThan:()=>tA,IsMaxLength:()=>sA,IsMinLength:()=>iA,IsMultipleOf:()=>nA,IsNull:()=>Pi,IsNumber:()=>Ri,IsObject:()=>Zo,IsObjectNotArray:()=>ZR,IsString:()=>Ai,IsSymbol:()=>QR,IsUndefined:()=>hc,IsUnsafePropertyKey:()=>Kf,IsValueLike:()=>Uf,Keys:()=>Si,ShiftLeft:()=>Mi,Some:()=>mA,SomeAll:()=>cA,Symbols:()=>gA,Values:()=>hA});function Xo(e){return Array.isArray(e)}function Yo(e){return ue(typeof e,"bigint")}function Df(e){return ue(typeof e,"boolean")}function XR(e){if(hc(e)||!_f(e))return!1;let t=Function.prototype.toString.call(e);return!!(/^class\s/.test(t)||/\[native code\]/.test(t))}function _f(e){return ue(typeof e,"function")}function gc(e){return Number.isInteger(e)}function Pi(e){return ue(e,null)}function Ri(e){return Number.isFinite(e)}function ZR(e){return Zo(e)&&!Xo(e)}function Zo(e){return ue(typeof e,"object")&&!Pi(e)}function Ai(e){return ue(typeof e,"string")}function QR(e){return ue(typeof e,"symbol")}function hc(e){return ue(e,void 0)}function ue(e,t){return e===t}function eA(e,t){return e>t}function tA(e,t){return e<t}function Nf(e,t){return e<=t}function qf(e,t){return e>=t}function nA(e,t){if(Yo(e)||Yo(t))return BigInt(e)%BigInt(t)===0n;let n=1e-10;if(!Ri(e)||gc(e)&&1/t%1===0)return!0;let r=e%t;return Math.min(Math.abs(r),Math.abs(r-t),Math.abs(r+t))<n}function rA(e){if(!Zo(e))return!1;let t=globalThis.Object.getPrototypeOf(e);return Pi(t)?!1:ue(typeof t.constructor,"function")&&!(ue(t.constructor,globalThis.Object)||ue(t.constructor.name,"Object"))}function Uf(e){return Yo(e)||Df(e)||Pi(e)||Ri(e)||Ai(e)||hc(e)}function oA(e){return Cf(e)}function sA(e,t){return Ff(e,t)}function iA(e,t){return Lf(e,t)}function aA(e,t,n){return e.every((r,o)=>o<t||n(r,o))}function uA(e,t,n){let r=!0;return e.forEach((o,s)=>{s>=t&&!n(o,s)&&(r=!1)}),r}function mA(e,t){return e.some((n,r)=>t(n,r))}function cA(e,t){let n=!1;return e.forEach((r,o)=>{t(r,o)&&(n=!0)}),n}function pA(e,t){return e.reduce((n,r,o)=>t(r,o)?++n:n,0)}function Mi(e,t,n){return ue(e.length,0)?n():t(e[0],e.slice(1))}function Kf(e){return ue(e,"__proto__")||ue(e,"constructor")||ue(e,"prototype")}function lA(e,t){return Kf(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function dA(e){return Si(e).map(t=>[new RegExp(`^${t}$`),e[t]])}function fA(e){return Object.entries(e)}function Si(e){return Object.getOwnPropertyNames(e)}function gA(e){return Object.getOwnPropertySymbols(e)}function hA(e){return Object.values(e)}function xA(e,t){if(!Zo(t))return!1;let n=Si(e);return ue(n.length,Si(t).length)&&n.every(r=>xc(e[r],t[r]))}function yA(e,t){return Xo(t)&&ue(e.length,t.length)&&e.every((n,r)=>xc(e[r],t[r]))}function xc(e,t){return Xo(e)?yA(e,t):Zo(e)?xA(e,t):ue(e,t)}var Qr=u(()=>{jf()});var Gf=u(()=>{Qr()});var Vn={};Mt(Vn,{IsBigInt64Array:()=>CA,IsBigUint64Array:()=>LA,IsBoolean:()=>wA,IsDate:()=>jA,IsFloat32Array:()=>MA,IsFloat64Array:()=>OA,IsInt16Array:()=>SA,IsInt32Array:()=>RA,IsInt8Array:()=>TA,IsMap:()=>_A,IsNumber:()=>IA,IsRegExp:()=>FA,IsSet:()=>DA,IsString:()=>$A,IsTypeArray:()=>kA,IsUint16Array:()=>PA,IsUint32Array:()=>AA,IsUint8Array:()=>vA,IsUint8ClampedArray:()=>EA});function wA(e){return e instanceof Boolean}function IA(e){return e instanceof Number}function $A(e){return e instanceof String}function kA(e){return globalThis.ArrayBuffer.isView(e)}function TA(e){return e instanceof globalThis.Int8Array}function vA(e){return e instanceof globalThis.Uint8Array}function EA(e){return e instanceof globalThis.Uint8ClampedArray}function SA(e){return e instanceof globalThis.Int16Array}function PA(e){return e instanceof globalThis.Uint16Array}function RA(e){return e instanceof globalThis.Int32Array}function AA(e){return e instanceof globalThis.Uint32Array}function MA(e){return e instanceof globalThis.Float32Array}function OA(e){return e instanceof globalThis.Float64Array}function CA(e){return e instanceof globalThis.BigInt64Array}function LA(e){return e instanceof globalThis.BigUint64Array}function FA(e){return e instanceof globalThis.RegExp}function jA(e){return e instanceof globalThis.Date}function DA(e){return e instanceof globalThis.Set}function _A(e){return e instanceof globalThis.Map}var Wf=u(()=>{});var Bf=u(()=>{Qr()});var O=u(()=>{Gf();Wf();Bf();Qr();Qr()});var an={};Mt(an,{Get:()=>KA,Reset:()=>qA,Set:()=>UA});function qA(){xn.immutableTypes=!1,xn.maxErrors=8,xn.maxInstantiationCount=128,xn.useAcceleration=!0,xn.exactOptionalPropertyTypes=!1,xn.enumerableKind=!1,xn.correctiveParse=!1,xn.unionPrioritySort=!0}function UA(e){for(let t of m.Keys(e)){let n=e[t];n!==void 0&&Object.defineProperty(xn,t,{value:n})}}function KA(){return xn}var xn,zf=u(()=>{O();xn={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0}});var wr=u(()=>{zf()});function Jn(e){return an.Get().immutableTypes?Object.freeze(e):e}var Qo=u(()=>{wr()});function GA(e,t){return sn.assign+=1,Jn({...e,...t})}var Hf=u(()=>{yr();Qo()});function WA(e){return m.HasPropertyKey(e,"~kind")||m.HasPropertyKey(e,"~unsafe")}function BA(e){let t={};for(let n of m.Keys(e)){if(m.IsUnsafePropertyKey(n))continue;let r=Object.getOwnPropertyDescriptor(e,n);r.value=Ir(r.value),m.IsEqual(r.enumerable,!0)?t[n]=r.value:Object.defineProperty(t,n,r)}return t}function zA(e){let t={};for(let n of m.Keys(e))m.IsUnsafePropertyKey(n)||(t[n]=Ir(e[n]));for(let n of m.Symbols(e))t[n]=Ir(e[n]);return t}function HA(e){return m.IsClassInstance(e)?e:WA(e)?BA(e):zA(e)}function VA(e){return e.map(t=>Ir(t))}function JA(e){return e.slice()}function YA(e){return new RegExp(e.source,e.flags)}function XA(e){return new Map(Ir([...e.entries()]))}function ZA(e){return new Set(Ir([...e.values()]))}function Ir(e){return Vn.IsTypeArray(e)?JA(e):Vn.IsRegExp(e)?YA(e):Vn.IsMap(e)?XA(e):Vn.IsSet(e)?ZA(e):m.IsArray(e)?VA(e):m.IsObject(e)?HA(e):e}function es(e){return sn.clone+=1,Ir(e)}var Oi=u(()=>{O();yr()});function QA(e,t){for(let n of Object.keys(t))Object.defineProperty(e,n,{configurable:!0,writable:!0,enumerable:!1,value:t[n]});return e}function Vf(e,t){return{...e,...t}}function eM(e,t,n={}){sn.create+=1;let r=Vf(t,n),o=an.Get().enumerableKind?Vf(r,e):QA(r,e);return Jn(o)}var Jf=u(()=>{wr();yr();Qo()});function tM(e,t){sn.discard+=1;let n={};for(let r of m.Keys(e)){if(t.includes(r))continue;let o=Object.getOwnPropertyDescriptor(e,r);o.value=es(o.value),Object.defineProperty(n,r,o)}return Jn(n)}var Yf=u(()=>{O();yr();Qo();Oi()});function nM(e,t,n){sn.update+=1;let r=an.Get(),o=es(e);for(let s of Object.keys(t))Object.defineProperty(o,s,{configurable:!0,writable:!0,enumerable:r.enumerableKind,value:t[s]});for(let s of Object.keys(n))Object.defineProperty(o,s,{configurable:!0,enumerable:!0,writable:!0,value:n[s]});return Jn(o)}var Xf=u(()=>{wr();yr();Qo();Oi()});var d={};Mt(d,{Assign:()=>GA,Clone:()=>es,Create:()=>eM,Discard:()=>tM,Metrics:()=>sn,Update:()=>nM});var Zf=u(()=>{Hf();Oi();Jf();Yf();yr();Xf()});var S=u(()=>{Zf()});function L(e,t){return m.IsObject(e)&&m.HasPropertyKey(e,"~kind")&&m.IsEqual(e["~kind"],t)}function _e(e){return m.IsObject(e)}var J=u(()=>{O()});function j(e,t,n){return d.Create({"~kind":"Deferred"},{type:"deferred",action:e,parameters:t,options:n},{})}function Yn(e){return L(e,"Deferred")}var ce=u(()=>{S();J()});function rM(e){return d.Update(e,{"~readonly":!0},{})}function ts(e,t){return d.Update(rM(e),{},t)}function Qf(e,t,n,r){let o=T(e,t,n);return ts(o,r)}var Ci=u(()=>{S();q()});function oM(e){return d.Update(e,{"~optional":!0},{})}function ns(e,t){return d.Update(oM(e),{},t)}function eg(e,t,n,r){let o=T(e,t,n);return ns(o,r)}var Li=u(()=>{S();q()});function qt(e,t){return d.Create({"~kind":"Array"},{type:"array",items:e},t)}function ke(e){return L(e,"Array")}function Fi(e){return d.Discard(e,["~kind","type","items"])}var gt=u(()=>{S();J()});function yn(e,t,n={}){return d.Create({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:t},n)}function Ge(e){return L(e,"Constructor")}function tg(e){return d.Discard(e,["~kind","type","parameters","instanceType"])}var Bt=u(()=>{S();J()});function bn(e,t,n={}){return d.Create({"~kind":"Function"},{type:"function",parameters:e,returnType:t},n)}function We(e){return L(e,"Function")}function ng(e){return d.Discard(e,["~kind","type","parameters","returnType"])}var zt=u(()=>{S();J()});function qn(e,t){return d.Create({"~kind":"Ref"},{$ref:e},t)}function Be(e){return L(e,"Ref")}var Ht=u(()=>{S();J()});function Xn(e,t){return d.Create({"~kind":"Generic"},{type:"generic",parameters:e,expression:t})}function eo(e){return L(e,"Generic")}var rs=u(()=>{S();J()});function to(e){return d.Create({"~kind":"Any"},{},e)}function Ee(e){return L(e,"Any")}var $t=u(()=>{S();J()});function ge(e){return d.Create({"~kind":"Never"},{not:{}},e)}function un(e){return L(e,"Never")}var rg,Je=u(()=>{S();J();rg="(?!)"});function wn(e,t={}){return j("AddOptional",[e],t)}function $r(e,t={}){return ns(e,t)}var os=u(()=>{ce();Li()});function og(e){return $r(e)}function ut(e){return _e(e)&&m.HasPropertyKey(e,"~optional")}var Zn=u(()=>{O();J();os()});function sg(e){return m.Keys(e).filter(t=>!ut(e[t]))}function ji(e){return m.Keys(e)}function Di(e){return m.Values(e)}var kr=u(()=>{O();Zn()});function W(e,t={}){let n=sg(e),r=n.length>0?{required:n}:{};return d.Create({"~kind":"Object"},{type:"object",...r,properties:e},t)}function pe(e){return L(e,"Object")}function ig(e){return d.Discard(e,["~kind","type","properties","required"])}var fe=u(()=>{S();J();kr()});function Ye(e){return d.Create({"~kind":"Unknown"},{},e)}function Oe(e){return L(e,"Unknown")}var nt=u(()=>{S();J()});function In(e,t,n){let r=m.Keys(e).reduce((o,s)=>({...o,[s]:d.Update(e[s],{},{$id:s})}),{});return d.Create({"~kind":"Cyclic"},{$defs:r,$ref:t},n)}function rt(e){return L(e,"Cyclic")}var kt=u(()=>{O();S();J()});function ag(e){return d.Update(e,{"~unsafe":null},{})}function _i(e){return m.IsObjectNotArray(e)&&m.HasPropertyKey(e,"~unsafe")&&m.IsNull(e["~unsafe"])}var Ni=u(()=>{O();S()});var $n={};Mt($n,{Match:()=>sM});function sM(e,t){return t[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}var ug=u(()=>{});var no=u(()=>{ug()});function ss(...e){let[t,n]=$n.Match(e,{2:(r,o)=>[r,o,o],1:r=>[r,Ye(),Ye()]});return d.Create({"~kind":"Infer"},{type:"infer",name:t,extends:n},{})}function Ce(e){return L(e,"Infer")}var Vt=u(()=>{no();S();J();nt()});function Tr(e,t,n,r={}){return d.Create({"~kind":"Dependent"},{if:e,then:t,else:n},r)}function Pe(e){return L(e,"Dependent")}function mg(e){return d.Discard(e,["~kind","if","then","else"])}var Ot=u(()=>{S();J()});function cg(e){return m.IsObjectNotArray(e)}function pg(e){return m.Keys(e).filter(n=>isNaN(n)).reduce((n,r)=>[...n,e[r]],[])}var qi=u(()=>{O()});function lg(e){return m.IsString(e)||m.IsNumber(e)}function dg(e,t){let n=cg(e)?pg(e):e;return d.Create({"~kind":"Enum"},{enum:n},t)}function ot(e){return L(e,"Enum")}var mn=u(()=>{O();S();J();qi();qi()});function Tt(e,t={}){return d.Create({"~kind":"Intersect"},{allOf:e},t)}function oe(e){return L(e,"Intersect")}function fg(e){return d.Discard(e,["~kind","allOf"])}var Ne=u(()=>{S();J()});var gg=u(()=>{wr();O()});var hg=u(()=>{gg()});var xg=u(()=>{hg()});function qe(){throw new Error("Unreachable")}var yc=u(()=>{});var kn=u(()=>{yc()});var yg,EU,SU,PU,RU,bg,AU,MU,OU,wg=u(()=>{kn();O();(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(yg||(yg={}));EU=BigInt("14695981039346656037"),[SU,PU]=[BigInt("1099511628211"),BigInt("18446744073709551616")],RU=Array.from({length:256}).map((e,t)=>BigInt(t)),bg=new Float64Array(1),AU=new DataView(bg.buffer),MU=new Uint8Array(bg.buffer),OU=new TextEncoder});var Ig=u(()=>{wg()});var bc=u(()=>{});var $g=u(()=>{bc()});var kg=u(()=>{});var Tg=u(()=>{});var vg=u(()=>{});var Eg=u(()=>{});var Sg=u(()=>{});var Pg=u(()=>{});var Rg=u(()=>{});var Ag=u(()=>{});var Mg=u(()=>{});var Og=u(()=>{});var Cg=u(()=>{});var wc=u(()=>{});var Lg=u(()=>{});var Fg=u(()=>{});var jg=u(()=>{});var Dg=u(()=>{});var _g=u(()=>{});var Ng=u(()=>{});var qg=u(()=>{});var Ug=u(()=>{});var Kg=u(()=>{});var Gg=u(()=>{});var Wg=u(()=>{});var Bg=u(()=>{});var zg=u(()=>{});var Hg=u(()=>{});var Vg=u(()=>{});var Jg=u(()=>{});var Yg=u(()=>{});var Xg=u(()=>{});var Zg=u(()=>{});var Qg=u(()=>{});var eh=u(()=>{});var th=u(()=>{});var nh=u(()=>{});var rh=u(()=>{});var oh=u(()=>{});var sh=u(()=>{$g();kg();Tg();vg();Eg();Sg();bc();Pg();Rg();Ag();Mg();Og();Cg();wc();wc();Lg();Fg();jg();Dg();_g();Ng();qg();Ug();Kg();Gg();Wg();Bg();zg();Hg();Vg();Jg();Yg();Xg();Zg();Qg();eh();th();nh();rh();oh()});var ih=u(()=>{sh()});var is=u(()=>{no();xg();Ig();ih();S();wr()});var uh=u(()=>{is();is();is()});function Ki(e){return new us(e)}function mh(e,t){return Ki(e).Decode(t).Encode(()=>{throw Error("Encode not implemented")})}function ch(e,t){return Ki(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(t)}function Ui(e){return _e(e)&&m.HasPropertyKey(e,"~codec")&&m.IsObject(e["~codec"])&&m.HasPropertyKey(e["~codec"],"encode")&&m.HasPropertyKey(e["~codec"],"decode")}var as,us,Ic=u(()=>{uh();O();J();as=class{constructor(t,n){this.type=t,this.decode=n}Encode(t){let n=this.type,r=Ui(n)?i=>this.decode(n["~codec"].decode(i)):this.decode,o=Ui(n)?i=>n["~codec"].encode(t(i)):t,s={decode:r,encode:o};return d.Update(this.type,{"~codec":s},{})}},us=class{constructor(t){this.type=t}Decode(t){return new as(this.type,t)}}});function ph(e){return ro(e)}function vr(e){return _e(e)&&m.HasPropertyKey(e,"~immutable")}var ms=u(()=>{O();J();cs()});function Tn(e,t={}){return j("AddReadonly",[e],t)}function Er(e,t={}){return ts(e,t)}var ps=u(()=>{ce();Ci()});function lh(e){return Er(e)}function Sr(e){return _e(e)&&m.HasPropertyKey(e,"~readonly")}var ls=u(()=>{O();J();ps()});function mM(e,t){let n=$c(e)?[...e["~refine"],t]:[t];return d.Update(e,{"~refine":n},{})}function dh(...e){let[t,n,r]=$n.Match(e,{3:(o,s,i)=>[o,s,i],2:(o,s)=>[o,s,()=>"Refine Error"]});return mM(t,{check:n,error:r})}function cM(e){return m.IsObjectNotArray(e)&&m.HasPropertyKey(e,"check")&&m.HasPropertyKey(e,"error")&&m.IsFunction(e.check)&&m.IsFunction(e.error)}function $c(e){return _e(e)&&m.HasPropertyKey(e,"~refine")&&m.IsArray(e["~refine"])&&m.Every(e["~refine"],0,t=>cM(t))}var kc=u(()=>{no();S();O();J()});function ds(e){return d.Create({"~kind":"BigInt"},{type:"bigint"},e)}function vn(e){return L(e,"BigInt")}var fh,Pr=u(()=>{S();J();fh="-?(?:0|[1-9][0-9]*)n"});function Gi(e){return d.Create({"~kind":"Boolean"},{type:"boolean"},e)}function Jt(e){return L(e,"Boolean")}var Qn=u(()=>{S();J()});function fs(e){return d.Create({"~kind":"Identifier"},{name:e})}function gh(e){return L(e,"Identifier")}var Tc=u(()=>{S();J()});function Rr(e){return d.Create({"~kind":"Integer"},{type:"integer"},e)}function ht(e){return L(e,"Integer")}var Wi,En=u(()=>{S();J();Wi="-?(?:0|[1-9][0-9]*)"});function pM(e){return m.IsBigInt(e)?"bigint":m.IsBoolean(e)?"boolean":m.IsNumber(e)?"number":m.IsString(e)?"string":(()=>{throw new vc(e)})()}function se(e,t){return d.Create({"~kind":"Literal"},{type:pM(e),const:e},t)}function Bi(e){return m.IsBigInt(e)||m.IsBoolean(e)||m.IsNumber(e)||m.IsString(e)}function hh(e){return le(e)&&m.IsNumber(e.const)}function xh(e){return le(e)&&m.IsString(e.const)}function le(e){return L(e,"Literal")}var vc,Le=u(()=>{S();O();J();vc=class extends Error{constructor(t){super("Invalid Literal value"),Object.defineProperty(this,"cause",{value:{value:t},writable:!1,configurable:!1,enumerable:!1})}}});function oo(e){return d.Create({"~kind":"Null"},{type:"null"},e)}function so(e){return L(e,"Null")}var io=u(()=>{S();J()});function Ct(e){return d.Create({"~kind":"Number"},{type:"number"},e)}function Fe(e){return L(e,"Number")}var zi,xt=u(()=>{S();J();zi="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?"});function ao(e){return d.Create({"~kind":"Symbol"},{type:"symbol"},e)}function er(e){return L(e,"Symbol")}var Ar=u(()=>{S();J()});function Mr(...e){let[t,n,r]=$n.Match(e,{3:(o,s,i)=>[o,s,i],2:(o,s)=>[o,s,s],1:o=>[o,Ye(),Ye()]});return d.Create({"~kind":"Parameter"},{name:t,extends:n,equals:r},{})}function yh(e){return L(e,"Parameter")}var Ec=u(()=>{no();S();J();nt()});function Yt(e){return d.Create({"~kind":"String"},{type:"string"},e)}function yt(e){return L(e,"String")}var Hi,Xt=u(()=>{S();J();Hi=".*"});function X(e,t={}){return d.Create({"~kind":"Union"},{anyOf:e},t)}function F(e){return L(e,"Union")}function bh(e){return d.Discard(e,["~kind","anyOf"])}var Q=u(()=>{S();J()});function gs(e){let t=wh(e);return m.IsEqual(t.length,2)?t[0]:[]}var hs=u(()=>{O();Vi()});function lM(e){return!0}function Ih(e){return m.ShiftLeft(e,(t,n)=>dM(t)?Ih(n):!1,()=>!0)}function $h(e){return m.IsEqual(e.length,0)?!1:Ih(e)}function dM(e){return F(e)?$h(e.anyOf):le(e)?lM(e.const):!1}function Ji(e){return $h(e)}var Yi=u(()=>{O();Le();Q()});function Xi(e){return d.Create({"~kind":"TemplateLiteral"},{type:"string",pattern:e},{})}var Zi=u(()=>{S()});function kh(e,t,n=[]){return m.ShiftLeft(e,(r,o)=>kh(o,t,[...n,`${r}${t}`]),()=>n)}function fM(e,t){return m.IsEqual(e.length,0)?[`${t}`]:kh(e,t)}function Th(e,t,n=[]){return m.ShiftLeft(t,(r,o)=>Th(e,o,[...n,...vh(e,r)]),()=>n)}function vh(e,t){return F(t)?Th(e,t.anyOf):le(t)?fM(e,t.const):qe()}function Eh(e,t){return m.ShiftLeft(t,(n,r)=>Eh(vh(e,n),r),()=>e)}function gM(e){return e.map(t=>se(t))}function hM(e){let t=Eh([],e),n=gM(t);return X(n)}function xM(e){return m.IsEqual(e.length,0)?qe():m.IsEqual(e.length,1)&&le(e[0])?e[0]:hM(e)}function Sc(e){let t=gs(e);return m.IsEqual(t.length,0)?Yt():Ji(t)?xM(t):Xi(e)}function Sh(e){let t=Sc(e);return Re(t)?Yt():t}var Qi=u(()=>{O();kn();Le();Xt();vt();Q();hs();Yi();Zi()});function Et(e,t){let n="object",r={[e]:t};return d.Create({"~kind":"Record"},{type:n,patternProperties:r})}var tr=u(()=>{S()});function Ph(e){return Et(cn,e)}var Rh=u(()=>{Xe();tr()});function Ah(e){return W({true:e,false:e})}var Mh=u(()=>{fe()});function je(e,t={}){let[n,r,o]=[e,e.length,!1];return d.Create({"~kind":"Tuple"},{type:"array",additionalItems:o,items:n,minItems:r},t)}function be(e){return L(e,"Tuple")}function Oh(e){return d.Discard(e,["~kind","type","items","minItems","additionalItems"])}var Ue=u(()=>{S();J()});function yM(e){return d.Discard(e,["~readonly"])}function Pc(e,t){return d.Update(yM(e),{},t)}function Ch(e,t,n,r){let o=T(e,t,n);return Pc(o,r)}var Rc=u(()=>{S();q()});function Lh(e,t={}){return j("RemoveReadonly",[e],t)}function Fh(e,t={}){return Pc(e,t)}var Ac=u(()=>{ce();Rc()});function bM(e){return d.Discard(e,["~optional"])}function Mc(e,t){return d.Update(bM(e),{},t)}function jh(e,t,n,r){let o=T(e,t,n);return Mc(o,r)}var Oc=u(()=>{S();q()});function Dh(e,t={}){return j("RemoveOptional",[e],t)}function ea(e,t={}){return Mc(e,t)}var ta=u(()=>{ce();Oc()});function Cc(e){return e.reduceRight((n,r,o)=>({[o]:r,...n}),{})}function _h(e){let t=Cc(e.items);return W(t)}var Lc=u(()=>{fe()});function Fc(e){return pe(e)||be(e)}function wM(e,t){return Sr(e)?!!Sr(t):!1}function IM(e,t){return ut(e)?!!ut(t):!1}function $M(e,t){let n=wM(e,t),r=IM(e,t),o=Te([e,t]),s=Fh(ea(o));return n&&r?Er($r(s)):n&&!r?Er(s):!n&&r?$r(s):s}function kM(e,t,n){return n in e?n in t?$M(e[n],t[n]):e[n]:n in t?t[n]:ge()}function TM(e,t){return[...new Set([...m.Keys(e),...m.Keys(t)])].reduce((o,s)=>({...o,[s]:kM(e,t,s)}),{})}function Nh(e){return pe(e)?e.properties:be(e)?Cc(e.items):{}}function qh(e,t){let n=Nh(e),r=Nh(t),o=TM(n,r);return W(o)}var jc=u(()=>{O();ls();Zn();fe();Je();Ue();ps();os();Ac();ta();Lc();Y()});function vM(e,t){let n=bs(e,t);return m.IsEqual(n,ys)?e:m.IsEqual(n,na)||m.IsEqual(n,xs)?t:ge()}function EM(e,t){let n=Fc(e),r=Fc(t);return n&&r?qh(e,t):n&&!r?e:!n&&r?t:vM(e,t)}function Uh(e,t){return un(e)||Ee(e)?e:Oe(e)||un(t)||Ee(t)?t:Oe(t)?e:EM(e,t)}var Dc=u(()=>{O();$t();Je();nt();ws();jc()});function SM(e,t){return F(e)||F(t)}function PM(e,t){let n=Zt(e),r=Zt(t);return SM(n,r)?Te([n,r]):Uh(n,r)}function Kh(e,t,n=[]){return m.ShiftLeft(t,(r,o)=>Kh(e,o,[...n,PM(r,e)]),()=>m.IsEqual(n.length,0)?[e]:n)}function Gh(e,t,n=[]){return m.ShiftLeft(e,(r,o)=>Gh(o,t,[...n,...Is([r],t)]),()=>n)}function Is(e,t=[]){return m.ShiftLeft(e,(n,r)=>F(n)?Is(r,Gh(n.anyOf,t)):Is(r,Kh(n,t)),()=>t)}var _c=u(()=>{O();Q();Dc();Y();Y()});function RM(e,t){let n=st({},e,t);return B.IsExtendsTrueLike(n)?[]:[e]}function Wh(e,t,n=[]){return m.ShiftLeft(e,(r,o)=>Wh(o,t,[...n,...RM(r,t)]),()=>n)}function ra(e,t){let n=Zt(e),r=F(n)?n.anyOf:[n],o=Wh(r,t);return St(o)}var Nc=u(()=>{O();Q();Sn();Y();Y()});function pn(e,t,n){let r=Te([e,t]),o=ra(n,e);return St([r,o])}function bt(e,t=[]){return m.ShiftLeft(e,(n,r)=>bt(r,[...t,se(n)]),()=>St(t))}function Te(e){let t=Is(e),n=qc(t);return St(n)}function mt(e){let t=Sh(e);return Zt(t)}function St(e){let t=qc(e);return nr(t)}function Zt(e){return Pe(e)?pn(e.if,e.then,e.else):ot(e)?bt(e.enum):oe(e)?Te(e.allOf):Re(e)?mt(e.pattern):F(e)?St(e.anyOf):e}function nr(e){return m.IsEqual(e.length,1)?e[0]:m.IsEqual(e.length,0)?ge():X(e)}var Y=u(()=>{O();Ot();mn();Ne();Le();Je();vt();Q();_c();Uc();Nc();Qi()});function Bh(e,t){let n=bt(e);return rr(n,t)}var zh=u(()=>{$s();Y()});function Hh(e,t){return Et(or,t)}var Vh=u(()=>{Xe();tr()});function Jh(e,t){let n=Te(e);return rr(n,t)}var Yh=u(()=>{Y();$s()});function Xh(e,t){return m.IsString(e)||m.IsNumber(e)?W({[e]:t}):m.IsEqual(e,!1)?W({false:t}):m.IsEqual(e,!0)?W({true:t}):W({})}var Zh=u(()=>{O();fe()});function Qh(e,t){return Et(uo,t)}var ex=u(()=>{Xe();tr()});function tx(e,t){return m.HasPropertyKey(e,"pattern")&&(m.IsString(e.pattern)||e.pattern instanceof RegExp)?Et(e.pattern.toString(),t):Et(cn,t)}var nx=u(()=>{O();Xe();tr()});function rx(e,t){let n=gs(e);return Ji(n)?rr(mt(e),t):Et(e,t)}var ox=u(()=>{$s();hs();Yi();Y();tr()});function AM(e){return F(e)?mo(e.anyOf):[e]}function mo(e,t=[]){return m.ShiftLeft(e,(n,r)=>mo(r,[...t,...AM(n)]),()=>t)}var oa=u(()=>{O();Q()});function MM(e){return e.some(t=>yt(t)||Fe(t)||ht(t))}function OM(e,t){return m.IsEqual(MM(e),!0)?Et(cn,t):void 0}function CM(e,t){return e.reduce((n,r)=>le(r)&&(m.IsString(r.const)||m.IsNumber(r.const))?{...n,[r.const]:t}:n,{})}function LM(e,t){let n=CM(e,t);return W(n)}function sx(e,t){let n=mo(e),r=OM(n,t);return _e(r)?r:LM(n,t)}var ix=u(()=>{O();J();Le();xt();En();fe();Xt();Xe();oa();tr()});function rr(e,t){return Ee(e)?Ph(t):Jt(e)?Ah(t):ot(e)?Bh(e.enum,t):ht(e)?Hh(e,t):oe(e)?Jh(e.allOf,t):le(e)?Xh(e.const,t):Fe(e)?Qh(e,t):F(e)?sx(e.anyOf,t):yt(e)?tx(e,t):Re(e)?rx(e.pattern,t):W({})}var $s=u(()=>{$t();Qn();mn();Ne();En();Le();xt();fe();Xt();vt();Q();Rh();Mh();zh();Vh();Yh();Zh();ex();nx();ox();ix()});function Kc(e,t,n){return V([e])?d.Update(rr(e,t),{},n):ia(e,t,n)}function ax(e,t,n,r,o){let s=T(e,t,n),i=T(e,t,r);return Kc(s,i,o)}var sa=u(()=>{S();Xe();$s();q()});function ia(e,t,n={}){return j("Record",[e,t],n)}function aa(e,t,n={}){return Kc(e,t,n)}function ux(e,t){return Et(e,t)}function ua(e){return m.IsEqual(e,cn)?Yt():m.IsEqual(e,or)?Rr():m.IsEqual(e,uo)?Ct():Sc(e)}function Qt(e){return m.Keys(e.patternProperties)[0]}function co(e){let t=Qt(e);return ua(t)}function wt(e){return e.patternProperties[Qt(e)]}function it(e){return L(e,"Record")}var or,uo,cn,Xe=u(()=>{S();O();J();En();xt();Xt();ce();Qi();tr();sa();or=`^${Wi}$`,uo=`^${zi}$`,cn=`^${Hi}$`});function Or(e){return d.Create({"~kind":"Rest"},{type:"rest",items:e},{})}function sr(e){return L(e,"Rest")}var po=u(()=>{S();J()});var mx=u(()=>{});function ma(e){return d.Create({"~kind":"This"},{$ref:"#"},e)}function ca(e){return L(e,"This")}var pa=u(()=>{S();J()});function lo(e){return d.Create({"~kind":"Undefined"},{type:"undefined"},e)}function fo(e){return L(e,"Undefined")}var go=u(()=>{S();J()});function la(e){return d.Create({"~kind":"Void"},{type:"void"},e)}function Pn(e){return L(e,"Void")}var Cr=u(()=>{S();J()});var da=u(()=>{Ic();ms();Zn();ls();kc();$t();gt();Pr();Qn();ho();Bt();kt();ce();mn();zt();rs();Tc();Ot();Vt();En();Ne();Le();Je();io();xt();nt();Ar();fe();Ec();kr();Xe();Ht();po();J();mx();Xt();Ar();vt();pa();Ue();go();Q();nt();Ni();Cr()});function jM(e,t){return m.IsEqual(e,"Array")?qt(t[0]):m.IsEqual(e,"Capitalize")?ga(t[0]):m.IsEqual(e,"ConstructorParameters")?wa(t[0]):m.IsEqual(e,"Evaluate")?pb(t[0]):m.IsEqual(e,"Exclude")?Ia(t[0],t[1]):m.IsEqual(e,"Extract")?$a(t[0],t[1]):m.IsEqual(e,"Index")?Es(t[0],t[1]):m.IsEqual(e,"InstanceType")?ka(t[0]):m.IsEqual(e,"Lowercase")?ha(t[0]):m.IsEqual(e,"NonNullable")?Ta(t[0]):m.IsEqual(e,"Omit")?va(t[0],t[1]):m.IsEqual(e,"Parameters")?Ea(t[0]):m.IsEqual(e,"Partial")?Sa(t[0]):m.IsEqual(e,"Pick")?Pa(t[0],t[1]):m.IsEqual(e,"Readonly")?Ra(t[0]):m.IsEqual(e,"KeyOf")?Ss(t[0]):m.IsEqual(e,"Record")?ia(t[0],t[1]):m.IsEqual(e,"Required")?Aa(t[0]):m.IsEqual(e,"ReturnType")?Ma(t[0]):m.IsEqual(e,"Uncapitalize")?xa(t[0]):m.IsEqual(e,"Uppercase")?ya(t[0]):vs(qn(e),t)}function Lr(){throw Error("Unreachable")}function fx(e,t=[]){return m.ShiftLeft(e,(n,r)=>fx(r,[...t,n[1]]),()=>t)}function Un(e){return m.IsEqual(e.length,3)?[e[0],...fx(e[1])]:[]}function gx(e){return Mr(e[0],e[2],e[4])}function hx(e){return Mr(e[0],e[2],e[2])}function xx(e){return Mr(e[0],Ye(),e[2])}function yx(e){return Mr(e,Ye(),Ye())}function bx(e){return Un(e)}function wx(e){return e[1]}function Ix(e){return Un(e)}function $x(e){return e[1]}function kx(e){return jM(e[0],e[1])}function Tx(e){return null}function vx(e){return Yt()}function Ex(e){return Ct()}function Sx(e){return Gi()}function Px(e){return lo()}function Rx(e){return oo()}function Ax(e){return Rr()}function Mx(e){return ds()}function Ox(e){return Ye()}function Cx(e){return to()}function Lx(e){return W({})}function Fx(e){return ge()}function jx(e){return ao()}function Dx(e){return la()}function _x(e){return ma()}function Nx(e){return se(BigInt(e))}function qx(e){return se(m.IsEqual(e,"true"))}function Ux(e){return se(parseFloat(e))}function Kx(e){return se(e)}function Gx(e){return e[1]}function Wx(e){return se(e)}function Bx(e){return m.IsEqual(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function zx(e){return e[1]}function Hx(e){return fa(e)}function Vx(e){return m.IsEqual(e.length,6)?Tr(e[1],e[3],e[5]):Tr(e[1],e[3],Ye())}function Jx(e){return e.length>0}function Yx(e){return e.reduce((t,n)=>m.IsEqual(n.length,3)?[...t,[n[1]]]:[...t,[]],[])}function Xx(e){return m.IsEqual(e.length,6)?[e[1],e[3],e[5]]:[]}function Zx(e){return m.IsArray(e)&&m.IsEqual(e.length,3)?e[1]:e}function Qx(e){return m.IsEqual(e.length,2)?e[1]:[]}function cx(e,t){return t.reduce((n,r)=>{let o=r;return m.IsEqual(o.length,1)?Es(n,o[0]):m.IsEqual(o.length,0)?qt(n):Lr()},e)}function px(e,t){return m.IsEqual(t.length,3)?ba(e,t[0],t[1],t[2]):e}function DM(e,t){return m.IsArray(t)&&m.IsEqual(t.length,0)?e:Oa(e,t)}function ey(e){let[t,n,r,o,s]=e;return DM(px(t?Ss(cx(n,r)):cx(n,r),o),s)}function Gc(e,t){return m.IsEqual(t.length,3)?(()=>{let[n,r,o]=t,s=Gc(r,o);if(m.IsEqual(n,"&"))return oe(s)?Tt([e,...s.allOf]):Tt([e,s]);if(m.IsEqual(n,"|"))return F(s)?X([e,...s.anyOf]):X([e,s]);Lr()})():e}function ty(e){let[t,n]=e;return Gc(t,n)}function ny(e){let[t,n]=e;return Gc(t,n)}function ry(e){return cb(e[1])}function oy(e){return e[1]}function sy(e){return Xn(e[0],e[2])}function iy(e){return m.IsEqual(e.length,4)?ss(e[1],e[3]):m.IsEqual(e.length,2)?ss(e[1],Ye()):Lr()}function ay(e){return`${e}`}function uy(e){return ht(e[3])?or:Fe(e[3])?uo:er(e[3])?cn:yt(e[3])?cn:Lr()}function my(e){return e.length>0}function cy(e){return e.length>0}function py(e){let[t,n,r,o,s]=e;return{[n]:t&&r?Tn(wn(s)):t&&!r?Tn(s):!t&&r?wn(s):s}}function ly(e){return Un(e)}function dy(e){return e.reduce((t,n)=>m.HasPropertyKey(n,or)||m.HasPropertyKey(n,uo)||m.HasPropertyKey(n,cn)?[t[0],d.Assign(t[1],n)]:[d.Assign(t[0],n),t[1]],[{},{}])}function fy(e){return dy(e[1])}function gy(e){let[t,n]=e,r=m.IsEqual(m.Keys(n).length,0)?{}:{patternProperties:n};return W(t,r)}function hy(e){return m.IsEqual(e.length,5)?Tn(wn(e[4])):m.IsEqual(e.length,3)?e[2]:m.IsEqual(e.length,4)?m.IsEqual(e[2],"readonly")?Tn(e[3]):wn(e[3]):Lr()}function xy(e){if(!m.IsArray(e)||!m.IsEqual(e.length,3))return e;let[t,n,r]=e;return t&&r?Tn(wn(n)):t&&!r?Tn(n):!t&&r?wn(n):n}function yy(e){return m.IsEqual(e.length,2)?Or(e[1]):m.IsEqual(e.length,1)?e[0]:Lr()}function by(e){return Un(e)}function wy(e){return je(e[1])}function Iy(e){return Tn(wn(e[4]))}function $y(e){return Tn(e[3])}function ky(e){return wn(e[3])}function Ty(e){return e[2]}function vy(e){return m.IsEqual(e.length,2)?Or(e[1]):m.IsEqual(e.length,1)?e[0]:Lr()}function Ey(e){return Un(e)}function Sy(e){return bn(e[1],e[4])}function Py(e){return yn(e[2],e[5])}function lx(e,t){return m.IsEqual(e,"remove")?Lh(t):m.IsEqual(e,"add")?Tn(t):t}function Ry(e){return m.IsEqual(e.length,2)&&m.IsEqual(e[0],"-")?"remove":m.IsEqual(e.length,2)&&m.IsEqual(e[0],"+")||m.IsEqual(e.length,1)?"add":"none"}function dx(e,t){return m.IsEqual(e,"remove")?Dh(t):m.IsEqual(e,"add")?wn(t):t}function Ay(e){return m.IsEqual(e.length,2)&&m.IsEqual(e[0],"-")?"remove":m.IsEqual(e.length,2)&&m.IsEqual(e[0],"+")||m.IsEqual(e.length,1)?"add":"none"}function My(e){return m.IsEqual(e.length,2)?[e[1]]:[]}function Oy(e){return m.IsArray(e[6])&&m.IsEqual(e[6].length,1)?ks(fs(e[3]),e[5],e[6][0],lx(e[1],dx(e[8],e[10]))):ks(fs(e[3]),e[5],qn(e[3]),lx(e[1],dx(e[8],e[10])))}function Cy(e){return qn(e)}function Ly(e){return BigInt(e)}function Fy(e){return parseFloat(e)}function jy(e){return m.IsEqual(e,"true")}function Dy(e){return null}function _y(e){return{[e[0]]:e[2]}}function Ny(e){return Un(e)}function _M(e){return e.reduce((t,n)=>d.Assign(t,n),{})}function qy(e){return _M(e[1])}function Uy(e){return Un(e)}function Ky(e){return e[1]}function Gy(e){return ds()}function Wy(e){return Yt()}function By(e){return Ct()}function zy(e){return Rr()}function Hy(e){return ge()}function Vy(e){return se(e)}function Jy(e){return X(e[1])}function Yy(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function Xy(e){return[e[0],...e[1]]}function Zy(e){return e[1]}function Qy(e){return Un(e)}function eb(e){return m.IsEqual(e.length,2)?e[1]:[]}function tb(e){let t=e[2],n=e[3],[r,o]=e[4],s=m.IsEqual(m.Keys(o).length,0)?{}:{patternProperties:o};return{[e[1]]:Xn(t,Ts(n,r,s))}}function nb(e){let t=e[2],[n,r]=e[3],o=m.IsEqual(m.Keys(r).length,0)?{}:{patternProperties:r};return{[e[1]]:Ts(t,n,o)}}function rb(e){return{[e[1]]:Xn(e[2],e[4])}}function ob(e){return{[e[1]]:e[3]}}function sb(e){return null}function ib(e){return Un(e)}function ab(e){return e[1]}function ub(e){let[t,n]=[e[0],e[1]];return lb(d.Assign(t,dy(n)[0]))}var mb=u(()=>{S();O();da();xo()});var Kn=u(()=>{Qr()});function Ps(e){return ue(e.length,2)}function te(e,t,n){return Ps(e)?t(e[0],e[1]):n()}var Lt=u(()=>{Kn()});function UM(e,t){return ue(t.indexOf(e),0)?[e,t.slice(e.length)]:[]}function Se(e,t){for(let n=0;n<e.length;n++){let r=UM(e[n],t);if(Ps(r))return r}return[]}var Rn=u(()=>{Lt();Kn()});function Wc(e,t){return Array.from({length:t-e+1},(n,r)=>String.fromCharCode(e+r))}var db,Bc,zc,yo,fb,bo,ir,Ca,gb,La,ct=u(()=>{db=[...Wc(97,122),...Wc(65,90)],Bc="0",zc=Wc(49,57),yo=[Bc,...zc],fb=" ",bo=`
|
|
14
14
|
`,ir="_",Ca=".",gb="$",La="-"});function yb(e){let t=e.indexOf(GM);return ue(t,-1)?"":e.slice(t+2)}function bb(e){let t=e.indexOf(bo);return ue(t,-1)?"":e.slice(t)}function WM(e){return e.replace(/^[ \t\r\f\v]+/,"")}function Fa(e){let t=WM(e);return t.startsWith(xb)?Fa(yb(t.slice(2))):t.startsWith(hb)?Fa(bb(t.slice(2))):t}function Ze(e){let t=e.trimStart();return t.startsWith(xb)?Ze(yb(t.slice(2))):t.startsWith(hb)?Ze(bb(t.slice(2))):t}var hb,xb,GM,An=u(()=>{Kn();ct();hb="//",xb="/*",GM="*/"});function ja(e,t){return te(Se([e],t),(n,r)=>[n,r],()=>["",t])}var Hc=u(()=>{Lt();Rn()});function BM(e,t){return e.includes(t)}function wo(e,t,n,r=""){return te(Se(e,n),(o,s)=>BM(t,o)?wo(e,t,s,r):wo(e,t,s,`${r}${o}`),()=>[r,n])}var Vc=u(()=>{Lt();Rn()});function zM(e){return Se(zc,e)}function VM(e){return wo(HM,[ir],e)}function JM(e){return te(Se([Bc],e),(t,n)=>[t,n],()=>te(zM(e),(t,n)=>te(VM(n),(r,o)=>[`${t}${r}`,o],()=>[]),()=>[]))}function Da(e){return JM(Ze(e))}var HM,_a=u(()=>{Lt();An();Rn();Vc();ct();ct();ct();ct();HM=[...yo,ir]});function YM(e){return ja(La,e)}function XM(e){return te(YM(e),(t,n)=>te(Da(n),(r,o)=>[`${t}${r}`,o],()=>[]),()=>[])}function wb(e){return XM(Ze(e))}var Jc=u(()=>{Lt();An();Hc();ct();_a()});function ZM(e){return te(wb(e),(t,n)=>te(Se(["n"],n),(r,o)=>[`${t}`,o],()=>[]),()=>[])}function Yc(e){return ZM(e)}var Ib=u(()=>{Lt();Rn();Jc()});function Xc(e,t){return Se([e],t)}function h(e,t){return ue(e,"")?["",t]:e.startsWith(bo)?Xc(e,Fa(t)):e.startsWith(fb)?Xc(e,t):Xc(e,Ze(t))}var $b=u(()=>{Kn();An();An();Rn();ct();ct()});function QM(e){return Se(kb,e)}function Tb(e,t=""){return te(Se(eO,e),(n,r)=>Tb(r,`${t}${n}`),()=>[t,e])}function tO(e){return te(QM(e),(t,n)=>te(Tb(n),(r,o)=>[`${t}${r}`,o],()=>[]),()=>[])}function Ae(e){return tO(Ze(e))}var kb,eO,vb=u(()=>{Lt();An();Rn();ct();ct();ct();ct();kb=[...db,ir,gb];eO=[...kb,...yo]});function rO(e){return Ps(Se([Ca],e))}function Eb(e){return te(wo(nO,[ir],e),(t,n)=>ue(t,"")?[]:[t,n],()=>[])}function oO(e){return te(Se([Ca],e),(t,n)=>te(Eb(n),(r,o)=>[`0${t}${r}`,o],()=>[]),()=>[])}function sO(e){return te(Da(e),(t,n)=>te(Se([Ca],n),(r,o)=>te(Eb(o),(s,i)=>[`${t}${r}${s}`,i],()=>[`${t}`,o]),()=>[`${t}`,n]),()=>[])}function iO(e){return rO(e)?oO(e):sO(e)}function Sb(e){return iO(Ze(e))}var nO,Zc=u(()=>{Kn();Lt();An();Rn();Vc();ct();ct();_a();nO=[...yo,ir]});function aO(e){return ja(La,e)}function uO(e){return te(aO(e),(t,n)=>te(Sb(n),(r,o)=>[`${t}${r}`,o],()=>[]),()=>[])}function Na(e){return uO(Ze(e))}var Pb=u(()=>{Lt();An();Hc();ct();Zc()});var Rb=u(()=>{Kn()});function mO(e){return ue(e,"")?[]:[e.slice(0,1),e.slice(1)]}function Ab(e,t){return Mi(e,(n,r)=>t.startsWith(n)?!0:Ab(r,t),()=>!1)}function ar(e,t,n=""){return te(mO(t),(r,o)=>Ab(e,t)?[n,t]:ar(e,o,`${n}${r}`),()=>[])}var qa=u(()=>{Lt();Kn()});function cO(e,t,n){return te(Se([e],n),(r,o)=>te(ar([t],o),(s,i)=>te(Se([t],i),(c,p)=>[`${s}`,p],()=>[]),()=>[]),()=>[])}function pO(e,t,n){return te(Se([e],n),(r,o)=>te(ar([bo,t],o),(s,i)=>te(Se([t],i),(c,p)=>[`${s}`,p],()=>[]),()=>[]),()=>[])}function Mb(e,t,n,r){return n?cO(e,t,Ze(r)):pO(e,t,Ze(r))}var Qc=u(()=>{Lt();An();ct();Rn();qa()});function lO(e,t){return Se(e,t)}function dO(e,t){return Mb(e,e,!1,t)}function fO(e,t){return te(lO(e,t),(n,r)=>dO(n,`${n}${r}`),()=>[])}function Ua(e,t){return fO(e,Ze(t))}var Ob=u(()=>{Lt();Rn();An();Qc()});function Cb(e,t){return te(ar(e,t),(n,r)=>ue(n,"")?[]:[n,r],()=>[])}var Lb=u(()=>{Kn();Lt();qa()});var Fb=u(()=>{Ib();$b();vb();Jc();Pb();Rb();Qc();Ob();_a();Zc();Lb();qa()});var a,hO,xO,yO,bO,_b,Nb,wO,np,qb,IO,$O,kO,Ub,Kb,Gb,TO,vO,EO,Wb,SO,PO,RO,AO,MO,Bb,OO,CO,LO,ep,zb,rp,FO,jO,DO,_O,NO,qO,UO,Hb,KO,GO,WO,BO,Vb,Jb,Yb,Xb,Ka,zO,HO,VO,JO,me,YO,XO,ZO,QO,Zb,Qb,ew,tw,Ga,nw,e0,op,t0,n0,jb,rw,ow,r0,o0,s0,i0,a0,u0,Db,sw,iw,aw,m0,c0,p0,l0,d0,f0,g0,h0,x0,y0,b0,w0,I0,uw,mw,$0,cw,pw,k0,T0,sp,v0,E0,S0,P0,R0,A0,M0,O0,lw,tp,ip,wh,dw,C0,fw,L0,F0,j0,D0,_0,gw,hw,N0,ap,q0,xw,Vi=u(()=>{mb();Fb();a=(e,t,n=()=>[])=>e.length===2?t(e):n(),hO=e=>a(a(Ae(e),([t,n])=>a(h("extends",n),([r,o])=>a(me(o),([s,i])=>a(h("=",i),([c,p])=>a(me(p),([f,w])=>[[t,r,s,c,f],w]))))),([t,n])=>[gx(t),n]),xO=e=>a(a(Ae(e),([t,n])=>a(h("extends",n),([r,o])=>a(me(o),([s,i])=>[[t,r,s],i]))),([t,n])=>[hx(t),n]),yO=e=>a(a(Ae(e),([t,n])=>a(h("=",n),([r,o])=>a(me(o),([s,i])=>[[t,r,s],i]))),([t,n])=>[xx(t),n]),bO=e=>a(Ae(e),([t,n])=>[yx(t),n]),_b=e=>a(a(hO(e),([t,n])=>[t,n],()=>a(xO(e),([t,n])=>[t,n],()=>a(yO(e),([t,n])=>[t,n],()=>a(bO(e),([t,n])=>[t,n],()=>[])))),([t,n])=>[t,n]),Nb=(e,t=[])=>a(a(h(",",e),([n,r])=>a(_b(r),([o,s])=>[[n,o],s])),([n,r])=>Nb(r,[...t,n]),()=>[t,e]),wO=e=>a(a(a(_b(e),([t,n])=>a(Nb(n),([r,o])=>a(a(h(",",o),([s,i])=>[[s],i],()=>[[],o]),([s,i])=>[[t,r,s],i]))),([t,n])=>[t,n],()=>a([[],e],([t,n])=>[t,n],()=>[])),([t,n])=>[bx(t),n]),np=e=>a(a(h("<",e),([t,n])=>a(wO(n),([r,o])=>a(h(">",o),([s,i])=>[[t,r,s],i]))),([t,n])=>[wx(t),n]),qb=(e,t=[])=>a(a(h(",",e),([n,r])=>a(me(r),([o,s])=>[[n,o],s])),([n,r])=>qb(r,[...t,n]),()=>[t,e]),IO=e=>a(a(a(me(e),([t,n])=>a(qb(n),([r,o])=>a(a(h(",",o),([s,i])=>[[s],i],()=>[[],o]),([s,i])=>[[t,r,s],i]))),([t,n])=>[t,n],()=>a([[],e],([t,n])=>[t,n],()=>[])),([t,n])=>[Ix(t),n]),$O=e=>a(a(h("<",e),([t,n])=>a(IO(n),([r,o])=>a(h(">",o),([s,i])=>[[t,r,s],i]))),([t,n])=>[$x(t),n]),kO=e=>a(a(Ae(e),([t,n])=>a($O(n),([r,o])=>[[t,r],o])),([t,n])=>[kx(t),n]),Ub=e=>a(a(a(h(";",e),([t,n])=>[[t],n]),([t,n])=>[t,n],()=>a([[],e],([t,n])=>[t,n],()=>[])),([t,n])=>[Tx(t),n]),Kb=e=>a(h("string",e),([t,n])=>[vx(t),n]),Gb=e=>a(h("number",e),([t,n])=>[Ex(t),n]),TO=e=>a(h("boolean",e),([t,n])=>[Sx(t),n]),vO=e=>a(h("undefined",e),([t,n])=>[Px(t),n]),EO=e=>a(h("null",e),([t,n])=>[Rx(t),n]),Wb=e=>a(h("integer",e),([t,n])=>[Ax(t),n]),SO=e=>a(h("bigint",e),([t,n])=>[Mx(t),n]),PO=e=>a(h("unknown",e),([t,n])=>[Ox(t),n]),RO=e=>a(h("any",e),([t,n])=>[Cx(t),n]),AO=e=>a(h("object",e),([t,n])=>[Lx(t),n]),MO=e=>a(h("never",e),([t,n])=>[Fx(t),n]),Bb=e=>a(h("symbol",e),([t,n])=>[jx(t),n]),OO=e=>a(h("void",e),([t,n])=>[Dx(t),n]),CO=e=>a(h("this",e),([t,n])=>[_x(t),n]),LO=e=>a(a(h("${",e),([t,n])=>a(me(n),([r,o])=>a(h("}",o),([s,i])=>[[t,r,s],i]))),([t,n])=>[Gx(t),n]),ep=e=>a(ar(["${","`"],e),([t,n])=>[Wx(t),n]),zb=e=>a(a(a(ep(e),([t,n])=>a(LO(n),([r,o])=>a(zb(o),([s,i])=>[[t,r,s],i]))),([t,n])=>[t,n],()=>a(a(ep(e),([t,n])=>[[t],n]),([t,n])=>[t,n],()=>a(a(ep(e),([t,n])=>[[t],n]),([t,n])=>[t,n],()=>[]))),([t,n])=>[Bx(t),n]),rp=e=>a(a(h("`",e),([t,n])=>a(zb(n),([r,o])=>a(h("`",o),([s,i])=>[[t,r,s],i]))),([t,n])=>[zx(t),n]),FO=e=>a(rp(e),([t,n])=>[Hx(t),n]),jO=e=>a(a(a(h("if",e),([t,n])=>a(me(n),([r,o])=>a(h("then",o),([s,i])=>a(me(i),([c,p])=>a(h("else",p),([f,w])=>a(me(w),([I,P])=>[[t,r,s,c,f,I],P])))))),([t,n])=>[t,n],()=>a(a(h("if",e),([t,n])=>a(me(n),([r,o])=>a(h("then",o),([s,i])=>a(me(i),([c,p])=>[[t,r,s,c],p])))),([t,n])=>[t,n],()=>[])),([t,n])=>[Vx(t),n]),DO=e=>a(Yc(e),([t,n])=>[Nx(t),n]),_O=e=>a(a(h("true",e),([t,n])=>[t,n],()=>a(h("false",e),([t,n])=>[t,n],()=>[])),([t,n])=>[qx(t),n]),NO=e=>a(Na(e),([t,n])=>[Ux(t),n]),qO=e=>a(Ua(["'",'"'],e),([t,n])=>[Kx(t),n]),UO=e=>a(a(a(h("keyof",e),([t,n])=>[[t],n]),([t,n])=>[t,n],()=>a([[],e],([t,n])=>[t,n],()=>[])),([t,n])=>[Jx(t),n]),Hb=(e,t=[])=>a(a(a(h("[",e),([n,r])=>a(me(r),([o,s])=>a(h("]",s),([i,c])=>[[n,o,i],c]))),([n,r])=>[n,r],()=>a(a(h("[",e),([n,r])=>a(h("]",r),([o,s])=>[[n,o],s])),([n,r])=>[n,r],()=>[])),([n,r])=>Hb(r,[...t,n]),()=>[t,e]),KO=e=>a(Hb(e),([t,n])=>[Yx(t),n]),GO=e=>a(a(a(h("extends",e),([t,n])=>a(me(n),([r,o])=>a(h("?",o),([s,i])=>a(me(i),([c,p])=>a(h(":",p),([f,w])=>a(me(w),([I,P])=>[[t,r,s,c,f,I],P])))))),([t,n])=>[t,n],()=>a([[],e],([t,n])=>[t,n],()=>[])),([t,n])=>[Xx(t),n]),WO=e=>a(a(a(h("(",e),([t,n])=>a(me(n),([r,o])=>a(h(")",o),([s,i])=>[[t,r,s],i]))),([t,n])=>[t,n],()=>a(Kb(e),([t,n])=>[t,n],()=>a(Gb(e),([t,n])=>[t,n],()=>a(TO(e),([t,n])=>[t,n],()=>a(vO(e),([t,n])=>[t,n],()=>a(EO(e),([t,n])=>[t,n],()=>a(Wb(e),([t,n])=>[t,n],()=>a(SO(e),([t,n])=>[t,n],()=>a(PO(e),([t,n])=>[t,n],()=>a(RO(e),([t,n])=>[t,n],()=>a(AO(e),([t,n])=>[t,n],()=>a(MO(e),([t,n])=>[t,n],()=>a(Bb(e),([t,n])=>[t,n],()=>a(OO(e),([t,n])=>[t,n],()=>a(CO(e),([t,n])=>[t,n],()=>a(DO(e),([t,n])=>[t,n],()=>a(_O(e),([t,n])=>[t,n],()=>a(NO(e),([t,n])=>[t,n],()=>a(qO(e),([t,n])=>[t,n],()=>a(FO(e),([t,n])=>[t,n],()=>a(jO(e),([t,n])=>[t,n],()=>a(t0(e),([t,n])=>[t,n],()=>a(o0(e),([t,n])=>[t,n],()=>a(c0(e),([t,n])=>[t,n],()=>a(m0(e),([t,n])=>[t,n],()=>a(f0(e),([t,n])=>[t,n],()=>a(kO(e),([t,n])=>[t,n],()=>a(g0(e),([t,n])=>[t,n],()=>[])))))))))))))))))))))))))))),([t,n])=>[Zx(t),n]),BO=e=>a(a(a(h("with",e),([t,n])=>a(cw(n),([r,o])=>[[t,r],o])),([t,n])=>[t,n],()=>a([[],e],([t,n])=>[t,n],()=>[])),([t,n])=>[Qx(t),n]),Vb=e=>a(a(UO(e),([t,n])=>a(WO(n),([r,o])=>a(KO(o),([s,i])=>a(GO(i),([c,p])=>a(BO(p),([f,w])=>[[t,r,s,c,f],w]))))),([t,n])=>[ey(t),n]),Jb=e=>a(a(a(h("&",e),([t,n])=>a(Vb(n),([r,o])=>a(Jb(o),([s,i])=>[[t,r,s],i]))),([t,n])=>[t,n],()=>a([[],e],([t,n])=>[t,n],()=>[])),([t,n])=>[t,n]),Yb=e=>a(a(Vb(e),([t,n])=>a(Jb(n),([r,o])=>[[t,r],o])),([t,n])=>[ty(t),n]),Xb=e=>a(a(a(h("|",e),([t,n])=>a(Yb(n),([r,o])=>a(Xb(o),([s,i])=>[[t,r,s],i]))),([t,n])=>[t,n],()=>a([[],e],([t,n])=>[t,n],()=>[])),([t,n])=>[t,n]),Ka=e=>a(a(Yb(e),([t,n])=>a(Xb(n),([r,o])=>[[t,r],o])),([t,n])=>[ny(t),n]),zO=e=>a(a(h("readonly",e),([t,n])=>a(Ka(n),([r,o])=>[[t,r],o])),([t,n])=>[ry(t),n]),HO=e=>a(a(h("|",e),([t,n])=>a(Ka(n),([r,o])=>[[t,r],o])),([t,n])=>[oy(t),n]),VO=e=>a(a(np(e),([t,n])=>a(h("=",n),([r,o])=>a(me(o),([s,i])=>[[t,r,s],i]))),([t,n])=>[sy(t),n]),JO=e=>a(a(a(h("infer",e),([t,n])=>a(Ae(n),([r,o])=>a(h("extends",o),([s,i])=>a(Ka(i),([c,p])=>[[t,r,s,c],p])))),([t,n])=>[t,n],()=>a(a(h("infer",e),([t,n])=>a(Ae(n),([r,o])=>[[t,r],o])),([t,n])=>[t,n],()=>[])),([t,n])=>[iy(t),n]),me=e=>a(a(JO(e),([t,n])=>[t,n],()=>a(HO(e),([t,n])=>[t,n],()=>a(zO(e),([t,n])=>[t,n],()=>a(Ka(e),([t,n])=>[t,n],()=>[])))),([t,n])=>[t,n]),YO=e=>a(Na(e),([t,n])=>[ay(t),n]),XO=e=>a(Ae(e),([t,n])=>[t,n]),ZO=e=>a(Ua(["'",'"'],e),([t,n])=>[t,n]),QO=e=>a(a(h("[",e),([t,n])=>a(Ae(n),([r,o])=>a(h(":",o),([s,i])=>a(a(Wb(i),([c,p])=>[c,p],()=>a(Gb(i),([c,p])=>[c,p],()=>a(Kb(i),([c,p])=>[c,p],()=>a(Bb(i),([c,p])=>[c,p],()=>[])))),([c,p])=>a(h("]",p),([f,w])=>[[t,r,s,c,f],w]))))),([t,n])=>[uy(t),n]),Zb=e=>a(a(YO(e),([t,n])=>[t,n],()=>a(XO(e),([t,n])=>[t,n],()=>a(ZO(e),([t,n])=>[t,n],()=>a(QO(e),([t,n])=>[t,n],()=>[])))),([t,n])=>[t,n]),Qb=e=>a(a(a(h("readonly",e),([t,n])=>[[t],n]),([t,n])=>[t,n],()=>a([[],e],([t,n])=>[t,n],()=>[])),([t,n])=>[my(t),n]),ew=e=>a(a(a(h("?",e),([t,n])=>[[t],n]),([t,n])=>[t,n],()=>a([[],e],([t,n])=>[t,n],()=>[])),([t,n])=>[cy(t),n]),tw=e=>a(a(Qb(e),([t,n])=>a(Zb(n),([r,o])=>a(ew(o),([s,i])=>a(h(":",i),([c,p])=>a(me(p),([f,w])=>[[t,r,s,c,f],w]))))),([t,n])=>[py(t),n]),Ga=e=>a(a(a(h(",",e),([t,n])=>a(h(`
|
|
15
15
|
`,n),([r,o])=>[[t,r],o])),([t,n])=>[t,n],()=>a(a(h(";",e),([t,n])=>a(h(`
|
|
16
16
|
`,n),([r,o])=>[[t,r],o])),([t,n])=>[t,n],()=>a(a(h(",",e),([t,n])=>[[t],n]),([t,n])=>[t,n],()=>a(a(h(";",e),([t,n])=>[[t],n]),([t,n])=>[t,n],()=>a(a(h(`
|
|
@@ -113,16 +113,16 @@ ${p.result??""}`).join(`
|
|
|
113
113
|
`).filter(c=>c.length>0).slice(0,hm);let r=nd(t),s=(typeof r.output=="string"?r.output:td(t).replace(/\n*Command exited with code \d+\s*$/,"")).trimEnd().split(`
|
|
114
114
|
`),i=s.slice(0,hm);return s.length>hm&&i.push(`\u2026 ${s.length-hm} more line(s)`),i}var OS,Zl,Ql,Xl,hm,rd=u(()=>{Zs();OS="\u25CF",Zl="\u2514",Ql="\u22EF",Xl=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];hm=400});import{Markdown as ID,wrapTextWithAnsi as $D}from"@earendil-works/pi-tui";function DS(e){return typeof e=="string"?e:e.map(t=>t.type==="text"?t.text:t.type==="thinking"?"":t.type==="image"?"[image]":(t.type==="toolCall","")).filter(Boolean).join("")}function kD(e){return e.content.filter(t=>t.type==="toolCall").map(t=>({name:t.name,arguments:t.arguments}))}function bm(e){let t=[];for(let n of e)if(n.role==="user"){let r=DS(n.content).trim();if(!r)continue;t.push({id:`u-${n.timestamp}`,kind:"user",title:"you",body:r})}else if(n.role==="assistant"){let r=DS(n.content).trim(),o=kD(n);r?t.push({id:`a-${n.timestamp}`,kind:n.stopReason==="error"?"error":"assistant",title:n.errorMessage?"failed":"fix",body:n.errorMessage?`${n.errorMessage}
|
|
115
115
|
|
|
116
|
-
${r}`:r}):n.errorMessage&&t.push({id:`e-${n.timestamp}`,kind:"error",title:"failed",body:n.errorMessage}),o.forEach((s,i)=>{t.push({id:`c-${n.timestamp}-${i}`,kind:"tool",title:"tool",body:jo(s.name,s.arguments)})})}else n.role==="toolResult"&&t.push({id:`r-${n.toolCallId}`,kind:"result",title:n.toolName,body:xm(n.toolName,{content:n.content},n.isError)});return t}function _S(e,t,n){return $D(e,Math.max(8,t)).map(r=>ne(r,n))}function TD(e){let t=e.body||" ",n=ni.get(e.id);if(n)return n.text!==t&&(n.component.setText(t),n.text=t),n.component;let r=new ID(t,0,0,KE);return ni.set(e.id,{text:t,component:r}),r}var ni,od,ym,NS=u(()=>{zl();Js();rd();ni=new Map;od=class{constructor(t){this.item=t}item;invalidate(){}shade(t){let n=Date.now()-(this.item.born??0);return Qs(_.dim,t,xS(n,Wl))}render(t){let n=this.item.body;if(this.item.kind==="user")return["",..._S(`> ${n}`,t,this.shade(_.user))];if(this.item.kind==="tool")return[ne(n,this.shade(_.tool))];if(this.item.kind==="result"){let o=n.startsWith("exit ")&&n!=="exit 0";if(this.item.panel)return["",...this.item.panel(t),...n?[ne(` ${Zl} ${n}`,o?_.bad:_.mute)]:[]];let s=[];this.item.call&&s.push(ne(this.item.call,this.shade(_.tool)));let i=` ${Zl} ${n}`;if(s.push(ne(i,o?_.bad:this.shade(_.mute))),this.item.expanded===!0&&(this.item.full?.length??0)>0){let w=ne(` ${this.item.full.length} line(s) \xB7 ctrl+e to collapse`,_.dim);s.push(ne(` ${Ql}`,_.dim));for(let I of this.item.full){let P=I.startsWith("+")?_.tool:I.startsWith("-")?_.bad:_.dim;s.push(ne(` ${I}`,P))}return s.push(w),s}let p=this.item.detail??[],f=Bl(Date.now()-(this.item.born??0),p.length);for(let w of p.slice(0,f)){let I=w.startsWith("+")?_.tool:w.startsWith("-")?_.bad:_.dim;s.push(ne(` ${w}`,this.shade(I)))}return(this.item.full?.length??0)>0&&s.push(ne(` ${Ql} ${this.item.full.length} line(s) \xB7 ctrl+e to expand`,_.dim)),s}if(this.item.kind==="error"||this.item.kind==="note"){let o=this.item.kind==="error"?_.bad:_.mute;return["",..._S(n,t,this.shade(o))]}return["",...TD(this.item).render(Math.max(8,t-2))]}},ym=class{items=[];status="";scrollOffset=0;scrollAnchor;settledOffset=0;viewportHeight=0;invalidate(){}entering(){let t=Date.now();return this.items.some(n=>{if(n.born===void 0)return!1;let r=t-n.born;return yS(r,Wl)?!0:(n.detail?.length??0)>Bl(r,n.detail?.length??0)})}render(t){if(ni.size>this.items.length){let o=new Set(this.items.map(s=>s.id));for(let s of ni.keys())o.has(s)||ni.delete(s)}let n=[];for(let o of this.items)o.born??=Date.now(),n.push(...new od(o).render(t));this.status&&n.push(ne(this.status,_.mute));let r=this.viewportHeight;if(r>0&&n.length>r){let o=n.length-r;this.scrollOffset!==this.settledOffset&&(this.scrollAnchor=void 0);let s=this.scrollAnchor,i;if(s!==void 0){let c=n.length-s;c>=0&&c<=o?i=c:i=Math.max(0,Math.min(this.scrollOffset,o))}else i=Math.max(0,Math.min(this.scrollOffset,o));return s===void 0&&(this.scrollOffset=i),this.settledOffset=this.scrollOffset,i===0?this.scrollAnchor=void 0:this.scrollAnchor===void 0&&(this.scrollAnchor=n.length-i),n.slice(o-i,o-i+r)}return n}}});function ft(e,t){return`${t}${e}${US}`}function ED(e){return e>=85?vD:e>=70?GS:KS}function WS(e,t,n,r){let o=ft(`[${e}]`,sd),s=ft(`${SD} ${t}`,Dn),i=ft(n,GS),c=r?` ${ft("git:(",qS)}${ft(r.replace(/^git:\(/,"").replace(/\)$/,""),sd)}${ft(")",qS)}`:"";return`${o}${ft(" \u2502 ",Dn)}${s}${ft(" \u2502 ",Dn)}${i}${c}`}function BS(e,t,n){if(!t)return e;let r=n===void 0?t:`${t} ${ft(BE(n),Dn)}`;return`${ft(r,sd)} ${ft("\u2502",Dn)} ${e}`}function zS(e,t){let n=Number.isFinite(e)?Math.min(100,Math.max(0,e)):0,r=Math.round(n/10),o=ED(n),s=`${o}${"\u2588".repeat(r)}${Dn}${"\u2591".repeat(10-r)}${US}`,i=ft(`${Math.round(n)}%`,o),c=t?`${ft(" \u2502 ",Dn)}${t}`:"";return`${ft("Context",Dn)} ${s} ${i}${c}`}function HS(e,t,n){let r=n===null?"":ft(` ${n}ms`,Dn);return`${ft("Cubence",Dn)} ${ft(t?`${t} ${e}`:e,KS)}${r}`}var US,Dn,vD,KS,GS,qS,sd,SD,id=u(()=>{Zs();US="\x1B[0m",Dn="\x1B[2m",vD="\x1B[31m",KS="\x1B[32m",GS="\x1B[33m",qS="\x1B[35m",sd="\x1B[36m";SD="\u2726"});import{mkdirSync as PD,readFileSync as JS}from"node:fs";import{homedir as RD}from"node:os";import{dirname as AD,join as MD}from"node:path";function VS(e){return e/1e6}function CD(){try{let e=JSON.parse(JS(MD(RD(),".claude","settings.json"),"utf8")),t=e.env?.ANTHROPIC_AUTH_TOKEN,n=e.env?.ANTHROPIC_BASE_URL;return!t||!n?void 0:{token:t,baseUrl:n.replace(/\/$/,"")}}catch{return}}function LD(){try{let e=JSON.parse(JS(ad,"utf8"));return!e.data||typeof e.cachedAt!="number"?void 0:{data:e.data,cachedAt:e.cachedAt}}catch{return}}function ri(e){let t=`$${e.balanceDollar.toFixed(2)}`,n=e.hasSubscription?`5h $${e.fiveHourUsedDollar.toFixed(2)}/$${e.fiveHourLimitDollar.toFixed(2)} bal`:"";return HS(t,n,e.latencyMs)}async function YS(){let e=LD();if(e&&Date.now()-e.cachedAt<OD)return ri(e.data);let t=CD();if(!t)return e?ri(e.data):void 0;let n=Date.now();try{let r=await fetch(`${t.baseUrl}/v1/user/subscription-info`,{headers:{authorization:`Bearer ${t.token}`,accept:"application/json"},signal:AbortSignal.timeout(3e3)});if(!r.ok)return e?ri(e.data):void 0;let o=await r.json(),s=o.subscription_window?.five_hour?.limit??0,i={balanceDollar:o.normal_balance?.amount_dollar??0,hasSubscription:s>0,fiveHourUsedDollar:VS(o.subscription_window?.five_hour?.used??0),fiveHourLimitDollar:VS(s),latencyMs:Date.now()-n};return PD(AD(ad),{recursive:!0}),tt(ad,JSON.stringify({data:i,cachedAt:Date.now()})),ri(i)}catch{return e?ri(e.data):void 0}}var ad,OD,XS=u(()=>{Nn();id();Hn();ad=Um,OD=18e4});import{createHash as QS,randomBytes as eP}from"node:crypto";import{createServer as FD}from"node:http";import{arch as jD,cpus as ZS,hostname as DD,platform as _D,userInfo as ND}from"node:os";function md(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function KD(){return md(eP(32))}function GD(e){return md(QS("sha256").update(e).digest())}function WD(){return md(eP(16))}function VD(e){let t=e??[DD(),_D(),jD(),ND().username,String(ZS().length),ZS()[0]?.model??""];return BD+QS("sha256").update(t.join("\0")).digest("hex").slice(0,32)}function JD(){return{"content-type":"application/json",[zD]:HD}}async function oi(e,t,n,r){let o=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n),signal:r}),s={};try{s=await o.json()}catch{}return{status:o.status,body:s}}async function XD(e,t,n){let r=await e(t,{headers:JD(),signal:n}),o={};try{o=await r.json()}catch{}return{status:r.status,body:o}}function cd(e){let t=e.data,n=[e.token,e.api_key,e.apiKey,e.key,t?.token,t?.api_key,t?.apiKey,t?.key];for(let r of n)if(typeof r=="string"&&r.trim().startsWith("sk-"))return r.trim()}function Do(e,t){let n=e.message??e.error;return typeof n=="string"&&n.trim()?n.trim():t}async function rP(e){let t=e.fetchImpl??fetch,n=(e.panelUrl??qD).replace(/\/+$/,""),r=e.timeoutMs??UD,o={...e,panel:n,fetchImpl:t,timeoutMs:r},s=await QD(o);if(s.ok||s.terminal)return s.result;let i=await ZD(o);if(i.ok||i.terminal)return i.result;let c=await e_(o);return c.ok?c:{ok:!1,message:`${s.result.ok?"":s.result.message}; ${i.result.ok?"":i.result.message}; ${c.message}. howtofix.id does not offer a browser login a local client can complete yet \u2014 run /connect and paste a token from ${n}/keys instead.`}}async function ZD(e){let t=KD(),n=WD(),r;try{r=await(e.loopback??YD)();let o=`http://127.0.0.1:${r.port}${nP}`,s=await oi(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:o,code_challenge:GD(t),code_challenge_method:"S256",state:n},e.signal);if(s.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(s.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:Do(s.body,`the panel refused the login (${s.status})`)}};let i=typeof s.body.authorize_url=="string"?s.body.authorize_url:"";if(!i)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not say where to send the browser"}};e.onProgress({kind:"browser",url:i});let c=await t_(r.waitForCode(n,e.signal),e.timeoutMs),p=await oi(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:s.body.flow_token,code:c,code_verifier:t},e.signal);if(p.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:Do(p.body,`the panel refused the exchange (${p.status})`)}};let f=cd(p.body);return f?{ok:!0,result:{ok:!0,token:f}}:{ok:!1,terminal:!0,result:{ok:!1,message:"the panel did not return an API key"}}}catch(o){let s=o instanceof Error?o.message:String(o);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}finally{r?.close()}}async function QD(e){let t=e.pollIntervalMs??tP,n=e.fingerprintId??VD();try{let r=await oi(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:n},e.signal);if(r.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login endpoint"}};if(r.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:Do(r.body,`the panel refused the login (${r.status})`)}};let o=typeof r.body.login_url=="string"?r.body.login_url:"";if(!o)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}};e.onProgress({kind:"browser",url:o});let s=Date.now()+e.timeoutMs;for(;Date.now()<s;){await ud(t,e.signal);let i=new URLSearchParams({fingerprint_id:n}),c=await XD(e.fetchImpl,`${e.panel}/api/auth/cli/status?${i}`,e.signal);if(c.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login status endpoint"}};let p=cd(c.body);if(p)return{ok:!0,result:{ok:!0,token:p}};if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:Do(c.body,`the panel refused the poll (${c.status})`)}}}return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in was not approved in time"}}}catch(r){let o=r instanceof Error?r.message:String(r);return{ok:!1,terminal:o==="cancelled",result:{ok:!1,message:o}}}}async function e_(e){let t=e.pollIntervalMs??tP;try{let n=await oi(e.fetchImpl,`${e.panel}/api/oauth/device`,{},e.signal);if(n.status===404)return{ok:!1,message:"the panel has no device-code endpoint"};if(n.status>=400)return{ok:!1,message:Do(n.body,`the panel refused the request (${n.status})`)};let r=typeof n.body.device_code=="string"?n.body.device_code:"",o=typeof n.body.user_code=="string"?n.body.user_code:"",s=typeof n.body.verification_uri=="string"?n.body.verification_uri:`${e.panel}/oauth/device`;if(!r||!o)return{ok:!1,message:"the panel did not return a code to show"};e.onProgress({kind:"code",code:o,url:s});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await ud(t,e.signal);let c=await oi(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:r},e.signal);if(c.status===404)return{ok:!1,message:"the panel has no device-code poll endpoint"};let p=typeof c.body.status=="string"?c.body.status:"";if(p==="pending")continue;if(p==="slow_down"){await ud(t,e.signal);continue}if(p==="denied")return{ok:!1,message:"the sign-in was refused in the browser"};if(p==="expired")return{ok:!1,message:"the code expired; run /connect again"};let f=cd(c.body);if(f)return{ok:!0,token:f};if(c.status>=400)return{ok:!1,message:Do(c.body,`the panel refused the poll (${c.status})`)}}return{ok:!1,message:"the code was not approved in time"}}catch(n){return{ok:!1,message:n instanceof Error?n.message:String(n)}}}function t_(e,t){return new Promise((n,r)=>{let o=setTimeout(()=>r(new Error("the sign-in was not finished in time")),t);e.then(s=>{clearTimeout(o),n(s)},s=>{clearTimeout(o),r(s)})})}function ud(e,t){return new Promise((n,r)=>{let o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new Error("cancelled"))},{once:!0})})}var qD,UD,tP,nP,BD,zD,HD,YD,oP=u(()=>{qD="https://howtofix.id",UD=300*1e3,tP=3e3,nP="/callback";BD="howtofix-cli-",zD="x-howtofix-client",HD="cli";YD=()=>new Promise((e,t)=>{let n=FD();n.once("error",t),n.listen(0,"127.0.0.1",()=>{let{port:r}=n.address();e({port:r,close:()=>n.close(),waitForCode:(o,s)=>new Promise((i,c)=>{let p=(I,P)=>{let A=new URL(I.url??"/","http://127.0.0.1");if(A.pathname!==nP){P.writeHead(404).end("not found");return}let C=(ee,ye)=>P.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${ee}</h2><p>${ye}</p>`),U=A.searchParams.get("error")??"",z=A.searchParams.get("code")??"",G=A.searchParams.get("state")??"";if(U){C("Sign-in was refused","You can close this tab."),f(new Error(`the browser reported: ${U}`));return}if(!z||G!==o){C("This callback did not belong to the login","You can close this tab."),f(new Error("the callback carried the wrong state"));return}C("Signed in","You can close this tab and go back to HowToFix."),f(void 0,z)},f=(I,P)=>{n.off("request",p),s?.removeEventListener("abort",w),I?c(I):i(P)},w=()=>f(new Error("cancelled"));s?.addEventListener("abort",w,{once:!0}),n.on("request",p)})})})})});function sP(){return{}}function iP(e,t,n,r=Date.now()){let o={...e};return t==="run"?(n===void 0||n===""?delete o.run:o.run={label:n,since:e.run?.since??r},o):(n===void 0||n===""?delete o[t]:o[t]=n,o)}function n_(e){let t=Math.max(0,Math.round(e/1e3)),n=Math.floor(t/60);return n>0?`${n}m ${String(t%60).padStart(2,"0")}s`:`${t}s`}function aP(e,t,n=Date.now()){return e.prompt?`? ${e.prompt}`:e.note?`* ${e.note}`:e.run?`${t} ${e.run.label} \xB7 ${n_(n-e.run.since)}`:e.tally?e.tally:""}var uP=u(()=>{});import{spawn as r_}from"node:child_process";function o_(e){switch(e){case"darwin":return{command:"open",args:[]};case"win32":return{command:"cmd",args:["/c","start",""]};case"linux":return{command:"xdg-open",args:[]};default:return}}async function wm(e,t=process.platform){let n=o_(t);return n?new Promise(r=>{try{let o=r_(n.command,[...n.args,e],{detached:!0,stdio:"ignore"});o.once("error",()=>r(!1)),o.once("spawn",()=>{o.unref(),r(!0)})}catch{r(!1)}}):!1}var mP=u(()=>{});function s_(e){return[qm,hr(e)]}function cP(e,t){let n=e.trim(),r=/^\/skill:([^\s]+)(?:\s+([\s\S]*))?$/.exec(n)??/^\/skill\s+([^\s]+)(?:\s+([\s\S]*))?$/.exec(n);if(!r)return;let o=r[1]??"";if(!t.includes(o))return;let s=(r[2]??"").trim();return s?`/skill:${o} ${s}`:`/skill:${o}`}function pP(e){if(e.length===0){let[t,n]=s_(process.cwd());return["no skills loaded.",`put a SKILL.md in ${t}`,`or in ${n}`,"invoke with /skill:<name>"].join(`
|
|
116
|
+
${r}`:r}):n.errorMessage&&t.push({id:`e-${n.timestamp}`,kind:"error",title:"failed",body:n.errorMessage}),o.forEach((s,i)=>{t.push({id:`c-${n.timestamp}-${i}`,kind:"tool",title:"tool",body:jo(s.name,s.arguments)})})}else n.role==="toolResult"&&t.push({id:`r-${n.toolCallId}`,kind:"result",title:n.toolName,body:xm(n.toolName,{content:n.content},n.isError)});return t}function _S(e,t,n){return $D(e,Math.max(8,t)).map(r=>ne(r,n))}function TD(e){let t=e.body||" ",n=ni.get(e.id);if(n)return n.text!==t&&(n.component.setText(t),n.text=t),n.component;let r=new ID(t,0,0,KE);return ni.set(e.id,{text:t,component:r}),r}var ni,od,ym,NS=u(()=>{zl();Js();rd();ni=new Map;od=class{constructor(t){this.item=t}item;invalidate(){}shade(t){let n=Date.now()-(this.item.born??0);return Qs(_.dim,t,xS(n,Wl))}render(t){let n=this.item.body;if(this.item.kind==="user")return["",..._S(`> ${n}`,t,this.shade(_.user))];if(this.item.kind==="tool")return[ne(n,this.shade(_.tool))];if(this.item.kind==="result"){let o=n.startsWith("exit ")&&n!=="exit 0";if(this.item.panel)return["",...this.item.panel(t),...n?[ne(` ${Zl} ${n}`,o?_.bad:_.mute)]:[]];let s=[];this.item.call&&s.push(ne(this.item.call,this.shade(_.tool)));let i=` ${Zl} ${n}`;if(s.push(ne(i,o?_.bad:this.shade(_.mute))),this.item.expanded===!0&&(this.item.full?.length??0)>0){let w=ne(` ${this.item.full.length} line(s) \xB7 ctrl+e to collapse`,_.dim);s.push(ne(` ${Ql}`,_.dim));for(let I of this.item.full){let P=I.startsWith("+")?_.tool:I.startsWith("-")?_.bad:_.dim;s.push(ne(` ${I}`,P))}return s.push(w),s}let p=this.item.detail??[],f=Bl(Date.now()-(this.item.born??0),p.length);for(let w of p.slice(0,f)){let I=w.startsWith("+")?_.tool:w.startsWith("-")?_.bad:_.dim;s.push(ne(` ${w}`,this.shade(I)))}return(this.item.full?.length??0)>0&&s.push(ne(` ${Ql} ${this.item.full.length} line(s) \xB7 ctrl+e to expand`,_.dim)),s}if(this.item.kind==="error"||this.item.kind==="note"){let o=this.item.kind==="error"?_.bad:_.mute;return["",..._S(n,t,this.shade(o))]}return["",...TD(this.item).render(Math.max(8,t-2))]}},ym=class{items=[];status="";scrollOffset=0;scrollAnchor;settledOffset=0;viewportHeight=0;invalidate(){}entering(){let t=Date.now();return this.items.some(n=>{if(n.born===void 0)return!1;let r=t-n.born;return yS(r,Wl)?!0:(n.detail?.length??0)>Bl(r,n.detail?.length??0)})}render(t){if(ni.size>this.items.length){let o=new Set(this.items.map(s=>s.id));for(let s of ni.keys())o.has(s)||ni.delete(s)}let n=[];for(let o of this.items)o.born??=Date.now(),n.push(...new od(o).render(t));this.status&&n.push(ne(this.status,_.mute));let r=this.viewportHeight;if(r>0&&n.length>r){let o=n.length-r;this.scrollOffset!==this.settledOffset&&(this.scrollAnchor=void 0);let s=this.scrollAnchor,i;if(s!==void 0){let c=n.length-s;c>=0&&c<=o?i=c:i=Math.max(0,Math.min(this.scrollOffset,o))}else i=Math.max(0,Math.min(this.scrollOffset,o));return s===void 0&&(this.scrollOffset=i),this.settledOffset=this.scrollOffset,i===0?this.scrollAnchor=void 0:this.scrollAnchor===void 0&&(this.scrollAnchor=n.length-i),n.slice(o-i,o-i+r)}return n}}});function ft(e,t){return`${t}${e}${US}`}function ED(e){return e>=85?vD:e>=70?GS:KS}function WS(e,t,n,r){let o=ft(`[${e}]`,sd),s=ft(`${SD} ${t}`,Dn),i=ft(n,GS),c=r?` ${ft("git:(",qS)}${ft(r.replace(/^git:\(/,"").replace(/\)$/,""),sd)}${ft(")",qS)}`:"";return`${o}${ft(" \u2502 ",Dn)}${s}${ft(" \u2502 ",Dn)}${i}${c}`}function BS(e,t,n){if(!t)return e;let r=n===void 0?t:`${t} ${ft(BE(n),Dn)}`;return`${ft(r,sd)} ${ft("\u2502",Dn)} ${e}`}function zS(e,t){let n=Number.isFinite(e)?Math.min(100,Math.max(0,e)):0,r=Math.round(n/10),o=ED(n),s=`${o}${"\u2588".repeat(r)}${Dn}${"\u2591".repeat(10-r)}${US}`,i=ft(`${Math.round(n)}%`,o),c=t?`${ft(" \u2502 ",Dn)}${t}`:"";return`${ft("Context",Dn)} ${s} ${i}${c}`}function HS(e,t,n){let r=n===null?"":ft(` ${n}ms`,Dn);return`${ft("Cubence",Dn)} ${ft(t?`${t} ${e}`:e,KS)}${r}`}var US,Dn,vD,KS,GS,qS,sd,SD,id=u(()=>{Zs();US="\x1B[0m",Dn="\x1B[2m",vD="\x1B[31m",KS="\x1B[32m",GS="\x1B[33m",qS="\x1B[35m",sd="\x1B[36m";SD="\u2726"});import{mkdirSync as PD,readFileSync as JS}from"node:fs";import{homedir as RD}from"node:os";import{dirname as AD,join as MD}from"node:path";function VS(e){return e/1e6}function CD(){try{let e=JSON.parse(JS(MD(RD(),".claude","settings.json"),"utf8")),t=e.env?.ANTHROPIC_AUTH_TOKEN,n=e.env?.ANTHROPIC_BASE_URL;return!t||!n?void 0:{token:t,baseUrl:n.replace(/\/$/,"")}}catch{return}}function LD(){try{let e=JSON.parse(JS(ad,"utf8"));return!e.data||typeof e.cachedAt!="number"?void 0:{data:e.data,cachedAt:e.cachedAt}}catch{return}}function ri(e){let t=`$${e.balanceDollar.toFixed(2)}`,n=e.hasSubscription?`5h $${e.fiveHourUsedDollar.toFixed(2)}/$${e.fiveHourLimitDollar.toFixed(2)} bal`:"";return HS(t,n,e.latencyMs)}async function YS(){let e=LD();if(e&&Date.now()-e.cachedAt<OD)return ri(e.data);let t=CD();if(!t)return e?ri(e.data):void 0;let n=Date.now();try{let r=await fetch(`${t.baseUrl}/v1/user/subscription-info`,{headers:{authorization:`Bearer ${t.token}`,accept:"application/json"},signal:AbortSignal.timeout(3e3)});if(!r.ok)return e?ri(e.data):void 0;let o=await r.json(),s=o.subscription_window?.five_hour?.limit??0,i={balanceDollar:o.normal_balance?.amount_dollar??0,hasSubscription:s>0,fiveHourUsedDollar:VS(o.subscription_window?.five_hour?.used??0),fiveHourLimitDollar:VS(s),latencyMs:Date.now()-n};return PD(AD(ad),{recursive:!0}),tt(ad,JSON.stringify({data:i,cachedAt:Date.now()})),ri(i)}catch{return e?ri(e.data):void 0}}var ad,OD,XS=u(()=>{Nn();id();Hn();ad=Um,OD=18e4});import{createHash as QS,randomBytes as eP}from"node:crypto";import{createServer as FD}from"node:http";import{arch as jD,cpus as ZS,hostname as DD,platform as _D,userInfo as ND}from"node:os";function md(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function KD(){return md(eP(32))}function GD(e){return md(QS("sha256").update(e).digest())}function WD(){return md(eP(16))}function VD(e){let t=e??[DD(),_D(),jD(),ND().username,String(ZS().length),ZS()[0]?.model??""];return BD+QS("sha256").update(t.join("\0")).digest("hex").slice(0,32)}function JD(){return{"content-type":"application/json",[zD]:HD}}async function oi(e,t,n,r){let o=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n),signal:r}),s={};try{s=await o.json()}catch{}return{status:o.status,body:s}}function XD(e){try{let t=new URL(e).searchParams.get("code");return t&&t.trim()!==""?t.trim():void 0}catch{return}}async function ZD(e,t,n){let r=await e(t,{headers:JD(),signal:n}),o={};try{o=await r.json()}catch{}return{status:r.status,body:o}}function cd(e){let t=e.data,n=[e.token,e.api_key,e.apiKey,e.key,t?.token,t?.api_key,t?.apiKey,t?.key];for(let r of n)if(typeof r=="string"&&r.trim().startsWith("sk-"))return r.trim()}function Do(e,t){let n=e.message??e.error;return typeof n=="string"&&n.trim()?n.trim():t}async function rP(e){let t=e.fetchImpl??fetch,n=(e.panelUrl??qD).replace(/\/+$/,""),r=e.timeoutMs??UD,o={...e,panel:n,fetchImpl:t,timeoutMs:r},s=await e_(o);if(s.ok||s.terminal)return s.result;let i=await QD(o);if(i.ok||i.terminal)return i.result;let c=await t_(o);return c.ok?c:{ok:!1,message:`${s.result.ok?"":s.result.message}; ${i.result.ok?"":i.result.message}; ${c.message}. howtofix.id does not offer a browser login a local client can complete yet \u2014 run /connect and paste a token from ${n}/keys instead.`}}async function QD(e){let t=KD(),n=WD(),r;try{r=await(e.loopback??YD)();let o=`http://127.0.0.1:${r.port}${nP}`,s=await oi(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:o,code_challenge:GD(t),code_challenge_method:"S256",state:n},e.signal);if(s.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(s.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:Do(s.body,`the panel refused the login (${s.status})`)}};let i=typeof s.body.authorize_url=="string"?s.body.authorize_url:"";if(!i)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not say where to send the browser"}};e.onProgress({kind:"browser",url:i});let c=await n_(r.waitForCode(n,e.signal),e.timeoutMs),p=await oi(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:s.body.flow_token,code:c,code_verifier:t},e.signal);if(p.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:Do(p.body,`the panel refused the exchange (${p.status})`)}};let f=cd(p.body);return f?{ok:!0,result:{ok:!0,token:f}}:{ok:!1,terminal:!0,result:{ok:!1,message:"the panel did not return an API key"}}}catch(o){let s=o instanceof Error?o.message:String(o);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}finally{r?.close()}}async function e_(e){let t=e.pollIntervalMs??tP,n=e.fingerprintId??VD();try{let r=await oi(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:n},e.signal);if(r.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login endpoint"}};if(r.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:Do(r.body,`the panel refused the login (${r.status})`)}};let o=typeof r.body.login_url=="string"?r.body.login_url:"",s=typeof r.body.code=="string"?r.body.code:XD(o);if(!o||!s)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}};e.onProgress({kind:"browser",url:o});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await ud(t,e.signal);let c=new URLSearchParams({code:s}),p=await ZD(e.fetchImpl,`${e.panel}/api/auth/cli/status?${c}`,e.signal);if(p.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login status endpoint"}};let f=cd(p.body);if(f)return{ok:!0,result:{ok:!0,token:f}};if(p.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:Do(p.body,`the panel refused the poll (${p.status})`)}}}return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in was not approved in time"}}}catch(r){let o=r instanceof Error?r.message:String(r);return{ok:!1,terminal:o==="cancelled",result:{ok:!1,message:o}}}}async function t_(e){let t=e.pollIntervalMs??tP;try{let n=await oi(e.fetchImpl,`${e.panel}/api/oauth/device`,{},e.signal);if(n.status===404)return{ok:!1,message:"the panel has no device-code endpoint"};if(n.status>=400)return{ok:!1,message:Do(n.body,`the panel refused the request (${n.status})`)};let r=typeof n.body.device_code=="string"?n.body.device_code:"",o=typeof n.body.user_code=="string"?n.body.user_code:"",s=typeof n.body.verification_uri=="string"?n.body.verification_uri:`${e.panel}/oauth/device`;if(!r||!o)return{ok:!1,message:"the panel did not return a code to show"};e.onProgress({kind:"code",code:o,url:s});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await ud(t,e.signal);let c=await oi(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:r},e.signal);if(c.status===404)return{ok:!1,message:"the panel has no device-code poll endpoint"};let p=typeof c.body.status=="string"?c.body.status:"";if(p==="pending")continue;if(p==="slow_down"){await ud(t,e.signal);continue}if(p==="denied")return{ok:!1,message:"the sign-in was refused in the browser"};if(p==="expired")return{ok:!1,message:"the code expired; run /connect again"};let f=cd(c.body);if(f)return{ok:!0,token:f};if(c.status>=400)return{ok:!1,message:Do(c.body,`the panel refused the poll (${c.status})`)}}return{ok:!1,message:"the code was not approved in time"}}catch(n){return{ok:!1,message:n instanceof Error?n.message:String(n)}}}function n_(e,t){return new Promise((n,r)=>{let o=setTimeout(()=>r(new Error("the sign-in was not finished in time")),t);e.then(s=>{clearTimeout(o),n(s)},s=>{clearTimeout(o),r(s)})})}function ud(e,t){return new Promise((n,r)=>{let o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new Error("cancelled"))},{once:!0})})}var qD,UD,tP,nP,BD,zD,HD,YD,oP=u(()=>{qD="https://howtofix.id",UD=300*1e3,tP=3e3,nP="/callback";BD="howtofix-cli-",zD="x-howtofix-client",HD="cli";YD=()=>new Promise((e,t)=>{let n=FD();n.once("error",t),n.listen(0,"127.0.0.1",()=>{let{port:r}=n.address();e({port:r,close:()=>n.close(),waitForCode:(o,s)=>new Promise((i,c)=>{let p=(I,P)=>{let A=new URL(I.url??"/","http://127.0.0.1");if(A.pathname!==nP){P.writeHead(404).end("not found");return}let C=(ee,ye)=>P.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${ee}</h2><p>${ye}</p>`),U=A.searchParams.get("error")??"",z=A.searchParams.get("code")??"",G=A.searchParams.get("state")??"";if(U){C("Sign-in was refused","You can close this tab."),f(new Error(`the browser reported: ${U}`));return}if(!z||G!==o){C("This callback did not belong to the login","You can close this tab."),f(new Error("the callback carried the wrong state"));return}C("Signed in","You can close this tab and go back to HowToFix."),f(void 0,z)},f=(I,P)=>{n.off("request",p),s?.removeEventListener("abort",w),I?c(I):i(P)},w=()=>f(new Error("cancelled"));s?.addEventListener("abort",w,{once:!0}),n.on("request",p)})})})})});function sP(){return{}}function iP(e,t,n,r=Date.now()){let o={...e};return t==="run"?(n===void 0||n===""?delete o.run:o.run={label:n,since:e.run?.since??r},o):(n===void 0||n===""?delete o[t]:o[t]=n,o)}function r_(e){let t=Math.max(0,Math.round(e/1e3)),n=Math.floor(t/60);return n>0?`${n}m ${String(t%60).padStart(2,"0")}s`:`${t}s`}function aP(e,t,n=Date.now()){return e.prompt?`? ${e.prompt}`:e.note?`* ${e.note}`:e.run?`${t} ${e.run.label} \xB7 ${r_(n-e.run.since)}`:e.tally?e.tally:""}var uP=u(()=>{});import{spawn as o_}from"node:child_process";function s_(e){switch(e){case"darwin":return{command:"open",args:[]};case"win32":return{command:"cmd",args:["/c","start",""]};case"linux":return{command:"xdg-open",args:[]};default:return}}async function wm(e,t=process.platform){let n=s_(t);return n?new Promise(r=>{try{let o=o_(n.command,[...n.args,e],{detached:!0,stdio:"ignore"});o.once("error",()=>r(!1)),o.once("spawn",()=>{o.unref(),r(!0)})}catch{r(!1)}}):!1}var mP=u(()=>{});function i_(e){return[qm,hr(e)]}function cP(e,t){let n=e.trim(),r=/^\/skill:([^\s]+)(?:\s+([\s\S]*))?$/.exec(n)??/^\/skill\s+([^\s]+)(?:\s+([\s\S]*))?$/.exec(n);if(!r)return;let o=r[1]??"";if(!t.includes(o))return;let s=(r[2]??"").trim();return s?`/skill:${o} ${s}`:`/skill:${o}`}function pP(e){if(e.length===0){let[t,n]=i_(process.cwd());return["no skills loaded.",`put a SKILL.md in ${t}`,`or in ${n}`,"invoke with /skill:<name>"].join(`
|
|
117
117
|
`)}return e.map(t=>{let n=t.disableModelInvocation?" (invoke only)":"";return`${t.name}${n}
|
|
118
118
|
${t.description}
|
|
119
119
|
${t.filePath}`}).join(`
|
|
120
|
-
`)}var lP=u(()=>{Nn()});import{mkdirSync as
|
|
121
|
-
`).filter(Boolean),r=n.filter(i=>i.startsWith("Reason:")),o=n.filter(i=>!i.startsWith("Reason:")&&!i.startsWith("Allow tool:"));return[...e.endsWith(" wants to run")?[]:[e],...r,...o.length>0?["",...o]:[]]}function _o(e){let t=e.getContextUsage();if(t?.percent!==null&&t?.percent!==void 0)return Math.min(100,Math.round(t.percent));let n=e.model,o=[...e.state.messages].reverse().find(s=>s.role==="assistant")?.usage?.totalTokens;return!n||typeof o!="number"||!Number.isFinite(o)||n.contextWindow<=0?0:Math.min(100,Math.round(o/n.contextWindow*100))}function dd(e){let n=[["init","write project notes to AGENTS.md"],["model","choose a model"],["providers","list providers"],["thinking","set thinking level"],["approval","set what needs approval"],["connect","sign in to howtofix.id (browser, or paste a token)"],["sync","re-sync models from howtofix.id"],["usage","show the account's quota and what it has spent"],["update","install the newest release"],["login","save a provider API key"],["logout","remove a provider"],["new","start a new session"],["resume","resume another session"],["compact","compact the session"],["name","name this session"],["stats","session tokens and cost"],["diff","show the working tree diff"],["commit","stage everything and commit"],["undo","undo the last commit"],["rewind","go back to an earlier message (Esc Esc)"],["review","ask the agent to review the diff"],["tools","list active tools"],["skills","list loaded skills"],["export","write the transcript to a markdown file"],["copy","copy the last answer to the clipboard"],["agents","show spawned agents"],["goal","set or view this session's goal"],["plan","toggle plan mode (design before editing)"],["workflow","show or clear the pinned workflow panel"],["session","show the current model"],["help","list commands"],["quit","quit"]].map(([r,o])=>({name:r,description:o}));for(let r of e.promptTemplates)n.push({name:r.name,description:r.description});for(let r of e.extensionRunner.getRegisteredCommands())n.push({name:r.invocationName,description:r.description});return n}function Em(e,t){if(e!=="workflow")return;let n=ti(t);if(!(typeof n.name!="string"||!Array.isArray(n.steps)))return n}function DP(e,t){let n=Em(e,t);return n?ii(n):void 0}function ii(e,t,n=!1){return r=>ZE(e,[],r,t?.selectedPhase,t?
|
|
122
|
-
`)||"nothing to do"),N()};i(!0),s("session start"),e.note&&r.items.push({id:"note",kind:"note",title:"note",body:e.note}),r.items.push(...bm(v.state.messages)),o.percent=_o(v),o.abandonAnimations(),o.thinking=v.thinkingLevel,c.setAutocompleteProvider(new EP(dd(v),e.cwd)),YS().then(l=>{l&&(o.cubence=l,n.requestRender())});let yd=async l=>{let{checkForUpdate:g,installUpdate:y}=await Promise.resolve().then(()=>(wi(),bi)),x=await g(l.current);if(!x.available){l.install&&E("update",x.message);return}if(!l.install){E("update",`${x.message}. run /update to install it.`);return}re("note",`installing HowToFix ${x.latest}\u2026`);let $=await y({version:x.latest});re("note",void 0),E("update",$.message),N()};e.update&&yd(e.update);let _n=null,bd="",wd=!1,Id=[],Uo,Pm=()=>{},N=()=>{Pm(),n.requestRender()},re=(l,g)=>{o.activity=iP(o.activity,l,g)},ai=new Map,Rm=new Set,GP=()=>[...ai].map(([l,g])=>`${Rm.has(l)?"!":"\u2713"} ${l} \xD7${g}`).join(" | "),WP=()=>{let l=GP();re("tally",l||void 0)},_t=(l,g,y,x,$=!1,K=[])=>{let b=new
|
|
120
|
+
`)}var lP=u(()=>{Nn()});import{mkdirSync as a_}from"node:fs";import{join as u_}from"node:path";import{matchesKey as Im}from"@earendil-works/pi-tui";function fP(){return{selectedPhase:0,filter:"all",paused:!1,expanded:!1,follow:!0}}function gP(e){if(Im(e,"up"))return"up";if(Im(e,"down"))return"down";if(Im(e,"enter"))return"enter";if(Im(e,"escape"))return"escape";if(e==="f")return"filter";if(e==="p")return"pause";if(e==="x")return"stop";if(e==="s")return"save"}function dP(e,t,n){if(t.length===0)return e;let r=Math.max(0,Math.min(t.length-1,e.selectedPhase+n));return{...e,selectedPhase:r,follow:!1}}function m_(e){let t=pd.indexOf(e);return pd[(t+1)%pd.length]}function hP(e,t,n){switch(t){case"up":return dP(e,n,-1);case"down":return dP(e,n,1);case"enter":return{...e,expanded:!e.expanded};case"filter":return{...e,filter:m_(e.filter)};case"pause":return{...e,paused:!e.paused};default:return e}}function xP(e,t){switch(t){case"running":return e.filter(n=>n.status==="running");case"failed":return e.filter(n=>n.status==="failed");case"done":return e.filter(n=>n.status!=="running");default:return[...e]}}function yP(e){return e==="all"?"":` \xB7 ${e}`}function wP(e,t,n=!0){if(!n)return"Ctrl+F panel keys \xB7 Esc unpin";let r=["\u2191/\u2193 phase",e.expanded?"Enter collapse":"Enter drill in"];return r.push(e.expanded?"Esc back out":"Esc unpin"),r.push(`f filter${e.filter==="all"?"":` (${e.filter})`}`),t?(r.push(e.paused?"p resume":"p pause"),r.push("x stop")):e.paused&&r.push("p resume"),r.push("s save script"),e.paused&&r.unshift("paused"),r.join(" \xB7 ")}function c_(e){let t=e.trim();if(!(!t||t.length>64)&&!(t==="."||t==="..")&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return t}function IP(e,t){if(!e)return{ok:!1,reason:"this run was started from a file, so it is already saved where you pointed the tool"};let n=c_(e.name);if(!n)return{ok:!1,reason:`"${e.name}" is not a usable filename, so the script was not written`};let r=u_(t,`${n}.js`);try{a_(t,{recursive:!0}),tt(r,e.code)}catch(o){return{ok:!1,reason:o instanceof Error?o.message:String(o)}}return{ok:!0,path:r}}var pd,bP,$P=u(()=>{Hn();pd=["all","running","failed","done"];bP="ctrl+f"});function kP(e){let t=()=>{};return{select:(n,r)=>e.select(n,r),confirm:(n,r)=>e.confirm(n,r),input:n=>e.input(n),notify:(n,r)=>e.notify(n,r),onTerminalInput:()=>t,setStatus:(n,r)=>e.setStatus(n,r),setWorkingMessage:t,setWorkingVisible:t,setWorkingIndicator:t,setHiddenThinkingLabel:t,setWidget:(n,r,o)=>{r!==void 0&&!Array.isArray(r)||e.setWidget?.(n,r,o?.placement)},setFooter:t,setHeader:t,setTitle:t,custom:async()=>{throw new Error("this screen has no custom component host; use the text commands instead")},pasteToEditor:t,setEditorText:t,getEditorText:()=>"",editor:async()=>{},addAutocompleteProvider:t,setEditorComponent:t,getEditorComponent:()=>{},theme:void 0,getAllThemes:()=>[],getTheme:()=>{},setTheme:()=>({success:!1,error:"themes are not available in the workbench"}),getToolsExpanded:()=>!1,setToolsExpanded:t}}var TP=u(()=>{});var _P={};Mt(_P,{Dock:()=>vm,Hud:()=>km,PinnedBlock:()=>Tm,approvalDetail:()=>jP,orderModelsForDefault:()=>LP,pickerPanel:()=>FP,runWorkbench:()=>F_,workflowPanel:()=>DP,workflowPanelFromRun:()=>ii,workflowRunOf:()=>Em});import{execFile as p_}from"node:child_process";import{promisify as l_}from"node:util";import{existsSync as d_,mkdirSync as f_,readFileSync as g_}from"node:fs";import{basename as h_,join as vP,resolve as x_}from"node:path";import{copyToClipboard as y_,SessionManager as b_}from"@earendil-works/pi-coding-agent";import{CombinedAutocompleteProvider as EP,Container as w_,Editor as I_,matchesKey as jt,ProcessTerminal as $_,ScrollView as k_,KeybindingsManager as AP,setKeybindings as MP,TUI_KEYBINDINGS as OP,SelectList as T_,TuiAltScreen as v_,truncateToWidth as si,VStack as E_,visibleWidth as $m,wrapTextWithAnsi as S_}from"@earendil-works/pi-tui";import{TreeSelectorComponent as P_,initTheme as R_}from"@earendil-works/pi-coding-agent";import{getKeybindings as SP}from"@earendil-works/pi-tui";function A_(e){if(typeof e!="object"||e===null)return;let t=e[CP];return typeof t=="function"?t.call(e):void 0}async function RP(e){try{let{stdout:t}=await fd("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"}),n=t.trim();if(!n||n==="HEAD")return"";let{stdout:r}=await fd("git",["-C",e,"status","--porcelain"],{encoding:"utf8"});return`git:(${n}${r.trim()?"*":""})`}catch{return null}}function LP(e){let t=n=>{if(O_.test(n))return 100;let r=M_.findIndex(o=>n.toLowerCase().includes(o));return r===-1?50:r};return e.map((n,r)=>({id:n,index:r})).sort((n,r)=>t(n.id)-t(r.id)||n.index-r.index).map(n=>n.id)}function FP(e,t,n,r=!1,o=[]){let s=Math.max(24,n),i=s-4,c=(z,G)=>{let ee=$m(z)>i?si(z,i,"\u2026"):z,ye=`${ee}${" ".repeat(Math.max(0,i-$m(ee)))}`;return`\u2502 ${G?G(ye):ye} \u2502`},p="\u2500".repeat(s-2),f=[c(` ${t}`),...e.render(i).map(z=>c(z))],w=o.flatMap(z=>z===""?[""]:S_(z,i)),I=w.length>0?[c(""),...w.map(z=>c(z,G=>ne(G,_.mute)))]:[];if(!r)return["",`\u250C${p}\u2510`,...f,...I,`\u2514${p}\u2518`];let P=bS(_.line,_.warn,Date.now(),1400),A=ne("\u2502",P),C=(z,G)=>ne(`${z}${p}${G}`,P),U=[...f,...I].map(z=>`${A}${z.slice(1,-1)}${A}`);return["",C("\u250C","\u2510"),...U,C("\u2514","\u2518")]}function jP(e,t){let n=t.split(`
|
|
121
|
+
`).filter(Boolean),r=n.filter(i=>i.startsWith("Reason:")),o=n.filter(i=>!i.startsWith("Reason:")&&!i.startsWith("Allow tool:"));return[...e.endsWith(" wants to run")?[]:[e],...r,...o.length>0?["",...o]:[]]}function _o(e){let t=e.getContextUsage();if(t?.percent!==null&&t?.percent!==void 0)return Math.min(100,Math.round(t.percent));let n=e.model,o=[...e.state.messages].reverse().find(s=>s.role==="assistant")?.usage?.totalTokens;return!n||typeof o!="number"||!Number.isFinite(o)||n.contextWindow<=0?0:Math.min(100,Math.round(o/n.contextWindow*100))}function dd(e){let n=[["init","write project notes to AGENTS.md"],["model","choose a model"],["providers","list providers"],["thinking","set thinking level"],["approval","set what needs approval"],["connect","sign in to howtofix.id (browser, or paste a token)"],["sync","re-sync models from howtofix.id"],["usage","show the account's quota and what it has spent"],["update","install the newest release"],["login","save a provider API key"],["logout","remove a provider"],["new","start a new session"],["resume","resume another session"],["compact","compact the session"],["name","name this session"],["stats","session tokens and cost"],["diff","show the working tree diff"],["commit","stage everything and commit"],["undo","undo the last commit"],["rewind","go back to an earlier message (Esc Esc)"],["review","ask the agent to review the diff"],["tools","list active tools"],["skills","list loaded skills"],["export","write the transcript to a markdown file"],["copy","copy the last answer to the clipboard"],["agents","show spawned agents"],["goal","set or view this session's goal"],["plan","toggle plan mode (design before editing)"],["workflow","show or clear the pinned workflow panel"],["session","show the current model"],["help","list commands"],["quit","quit"]].map(([r,o])=>({name:r,description:o}));for(let r of e.promptTemplates)n.push({name:r.name,description:r.description});for(let r of e.extensionRunner.getRegisteredCommands())n.push({name:r.invocationName,description:r.description});return n}function Em(e,t){if(e!=="workflow")return;let n=ti(t);if(!(typeof n.name!="string"||!Array.isArray(n.steps)))return n}function DP(e,t){let n=Em(e,t);return n?ii(n):void 0}function ii(e,t,n=!1){return r=>ZE(e,[],r,t?.selectedPhase,t?C_(e,t,n):void 0)}function C_(e,t,n){return{filter:r=>xP(r,t.filter),footerText:wP(t,e.endedAt===void 0,n),filterLabel:yP(t.filter),drill:t.expanded}}function L_(){let e=new AP(OP,{"tui.altScreen.pageUp":[],"tui.altScreen.pageDown":[],"tui.altScreen.halfPageUp":[],"tui.altScreen.halfPageDown":[],"tui.altScreen.top":[],"tui.altScreen.bottom":[]});MP(e)}async function F_(e){let t=new $_,n=new v_(t,!0,void 0,{mouse:!0}),r=new ym,o=new km(e.cwd,e.modelLabel),s=l=>{let g=Date.now();(async()=>{try{let y=gn(),x=await SS(y,v.getSessionStats().sessionId,l);x&&g>=Wt&&(No=x,Wt=g)}catch{}})()},i=(l=!1)=>{!l&&!o.live||RP(e.cwd).then(g=>{g!==null&&(o.git=g,N())})},c=new I_(n,PP,{paddingX:1}),p=new Map,f=(l,g)=>{g===void 0?p.delete(l):typeof g=="function"?p.set(l,g):p.set(l,()=>g)},w=()=>Math.max(20,t.columns),I,P=0,A=fP(),C,U=null,z=!1,G,ee=!1,ye,De=()=>{!C||!z||f("workflow",l=>ii(C,A,ee)(l))},Qe=()=>{C&&(G=C.name),z=!1,ee=!1,f("workflow",void 0)};eS({onStop:l=>{U=l},isPaused:()=>A.paused});let xe=l=>{if(G===l.name)return;I=l;let g=l.endedAt??Date.now();P=Math.max(P,g+cm),C=l,z=!0,f("workflow",y=>ii(l,A,ee)(y))},ie=new vm(c,o),v=e.session,He=!1,Gt,gn=()=>Gt??=vS(e.cwd),No,rn="",Wt=0,Ke,Dt=()=>{let l=new Set(["session_info","usage","label","context_edit","custom","model_change","thinking_level_change"]),g=[],y=x=>{for(let $ of x)l.has($.entry.type)||g.push($.entry.id),y($.children)};return y(v.sessionManager.getTree()),g},qo=!1,qP=()=>{if(qo)return;qo=!0;let l=SP().getResolvedBindings();MP(new AP(OP,{...l,"app.tree.foldOrUp":["alt+left","ctrl+left"],"app.tree.unfoldOrDown":["alt+right","ctrl+right"],"app.tree.editLabel":["shift+l"],"app.tree.toggleLabelTimestamp":["shift+t"],"app.message.copy":["ctrl+x"],"app.tree.filter.default":["alt+0"],"app.tree.filter.noTools":["alt+1"],"app.tree.filter.userOnly":["alt+2"],"app.tree.filter.labeledOnly":["alt+3"],"app.tree.filter.all":["alt+4"],"app.tree.filter.cycleForward":["alt+f"],"app.tree.filter.cycleBackward":["alt+shift+f"]}))},gd=!1,UP=()=>{gd||(gd=!0,R_())},hd=()=>{let l=v.sessionManager.getTree();if(l.length===0){E("rewind","nothing to rewind to yet");return}gn().disabled&&E("rewind","conversation rewind only \u2014 this directory is not a git repository"),UP(),qP();let g=Math.max(8,Math.floor(t.rows*.6)),y=new P_(l,v.sessionManager.getLeafId(),g*2,x=>{Sm(),KP(x)},()=>Sm());if(!y.getTreeList().getSelectedNode()){E("rewind","nothing to rewind to yet");return}Ke=y,Ke.focused=!0,f("rewind",x=>Ke?.render(x)??[]),N()},Sm=()=>{Ke=void 0,f("rewind",void 0),N()},KP=async l=>{let g=gn(),x=v.getUserMessagesForForking().findIndex(b=>b.entryId===l),$=x>=0?Yl(g,v.getSessionStats().sessionId)[x]:void 0,K=$?(await RS(g,$)).length:0;if(K===0){await xd(l,void 0,"conversation");return}_t(`Rewind to this point? ${K} file(s) differ`,[{value:"both",label:"conversation and code",description:`drop the messages after this point and restore ${K} file(s)`},{value:"conversation",label:"conversation only",description:"drop the messages after this point, leave the files alone"},{value:"code",label:"code only",description:`restore ${K} file(s), keep the conversation`}],b=>{xd(l,$,b)})},xd=async(l,g,y)=>{let x=[];if((y==="both"||y==="conversation")&&!v.isStreaming)try{let $=await v.navigateTree(l);if($.cancelled){E("rewind","conversation rewind cancelled");return}x.push("conversation rewound"),r.items=bm(v.state.messages),$.editorText&&(c.setText($.editorText),x.push("prompt restored to the editor"))}catch($){hn(`conversation rewind failed: ${$ instanceof Error?$.message:String($)}`);return}if((y==="both"||y==="code")&&g){let $=await PS(gn(),g);if(!$.ok){hn(`code rewind failed: ${$.output}`);return}x.push($.output),$.removed.length>0&&x.push(`removed ${$.removed.length} file(s)`),i()}E("rewind",x.join(`
|
|
122
|
+
`)||"nothing to do"),N()};i(!0),s("session start"),e.note&&r.items.push({id:"note",kind:"note",title:"note",body:e.note}),r.items.push(...bm(v.state.messages)),o.percent=_o(v),o.abandonAnimations(),o.thinking=v.thinkingLevel,c.setAutocompleteProvider(new EP(dd(v),e.cwd)),YS().then(l=>{l&&(o.cubence=l,n.requestRender())});let yd=async l=>{let{checkForUpdate:g,installUpdate:y}=await Promise.resolve().then(()=>(wi(),bi)),x=await g(l.current);if(!x.available){l.install&&E("update",x.message);return}if(!l.install){E("update",`${x.message}. run /update to install it.`);return}re("note",`installing HowToFix ${x.latest}\u2026`);let $=await y({version:x.latest});re("note",void 0),E("update",$.message),N()};e.update&&yd(e.update);let _n=null,bd="",wd=!1,Id=[],Uo,Pm=()=>{},N=()=>{Pm(),n.requestRender()},re=(l,g)=>{o.activity=iP(o.activity,l,g)},ai=new Map,Rm=new Set,GP=()=>[...ai].map(([l,g])=>`${Rm.has(l)?"!":"\u2713"} ${l} \xD7${g}`).join(" | "),WP=()=>{let l=GP();re("tally",l||void 0)},_t=(l,g,y,x,$=!1,K=[])=>{let b=new T_(g,8,PP.selectList);b.onSelect=k=>{_n=null,Uo=void 0,y(k.value)},b.onCancel=()=>{_n=null,Uo=void 0,x?.(),N()},Uo=()=>b.onCancel?.(),bd=l,wd=$,Id=K,_n=b,N()},E=(l,g)=>{r.items.push({id:`cmd-${Date.now()}-${r.items.length}`,kind:"note",title:l,body:g}),re("tally",void 0),N()},hn=l=>{r.items.push({id:`err-${Date.now()}-${r.items.length}`,kind:"error",title:"failed",body:l}),re("tally",void 0),N()};pc((l,g)=>{let{promise:y,resolve:x}=Promise.withResolvers();return _t(l,[{value:"allow",label:"allow"},{value:"deny",label:"deny"}],$=>x($==="allow"),()=>x(!1),!0,jP(l,g)),y});let Am=new Map,$d=l=>{let g=kP({select:(y,x)=>{let{promise:$,resolve:K}=Promise.withResolvers();return _t(y,x.map(b=>({value:b,label:b})),K,()=>K(void 0)),$},confirm:(y,x)=>{let{promise:$,resolve:K}=Promise.withResolvers();return _t(`${y} \u2014 ${x}`,[{value:"yes",label:"yes"},{value:"no",label:"no"}],b=>K(b==="yes"),()=>K(!1)),$},input:y=>{let{promise:x,resolve:$}=Promise.withResolvers();return re("prompt",y),N(),nn=K=>{nn=void 0,re("prompt",void 0),$(K),N()},x},notify:(y,x)=>{x==="error"?hn(y):E("mcp",y)},setStatus:(y,x)=>{x===void 0?Am.delete(y):Am.set(y,x),re("note",[...Am.values()].join(" | ")||void 0),N()},setWidget:(y,x)=>{f(y,x),N()}});l.bindExtensions({uiContext:g,mode:"print",onError:y=>hn(`${y.event}: ${y.error}`)}).catch(y=>hn(y instanceof Error?y.message:String(y)))};$d(v);let zr=new w_,BP={invalidate:()=>r.invalidate(),render:l=>{let g=zr.render(Math.max(20,l)).length;return r.viewportHeight=Math.max(1,Math.max(8,t.rows)-g),r.render(l)},handleMouse:l=>{if(Ad(l))return jm(),{handled:!0};let g=l.type==="wheel"?l.wheelDelta??0:0;if(g!==0)return r.scrollOffset=Math.max(0,r.scrollOffset-g*3),N(),{handled:!0}}},zP=new k_(BP,{follow:"none",overscroll:"contain"}),ui=new E_([{component:zP,grow:1,shrink:1},{component:zr,grow:0,shrink:0,basis:"auto"}]),kd="",HP=()=>`${_n?"picker":"dock"}|${[...p.keys()].join(",")}`;Pm=()=>{let l=HP();if(l===kd)return;kd=l,zr.clear();for(let y of p.values())zr.addChild(new Tm(y));let g=_n;if(g){let y=bd,x=wd,$=Id;zr.addChild({render:K=>FP(g,y,K,x,$),invalidate:()=>{}})}else zr.addChild(ie);ui.invalidate()},Pm();let Td={focused:!1,invalidate(){r.invalidate(),ie.invalidate(),_n?.invalidate(),ui.invalidate()},[CP]:()=>A_(ui),render:l=>ui.render(l),handleMouse(l){if(Ad(l))return jm(),{handled:!0}},handleInput(l){c.handleInput(l)}};n.setLayoutRoot(Td),n.setFocus(Td);let It=0,zn="",Mm=!1,gr=!1,Om,Hr="",vd=0,Ko=!1,mi=Date.now(),ci=!1,pi=new Map,Ed=l=>{if(l.type==="agent_start"||l.type==="turn_start")l.type==="agent_start"&&uf(),o.live||o.beginRun(),zn="",gr=!1,Ko=!1,mi=Date.now(),Hr="";else if(l.type==="message_update"&&l.assistantMessageEvent.type==="thinking_delta"){gr=!0,Hr===""&&(vd=Date.now()),Hr+=l.assistantMessageEvent.delta;let g=`think-${It}`,y=r.items.find($=>$.id===g),x=Hr.split(`
|
|
123
123
|
`).slice(-6).join(`
|
|
124
124
|
`);y?y.body=x:r.items.push({id:g,kind:"note",title:"thinking",body:x})}else if(l.type==="message_update"&&l.assistantMessageEvent.type==="thinking_end"){let g=`think-${It}`,y=r.items.find(x=>x.id===g);if(y){let x=Math.max(1,Math.round((Date.now()-vd)/1e3));y.title="thought",y.body=`${x}s \xB7 ${Hr.length} chars of reasoning`}Hr=""}else if(l.type==="message_update"&&l.assistantMessageEvent.type==="text_delta"){gr=!0,zn+=l.assistantMessageEvent.delta;let g=`live-${It}`,y=r.items.find(x=>x.id===g);y?y.body=zn:r.items.push({id:g,kind:"assistant",title:"HowToFix",body:zn})}else if(l.type==="tool_execution_start"){pi.set(l.toolCallId,l.args),gr=!1,Ko=!1,mi=Date.now();let g=`tool-${l.toolCallId}`,y=jo(l.toolName,l.args),x=r.items.find($=>$.id===g);if(x?(x.kind="tool",x.title=l.toolName,x.body=y,x.live=!0):r.items.push({id:g,kind:"tool",title:l.toolName,body:y,live:!0}),Om=l.toolName,l.toolName==="task"){let $=en.filter(K=>K.status==="queued"||K.status==="running");re("note",$.map(K=>`${K.agent} ${K.status}`).join(" | ")||"agent running")}}else if(l.type==="tool_execution_update"){let g=DP(l.toolName,l.partialResult);if(g){let y=`tool-${l.toolCallId}`,x=r.items.find(K=>K.id===y);x?x.panel=g:r.items.push({id:y,kind:"tool",title:l.toolName,body:jo(l.toolName,pi.get(l.toolCallId)),panel:g,live:!0});let $=Em(l.toolName,l.partialResult);$&&G!==$.name&&xe($),N()}}else if(l.type==="tool_execution_end"){o.percent=_o(v);let g=r.items.find(R=>R.id===`tool-${l.toolCallId}`);g&&(g.live=!1,g.body=jo(l.toolName,pi.get(l.toolCallId))),pi.delete(l.toolCallId),Om=void 0,gr=!0,Ko=!1,ai.set(l.toolName,(ai.get(l.toolName)??0)+1),l.isError&&Rm.add(l.toolName),WP();let y=FS(l.toolName,l.result),x=jS(l.toolName,l.result),$=Em(l.toolName,l.result),K=$?ii($):void 0;$&&G!==$.name&&xe($);let b=r.items.find(R=>R.id===`tool-${l.toolCallId}`),k=xm(l.toolName,l.result,l.isError);b?(b.kind="result",b.call=b.body,b.body=k,b.live=!1,y.length>0&&(b.detail=y),x.length>0&&(b.full=x),K&&(b.panel=K)):r.items.push({id:`tool-${l.toolCallId}`,kind:"result",title:l.toolName,body:k,...y.length>0?{detail:y}:{},...x.length>0?{full:x}:{},...K?{panel:K}:{}}),(l.toolName==="bash"||l.toolName==="powershell"||l.toolName==="edit"||l.toolName==="write")&&i()}else if(l.type==="compaction_start"){gr=!0;let g=l.reason==="manual"?"on request":"context is nearly full",y=r.items.find(K=>K.id===`compact-${It}`),x="compacting context",$=`${g} \xB7 summarizing the older turns`;y?(y.title=x,y.body=$):r.items.push({id:`compact-${It}`,kind:"note",title:x,body:$,live:!0}),re("note","compacting context")}else if(l.type==="compaction_end"){let g=r.items.find(K=>K.id===`compact-${It}`),y=l.result,x="compacted",$;if(l.aborted)$="cancelled";else if(l.errorMessage)$=`failed: ${l.errorMessage}`;else if(y){let K=Math.round(y.tokensBefore/1e3),b=y.estimatedTokensAfter!==void 0?Math.round(y.estimatedTokensAfter/1e3):void 0,k=y.estimatedTokensAfter!==void 0?y.tokensBefore-y.estimatedTokensAfter:void 0,R=k!==void 0&&k<2e3;$=b!==void 0?`${K}k \u2192 ${b}k tokens \xB7 older turns summarized${R?`
|
|
125
|
-
this freed almost nothing \u2014 the window may be too small for this work`:""}`:`${K}k tokens \xB7 older turns summarized`}else $="nothing to compact";g?(g.title=x,g.body=$,g.live=!1):r.items.push({id:`compact-${It}`,kind:"note",title:x,body:$}),o.percent=_o(v),re("note",void 0)}else if(l.type==="message_end"&&l.message.role==="assistant"){let g=r.items.find(y=>y.id===`live-${It}`);g&&(g.id=`done-${It}`),It+=1,zn="",o.percent=_o(v)}else if(l.type==="agent_settled"){if(o.live=!1,s(rn),rn="",re("run",void 0),Mm){let g=r.items.find(y=>y.id===`live-${It}`);g?(g.id=`stopped-${It}`,g.title="stopped",g.body=zn.trim()||"(no output)",g.live=!1):r.items.push({id:`stopped-${It}`,kind:"note",title:"stopped",body:"run cancelled"}),It+=1,zn="",E("stopped","run cancelled by Esc"),Mm=!1}o.percent=_o(v),RP(e.cwd).then(g=>{g!==null&&(o.git=g,N())}),c.disableSubmit=!1}else l.type==="thinking_level_changed"?o.thinking=l.level:l.type==="auto_retry_start"&&re("note",`retry ${l.attempt}/${l.maxAttempts}`);N()},Cm=v.subscribe(Ed),Sd=setInterval(()=>{let l=I!==void 0&&Date.now()<P;if((ci||v.isStreaming||o.settling()||r.entering()||_n||l)&&N(),(ci||v.isStreaming)&&!gr&&!Ko&&Date.now()-mi>
|
|
125
|
+
this freed almost nothing \u2014 the window may be too small for this work`:""}`:`${K}k tokens \xB7 older turns summarized`}else $="nothing to compact";g?(g.title=x,g.body=$,g.live=!1):r.items.push({id:`compact-${It}`,kind:"note",title:x,body:$}),o.percent=_o(v),re("note",void 0)}else if(l.type==="message_end"&&l.message.role==="assistant"){let g=r.items.find(y=>y.id===`live-${It}`);g&&(g.id=`done-${It}`),It+=1,zn="",o.percent=_o(v)}else if(l.type==="agent_settled"){if(o.live=!1,s(rn),rn="",re("run",void 0),Mm){let g=r.items.find(y=>y.id===`live-${It}`);g?(g.id=`stopped-${It}`,g.title="stopped",g.body=zn.trim()||"(no output)",g.live=!1):r.items.push({id:`stopped-${It}`,kind:"note",title:"stopped",body:"run cancelled"}),It+=1,zn="",E("stopped","run cancelled by Esc"),Mm=!1}o.percent=_o(v),RP(e.cwd).then(g=>{g!==null&&(o.git=g,N())}),c.disableSubmit=!1}else l.type==="thinking_level_changed"?o.thinking=l.level:l.type==="auto_retry_start"&&re("note",`retry ${l.attempt}/${l.maxAttempts}`);N()},Cm=v.subscribe(Ed),Sd=setInterval(()=>{let l=I!==void 0&&Date.now()<P;if((ci||v.isStreaming||o.settling()||r.entering()||_n||l)&&N(),(ci||v.isStreaming)&&!gr&&!Ko&&Date.now()-mi>D_){Ko=!0;let g=Om,y=Math.round((Date.now()-mi)/1e3);re("note",g?`${g} has been running for ${y}s \u2014 it may be blocked; esc cancels`:`no answer yet after ${y}s \u2014 the provider may be stalled; ctrl+c cancels`),N()}},j_);Sd.unref?.();let Pd=async l=>{Uo?.(),Uo=void 0,Cm(),Gt&&AS(Gt,v.getSessionStats().sessionId),No=void 0,Wt=0,v.dispose(),v=l.session,It=0,zn="",r.items=[],r.scrollOffset=0,l.note&&r.items.push({id:"note",kind:"note",title:"note",body:l.note}),r.items.push(...bm(v.state.messages)),o.model=l.modelLabel.split("/").at(-1)||"no-model",o.thinking=v.thinkingLevel,o.percent=_o(v),o.abandonAnimations(),re("tally",void 0),re("run",void 0),c.setAutocompleteProvider(new EP(dd(v),e.cwd)),c.disableSubmit=!1,$d(v),Cm=v.subscribe(Ed),N()},li=()=>{He||(He=!0,clearInterval(Sd),Cm(),v.dispose(),n.stop(),process.stdout.write("\x1B[0m"),process.exit(0))},Rd=l=>{r.items.push({id:`you-${Date.now()}`,kind:"user",title:"you",body:l}),re("tally",void 0),ai.clear(),Rm.clear(),re("run","thinking"),o.beginRun(),N(),c.disableSubmit=!1;let g=tc(l,e.cwd);rn=l,ci=!0;let y=v.isStreaming?v.prompt(g,{streamingBehavior:"steer"}):v.prompt(g);ci=!1,y.catch(x=>hn(x instanceof Error?x.message:String(x)))},Lm=l=>{let g=l.trim();if(g){if(nn){let y=nn;nn=void 0,c.setText(""),y(g);return}if(c.setText(""),c.addToHistory(g),g.startsWith("!")){let y=g.slice(1).trim();if(!y)return;r.items.push({id:`sh-${Date.now()}`,kind:"tool",title:"$",body:y}),re("run","shell"),N(),v.executeBash(y,x=>{re("run",`shell \xB7 ${x.length} bytes`),N()}).then(x=>{let $=x.output.trim();r.items.push({id:`sh-out-${Date.now()}`,kind:x.exitCode===0?"result":"error",title:`exit ${x.exitCode??"?"}`,body:$||"(no output)"}),re("tally",void 0),N()}).catch(x=>hn(x instanceof Error?x.message:String(x)));return}if(g.startsWith("/")){VP(g);return}Rd(g)}};c.onSubmit=Lm;let Fm=0,jm=()=>{uS().then(l=>{l.ok?c.insertTextAtCursor(l.text):E("paste",l.reason),N()}).catch(l=>{E("paste",`could not read the clipboard: ${l instanceof Error?l.message:String(l)}`),N()})},Ad=l=>mS()&&l.type==="press"&&l.button==="right";n.addInputListener(l=>{if(Ke){if(jt(l,"escape"))return Sm(),{consume:!0};let y=SP(),x=y.matches(l,"tui.select.up"),$=y.matches(l,"tui.select.down");if(x||$){let b=Ke.getTreeList().getSelectedNode()?.entry.id,k=Dt(),R=b===void 0?-1:k.indexOf(b);if(x?R===0:R===k.length-1)return N(),{consume:!0}}return Ke.handleInput(l),N(),{consume:!0}}if(z&&C&&jt(l,"escape"))return ee?(ee=!1,E("workflow","panel keys off \u2014 the editor has the keyboard")):A.expanded?(A.expanded=!1,E("workflow","collapsed the drill-in")):(Qe(),E("workflow","panel unpinned; the run is still in the transcript")),De(),N(),{consume:!0};if(_n)return _n.handleInput(l),N(),{consume:!0};if(jt(l,"escape")){if(v.isStreaming)return Mm=!0,v.abort(),re("note","stopping"),N(),{consume:!0};let y=Date.now();if(c.getText().length===0&&y-Fm<600)return Fm=0,hd(),{consume:!0};Fm=y;return}if(jt(l,"ctrl+c"))return v.isStreaming?(v.abort(),re("note","stopping"),N()):c.getText().length>0?(c.setText(""),re("note","draft cleared \u2014 ctrl+c again quits"),N()):li(),{consume:!0};if(jt(l,"ctrl+d")&&c.getText().length===0)return li(),{consume:!0};let g=Math.max(1,r.viewportHeight-1);if(jt(l,"pageUp"))return r.scrollOffset+=g,N(),{consume:!0};if(jt(l,"pageDown"))return r.scrollOffset=Math.max(0,r.scrollOffset-g),N(),{consume:!0};if(jt(l,"home"))return r.scrollOffset=Number.MAX_SAFE_INTEGER,N(),{consume:!0};if(jt(l,"end"))return r.scrollOffset=0,N(),{consume:!0};if(jt(l,"ctrl+v"))return jm(),{consume:!0};if(jt(l,"ctrl+l"))return r.scrollOffset=0,n.scrollToBottom(),N(),{consume:!0};if(jt(l,"ctrl+e")){let y=[...r.items].reverse().find(x=>(x.full?.length??0)>0);return y?(y.expanded=y.expanded!==!0,N(),{consume:!0}):(E("expand","nothing to expand in this transcript yet"),{consume:!0})}if(jt(l,"ctrl+o")&&!v.isStreaming)return r.items=[{id:"cleared",kind:"note",title:"bench",body:"screen cleared. session history is still stored."}],N(),{consume:!0};if(jt(l,bP)&&z&&C)return ee=!ee,E("workflow",ee?"panel keys active \u2014 Esc gives the keyboard back":"panel keys off \u2014 the editor has the keyboard"),De(),N(),{consume:!0};if(ee&&z&&C){let y=gP(l);if(y){let x=Fo(C,Date.now());if(y==="stop")return U?(U(),U=null,E("workflow","stopping the run \u2014 in-flight agents resolve as null")):E("workflow","the run has already finished"),{consume:!0};if(y==="save"){let $=IP(ye,Km);return E("workflow",$.ok?`saved ${$.path}`:$.reason),N(),{consume:!0}}return Object.assign(A,hP(A,y,x)),De(),N(),{consume:!0}}}});let Dm=l=>{let g=y=>{re("prompt",`API key for ${y}. Paste it, then press enter.`),N();let x=nn;nn=$=>{nn=x;let K=$.trim();if(!K){re("prompt",void 0),N();return}v.modelRuntime.setRuntimeApiKey(y,K).then(()=>E("login",`saved API key for ${y}`),b=>E("login",b instanceof Error?b.message:String(b)))}};if(l){g(l);return}v.modelRuntime.getAvailable().then(y=>{let x=[...new Set(y.map($=>$.provider))].sort();if(x.length===0){E("login","no providers are configured; pass one explicitly, e.g. /login nrimo");return}_t("Login",x.map($=>({value:$,label:$})),g)},y=>E("login",y instanceof Error?y.message:String(y)))},Md=async(l,g)=>{let y=vP(Ve,"models.json"),x,$=!1;try{x=JSON.parse(g_(y,"utf8"))}catch(on){if(!(on instanceof Error&&"code"in on&&on.code==="ENOENT"))return`could not read ${y}; the models were not added`;x={providers:{}},$=!0}(!x.providers||typeof x.providers!="object")&&(x.providers={});let K=x.providers[l];K||(K=Bm(),x.providers[l]=K,$=!0);let b=Array.isArray(K.models)?K.models:[],k=Jm(b,g),R=xi(Vm(b,g));K.models=R.models;try{f_(Ve,{recursive:!0}),tt(y,`${JSON.stringify(x,null,2)}
|
|
126
126
|
`)}catch{return`could not write ${y}; the models were not added`}let D=!1;try{await v.modelRuntime.refresh(),D=!0}catch{D=!1}let ve=R.changed>0?`, repaired ${R.changed}`:"",et=D?"":"; restart the CLI to see them all",At=$?` (created ${y})`:"";return k===0?`all ${g.length} models were already configured${ve}${At}${et}`:`added ${k} model(s) to "${l}"${ve}${At}${et}`},di=l=>{(async()=>{if(!l){let k=await rP({onProgress:D=>{D.kind==="browser"?(wm(D.url),E("connect",["finish signing in to howtofix.id:"," a browser window is opening \u2014 approve the sign-in there",` if it did not open, visit ${D.url}`].join(`
|
|
127
127
|
`))):(wm(D.url),E("connect",["finish signing in to howtofix.id:",` 1. go to ${D.url}`,` 2. enter the code: ${D.code}`," waiting\u2026"].join(`
|
|
128
128
|
`))),N()}});if(k.ok){re("prompt",void 0),nn=void 0,di(k.token);return}let R=await wm(gi);E("connect",[`browser sign-in: ${k.message}`,"","connect with a token instead:",` 1. ${R?"the keys page is opening in your browser":`open ${gi}`}`," 2. sign in if asked, then create a key (starts with sk-)"," 3. run /connect <token>"," or /connect again, and paste the key when asked"].join(`
|
|
@@ -130,7 +130,7 @@ this freed almost nothing \u2014 the window may be too small for this work`:""}`
|
|
|
130
130
|
`)),N()})().catch(g=>{re("note",void 0),E("connect",g instanceof Error?g.message:String(g)),N()})},_m=(l,g)=>{let y=[`${l} account`];if(!g.ok)return[...y,` ${g.message}`].join(`
|
|
131
131
|
`);if(g.unlimited)y.push(" quota no limit on this token");else{let x=$=>`${$.toFixed(2)} ${g.unit}`;g.limit!==void 0&&y.push(` granted ${x(g.limit)}`),g.used!==void 0&&y.push(` spent ${x(g.used)}`),g.remaining!==void 0&&y.push(` remaining ${x(g.remaining)}`)}return y.join(`
|
|
132
132
|
`)},VP=async l=>{let[g,...y]=l.slice(1).split(/\s+/),x=y.join(" ");if(g==="quit"||g==="exit"){li();return}if(g==="help"){E("help",dd(v).map(b=>`/${b.name} ${b.description??""}`).join(`
|
|
133
|
-
`));return}if(g==="init"){let b=vP(e.cwd,"AGENTS.md");if(
|
|
133
|
+
`));return}if(g==="init"){let b=vP(e.cwd,"AGENTS.md");if(d_(b)&&x!=="force"){E("init",`AGENTS.md already exists at ${b}. run /init force to overwrite.`);return}tt(b,Ld),E("init",`wrote ${b}; asking the agent to fill it in`),await v.prompt("Read AGENTS.md, then fill it in with the real build, test, and layout facts of this repo. Keep it short.");return}if(g==="login"){Dm(x);return}if(g==="connect"){if(x.trim()){di(x.trim());return}di(""),re("prompt","paste your howtofix.id token, then press enter"),N();let b=nn;nn=k=>{nn=b,re("prompt",void 0),di(k.trim())};return}if(g==="sync"){let b=new Set((await v.modelRuntime.getAvailable()).map(on=>on.provider).filter(on=>xr(on))),k=Yr.find(on=>b.has(on));if(!k){E("sync","no howtofix.id account is connected; run /connect first");return}re("note",`re-syncing ${k} from howtofix.id`),N();let D=(await v.modelRuntime.getAuth(k))?.auth?.apiKey;if(!D){re("note",void 0),E("sync",`${k} has no usable key; run /connect to sign in again`),N();return}let ve=await yi(D);if(!ve.ok){re("note",void 0),E("sync",ve.message),N();return}let et=await Md(k,ve.models),At=await Bo(D);re("note",void 0),E("sync",`${et}
|
|
134
134
|
${_m(k,At)}`),await v.modelRuntime.refresh(),N();return}if(g==="usage"){let b=new Set((await v.modelRuntime.getAvailable()).map(et=>et.provider).filter(et=>xr(et))),k=Yr.find(et=>b.has(et));if(!k){E("usage","no howtofix.id account is connected; run /connect first");return}re("note","asking howtofix.id for the account usage"),N();let D=(await v.modelRuntime.getAuth(k))?.auth?.apiKey;if(!D){re("note",void 0),E("usage",`${k} has no usable key; run /connect to sign in again`),N();return}let ve=await Bo(D);re("note",void 0),E("usage",_m(k,ve)),N();return}if(g==="logout"){let b=await v.modelRuntime.getAvailable(),k=[...new Set(b.map(R=>R.provider))].sort();if(k.length===0){E("logout","no providers are configured");return}_t("Logout",k.map(R=>({value:R,label:R})),R=>{v.modelRuntime.logout(R).then(()=>E("logout",`logged out ${R}`),D=>E("logout",D instanceof Error?D.message:String(D)))});return}if(g==="providers"){let b=await v.modelRuntime.getAvailable(),k=[...new Set(b.map(R=>R.provider))].sort();k.sort((R,D)=>Number(xr(D))-Number(xr(R))),_t("Providers",k.map(R=>({value:R,label:R})),R=>{let D=v.modelRuntime.getModels(R);if(D.length===0){Dm(R);return}_t(R,D.map(ve=>({value:ve.id,label:ve.id})),ve=>{let et=D.find(At=>At.id===ve);et&&v.setModel(et).then(()=>{o.model=et.id,E("providers",`${R}/${et.id}`)},()=>Dm(R))})});return}if(g==="name"){if(!x){E("name","usage: /name <session name>");return}v.setSessionName(x),E("name",`session name: ${x}`);return}if(g==="update"){await yd({current:Nt,install:!0});return}if(g==="stats"){let b=v.getSessionStats(),k=v.getContextUsage(),R=D=>Number.isFinite(D)?String(D):"\u2014";E("stats",[`session ${b.sessionId}`,b.sessionFile?`file ${b.sessionFile}`:"not persisted",`messages ${R(b.totalMessages)} (user ${R(b.userMessages)}, assistant ${R(b.assistantMessages)}, tools ${R(b.toolCalls)})`,`tokens in ${R(b.tokens.input)} out ${R(b.tokens.output)} cache ${R(b.tokens.cacheRead)}/${R(b.tokens.cacheWrite)}`,`cost $${Number.isFinite(b.cost)?b.cost.toFixed(4):"\u2014"}`,k?`context ${k.percent===null||!Number.isFinite(k.percent)?"?":`${Math.round(k.percent)}%`} of ${k.contextWindow}`:"context unknown"].join(`
|
|
135
135
|
`));return}if(g==="diff"){let b=async et=>{try{let{stdout:At}=await fd("git",et,{cwd:e.cwd,encoding:"utf8"});return At.trim()}catch{return""}},k=await b(["diff","--stat"])+`
|
|
136
136
|
|
|
@@ -138,12 +138,12 @@ ${_m(k,At)}`),await v.modelRuntime.refresh(),N();return}if(g==="usage"){let b=ne
|
|
|
138
138
|
|
|
139
139
|
`,2),ve=AE(D);E("diff",[R.trim(),ve].filter(Boolean).join(`
|
|
140
140
|
|
|
141
|
-
`)||"working tree clean");return}if(g==="copy"){let b=[...v.state.messages].reverse().find(D=>D.role==="assistant"),R=(Array.isArray(b?.content)?b.content:[]).filter(D=>D.type==="text").map(D=>D.text).join("");if(!R){E("copy","nothing to copy");return}try{await
|
|
142
|
-
`))}catch(D){E("export",`could not write ${k}: ${D instanceof Error?D.message:String(D)}`);return}E("export",`wrote ${k}`);return}if(g==="agents"){let[b="",...k]=x.split(/\s+/).filter(Boolean),R=k.join(" ").trim();if(b&&R){E("agents",await kE(b,R));return}E("agents",b?Ml(b):Al());return}if(g==="new"){let b=await e.reopen({noSession:!1});await Pd(b),E("new","started a new session");return}if(g==="resume"){let b=await
|
|
141
|
+
`)||"working tree clean");return}if(g==="copy"){let b=[...v.state.messages].reverse().find(D=>D.role==="assistant"),R=(Array.isArray(b?.content)?b.content:[]).filter(D=>D.type==="text").map(D=>D.text).join("");if(!R){E("copy","nothing to copy");return}try{await y_(R),E("copy",`copied ${R.length} characters`)}catch(D){E("copy",D instanceof Error?D.message:String(D))}return}if(g==="export"){let b=r.items.filter(D=>D.body.trim().length>0);if(b.length===0){E("export","nothing to export yet \u2014 the transcript is empty");return}let k=x_(e.cwd,x||`howtofix-session-${Date.now()}.md`),R=[`# ${at} session`,"",`model ${o.model}`,""];for(let D of b)R.push(`## ${D.title||D.kind}`,"",D.body,"");try{tt(k,R.join(`
|
|
142
|
+
`))}catch(D){E("export",`could not write ${k}: ${D instanceof Error?D.message:String(D)}`);return}E("export",`wrote ${k}`);return}if(g==="agents"){let[b="",...k]=x.split(/\s+/).filter(Boolean),R=k.join(" ").trim();if(b&&R){E("agents",await kE(b,R));return}E("agents",b?Ml(b):Al());return}if(g==="new"){let b=await e.reopen({noSession:!1});await Pd(b),E("new","started a new session");return}if(g==="resume"){let b=await b_.list(e.cwd);if(b.length===0){E("resume","no saved sessions for this folder");return}_t("Resume session",b.slice(0,30).map(k=>({value:k.path,label:k.name||`${k.id.slice(0,8)} ${k.firstMessage.slice(0,40)}`,description:`${k.modified.toISOString().slice(0,16)} ${k.messageCount} messages`})),k=>{e.reopen({sessionPath:k}).then(Pd,R=>hn(R instanceof Error?R.message:String(R)))});return}if(g==="model"){let b=await v.modelRuntime.getAvailable(),k=x?b.find(R=>`${R.provider}/${R.id}`===x||R.id===x):void 0;if(!x){_t("Select model",b.map(R=>({value:`${R.provider}/${R.id}`,label:R.id,description:R.provider})),R=>{let D=b.find(ve=>`${ve.provider}/${ve.id}`===R);D&&v.setModel(D).then(()=>{o.model=D.id,E("model",`model ${R}`)})});return}if(!k){E("model",`unknown model ${x}`);return}await v.setModel(k),o.model=k.id,E("model",`model ${k.provider}/${k.id}`);return}if(g==="thinking"){if(!x){_t("Thinking level",ld.map(b=>({value:b,label:b})),b=>{v.setThinkingLevel(b),o.thinking=b,E("thinking",`thinking ${b}`)});return}if(!ld.includes(x)){E("thinking",`thinking: ${ld.join(", ")}`);return}v.setThinkingLevel(x),o.thinking=x,E("thinking",`thinking ${x}`);return}if(g==="compact"){try{await v.compact(x||void 0),E("compact","session compacted")}catch(b){E("compact",b instanceof Error?b.message:String(b))}return}if(g==="approval"){let b=k=>{cc(k),E("approval",vi[k])};if(!x){_t("Approval mode",Xr.map(k=>({value:k,label:k,description:vi[k]})),k=>b(k));return}if(!Xr.includes(x)){E("approval",`modes: ${Xr.join(", ")}`);return}b(x);return}if(g==="tools"){let b=v.getActiveToolNames().sort();E("tools",b.length?b.join(`
|
|
143
143
|
`):"no tools enabled");return}if(g==="rewind"){hd();return}if(g==="undo"){if(!await um(e.cwd)){E("undo","not a git repository");return}let b=await PE(e.cwd);E("undo",b.ok?`undone: ${b.output}`:`undo failed: ${b.output}`),i(!0);return}if(g==="commit"){if(!um(e.cwd)){E("commit","not a git repository");return}if(!await EE(e.cwd)){E("commit","nothing to commit");return}let b=x||`howtofix: session update ${new Date().toISOString().slice(0,16)}`,k=await SE(e.cwd,b);E("commit",k.ok?k.output:`commit failed: ${k.output}`),i(!0);return}if(g==="review"){if(!(await RE(e.cwd)).trim()){E("review","no changes to review");return}Lm("Review the uncommitted changes. Report concrete issues with file evidence. Do not edit files.");return}if(g==="workflow"){if(x.trim()==="clear"){Qe(),E("workflow","cleared the pinned workflow panel");return}if(!C){E("workflow","no workflow run in this session yet");return}let b=Fo(C,Date.now()),k=b[A.selectedPhase];E("workflow",[`panel ${z?"pinned above the editor":"unpinned"}`,`phase ${A.selectedPhase+1}/${b.length}: ${k?.title??"(none)"}`,`filter: ${A.filter}${A.paused?" \xB7 paused":""}`,"keys: \u2191/\u2193 phase \xB7 Enter drill in \xB7 Esc unpin \xB7 f filter \xB7 p pause \xB7 x stop \xB7 s save","clear it with /workflow clear"].join(`
|
|
144
144
|
`));return}if(g==="plan"){if(Jv()||Zu().state==="pending"){Co(Hv(Zu())),E("plan","plan mode off \u2014 edits are allowed again");return}Co(zv(Zu())),E("plan",`plan mode armed \u2014 send your next prompt to start planning
|
|
145
145
|
plan file: ${Vv()??"(unknown)"}`);return}if(g==="goal"){let b=x.trim();if(!b){E("goal",zu(Hu()));return}let{goal:k,error:R}=ll(Hu(),"set",b,void 0,void 0);if(R){hn(R);return}ln(k),await v.sendCustomMessage({customType:pr,content:b,display:!1,details:k}),E("goal",`goal set
|
|
146
|
-
${zu(k)}`);return}if(g==="session"){let b=v.model;E("session",b?`${b.provider}/${b.id}`:"no model");return}if(g==="skills"){E("skills",pP(v.resourceLoader.getSkills().skills));return}let $=cP(l,v.resourceLoader.getSkills().skills.map(b=>b.name));if($){Rd($);return}let K=v.extensionRunner.getCommand(g??"");if(K){try{await K.handler(x,v.extensionRunner.createCommandContext())}catch(b){hn(b instanceof Error?b.message:String(b))}return}E("command",`/${g??""} is not available in this screen yet`)};Tf((l,g)=>{let{promise:y,resolve:x}=Promise.withResolvers();return _t(l,g.map($=>({value:$,label:$})),x,()=>x("cancelled")),y}),process.on("SIGTERM",li),t.setTitle(`${at} ${Nt}`),
|
|
146
|
+
${zu(k)}`);return}if(g==="session"){let b=v.model;E("session",b?`${b.provider}/${b.id}`:"no model");return}if(g==="skills"){E("skills",pP(v.resourceLoader.getSkills().skills));return}let $=cP(l,v.resourceLoader.getSkills().skills.map(b=>b.name));if($){Rd($);return}let K=v.extensionRunner.getCommand(g??"");if(K){try{await K.handler(x,v.extensionRunner.createCommandContext())}catch(b){hn(b instanceof Error?b.message:String(b))}return}E("command",`/${g??""} is not available in this screen yet`)};Tf((l,g)=>{let{promise:y,resolve:x}=Promise.withResolvers();return _t(l,g.map($=>({value:$,label:$})),x,()=>x("cancelled")),y}),process.on("SIGTERM",li),t.setTitle(`${at} ${Nt}`),L_(),n.start(),n.requestRender(!0),e.initialPrompt&&Lm(e.initialPrompt),await new Promise(()=>{})}var PP,ld,CP,fd,km,Tm,vm,M_,O_,nn,j_,D_,NP=u(()=>{Go();cS();zl();MS();nc();NS();Js();XS();oP();id();Vs();dc();rd();uP();Zs();ql();Xm();mP();Nn();lP();$P();Ol();Jo();rc();Ju();hl();TP();Hn();PP={borderColor:()=>"",selectList:{selectedPrefix:e=>ne(e,_.accent),selectedText:e=>ne(e,_.text,{bold:!0}),description:e=>ne(e,_.mute),scrollInfo:e=>ne(e,_.dim),noMatch:e=>ne(e,_.mute)}},ld=["off","minimal","low","medium","high","xhigh","max"],CP=Symbol.for("@earendil-works/pi-tui/layout-node");fd=l_(p_);km=class{folder;model;git;percent=0;meter=new fm(0);activity=sP();live=!1;activitySince=Date.now();thinking="medium";cubence="";constructor(t,n){this.folder=h_(t),this.model=n.split("/").at(-1)||"no-model",this.git=""}invalidate(){}settling(){return this.meter.moving}meterValue(){return this.meter.value!==this.percent&&this.meter.set(this.percent),this.meter.step()}beginRun(){this.live=!0,this.activitySince=Date.now()}waitedMs(){return Date.now()-this.activitySince}abandonAnimations(){this.meter.snap(this.percent)}render(t){let n=Date.now(),r=this.percent===0&&this.meter.value===0?0:this.meterValue(),o=WS(this.model,this.thinking,this.folder,this.git),s=[si(`${BS(o,this.live?ed():"",this.live?this.waitedMs():void 0)} ${zS(r,this.cubence)}`,t)],i=Zv();i&&s.push(si(ne(i,_.warn),t));let c=jv(Hu());c&&s.push(si(ne(c,_.accent),t));let p=aP(this.activity,ed(),n),f=this.live?wS(p,{base:Gl(this.waitedMs(),_.mute,_.warn,_.bad),bright:_.text,charMs:45},n):ne(p,Gl(this.waitedMs(),_.mute,_.warn,_.bad));return s.push(si(f,t)),s}},Tm=class{constructor(t){this.draw=t}draw;render(t){return this.draw(t)}invalidate(){}},vm=class{constructor(t,n){this.editor=t;this.hud=n}editor;hud;focused=!1;invalidate(){this.editor.invalidate()}render(t){let n=Math.max(10,t-4),r=this.editor.render(n).filter(c=>$m(c)>0),o=r.length>0?r:[""],s="\u2500".repeat(Math.max(0,t-2)),i=o.map(c=>{let p=Math.max(0,n-$m(c));return`\u2502 ${c}${" ".repeat(p)} \u2502`});return[`\u250C${s}\u2510`,...i,`\u2514${s}\u2518`,...this.hud.render(t)]}handleInput(t){this.editor.handleInput(t)}},M_=["deepseek","qwen","claude","gpt-5","gpt-4","gemini","glm","mimo","kimi","llama"],O_=/(image|embedding|embed|whisper|tts|audio|video|rerank|moderation|dall-e|stable-diffusion|sora)/i;j_=1e3/30,D_=45e3});Go();var Fd={off:!0,minimal:!0,low:!0,medium:!0,high:!0,xhigh:!0,max:!0},jd={suggest:!0,"auto-edit":!0,"full-auto":!0};function fi(e,t,n){let r=e[t];if(r?.includes("="))return r.slice(r.indexOf("=")+1);let o=e[t+1];if(!o||o.startsWith("-"))throw new Error(`${n} needs a value`);return e.splice(t+1,1),o}function Dd(e){let t={print:!1,continueSession:!1,noSession:!1,help:!1,version:!1,update:!1,checkUpdate:!1,prompt:""},n=[],r=[...e];for(let o=0;o<r.length;o++){let s=r[o]??"";if(s==="--"){n.push(...r.slice(o+1));break}if(s==="-h"||s==="--help")t.help=!0;else if(s==="-v"||s==="--version")t.version=!0;else if(s==="-p"||s==="--print")t.print=!0;else if(s==="-c"||s==="--continue")t.continueSession=!0;else if(s==="--no-session")t.noSession=!0;else if(s==="--update")t.update=!0;else if(s==="--check-update")t.checkUpdate=!0;else if(s==="-r"||s==="--resume")t.continueSession=!0;else if(s==="--session"||s.startsWith("--session="))t.sessionPath=fi(r,o,"--session");else if(s==="-m"||s==="--model"||s.startsWith("--model="))t.model=fi(r,o,"--model");else if(s==="--thinking"||s.startsWith("--thinking="))t.thinking=fi(r,o,"--thinking");else if(s==="--approval"||s.startsWith("--approval="))t.approval=fi(r,o,"--approval");else{if(s.startsWith("-"))throw new Error(`unknown option ${s}`);n.push(s)}}if(t.thinking&&!Fd[t.thinking])throw new Error(`thinking must be one of: ${Object.keys(Fd).join(", ")}`);if(t.approval&&!jd[t.approval])throw new Error(`approval must be one of: ${Object.keys(jd).join(", ")}`);if(t.prompt=n.join(" ").trim(),t.update&&t.checkUpdate)throw new Error("--update installs; --check-update only looks. pick one");if((t.update||t.checkUpdate)&&(t.print||t.continueSession||t.sessionPath||t.prompt))throw new Error("--update and --check-update act on the installation, not a session; they take no prompt");if(t.continueSession&&t.noSession)throw new Error("--continue and --no-session cannot be combined");if(t.sessionPath&&t.noSession)throw new Error("--session and --no-session cannot be combined");if(t.sessionPath&&t.continueSession)throw new Error("--session and --continue cannot be combined");if(t.print&&(t.continueSession||t.sessionPath))throw new Error("--print runs one prompt in a throwaway session; it cannot be combined with --continue or --session");if(t.sessionPath&&!t.sessionPath.endsWith(".jsonl"))throw new Error(`--session expects a session file, got '${t.sessionPath}'`);return t}function Nm(){return`${at} ${Nt}
|
|
147
147
|
coding agent. layout is a workbench, not a chat log.
|
|
148
148
|
|
|
149
149
|
usage:
|
|
@@ -190,7 +190,7 @@ an npm install checks for a newer release at startup and can install it itself;
|
|
|
190
190
|
/update does it on demand. config and sessions live in ~/.howtofix/agent.
|
|
191
191
|
/connect signs in to howtofix.id in your browser, and falls back to a pasted
|
|
192
192
|
token; /login takes another provider's key.
|
|
193
|
-
`}Go();Nn();function
|
|
193
|
+
`}Go();Nn();function __(){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 N_(){process.stdout.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e})}async function q_(){N_(),Gm();let e=__();if("error"in e){console.error(`${at}: ${e.error}`),process.exitCode=1;return}let t=e.cwd,{repairGatewayModels:n,ensureGatewaySettings:r}=await Promise.resolve().then(()=>(Xm(),zd)),{AGENT_DIR:o}=await Promise.resolve().then(()=>(Nn(),_d)),s=n(o);s>0&&console.error(`${at}: repaired ${s} howtofix model(s) that the gateway would have rejected`),r(o)&&console.error(`${at}: set httpIdleTimeoutMs in settings.json so a stalled provider recovers instead of hanging`);let i;try{i=Dd(process.argv.slice(2))}catch(G){let ee=G instanceof Error?G.message:String(G);console.error(`${at}: ${ee}
|
|
194
194
|
${Nm()}`),process.exitCode=2;return}if(i.help){console.log(Nm());return}if(i.version){console.log(`${at} ${Nt}`);return}if(i.update||i.checkUpdate){let{PACKAGE_NAME:G,checkForUpdate:ee,installUpdate:ye,isInstalledCopy:De}=await Promise.resolve().then(()=>(wi(),bi)),Qe=await ee(Nt);if(!Qe.latest){console.error(`${at}: ${Qe.message}`),process.exitCode=i.update?1:0;return}if(console.log(Qe.message),i.checkUpdate||!Qe.available)return;if(!De()){console.error(`${at}: this copy was not installed by npm, so npm cannot replace it. install it with: npm install -g ${G}`),process.exitCode=1;return}let xe=await ye({version:Qe.latest});console.log(xe.message),xe.ok||(process.exitCode=1);return}if(i.print&&!i.prompt){console.error(`${at}: --print needs a prompt`),process.exitCode=2;return}let{expandFileReferences:c}=await Promise.resolve().then(()=>(nc(),sf)),{isApprovalMode:p,setApprovalMode:f}=await Promise.resolve().then(()=>(Jo(),wf)),{openSession:w}=await Promise.resolve().then(()=>(aS(),iS));f(i.approval&&p(i.approval)?i.approval:"full-auto");let I=G=>w({cwd:t,model:i.model,thinking:i.thinking,continueSession:G.continueSession??!1,noSession:G.noSession??!1,sessionPath:G.sessionPath}),P=await I({continueSession:i.continueSession,sessionPath:i.sessionPath,noSession:i.noSession||i.print});if(i.print){P.note&&console.error(P.note);try{await P.session.prompt(c(i.prompt,t));let G=P.session.getLastAssistantText()??"";process.stdout.write(G.endsWith(`
|
|
195
195
|
`)?G:`${G}
|
|
196
|
-
`);let ee=P.session.state.messages.at(-1);ee?.role==="assistant"&&((ee.stopReason==="error"||ee.stopReason==="aborted"||ee.errorMessage)&&(process.exitCode=1),process.exitCode===1&&ee.errorMessage&&console.error(`${at}: ${ee.errorMessage}`))}finally{P.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${at}: interactive mode needs a terminal. use --print for pipes.`),P.dispose(),process.exitCode=2;return}let{runWorkbench:A}=await Promise.resolve().then(()=>(NP(),_P)),{autoUpdateEnabled:C,isInstalledCopy:U}=await Promise.resolve().then(()=>(wi(),bi)),z=U()&&C(`${o}/settings.json`);await A({cwd:t,modelLabel:P.modelLabel,session:P.session,initialPrompt:i.prompt||void 0,note:P.note,update:z?{current:Nt,install:!0}:void 0,reopen:I})}
|
|
196
|
+
`);let ee=P.session.state.messages.at(-1);ee?.role==="assistant"&&((ee.stopReason==="error"||ee.stopReason==="aborted"||ee.errorMessage)&&(process.exitCode=1),process.exitCode===1&&ee.errorMessage&&console.error(`${at}: ${ee.errorMessage}`))}finally{P.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${at}: interactive mode needs a terminal. use --print for pipes.`),P.dispose(),process.exitCode=2;return}let{runWorkbench:A}=await Promise.resolve().then(()=>(NP(),_P)),{autoUpdateEnabled:C,isInstalledCopy:U}=await Promise.resolve().then(()=>(wi(),bi)),z=U()&&C(`${o}/settings.json`);await A({cwd:t,modelLabel:P.modelLabel,session:P.session,initialPrompt:i.prompt||void 0,note:P.note,update:z?{current:Nt,install:!0}:void 0,reopen:I})}q_().catch(e=>{let t=e instanceof Error?e.message:String(e);console.error(`${at}: ${t}`),process.exitCode=1});
|