@kodax-ai/kodax 0.7.75 → 0.7.76

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.
Files changed (50) hide show
  1. package/CHANGELOG.md +27 -5
  2. package/README.md +7 -1
  3. package/README_CN.md +6 -1
  4. package/dist/chunks/{agent-LVZJB2GQ.js → agent-7X5CFET2.js} +1 -1
  5. package/dist/chunks/argument-completer-3NHIKB4N.js +2 -0
  6. package/dist/chunks/{chunk-SB75RNNR.js → chunk-4PWPNCNK.js} +2 -2
  7. package/dist/chunks/{chunk-737LI7OS.js → chunk-7FJNLJLF.js} +4 -4
  8. package/dist/chunks/chunk-COQYLD4U.js +5 -0
  9. package/dist/chunks/{chunk-Q65EAOX6.js → chunk-D3T24FJW.js} +2 -2
  10. package/dist/chunks/{chunk-F7AIEHSS.js → chunk-EI4JBQKL.js} +2 -2
  11. package/dist/chunks/{chunk-QRBWNYFV.js → chunk-HGT6WQ24.js} +4 -4
  12. package/dist/chunks/{chunk-OJQQRLZJ.js → chunk-HS3XHF3R.js} +2 -2
  13. package/dist/chunks/{chunk-BN3W2DQY.js → chunk-IDCGNQ4H.js} +1 -1
  14. package/dist/chunks/{chunk-6ZMKX3XF.js → chunk-KAY2XLCP.js} +2 -2
  15. package/dist/chunks/{chunk-5WSOB34U.js → chunk-OD6LVXU6.js} +2 -2
  16. package/dist/chunks/{chunk-UJRRZINL.js → chunk-OSF3H4RR.js} +2 -2
  17. package/dist/chunks/{chunk-G5VW55T4.js → chunk-PXKSE54E.js} +1 -1
  18. package/dist/chunks/{chunk-4PVSDE5L.js → chunk-RDXRM3UI.js} +1 -1
  19. package/dist/chunks/{chunk-N6M2LYEP.js → chunk-SMT2JSM3.js} +1 -1
  20. package/dist/chunks/{chunk-DEHOFNQA.js → chunk-TGMBHGZO.js} +2 -2
  21. package/dist/chunks/{chunk-QSMXI4MH.js → chunk-VWSLC2WO.js} +1 -1
  22. package/dist/chunks/{chunk-OGL227XV.js → chunk-Y3AMP22L.js} +1 -1
  23. package/dist/chunks/compaction-config-7J2XE35D.js +2 -0
  24. package/dist/chunks/{construction-bootstrap-3TQWTHSQ.js → construction-bootstrap-5F5KF2BZ.js} +1 -1
  25. package/dist/chunks/{dist-D3EPVAOZ.js → dist-2RA7LSH3.js} +1 -1
  26. package/dist/chunks/{dist-ZJFTZJ55.js → dist-URKXBOC6.js} +1 -1
  27. package/dist/chunks/host-RKZ2OGFT.js +2 -0
  28. package/dist/chunks/run-manager-7RM4HEH6.js +2 -0
  29. package/dist/chunks/{utils-HMVP6XPH.js → utils-X3TEH6IO.js} +1 -1
  30. package/dist/index.js +1 -1
  31. package/dist/kodax_cli.js +8 -8
  32. package/dist/provider-capabilities.json +35 -7
  33. package/dist/runtime-worker.js +7 -7
  34. package/dist/sdk-a2a.js +1 -1
  35. package/dist/sdk-agent.js +1 -1
  36. package/dist/sdk-coding.js +1 -1
  37. package/dist/sdk-experimental-memory.js +1 -1
  38. package/dist/sdk-llm.js +1 -1
  39. package/dist/sdk-mcp.js +1 -1
  40. package/dist/sdk-media.js +1 -1
  41. package/dist/sdk-repl.js +1 -1
  42. package/dist/sdk-runtime.js +1 -1
  43. package/dist/sdk-session.js +1 -1
  44. package/dist/sdk-skills.js +1 -1
  45. package/package.json +1 -1
  46. package/dist/chunks/argument-completer-GHWEWPVQ.js +0 -2
  47. package/dist/chunks/chunk-6YUDR7WN.js +0 -5
  48. package/dist/chunks/compaction-config-L2YZK7Q3.js +0 -2
  49. package/dist/chunks/host-KHDXYFVG.js +0 -2
  50. package/dist/chunks/run-manager-CD24OO4V.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{$ as ws,A as fs,B as Vn,E as Xo,G as ms,K as ps,M as Vo,U as be,Z as gs,aa as hs,ba as ys,u as cs,w as He,y as ds,z as us}from"./chunk-SB75RNNR.js";import{a as vs}from"./chunk-4PVSDE5L.js";import{Fa as ss,Ga as is,Ka as as,Ma as ls}from"./chunk-DEHOFNQA.js";import{i as Go}from"./chunk-N6M2LYEP.js";import{A as ns,D as $e,J as Fe,m as zo,n as qo,o as je,q as lo,r as Ko,s as Zr,t as Qr,v as es,w as Xn,x as os,y as co}from"./chunk-UJRRZINL.js";import{Aa as rs,L as Jr,za as ts}from"./chunk-5WSOB34U.js";import{Bc as se,H as Br,Hb as Kn,Ib as Bo,Lb as Kr,Qc as Vr,Sc as Yr,mb as Gr,ob as zr,pb as qr,sb as qn,xa as Ho,zc as Xr}from"./chunk-737LI7OS.js";import{C as Er,Ma as Bn,Na as We,Oa as Oe}from"./chunk-Q65EAOX6.js";import{Dd as Ue,Ed as Fr,Fa as Cr,Fb as Ur,Ga as Ir,Ha as Gn,Id as zn,Sd as Fo,dd as jr,he as Hr,k as No}from"./chunk-QSMXI4MH.js";import{H as Lr,I as Mr,J as Wr,W as Se,X as De,aa as Or,b as q,ca as Uo,e as Ne,ea as jo,f as B,fa as Nr,g as D,ga as Dr,h as Do,q as Tr,r as _r,w as Pr}from"./chunk-OGL227XV.js";import{a,b as Hn,d as Ka}from"./chunk-ONUPGMER.js";var Cs=Hn((Tm,Es)=>{"use strict";Es.exports=a(function(o){return o.map(function(n){return n===""?"''":n&&typeof n=="object"?n.op.replace(/(.)/g,"\\$1"):/["\s\\]/.test(n)&&!/'/.test(n)?"'"+n.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(n)?'"'+n.replace(/(["\\$`!])/g,"\\$1")+'"':String(n).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")}).join(" ")},"quote")});var Ws=Hn((Pm,Ms)=>{"use strict";var Ls="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",Is=new RegExp("^"+Ls+"$"),Ts="|&;()<> \\t",Ya='"((\\\\"|[^"])*?)"',Ja="'((\\\\'|[^'])*?)'",Za=/^#$/,_s="'",Ps='"',Yn="$",xe="",Qa=4294967296;for(Jn=0;Jn<4;Jn++)xe+=(Qa*Math.random()).toString(16);var Jn,el=new RegExp("^"+xe);function ol(e,o){for(var n=o.lastIndex,t=[],r;r=o.exec(e);)t.push(r),o.lastIndex===r.index&&(o.lastIndex+=1);return o.lastIndex=n,t}a(ol,"matchAll");function nl(e,o,n){var t=typeof e=="function"?e(n):e[n];return typeof t>"u"&&n!=""?t="":typeof t>"u"&&(t="$"),typeof t=="object"?o+xe+JSON.stringify(t)+xe:o+t}a(nl,"getVar");function tl(e,o,n){n||(n={});var t=n.escape||"\\",r="(\\"+t+`['"`+Ts+`]|[^\\s'"`+Ts+"])+",i=new RegExp(["("+Ls+")","("+r+"|"+Ya+"|"+Ja+")+"].join("|"),"g"),l=ol(e,i);if(l.length===0)return[];o||(o={});var c=!1;return l.map(function(d){var u=d[0];if(!u||c)return;if(Is.test(u))return{op:u};var f=!1,m=!1,v="",k=!1,y;function $(){y+=1;var T,L,Y=u.charAt(y);if(Y==="{"){if(y+=1,u.charAt(y)==="}")throw new Error("Bad substitution: "+u.slice(y-2,y+1));if(T=u.indexOf("}",y),T<0)throw new Error("Bad substitution: "+u.slice(y));L=u.slice(y,T),y=T}else if(/[*@#?$!_-]/.test(Y))L=Y,y+=1;else{var J=u.slice(y);T=J.match(/[^\w\d_]/),T?(L=J.slice(0,T.index),y+=T.index-1):(L=J,y=u.length)}return nl(o,"",L)}for(a($,"parseEnvVar"),y=0;y<u.length;y++){var g=u.charAt(y);if(k=k||!f&&(g==="*"||g==="?"),m)v+=g,m=!1;else if(f)g===f?f=!1:f==_s?v+=g:g===t?(y+=1,g=u.charAt(y),g===Ps||g===t||g===Yn?v+=g:v+=t+g):g===Yn?v+=$():v+=g;else if(g===Ps||g===_s)f=g;else{if(Is.test(g))return{op:u};if(Za.test(g)){c=!0;var x={comment:e.slice(d.index+y+1)};return v.length?[v,x]:[x]}else g===t?m=!0:g===Yn?v+=$():v+=g}}return k?{op:"glob",pattern:v}:v}).reduce(function(d,u){return typeof u>"u"?d:d.concat(u)},[])}a(tl,"parseInternal");Ms.exports=a(function(o,n,t){var r=tl(o,n,t);return typeof n!="function"?r:r.reduce(function(i,l){if(typeof l=="object")return i.concat(l);var c=l.split(RegExp("("+xe+".*?"+xe+")","g"));return c.length===1?i.concat(c[0]):i.concat(c.filter(Boolean).map(function(d){return el.test(d)?JSON.parse(d.split(xe)[1]):d}))},[])},"parse")});var Os=Hn(Zn=>{"use strict";Zn.quote=Cs();Zn.parse=Ws()});import*as On from"fs";import*as Mo from"path";import*as Pn from"fs";import _n from"path";import s from"chalk";var Yo=["plan","accept-edits","auto","auto-in-project"];function bm(e){return e==="auto"||e==="auto-in-project"}a(bm,"isAutoMode");function Xa(e){switch(e){case"plan":return"Plan";case"accept-edits":return"Edits";case"auto":case"auto-in-project":return"Auto"}}a(Xa,"permissionModeDisplayName");var Va='[deprecated] permissionMode "auto-in-project" is now an alias for "auto" (FEATURE_092, v0.7.33). The alias will be removed in v0.7.38 \u2014 please update ~/.kodax/config.json to use "auto".';function xm(e=o=>{q({source:"repl:permission",level:"warn",message:o})}){let o=!1;return()=>{o||(o=!0,e(Va))}}a(xm,"createAutoInProjectDeprecationEmitter");var ks=Vr(),uo=new Set(ks.filter(e=>e.sideEffect==="mutates-fs"&&e.requiredParams.includes("path")).map(e=>e.name)),Ss=new Set(ks.filter(e=>e.sideEffect!=="readonly").map(e=>e.name)),$s=new Set(["npm install","npm i","npm uninstall","npm remove","npm update","npm ci","yarn add","yarn remove","yarn upgrade","pnpm add","pnpm remove","pnpm update","git clean","git reset","git checkout","git switch","git merge","git rebase","git cherry-pick","git revert","git commit","git push","git pull","rm","mv","cp","mkdir","rmdir","touch","chmod","chown","del","erase","rd","copy","move","ren","curl","wget","dd","tar","kill","pkill","killall"]),bs=new Set(["ls","cat","pwd","echo","whoami","date","which","whereis","tree","dir","type","get-childitem","get-content","select-string","get-location","where","grep","find","awk","sed","head","tail","less","more","wc","findstr","fc","git status","git diff","git log","git show","git branch","git remote","git ls-files","git rev-parse","git grep","git tag","git stash list","git describe","git config --get","node","npm","yarn","pnpm","tsc","python","pip","go","cargo","rustc"]);function xs(e){switch(e){case"plan":return new Set(["bash","write","edit","undo"]);case"accept-edits":return new Set(["bash"]);case"auto":case"auto-in-project":return new Set}}a(xs,"computeConfirmTools");function As(e){return e!==void 0&&Yo.includes(e)}a(As,"isPermissionMode");function fo(e,o){return As(e)?e:o}a(fo,"normalizePermissionMode");async function Rs(e){let o=e.resolve(e.provider),n=[];for(let t of e.efforts){if(e.signal?.aborted)break;let r=!1;try{await o.stream([{role:"user",content:"ping"}],[],"",{effort:t},{modelOverride:e.model,maxOutputTokensOverride:1,onReasoningEffortRejected:a(()=>{r=!0},"onReasoningEffortRejected"),onTextDelta:a(()=>{},"onTextDelta")},e.signal)}catch(i){n.push({effort:t,status:"error",error:i instanceof Error?i.message:String(i)});continue}r?(Ir(e.provider,e.model,t,"probed",e.now()),n.push({effort:t,status:"rejected"})):n.push({effort:t,status:"accepted"})}return n}a(Rs,"probeProviderReasoningEfforts");import rn from"fs";import di from"path";import Jo from"fs";import W from"path";import wo from"os";var Us=Ka(Os(),1);var Ns=new Set(["/dev/null","nul","NUL"]);function Qn(e){return Ns.has(e)||Ns.has(e.toLowerCase())}a(Qn,"isNullDevice");function mo(e){let o=e.trim();if(!o)return{statements:[],unparseable:!1};if(o.includes("`"))return{statements:[],unparseable:!0};let n;try{n=(0,Us.parse)(o,m=>`$${m}`)}catch{return{statements:[],unparseable:!0}}let t=[],r=[],i=[],l=[],c=null,d=!1,u=a(()=>{(i.length>0||l.length>0)&&(r.push({argv:i,redirections:l}),i=[],l=[])},"flushStage"),f=a(m=>{u(),r.length>0&&(t.push({precedingOp:c,stages:r}),r=[]),c=m},"flushStatement");for(let m=0;m<n.length;m+=1){let v=n[m];if(typeof v=="string"){i.push(v);continue}if("op"in v){let k=v.op;if(k==="&&"||k==="||"||k===";"){f(k);continue}if(k==="|"){u();continue}if(k==="&"){let y=n[m+1];if(y!==void 0&&typeof y!="string"&&"op"in y&&(y.op===">"||y.op===">>")){let $=n[m+2];if(typeof $!="string"){d=!0,m+=1;continue}l.push(Ds(`&${y.op}`,$)),m+=2;continue}d=!0;continue}if(sl(k)){let y=null,$=i[i.length-1];$!==void 0&&/^[0-9]+$/.test($)&&(y=$,i.pop());let g=n[m+1];if(typeof g!="string"){d=!0;continue}l.push(Ds(y?`${y}${k}`:k,g)),m+=1;continue}if(k==="glob"){let y=v.pattern;typeof y=="string"?i.push(y):d=!0;continue}d=!0;continue}if("comment"in v)break;d=!0}return f(null),{statements:t,unparseable:d}}a(mo,"parseBashCommand");var rl=new Set([">",">>","<","<<","<<<","&>","&>>"]),js=/^([0-9]+|&)(>>?|<<?)$/;function sl(e){return rl.has(e)||js.test(e)}a(sl,"isRedirectionOp");function Ds(e,o){let n=null,t=e,r=js.exec(e);return r&&(n=r[1],t=r[2]),{op:e,fd:n,append:t===">>"||e==="&>>",input:t==="<"||t==="<<"||e==="<<<",target:o}}a(Ds,"parseRedirection");import Ge from"node:path";var il={verbose:"switch",debug:"switch",erroraction:"value",warningaction:"value",informationaction:"value",progressaction:"value",errorvariable:"value",warningvariable:"value",informationvariable:"value",outvariable:"value",outbuffer:"value",pipelinevariable:"value",whatif:"switch",confirm:"switch",usetransaction:"switch"},po={path:"value",literalpath:"value",filter:"value",include:"value",exclude:"value"},Hs={"copy-item":ie(["path","destination"],{...po,destination:"value",container:"switch",recurse:"switch",force:"switch",passthru:"switch",credential:"value",fromsession:"value",tosession:"value"}),"move-item":ie(["path","destination"],{...po,destination:"value",force:"switch",passthru:"switch",credential:"value"}),"set-content":ie(["path","value"],{...po,value:"value",passthru:"switch",force:"switch",credential:"value",nonewline:"switch",encoding:"value",asbytestream:"switch",stream:"value"}),"add-content":ie(["path","value"],{...po,value:"value",passthru:"switch",force:"switch",credential:"value",nonewline:"switch",encoding:"value",asbytestream:"switch",stream:"value"}),"out-file":ie(["filepath","encoding"],{filepath:"value",literalpath:"value",inputobject:"value",encoding:"value",append:"switch",force:"switch",noclobber:"switch",width:"value",nonewline:"switch"}),"new-item":ie(["path"],{path:"value",name:"value",itemtype:"value",value:"value",force:"switch",credential:"value"}),ni:ie(["path"],{path:"value",name:"value",itemtype:"value",value:"value",force:"switch",credential:"value"}),"remove-item":ie(["path"],{...po,recurse:"switch",force:"switch",credential:"value",stream:"value"}),"rename-item":ie(["path","newname"],{path:"value",literalpath:"value",newname:"value",force:"switch",passthru:"switch",credential:"value"})},al={ea:"erroraction",ev:"errorvariable",wa:"warningaction",wv:"warningvariable",ia:"informationaction",infa:"informationaction",iv:"informationvariable",ov:"outvariable",ob:"outbuffer",pv:"pipelinevariable",vb:"verbose",db:"debug",wi:"whatif",cf:"confirm",usetx:"usetransaction",pspath:"literalpath",nooverwrite:"noclobber",type:"itemtype",target:"value"};function ie(e,o){return{positionals:e,parameters:{...il,...o}}}a(ie,"spec");function Dm(e){return Hs[e.toLowerCase()]!==void 0}a(Dm,"isPowerShellMutationCommand");function Bs(e){let o=vl(e[0]??""),n=Hs[o];if(!n)return Be(`unsupported PowerShell command: ${o||"<empty>"}`);let t=ll(e.slice(1),n);if(!t.complete)return Be(t.reason??"PowerShell parameter binding is incomplete");if(t.values.has("fromsession")||t.values.has("tosession"))return Be("PowerShell remoting changes the filesystem host");if((o==="new-item"||o==="ni")&&/^(?:symboliclink|junction|hardlink)$/i.test(t.values.get("itemtype")??""))return Be("PowerShell link creation has an unmodelled target relationship");if(ml(t))return Be("PowerShell path contains bracket wildcard syntax");let r=dl(o,t);return r?ul(r).some(fl)?{status:"incomplete",operations:[r],reason:"PowerShell path contains dynamic, wildcard, or array syntax"}:{status:"complete",operations:[r]}:Be("PowerShell mutation target is missing or ambiguous")}a(Bs,"analyzePowerShellMutation");function ll(e,o){let n=new Map,t=new Set,r=0,i=!1;for(let l=0;l<e.length;l+=1){let c=e[l];if(c==="--"){i=!0;continue}if(!i&&c.startsWith("-")){let u=cl(c,o);if(!u)return go(n,t,`unknown or ambiguous parameter ${c}`);if(u.kind==="switch"){let m=gl(u.inlineValue);if(m===void 0)return go(n,t,`switch ${c} has an unsupported value`);m&&t.add(u.name);continue}let f=u.inlineValue??e[l+1];if(f===void 0||u.inlineValue===void 0&&f.startsWith("-"))return go(n,t,`parameter ${c} has no bound value`);if(n.has(u.name))return go(n,t,`parameter ${c} is repeated`);n.set(u.name,f),u.inlineValue===void 0&&(l+=1);continue}for(;o.positionals[r]&&n.has(o.positionals[r]);)r+=1;let d=o.positionals[r];if(!d||n.has(d))return go(n,t,`unexpected positional argument ${c}`);n.set(d,c),r+=1}return{complete:!0,values:n,switches:t}}a(ll,"bindArguments");function cl(e,o){let n=/^--?([^:]+)(?::(.*))?$/.exec(e);if(!n)return;let t=n[1].toLowerCase(),r=al[t],i=Object.keys(o.parameters),l=r&&o.parameters[r]!==void 0?[r]:i.filter(u=>u.startsWith(t));if(l.length!==1)return;let c=l[0],d=o.parameters[c];return n[2]===void 0?{name:c,kind:d}:{name:c,kind:d,inlineValue:n[2]}}a(cl,"parseParameter");function dl(e,o){let n=Fs(o,"path","literalpath"),t=o.switches.has("force"),r=o.switches.has("whatif")?{whatIf:!0}:{};if(e==="copy-item"||e==="move-item"){if(!n)return;let l=o.values.get("destination")??wl(n);return{kind:e==="copy-item"?"copy":"move",source:n,destination:l,options:{force:t,...r,recursive:e==="copy-item"&&o.switches.has("recurse"),overwritePossible:!0}}}if(e==="rename-item"){let l=o.values.get("newname");return!n||!l||/[\\/]/.test(l)?void 0:{kind:"rename",source:n,destination:hl(n,l),options:{force:t,...r}}}if(e==="new-item"||e==="ni"){let l=o.values.get("name"),c=l?yl(o.values.get("path")??".",l):o.values.get("path"),d=o.values.get("itemtype"),u=d?{force:t,...r,itemType:d}:{force:t,...r};return c?{kind:"create",target:c,options:u}:void 0}let i=e==="out-file"?Fs(o,"filepath","literalpath"):n;if(i)return e==="remove-item"?{kind:"delete",target:i,options:{force:t,...r,recursive:o.switches.has("recurse")}}:{kind:"write",target:i,options:{force:t,...r,append:e==="add-content"||o.switches.has("append")}}}a(dl,"buildOperation");function Fs(e,...o){let n=o.map(t=>e.values.get(t)).filter(t=>!!t);return n.length===1?n[0]:void 0}a(Fs,"pathValue");function ul(e){return"target"in e?[e.target]:[e.source,e.destination]}a(ul,"operationPaths");function fl(e){return/[,*?`$]|@\(|[{}]/.test(e)||pl(e)}a(fl,"isAmbiguousPathExpression");function ml(e){return["path","filepath","destination","newname","name"].some(o=>/[\[\]]/.test(e.values.get(o)??""))}a(ml,"hasUnmodelledBracketWildcard");function pl(e){return/^[a-z]:[\\/]/i.test(e)?!1:/^[a-z][a-z0-9_.-]*:/i.test(e)}a(pl,"isPowerShellProviderPath");function gl(e){if(e===void 0||/^\$?true$|^1$/i.test(e))return!0;if(/^\$?false$|^0$/i.test(e))return!1}a(gl,"parseSwitchValue");function wl(e){let o=/^[a-z]:|\\/i.test(e)?Ge.win32:Ge.posix;return o.join(".",o.basename(e))}a(wl,"defaultDestination");function hl(e,o){let n=/^[a-z]:|\\/i.test(e)?Ge.win32:Ge.posix;return n.join(n.dirname(e),o)}a(hl,"joinSourceParent");function yl(e,o){return(/^[a-z]:|\\/i.test(e)?Ge.win32:Ge.posix).join(e,o)}a(yl,"joinPath");function vl(e){return e.replace(/\\/g,"/").split("/").at(-1)?.toLowerCase()??""}a(vl,"commandName");function go(e,o,n){return{complete:!1,values:e,switches:o,reason:n}}a(go,"failed");function Be(e){return{status:"incomplete",operations:[],reason:e}}a(Be,"incomplete");var kl=W.join(".agent","plan_mode_doc.md"),Zo=new Map,Qo=null;function Sl(e){if(!e||!e.trim())return!1;let o=e.trim().replace(/\s+/g," ").toLowerCase();for(let n of bs)if(o===n||o.startsWith(n+" ")){if(n==="sed"&&o.split(/\s+/).some(i=>i.startsWith("-i")||i==="--in-place"))return!1;if(n==="awk"){let r=o.split(/\s+/);if(r.includes("-f")||r.includes("--file"))return!1}if(["node","npm","yarn","pnpm","tsc","python","pip","go","cargo","rustc","ruby","perl"].includes(n)){let r=o.split(/\s+/).slice(1);if(r.length>0&&!r.every(i=>/^(-v|--version|-h|--help)$/.test(i)))return!1}return!0}return!1}a(Sl,"isSingleBashReadCommand");var $l=/^[a-zA-Z0-9]+$/;function bl(e){let o=e.trim();if(!o.endsWith("--help")||o.includes('"')||o.includes("'"))return!1;let n=!1;for(let t of o.split(/\s+/))if(t.startsWith("-"))if(t==="--help")n=!0;else return!1;else if(!$l.test(t))return!1;return n}a(bl,"isHelpCommand");function rt(e){if(!e||!e.trim())return!1;if(bl(e))return!0;let o=e.trim().replace(/\\\r?\n/g," "),n=mo(o);if(n.unparseable||n.statements.length===0)return!1;let t=n.statements.length>1||(n.statements[0]?.stages.length??0)>1;for(let r of n.statements){if(r.precedingOp!==null&&r.precedingOp!=="&&")return!1;for(let i of r.stages){for(let c of i.redirections)if(c.input||!Qn(c.target))return!1;let l=i.argv.join(" ");if(l&&!(t&&i.argv[0]?.toLowerCase()==="cd"&&i.argv.length>=2)&&!Sl(l))return!1}}return!0}a(rt,"isBashReadCommand");function xl(e){let o=e.trim();return o?rt(o)?null:"[Blocked] Direct !command execution only supports safe read-only commands. Use the bash tool for commands that write files, invoke shells, or require confirmation.":"[Shell: No command provided]"}a(xl,"getDirectShellBypassBlockReason");var Vs=new Set(["remove-item","set-content","add-content","out-file","new-item","copy-item","move-item","rename-item","ni"]),Al={bash:new Set(["-c"]),dash:new Set(["-c"]),sh:new Set(["-c"]),zsh:new Set(["-c"]),cmd:new Set(["/c"]),powershell:new Set(["-command","-c"]),pwsh:new Set(["-command","-c"])};function ot(e){let o=e[0]?.replace(/\\/g,"/"),n=o?.slice(o.lastIndexOf("/")+1).replace(/\.exe$/i,"").toLowerCase();if(!n)return;let t=Al[n];if(!t)return;let r=e.findIndex((i,l)=>l>0&&t.has(i.toLowerCase()));return r>=0?e[r+1]:void 0}a(ot,"getNestedShellCommand");function st(e){return Ys(e,0)}a(st,"isBashWriteCommand");function Ys(e,o){if(!e||!e.trim())return!1;let n=mo(e);if(n.unparseable)return!1;for(let t of n.statements)for(let r of t.stages){let i=r.argv.map(c=>c.toLowerCase());if(i.length>0){let c=i[0],d=i.length>=2?`${i[0]} ${i[1]}`:null;for(let u of $s)if(u===c||d!==null&&u===d)return!0}for(let c of i)if(Vs.has(c))return!0;for(let c of r.redirections)if(!c.input&&!Qn(c.target))return!0;let l=o<3?ot(r.argv):void 0;if(l!==void 0&&Ys(l,o+1))return!0}return!1}a(Ys,"isBashWriteCommandAtDepth");function it(e){let o=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\((.+)\)$/);return o?{tool:o[1].toLowerCase(),pattern:o[2]}:{tool:e.toLowerCase(),pattern:null}}a(it,"parseAllowedToolPattern");function Rl(e,o){if(o==="*")return!1;if(o.endsWith(":*")){let n=o.slice(0,-2);return e.startsWith(n)}return e===o}a(Rl,"matchesBashPatternLegacy");function El(e,o){if(o==="*")return!1;if(o.endsWith(":*")){let n=o.slice(0,-2);return e===n}return e===o}a(El,"matchesBashPatternByExtractedPrefix");async function at(e,o,n,t,r){if(e.toLowerCase()!=="bash")return!1;let i=o.command??"",l=[];for(let c of n){let d=it(c);if(d.tool==="bash"){if(d.pattern===null)return!0;l.push({pattern:d.pattern})}}if(l.length===0)return!1;if(t){let c;try{c=await t.extract(i,r)}catch{return!1}if(c.kind!=="prefix")return!1;for(let{pattern:d}of l)if(d&&El(c.value,d))return!0;return!1}for(let{pattern:c}of l)if(c&&Rl(i,c))return!0;return!1}a(at,"isToolCallAllowed");function lt(e,o,n){if(e.toLowerCase()!=="bash")return"";let t=o.command??"",r=t.split(" ");return r.length>1?`Bash(${r.slice(0,2).join(" ")}:*)`:`Bash(${t})`}a(lt,"generateSavePattern");function ho(e,o){try{let n=W.resolve(e),t=W.resolve(o),r=Ne(),i=W.join(t,".kodax");return D(n,i)||D(n,r)?!0:!(D(n,t)||ni().some(c=>D(n,c)))}catch{return!1}}a(ho,"isAlwaysConfirmPath");function Gs(e){return!e||e.startsWith("-")?!1:/^\.\.?[/\\]/.test(e)||e.startsWith("~/")||e.startsWith("~\\")||/^[a-zA-Z]:[/\\]/.test(e)?!0:e.startsWith("/")&&e.length>1?!(process.platform==="win32"&&nt.test(e)):!!(e.startsWith(".")&&/[/\\]/.test(e)||e.split(/[/\\]+/).includes(".."))}a(Gs,"looksLikePath");var nt=/^\/[A-Za-z][A-Za-z0-9]*(?::[A-Za-z0-9]+)?$/,zs={python:new Set(["-c"]),py:new Set(["-c"]),node:new Set(["-e","--eval","-p","--print"]),ruby:new Set(["-e"]),perl:new Set(["-e"])},Cl=new Set(["rg","ripgrep","grep","egrep","fgrep","findstr","select-string","sed","awk"]),Il=new Set(["-e","--regexp","--regex","-pattern"]),Tl=new Set(["-f","--file"]),qs=new Set(["-g","--glob","--iglob","-r","--replace"]),et=new Set(["--include","--exclude","--exclude-dir"]),_l={rg:qs,ripgrep:qs,grep:et,egrep:et,fgrep:et,awk:new Set(["-v","--assign"]),"select-string":new Set(["-inputobject"])},Pl={rg:new Set(["--ignore-file"]),ripgrep:new Set(["--ignore-file"]),grep:new Set(["--exclude-from"]),egrep:new Set(["--exclude-from"]),fgrep:new Set(["--exclude-from"]),"select-string":new Set(["-path","-literalpath"])};function ct(e){let o=e.replace(/\\/g,"/");return(o.split("/").pop()??o).toLowerCase().replace(/\.exe$/,"")}a(ct,"commandBasename");function Ll(){return{sourceIndexes:new Set,pathIndexes:new Set,pathValues:new Set}}a(Ll,"createCommandArgumentRoles");function ze(e,o,n,t){let r=e[o];r!==void 0&&(n.add(o),t?.add(r))}a(ze,"addIndexedValue");function en(e,o){let n=e.toLowerCase();if(o.startsWith("--")){let t=`${o}=`;return n.startsWith(t)?e.slice(t.length):void 0}return n.startsWith(o)&&e.length>o.length?e.slice(o.length):void 0}a(en,"attachedOptionValue");function Ml(e,o,n){for(let t=1;t<e.length;t+=1){let r=e[t]??"",i=r.toLowerCase();for(let l of o){if(i===l){ze(e,t+1,n.sourceIndexes);break}if(en(r,l)!==void 0){n.sourceIndexes.add(t);break}}}}a(Ml,"collectScriptSourceRoles");function Ks(e,o,n,t){if(o)for(let r=1;r<e.length;r+=1){let i=e[r]??"";if(i==="--")break;let l=i.toLowerCase();for(let c of o){if(l===c){ze(e,r+1,n,t);break}let d=en(i,c);if(d!==void 0){n.add(r),t?.add(d);break}}}}a(Ks,"collectFlagValueRoles");function Wl(e,o){let n=ct(e[0]??"");Ks(e,_l[n],o.sourceIndexes),Ks(e,Pl[n],o.pathIndexes,o.pathValues);let t=!1;for(let i=1;i<e.length;i+=1){let l=e[i]??"";if(l==="--")break;let c=l.toLowerCase();if(n==="findstr"&&c.startsWith("/c:")){o.sourceIndexes.add(i),t=!0;continue}if(n==="findstr"&&c.startsWith("/g:")){o.pathIndexes.add(i),o.pathValues.add(l.slice(3)),t=!0;continue}for(let d of Il){if(c===d){ze(e,i+1,o.sourceIndexes),t=!0;break}if(en(l,d)!==void 0){o.sourceIndexes.add(i),t=!0;break}}for(let d of Tl){if(c===d){ze(e,i+1,o.pathIndexes,o.pathValues),t=!0;break}let u=en(l,d);if(u!==void 0){o.pathValues.add(u),t=!0;break}}}if(!t){let i=!1;for(let l=1;l<e.length;l+=1){let c=e[l]??"";if(c==="--"){i=!0;continue}if(!(o.sourceIndexes.has(l)||o.pathIndexes.has(l))&&!(!i&&c.startsWith("-"))&&!(n==="findstr"&&nt.test(c))){ze(e,l,o.sourceIndexes);break}}}let r=!1;for(let i=1;i<e.length;i+=1){let l=e[i]??"";if(l==="--"){r=!0;continue}!r&&l.startsWith("-")||o.sourceIndexes.has(i)||o.pathIndexes.has(i)||n==="findstr"&&nt.test(l)||ze(e,i,o.pathIndexes,o.pathValues)}}a(Wl,"collectRegexArgumentRoles");function Js(e){let o=Ll(),n=ct(e[0]??""),t=/^python(?:\d+(?:\.\d+)*)?$/.test(n)?zs.python:zs[n];return t&&Ml(e,t,o),Cl.has(n)&&Wl(e,o),o}a(Js,"collectCommandArgumentRoles");function Zs(e){let o=[],n=[],t="",r=-1,i,l=a(d=>{r<0||(n.push({value:t,start:r,end:d}),t="",r=-1)},"finishWord"),c=a(()=>{n.length>0&&o.push(n),n=[]},"finishStage");for(let d=0;d<e.length;d+=1){let u=e[d];if(i){u===i?i=void 0:i==='"'&&u==="\\"&&e[d+1]==='"'?(t+=`${u}${e[d+1]}`,d+=1):t+=u;continue}u==='"'||u==="'"?(r<0&&(r=d),i=u):/\s/.test(u)?l(d):u==="|"||u==="&"||u===";"?(l(d),c()):(r<0&&(r=d),t+=u)}return i?[]:(l(e.length),c(),o)}a(Zs,"tokenizeRawCommandStages");function Qs(e){let o=e.split("");for(let n of Zs(e)){let t=Js(n.map(r=>r.value));for(let r of t.sourceIndexes){let i=n[r];if(i)for(let l=i.start;l<i.end;l+=1)o[l]=" "}}return o.join("")}a(Qs,"maskRawInlineSources");function Ol(e){let o=[],n;for(let i of[/"([A-Za-z]:\\[^"\r\n]+)"/g,/'([A-Za-z]:\\[^'\r\n]+)'/g])for(;(n=i.exec(e))!==null;)o.push(n[1]);let t=/(?:^|\s)(\.\.?\/[^\s]+|\.\.?\\[^\s]+|~\/[^\s]+|\.[^\s]*[/\\][^\s]*)/g;for(;(n=t.exec(e))!==null;)o.push(n[1]);let r=/(?:^|[\s:=<>])([a-zA-Z]:\\[^\s"'|;&<>]+)/g;for(;(n=r.exec(e))!==null;)o.push(n[1]);return o}a(Ol,"legacyRegexPathScan");function nn(e){let o=new Set,n=mo(e);if(!n.unparseable)for(let t of n.statements)for(let r of t.stages){let i=Js(r.argv);for(let l of i.pathValues)o.add(l);for(let l=0;l<r.argv.length;l+=1){let c=r.argv[l];i.sourceIndexes.has(l)||i.pathIndexes.has(l)||Gs(c)&&o.add(c)}for(let l of r.redirections)Gs(l.target)&&o.add(l.target)}for(let t of Ol(Qs(e)))o.add(t);return Array.from(o)}a(nn,"extractPathsFromCommand");function Nl(e,o,n=o){let t=nn(e);for(let r of t){let i=Do(r,n);if(ho(i,o))return!0}return!1}a(Nl,"isCommandOnProtectedPath");function Xs(e){let o=W.normalize(e);return process.platform==="win32"?o.toLowerCase():o}a(Xs,"normalizePathForComparison");function Dl(e,o){return Xs(e)===Xs(o)}a(Dl,"pathsEqual");function dt(e,o){try{let n=W.resolve(o),t=W.resolve(n,oi(ei(e)));return D(t,n)}catch{return!1}}a(dt,"isPathInsideProject");function Ul(e){let o=e.match(/[A-Za-z]:[\\/][^\s;|&<>(){}'"]+|\/[^\s;|&<>(){}'"]+/g);return o?o.filter(n=>!/^(?:\/dev\/|\/proc\/)/i.test(n)):[]}a(Ul,"collectAbsolutePathCandidates");function ut(e){let o=W.resolve(e),n=Zo.get(o);if(n)return n;if(Jo.existsSync(o)){let c=Jo.realpathSync.native(o);return Zo.set(o,c),c}let t=[],r=o;for(;!Jo.existsSync(r);){let c=W.dirname(r);if(c===r)return Zo.set(o,o),o;t.unshift(W.basename(r)),r=c}let i=Jo.realpathSync.native(r),l=W.join(i,...t);return Zo.set(o,l),l}a(ut,"resolveExistingPathPrefix");function ei(e){return e==="~"?wo.homedir():e.startsWith(`~${W.sep}`)||e.startsWith("~/")||e.startsWith("~\\")?W.join(wo.homedir(),e.slice(2)):e}a(ei,"expandHomeDirectory");function oi(e){let o=wo.tmpdir(),n=[[/^%temp%/i,o],[/^%tmp%/i,o],[/^\$env:temp\b/i,o],[/^\$env:tmp\b/i,o],[/^\$tmpdir\b/i,o],[/^\$temp\b/i,o],[/^\$tmp\b/i,o]];for(let[t,r]of n)if(t.test(e))return e.replace(t,r);return e}a(oi,"expandSystemTempAlias");function jl(e,o,n=o){let t=W.resolve(n??o??process.cwd()),r=oi(ei(e)),i=W.isAbsolute(r)?W.resolve(r):W.resolve(t,r);return ut(i)}a(jl,"resolvePermissionPath");function ni(){if(Qo)return Qo;let e=new Set,o=[wo.tmpdir(),process.env.TEMP,process.env.TMP,process.env.TMPDIR].filter(n=>typeof n=="string"&&n.trim().length>0);for(let n of o)try{e.add(ut(n))}catch{}return Qo=Array.from(e),Qo}a(ni,"getSystemTempDirectories");function ft(e){let o=ut(e??process.cwd());return{projectPlanDoc:W.join(o,kl),systemTempDirs:ni()}}a(ft,"getPlanModeAllowedWritablePaths");function tt(e,o,n=o){let t=jl(e,o,n),{projectPlanDoc:r,systemTempDirs:i}=ft(o);return Dl(t,r)?!0:i.some(l=>D(t,l))}a(tt,"isPlanModeAllowedPath");function Fl(e){let{projectPlanDoc:o,systemTempDirs:n}=ft(e),t=n[0]??wo.tmpdir();return`${o} or the system temp directory (${t})`}a(Fl,"formatPlanModeAllowedLocations");var Hl=new Set(["-a","--append","-i","--ignore-interrupts"]);function Bl(e){let o=[];for(let n=1;n<e.argv.length;n+=1){let t=e.argv[n];Hl.has(t)||t.startsWith("-")||o.push(t)}return o}a(Bl,"collectTeeTargets");function Gl(e){let o=Bs(e.argv),n=[];for(let t of o.operations)"target"in t?n.push(t.target):t.kind==="copy"?n.push(t.destination):n.push(t.source,t.destination);return n}a(Gl,"collectPowerShellWriteTargets");function qe(e){return on(e,0,!0)}a(qe,"collectBashWriteTargets");function ti(e){return on(e,0,!1)}a(ti,"collectDeterministicBashWriteTargets");var zl=new Set(["rm","rmdir","mkdir","touch","mv","move","ren","del","erase","rd"]),ql=new Set(["cp","copy"]);function Kl(e,o=1){let n=[],t=!1;for(let r=o;r<e.length;r+=1){let i=e[r];i==="--"?t=!0:(t||!i.startsWith("-"))&&n.push(i)}return n}a(Kl,"collectPositionalArgs");function Xl(e){let o=ct(e.argv[0]??""),n=Kl(e.argv);if(zl.has(o))return n;if(ql.has(o)){let t=e.argv.findIndex(i=>i==="-t"||i==="--target-directory");if(t>=0){let i=e.argv[t+1];return i?[i]:[]}let r=e.argv.find(i=>i.startsWith("--target-directory="));return r?[r.slice(19)]:n.slice(-1)}if(o==="chmod"||o==="chown")return n.slice(1);if(o==="dd"){let t=e.argv.find(r=>r.startsWith("of="));return t?[t.slice(3)]:[]}return[]}a(Xl,"collectDirectCommandWriteTargets");function Vl(e){let o=[],n=Qs(e),t;for(let r=0;r<n.length;r+=1){let i=n[r];if(t!==void 0){i===t?t=void 0:i==="\\"&&t==='"'&&(r+=1);continue}if(i==='"'||i==="'"){t=i;continue}if(i==="\\"){r+=1;continue}if(i!==">")continue;for(n[r+1]===">"&&(r+=1);/\s/.test(n[r+1]??"");)r+=1;let l=n[r+1],c=r+(l==='"'||l==="'"?2:1),d=c;for(;d<n.length;){let u=n[d];if(l==='"'||l==="'"){if(u===l)break}else if(/\s|[|;&<>]/.test(u))break;d+=1}d>c&&o.push(n.slice(c,d)),r=d}return o}a(Vl,"collectRawOutputRedirectionTargets");function on(e,o,n){let t=new Set,r=a(l=>{let c=l?.trim();c&&t.add(c)},"pushTarget");if(n)for(let l of nn(e))r(l);else for(let l of Vl(e))r(l);let i=mo(e);if(i.unparseable){if(o<3)for(let l of Zs(e)){let c=ot(l.map(d=>d.value));if(c!==void 0)for(let d of on(c,o+1,n))r(d)}return Array.from(t)}for(let l of i.statements)for(let c of l.stages){for(let f of c.redirections)f.input||r(f.target);let d=c.argv[0]?.toLowerCase();if(!d)continue;if(d==="tee")for(let f of Bl(c))r(f);else if(Vs.has(d))for(let f of Gl(c))r(f);if(!n)for(let f of Xl(c))r(f);let u=o<3?ot(c.argv):void 0;if(u!==void 0)for(let f of on(u,o+1,n))r(f)}return Array.from(t)}a(on,"collectBashWriteTargetsAtDepth");function ri(e,o){if(!st(e))return{dangerous:!1};let n=new Set([...qe(e),...Ul(e)]);for(let t of n)if(!dt(t,o))return{dangerous:!0,reason:`Command may modify file outside project: ${t}`};return{dangerous:!1}}a(ri,"getBashOutsideProjectWriteRisk");function si(e,o,n,t=n){let r=Fl(n);if(Yr(e))return null;if(uo.has(e)){let i=typeof o.path=="string"?o.path:"";return i?tt(i,n,t)?null:`[Blocked] Plan mode only allows file modifications in ${r}. Requested path: ${i}`:`[Blocked] Tool '${e}' is not allowed in plan mode unless it targets ${r}.`}if(e==="bash"){let i=o.command??"";if(!st(i))return null;let l=qe(i);if(l.length===0)return`[Blocked] Plan mode only allows bash write operations when every target is either ${r}. Could not determine a safe target from: ${i.slice(0,80)}${i.length>80?"...":""}`;let c=l.find(d=>!tt(d,n,t));return c?`[Blocked] Plan mode only allows bash write operations in ${r}. Blocked target: ${c}`:null}return`[Blocked] Tool '${e}' has side effects and is not permitted in plan mode. Switch to accept-edits or auto mode to use it, or work within ${r}.`}a(si,"getPlanModeBlockReason");import tn from"node:path";import pt from"node:os";function ai(){try{return Ne()}catch{return}}a(ai,"safeGetAgentConfigHome");function mt(e,o){let n=process.platform==="win32"?/^(?:\$\{home\}|\$home|\$env:(?:home|userprofile)|%userprofile%)(?=$|[\\/])/i:/^(?:\$\{HOME\}|\$HOME)(?=$|[\\/])/;return Do(e.replace(n,pt.homedir()),o)}a(mt,"resolveShellWriteTarget");function ii(e,o){let n=ai();if(n&&D(e,n))return"user-kodax";let t=tn.join(tn.resolve(o),".kodax");if(D(e,t))return"project-kodax"}a(ii,"resolveProtectedZone");function Yl(){let e=new Set;try{e.add(pt.tmpdir())}catch{}for(let o of["TEMP","TMP","TMPDIR"]){let n=process.env[o];n&&n.length>0&&e.add(n)}return Array.from(e)}a(Yl,"getSystemTempDirs");var Jl=new Set(["bash"]),Zl={toolNames:Jl,collect(e,o,n=o){let t=typeof e.input.command=="string"?e.input.command:"";if(!t||!o)return[];let r=[],i=new Set,l=new Set,c=Yl(),d=tn.resolve(o);for(let u of nn(t)){let f;try{f=mt(u,n)}catch{continue}let m=ii(f,o);if(m){i.has(f)||(i.add(f),r.push({kind:"protected_path",path:u,zone:m}));continue}if(ho(f,o)){let v=c.some(y=>D(f,y)),k=D(f,d);!v&&!k&&!l.has(f)&&(l.add(f),r.push({kind:"outside_project",path:u}))}}for(let u of qe(t)){let f;try{f=mt(u,n)}catch{continue}ii(f,o)||D(f,d)||c.some(k=>D(f,k))||r.push({kind:"shell_redirect_outside",target:u})}return r}},cp=a((e,o,n)=>{if(e.name!=="bash")return{denied:!1};let t=typeof e.input.command=="string"?e.input.command:"",r=new Set([tn.join(pt.homedir(),".kodax")]),i=ai();i&&r.add(i);for(let l of ti(t)){let c=mt(l,n);if([...r].some(d=>D(c,d)))return{denied:!0,patternId:"user_kodax_write",reason:`Shell write to credential-zone path \`${l}\` (under ~/.kodax/) is permanently denied. KodaX config edits must use the \`kodax config\` CLI or SDK config API.`}}return{denied:!1}},"replBashUserKodaxWriteDeny");var sn=B("config.json");function ui(){return di.join(process.cwd(),".kodax","config.local.json")}a(ui,"getProjectConfigFile");function xp(e=process.env){let o=yo(sn);return Ql({settings:o.autoMode,env:e})}a(xp,"loadAutoModeSettings");function Ql(e={}){let o=e.settings??{},n=e.env??{},t=n.KODAX_AUTO_MODE_ENGINE?.trim(),r=t==="llm"||t==="rules"?t:void 0,i=o.engine==="llm"||o.engine==="rules"?o.engine:void 0,l=r??i??"llm",c=ci(o.classifierModel),d=ci(n.KODAX_AUTO_MODE_CLASSIFIER_MODEL),u=n.KODAX_AUTO_MODE_TIMEOUT_MS?.trim(),f=u!==void 0?Number(u):NaN,m=Number.isFinite(f)&&f>0?Math.floor(f):void 0,v=typeof o.timeoutMs=="number"&&o.timeoutMs>0?Math.floor(o.timeoutMs):void 0,k=li(n.KODAX_AUTO_SPECULATIVE_WINDOW_MS?.trim()),y=typeof o.speculativeWindowMs=="number"?li(String(o.speculativeWindowMs)):void 0;return{engine:l,classifierModel:c,classifierModelEnv:d,timeoutMs:m??v,speculativeWindowMs:k??y}}a(Ql,"resolveAutoModeSettings");function li(e){if(e===void 0||e==="")return;let o=Number(e);if(Number.isFinite(o))return o<0?0:Math.floor(o)}a(li,"parseSpeculativeWindow");function ci(e){if(typeof e!="string")return;let o=e.trim();return o.length===0?void 0:o}a(ci,"nonEmptyString");function yo(e){try{if(rn.existsSync(e))return JSON.parse(rn.readFileSync(e,"utf-8"))}catch{}return{}}a(yo,"readJsonFile");function fi(e,o){rn.mkdirSync(di.dirname(e),{recursive:!0}),rn.writeFileSync(e,JSON.stringify(o,null,2))}a(fi,"writeJsonFile");function gt(e){let o=yo(sn);fi(sn,{...o,permissionMode:e})}a(gt,"savePermissionModeUser");function Ap(){let e=yo(sn),o=yo(ui()),n=e.alwaysAllowTools??[],t=o.alwaysAllowTools??[];return[...new Set([...n,...t])]}a(Ap,"loadAlwaysAllowTools");function Rp(e,o,n=!1){let t=lt(e,o,n);if(!t)return;let r=ui(),i=yo(r),l=i.alwaysAllowTools??[];l.includes(t)||fi(r,{...i,alwaysAllowTools:[...l,t]})}a(Rp,"saveAlwaysAllowToolPattern");var wt=["ama","sa"];function mi(e){let o=wt.indexOf(e);return wt[(o+1)%wt.length]??"ama"}a(mi,"nextAgentMode");var ge=class{static{a(this,"CommandRegistry")}commands=new Map;aliases=new Map;register(o){let n=o.name.toLowerCase();if(this.commands.has(n))throw new Error(`Command "${o.name}" is already registered`);if(this.aliases.has(n)){let r=this.aliases.get(n);throw new Error(`Command "${o.name}" conflicts with existing alias for "${r}"`)}let t=new Set;for(let r of o.aliases??[]){let i=r.toLowerCase();if(i!==n){if(t.has(i))throw new Error(`Alias "${r}" is duplicated within command "${o.name}"`);if(this.commands.has(i))throw new Error(`Alias "${r}" conflicts with existing command "${i}"`);if(this.aliases.has(i)){let l=this.aliases.get(i);throw new Error(`Alias "${r}" is already registered for "${l}"`)}t.add(i)}}if(this.commands.set(n,{...o,source:o.source??"builtin"}),o.aliases)for(let r of o.aliases){let i=r.toLowerCase();i!==n&&this.aliases.set(i,n)}}unregister(o){let n=o.toLowerCase(),t=this.aliases.get(n)??n;if(!this.commands.has(t))return!1;let r=this.commands.get(t);if(r?.aliases)for(let i of r.aliases)this.aliases.delete(i.toLowerCase());return this.commands.delete(t),!0}get(o){let n=o.toLowerCase(),t=this.aliases.get(n)??n;return this.commands.get(t)}has(o){let n=o.toLowerCase(),t=this.aliases.get(n)??n;return this.commands.has(t)}getAll(o){let n=new Map;for(let[t,r]of this.commands)o&&r.source!==o||n.has(t)||n.set(t,{name:r.name,aliases:r.aliases,description:r.description,source:r.source??"builtin",usage:r.usage,priority:r.priority,location:r.location,path:r.path,userInvocable:r.userInvocable,disableModelInvocation:r.disableModelInvocation,allowedTools:r.allowedTools,context:r.context,agent:r.agent,argumentHint:r.argumentHint,model:r.model});return Array.from(n.values()).sort((t,r)=>t.name.localeCompare(r.name))}getBySource(o){return this.getAll(o)}getNames(){return Array.from(this.commands.keys()).sort()}clear(){this.commands.clear(),this.aliases.clear()}get size(){return this.commands.size}get aliasCount(){return this.aliases.size}},ec=new ge;function ht(e){return[`ready=${e.ready}`,`new=${e.newlyActive}`,`attention=${e.attention}`,`active=${e.active}`].join(" ")}a(ht,"formatLearningStatus");function Lp(e){if(e.ready+e.newlyActive+e.attention!==0)return`Learning recovery: ${ht(e)} [/learn]`}a(Lp,"formatLearningRecoverySummary");import K from"chalk";import{Buffer as hi}from"node:buffer";import{spawn as oc}from"node:child_process";import pi from"node:process";var Ae="\x1B",nc="\x07",yt=`${Ae}\\`;function gi(e,o){return e.SSH_CONNECTION?!1:o==="win32"||o==="darwin"||o==="linux"}a(gi,"shouldPreferNativeClipboard");function tc(e,o){let n=hi.from(e,"utf8").toString("base64"),t=o.TERM==="xterm-kitty"?yt:nc,r=`${Ae}]52;c;${n}${t}`;return o.TMUX?`${Ae}Ptmux;${r.replaceAll(Ae,`${Ae}${Ae}`)}${yt}`:o.STY?`${Ae}P${r}${yt}`:r}a(tc,"buildOscSequence");async function an(e,o,n){return new Promise((t,r)=>{let i=oc(e,o,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),l="";i.on("error",r),i.stderr?.on("data",c=>{l+=c.toString()}),i.on("close",c=>{if(c===0){t(!0);return}r(new Error(l.trim()||`${e} exited with code ${c??"unknown"}`))}),i.stdin?.write(n),i.stdin?.end()})}a(an,"execClipboardCommand");function rc(e){let o="$stream = [Console]::OpenStandardInput(); $buffer = New-Object byte[] 8192; $memory = New-Object System.IO.MemoryStream; while (($read = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) { $memory.Write($buffer, 0, $read) }; $text = [System.Text.Encoding]::UTF8.GetString($memory.ToArray()); Set-Clipboard -Value $text",n=hi.from(e,"utf8");return[["powershell",["-NoProfile","-NonInteractive","-Command",o],n],["pwsh",["-NoProfile","-NonInteractive","-Command",o],n],["cmd",["/c","chcp 65001 >nul & clip"],n]]}a(rc,"buildWindowsClipboardCandidates");async function wi(e,o,n){if(o.SSH_CONNECTION)return!1;switch(n){case"win32":{let t=rc(e);for(let[r,i,l]of t)try{if(await an(r,i,l))return!0}catch{}return!1}case"darwin":return an("pbcopy",[],e);case"linux":{let t=[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]];for(let[r,i]of t)try{if(await an(r,i,e))return!0}catch{}return!1}default:return!1}}a(wi,"tryNativeClipboard");async function sc(e,o){if(!o.TMUX)return!1;let n=o.LC_TERMINAL==="iTerm2"?["load-buffer","-"]:["load-buffer","-w","-"];try{return await an("tmux",n,e)}catch{return!1}}a(sc,"tryTmuxClipboard");async function yi(e,o={}){let n=o.env??pi.env,t=o.platform??pi.platform,r=e.trimEnd(),i=tc(r,n);if(!r)throw new Error("Nothing to copy.");if(gi(n,t))try{if(await wi(r,n,t))return{path:"native"}}catch{}if(await sc(r,n))return{path:"tmux-buffer"};if(o.terminalWrite?.(i))return{path:"osc52"};if(!gi(n,t))try{if(await wi(r,n,t))return{path:"native"}}catch{}throw new Error("Unable to access any clipboard path.")}a(yi,"copyTextToClipboard");var vt;(function(e){e.Idle="idle",e.Responding="responding",e.WaitingForConfirmation="waiting_for_confirmation"})(vt||(vt={}));var z;(function(e){e.Scheduled="scheduled",e.Validating="validating",e.AwaitingApproval="awaiting_approval",e.Executing="executing",e.Success="success",e.Error="error",e.Cancelled="cancelled"})(z||(z={}));var Fp={[z.Scheduled]:"\u25CB",[z.Validating]:"\u25CC",[z.AwaitingApproval]:"?",[z.Executing]:"\u25CB",[z.Success]:"\u2713",[z.Error]:"\u2717",[z.Cancelled]:"-"},vi;(function(e){e[e.Low=-100]="Low",e[e.Normal=0]="Normal",e[e.High=100]="High",e[e.Critical=200]="Critical"})(vi||(vi={}));var Hp={streamingState:vt.Idle,currentResponse:"",history:[],pendingToolCalls:[],sessionId:"",provider:"",model:"",isLoading:!1};var ic="[redacted]",ki="[truncated]";function ae(e,o=2e3){return e.length>o?`${e.slice(0,o-3)}...`:e}a(ae,"truncateToolReplayText");function ac(e){let o=e.toLowerCase().replace(/[\s_-]/g,"");return o.includes("token")||o.includes("password")||o.includes("secret")||o.includes("apikey")||o.includes("accesstoken")||o==="authorization"||o==="cookie"||o==="setcookie"}a(ac,"isSensitiveToolInputKey");function Si(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Si,"isRecord");function kt(e,o=0,n=new WeakSet){if(e===null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string")return ae(e);if(o>=6)return ki;if(typeof e=="object"&&e!==null){if(n.has(e))return ki;if(n.add(e),Array.isArray(e))return e.slice(0,50).map(r=>kt(r,o+1,n));if(!Si(e))return ae(String(e));let t={};for(let[r,i]of Object.entries(e).slice(0,50))t[r]=ac(r)?ic:kt(i,o+1,n);return t}return ae(String(e))}a(kt,"sanitizeToolJsonValue");function $i(e){if(!e)return;let o=kt(e);return Si(o)?o:void 0}a($i,"sanitizeToolInput");function bi(e){if(e!==void 0){if(typeof e=="string")return ae(e);try{return ae(JSON.stringify(e))}catch{return ae(String(e))}}}a(bi,"stringifyToolReplayValue");function Xp(e){return e.type==="tool_summary"||e.type==="task_completed"?{type:"event",text:e.text,icon:"tool",...e.timestamp===void 0?{}:{timestamp:e.timestamp}}:e.type==="tool_group"?{type:"tool_group",tools:e.tools.map(gc),...e.timestamp===void 0?{}:{timestamp:e.timestamp}}:e}a(Xp,"seedToHistoryItem");var lc="[Thinking]",cc="[/Thinking]",dc="Untitled Session",xi=50,uc=60,Ri="...",Ei=["[Managed Task]","[Managed Task Protocol Retry]","Assigned native agent identity:","Tool policy:","Blocked tools:","Allowed shell patterns:","Dependency handoff artifacts:","Dependency summary preview:","Preferred agent:","Read structured bundle first:","Read human summary next:"],Ci=[/(?:^|\n)You are the [^\n]+ role for a managed KodaX task\./,/(?:^|\n)Primary task:/,/(?:^|\n)Work intent:/,/(?:^|\n)Complexity:/,/(?:^|\n)Risk:/,/(?:^|\n)Harness:/,/(?:^|\n)Brainstorm required:/],fc=/(^|\r?\n)\[Thinking\]\r?\n([\s\S]*?)\r?\n\[\/Thinking\](?=\r?\n|$)/g,mc="Session ended before the tool completed.";function pc(e){switch(e){case"success":return z.Success;case"error":return z.Error;case"cancelled":return z.Cancelled;case"awaiting_approval":return z.AwaitingApproval;default:return e}}a(pc,"toolCallSeedToHistoryToolStatus");function gc(e){return{id:e.id,name:e.name,status:pc(e.status),...e.input!==void 0?{input:e.input}:{},...e.preview!==void 0?{preview:e.preview}:{},...e.output!==void 0?{output:e.output}:{},...e.error!==void 0?{error:e.error}:{},startTime:e.startTime??Date.now(),...e.endTime!==void 0?{endTime:e.endTime}:{}}}a(gc,"toolCallSeedToHistoryToolCall");function wc(e){let o=-1;for(let n of Ei){let t=e.indexOf(n);t>=0&&(o===-1||t<o)&&(o=t)}for(let n of Ci){let t=n.exec(e);t&&t.index>=0&&(o===-1||t.index<o)&&(o=t.index)}return o}a(wc,"findControlPlaneCutIndex");function hc(e){return Ei.some(o=>e.includes(o))||Ci.some(o=>o.test(e))}a(hc,"hasControlPlaneSignal");function Ii(e){let o=[];for(let n of e)n&&typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&o.push(String(n.text));return o}a(Ii,"collectTextBlocks");function cn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(cn,"isRecord");function yc(e){if(typeof e=="string")return ae(e);if(e===void 0)return"";try{return bi(e)??""}catch{return ae(String(e))}}a(yc,"toolResultContentToString");function vc(e){let o=yc(e.content),n=o.trimStart(),t=e.is_error===!0||n.startsWith("[Tool Error]")||n.startsWith("[Error]"),r=n.startsWith("[Cancelled]")||n.startsWith("[Blocked]");return t?{status:"error",error:o}:r?{status:"cancelled",error:o}:{status:"success",output:o}}a(vc,"inferToolResultSeed");function kc(e){let o=new Map;if(!e||e.role!=="user"||!Array.isArray(e.content))return o;for(let n of e.content)!cn(n)||n.type!=="tool_result"||typeof n.tool_use_id!="string"||o.set(n.tool_use_id,vc(n));return o}a(kc,"collectToolResultSeeds");function Sc(e,o){if(e.type!=="tool_use"||typeof e.id!="string"||typeof e.name!="string")return;let n=o.get(e.id)??{status:"cancelled",error:mc};return{id:e.id,name:e.name,status:n.status,...e.input!==void 0?{input:$i(cn(e.input)?e.input:{})??{}}:{},...n.output!==void 0?{output:n.output}:{},...n.error!==void 0?{error:n.error}:{}}}a(Sc,"buildToolCallSeed");function $c(e){return typeof e=="string"?e:Array.isArray(e)?Ii(e).join(`
2
+ import{$ as ws,A as fs,B as Vn,E as Xo,G as ms,K as ps,M as Vo,U as be,Z as gs,aa as hs,ba as ys,u as cs,w as He,y as ds,z as us}from"./chunk-4PWPNCNK.js";import{a as vs}from"./chunk-RDXRM3UI.js";import{Fa as ss,Ga as is,Ka as as,Ma as ls}from"./chunk-TGMBHGZO.js";import{i as Go}from"./chunk-SMT2JSM3.js";import{A as ns,D as $e,J as Fe,m as zo,n as qo,o as je,q as lo,r as Ko,s as Zr,t as Qr,v as es,w as Xn,x as os,y as co}from"./chunk-OSF3H4RR.js";import{Aa as rs,L as Jr,za as ts}from"./chunk-OD6LVXU6.js";import{Bc as se,H as Br,Hb as Kn,Ib as Bo,Lb as Kr,Qc as Vr,Sc as Yr,mb as Gr,ob as zr,pb as qr,sb as qn,xa as Ho,zc as Xr}from"./chunk-7FJNLJLF.js";import{C as Er,Ma as Bn,Na as We,Oa as Oe}from"./chunk-D3T24FJW.js";import{Dd as Ue,Ed as Fr,Fa as Cr,Fb as Ur,Ga as Ir,Ha as Gn,Id as zn,Sd as Fo,dd as jr,he as Hr,k as No}from"./chunk-VWSLC2WO.js";import{H as Lr,I as Mr,J as Wr,W as Se,X as De,aa as Or,b as q,ca as Uo,e as Ne,ea as jo,f as B,fa as Nr,g as D,ga as Dr,h as Do,q as Tr,r as _r,w as Pr}from"./chunk-Y3AMP22L.js";import{a,b as Hn,d as Ka}from"./chunk-ONUPGMER.js";var Cs=Hn((Tm,Es)=>{"use strict";Es.exports=a(function(o){return o.map(function(n){return n===""?"''":n&&typeof n=="object"?n.op.replace(/(.)/g,"\\$1"):/["\s\\]/.test(n)&&!/'/.test(n)?"'"+n.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(n)?'"'+n.replace(/(["\\$`!])/g,"\\$1")+'"':String(n).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")}).join(" ")},"quote")});var Ws=Hn((Pm,Ms)=>{"use strict";var Ls="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",Is=new RegExp("^"+Ls+"$"),Ts="|&;()<> \\t",Ya='"((\\\\"|[^"])*?)"',Ja="'((\\\\'|[^'])*?)'",Za=/^#$/,_s="'",Ps='"',Yn="$",xe="",Qa=4294967296;for(Jn=0;Jn<4;Jn++)xe+=(Qa*Math.random()).toString(16);var Jn,el=new RegExp("^"+xe);function ol(e,o){for(var n=o.lastIndex,t=[],r;r=o.exec(e);)t.push(r),o.lastIndex===r.index&&(o.lastIndex+=1);return o.lastIndex=n,t}a(ol,"matchAll");function nl(e,o,n){var t=typeof e=="function"?e(n):e[n];return typeof t>"u"&&n!=""?t="":typeof t>"u"&&(t="$"),typeof t=="object"?o+xe+JSON.stringify(t)+xe:o+t}a(nl,"getVar");function tl(e,o,n){n||(n={});var t=n.escape||"\\",r="(\\"+t+`['"`+Ts+`]|[^\\s'"`+Ts+"])+",i=new RegExp(["("+Ls+")","("+r+"|"+Ya+"|"+Ja+")+"].join("|"),"g"),l=ol(e,i);if(l.length===0)return[];o||(o={});var c=!1;return l.map(function(d){var u=d[0];if(!u||c)return;if(Is.test(u))return{op:u};var f=!1,m=!1,v="",k=!1,y;function $(){y+=1;var T,L,Y=u.charAt(y);if(Y==="{"){if(y+=1,u.charAt(y)==="}")throw new Error("Bad substitution: "+u.slice(y-2,y+1));if(T=u.indexOf("}",y),T<0)throw new Error("Bad substitution: "+u.slice(y));L=u.slice(y,T),y=T}else if(/[*@#?$!_-]/.test(Y))L=Y,y+=1;else{var J=u.slice(y);T=J.match(/[^\w\d_]/),T?(L=J.slice(0,T.index),y+=T.index-1):(L=J,y=u.length)}return nl(o,"",L)}for(a($,"parseEnvVar"),y=0;y<u.length;y++){var g=u.charAt(y);if(k=k||!f&&(g==="*"||g==="?"),m)v+=g,m=!1;else if(f)g===f?f=!1:f==_s?v+=g:g===t?(y+=1,g=u.charAt(y),g===Ps||g===t||g===Yn?v+=g:v+=t+g):g===Yn?v+=$():v+=g;else if(g===Ps||g===_s)f=g;else{if(Is.test(g))return{op:u};if(Za.test(g)){c=!0;var x={comment:e.slice(d.index+y+1)};return v.length?[v,x]:[x]}else g===t?m=!0:g===Yn?v+=$():v+=g}}return k?{op:"glob",pattern:v}:v}).reduce(function(d,u){return typeof u>"u"?d:d.concat(u)},[])}a(tl,"parseInternal");Ms.exports=a(function(o,n,t){var r=tl(o,n,t);return typeof n!="function"?r:r.reduce(function(i,l){if(typeof l=="object")return i.concat(l);var c=l.split(RegExp("("+xe+".*?"+xe+")","g"));return c.length===1?i.concat(c[0]):i.concat(c.filter(Boolean).map(function(d){return el.test(d)?JSON.parse(d.split(xe)[1]):d}))},[])},"parse")});var Os=Hn(Zn=>{"use strict";Zn.quote=Cs();Zn.parse=Ws()});import*as On from"fs";import*as Mo from"path";import*as Pn from"fs";import _n from"path";import s from"chalk";var Yo=["plan","accept-edits","auto","auto-in-project"];function bm(e){return e==="auto"||e==="auto-in-project"}a(bm,"isAutoMode");function Xa(e){switch(e){case"plan":return"Plan";case"accept-edits":return"Edits";case"auto":case"auto-in-project":return"Auto"}}a(Xa,"permissionModeDisplayName");var Va='[deprecated] permissionMode "auto-in-project" is now an alias for "auto" (FEATURE_092, v0.7.33). The alias will be removed in v0.7.38 \u2014 please update ~/.kodax/config.json to use "auto".';function xm(e=o=>{q({source:"repl:permission",level:"warn",message:o})}){let o=!1;return()=>{o||(o=!0,e(Va))}}a(xm,"createAutoInProjectDeprecationEmitter");var ks=Vr(),uo=new Set(ks.filter(e=>e.sideEffect==="mutates-fs"&&e.requiredParams.includes("path")).map(e=>e.name)),Ss=new Set(ks.filter(e=>e.sideEffect!=="readonly").map(e=>e.name)),$s=new Set(["npm install","npm i","npm uninstall","npm remove","npm update","npm ci","yarn add","yarn remove","yarn upgrade","pnpm add","pnpm remove","pnpm update","git clean","git reset","git checkout","git switch","git merge","git rebase","git cherry-pick","git revert","git commit","git push","git pull","rm","mv","cp","mkdir","rmdir","touch","chmod","chown","del","erase","rd","copy","move","ren","curl","wget","dd","tar","kill","pkill","killall"]),bs=new Set(["ls","cat","pwd","echo","whoami","date","which","whereis","tree","dir","type","get-childitem","get-content","select-string","get-location","where","grep","find","awk","sed","head","tail","less","more","wc","findstr","fc","git status","git diff","git log","git show","git branch","git remote","git ls-files","git rev-parse","git grep","git tag","git stash list","git describe","git config --get","node","npm","yarn","pnpm","tsc","python","pip","go","cargo","rustc"]);function xs(e){switch(e){case"plan":return new Set(["bash","write","edit","undo"]);case"accept-edits":return new Set(["bash"]);case"auto":case"auto-in-project":return new Set}}a(xs,"computeConfirmTools");function As(e){return e!==void 0&&Yo.includes(e)}a(As,"isPermissionMode");function fo(e,o){return As(e)?e:o}a(fo,"normalizePermissionMode");async function Rs(e){let o=e.resolve(e.provider),n=[];for(let t of e.efforts){if(e.signal?.aborted)break;let r=!1;try{await o.stream([{role:"user",content:"ping"}],[],"",{effort:t},{modelOverride:e.model,maxOutputTokensOverride:1,onReasoningEffortRejected:a(()=>{r=!0},"onReasoningEffortRejected"),onTextDelta:a(()=>{},"onTextDelta")},e.signal)}catch(i){n.push({effort:t,status:"error",error:i instanceof Error?i.message:String(i)});continue}r?(Ir(e.provider,e.model,t,"probed",e.now()),n.push({effort:t,status:"rejected"})):n.push({effort:t,status:"accepted"})}return n}a(Rs,"probeProviderReasoningEfforts");import rn from"fs";import di from"path";import Jo from"fs";import W from"path";import wo from"os";var Us=Ka(Os(),1);var Ns=new Set(["/dev/null","nul","NUL"]);function Qn(e){return Ns.has(e)||Ns.has(e.toLowerCase())}a(Qn,"isNullDevice");function mo(e){let o=e.trim();if(!o)return{statements:[],unparseable:!1};if(o.includes("`"))return{statements:[],unparseable:!0};let n;try{n=(0,Us.parse)(o,m=>`$${m}`)}catch{return{statements:[],unparseable:!0}}let t=[],r=[],i=[],l=[],c=null,d=!1,u=a(()=>{(i.length>0||l.length>0)&&(r.push({argv:i,redirections:l}),i=[],l=[])},"flushStage"),f=a(m=>{u(),r.length>0&&(t.push({precedingOp:c,stages:r}),r=[]),c=m},"flushStatement");for(let m=0;m<n.length;m+=1){let v=n[m];if(typeof v=="string"){i.push(v);continue}if("op"in v){let k=v.op;if(k==="&&"||k==="||"||k===";"){f(k);continue}if(k==="|"){u();continue}if(k==="&"){let y=n[m+1];if(y!==void 0&&typeof y!="string"&&"op"in y&&(y.op===">"||y.op===">>")){let $=n[m+2];if(typeof $!="string"){d=!0,m+=1;continue}l.push(Ds(`&${y.op}`,$)),m+=2;continue}d=!0;continue}if(sl(k)){let y=null,$=i[i.length-1];$!==void 0&&/^[0-9]+$/.test($)&&(y=$,i.pop());let g=n[m+1];if(typeof g!="string"){d=!0;continue}l.push(Ds(y?`${y}${k}`:k,g)),m+=1;continue}if(k==="glob"){let y=v.pattern;typeof y=="string"?i.push(y):d=!0;continue}d=!0;continue}if("comment"in v)break;d=!0}return f(null),{statements:t,unparseable:d}}a(mo,"parseBashCommand");var rl=new Set([">",">>","<","<<","<<<","&>","&>>"]),js=/^([0-9]+|&)(>>?|<<?)$/;function sl(e){return rl.has(e)||js.test(e)}a(sl,"isRedirectionOp");function Ds(e,o){let n=null,t=e,r=js.exec(e);return r&&(n=r[1],t=r[2]),{op:e,fd:n,append:t===">>"||e==="&>>",input:t==="<"||t==="<<"||e==="<<<",target:o}}a(Ds,"parseRedirection");import Ge from"node:path";var il={verbose:"switch",debug:"switch",erroraction:"value",warningaction:"value",informationaction:"value",progressaction:"value",errorvariable:"value",warningvariable:"value",informationvariable:"value",outvariable:"value",outbuffer:"value",pipelinevariable:"value",whatif:"switch",confirm:"switch",usetransaction:"switch"},po={path:"value",literalpath:"value",filter:"value",include:"value",exclude:"value"},Hs={"copy-item":ie(["path","destination"],{...po,destination:"value",container:"switch",recurse:"switch",force:"switch",passthru:"switch",credential:"value",fromsession:"value",tosession:"value"}),"move-item":ie(["path","destination"],{...po,destination:"value",force:"switch",passthru:"switch",credential:"value"}),"set-content":ie(["path","value"],{...po,value:"value",passthru:"switch",force:"switch",credential:"value",nonewline:"switch",encoding:"value",asbytestream:"switch",stream:"value"}),"add-content":ie(["path","value"],{...po,value:"value",passthru:"switch",force:"switch",credential:"value",nonewline:"switch",encoding:"value",asbytestream:"switch",stream:"value"}),"out-file":ie(["filepath","encoding"],{filepath:"value",literalpath:"value",inputobject:"value",encoding:"value",append:"switch",force:"switch",noclobber:"switch",width:"value",nonewline:"switch"}),"new-item":ie(["path"],{path:"value",name:"value",itemtype:"value",value:"value",force:"switch",credential:"value"}),ni:ie(["path"],{path:"value",name:"value",itemtype:"value",value:"value",force:"switch",credential:"value"}),"remove-item":ie(["path"],{...po,recurse:"switch",force:"switch",credential:"value",stream:"value"}),"rename-item":ie(["path","newname"],{path:"value",literalpath:"value",newname:"value",force:"switch",passthru:"switch",credential:"value"})},al={ea:"erroraction",ev:"errorvariable",wa:"warningaction",wv:"warningvariable",ia:"informationaction",infa:"informationaction",iv:"informationvariable",ov:"outvariable",ob:"outbuffer",pv:"pipelinevariable",vb:"verbose",db:"debug",wi:"whatif",cf:"confirm",usetx:"usetransaction",pspath:"literalpath",nooverwrite:"noclobber",type:"itemtype",target:"value"};function ie(e,o){return{positionals:e,parameters:{...il,...o}}}a(ie,"spec");function Dm(e){return Hs[e.toLowerCase()]!==void 0}a(Dm,"isPowerShellMutationCommand");function Bs(e){let o=vl(e[0]??""),n=Hs[o];if(!n)return Be(`unsupported PowerShell command: ${o||"<empty>"}`);let t=ll(e.slice(1),n);if(!t.complete)return Be(t.reason??"PowerShell parameter binding is incomplete");if(t.values.has("fromsession")||t.values.has("tosession"))return Be("PowerShell remoting changes the filesystem host");if((o==="new-item"||o==="ni")&&/^(?:symboliclink|junction|hardlink)$/i.test(t.values.get("itemtype")??""))return Be("PowerShell link creation has an unmodelled target relationship");if(ml(t))return Be("PowerShell path contains bracket wildcard syntax");let r=dl(o,t);return r?ul(r).some(fl)?{status:"incomplete",operations:[r],reason:"PowerShell path contains dynamic, wildcard, or array syntax"}:{status:"complete",operations:[r]}:Be("PowerShell mutation target is missing or ambiguous")}a(Bs,"analyzePowerShellMutation");function ll(e,o){let n=new Map,t=new Set,r=0,i=!1;for(let l=0;l<e.length;l+=1){let c=e[l];if(c==="--"){i=!0;continue}if(!i&&c.startsWith("-")){let u=cl(c,o);if(!u)return go(n,t,`unknown or ambiguous parameter ${c}`);if(u.kind==="switch"){let m=gl(u.inlineValue);if(m===void 0)return go(n,t,`switch ${c} has an unsupported value`);m&&t.add(u.name);continue}let f=u.inlineValue??e[l+1];if(f===void 0||u.inlineValue===void 0&&f.startsWith("-"))return go(n,t,`parameter ${c} has no bound value`);if(n.has(u.name))return go(n,t,`parameter ${c} is repeated`);n.set(u.name,f),u.inlineValue===void 0&&(l+=1);continue}for(;o.positionals[r]&&n.has(o.positionals[r]);)r+=1;let d=o.positionals[r];if(!d||n.has(d))return go(n,t,`unexpected positional argument ${c}`);n.set(d,c),r+=1}return{complete:!0,values:n,switches:t}}a(ll,"bindArguments");function cl(e,o){let n=/^--?([^:]+)(?::(.*))?$/.exec(e);if(!n)return;let t=n[1].toLowerCase(),r=al[t],i=Object.keys(o.parameters),l=r&&o.parameters[r]!==void 0?[r]:i.filter(u=>u.startsWith(t));if(l.length!==1)return;let c=l[0],d=o.parameters[c];return n[2]===void 0?{name:c,kind:d}:{name:c,kind:d,inlineValue:n[2]}}a(cl,"parseParameter");function dl(e,o){let n=Fs(o,"path","literalpath"),t=o.switches.has("force"),r=o.switches.has("whatif")?{whatIf:!0}:{};if(e==="copy-item"||e==="move-item"){if(!n)return;let l=o.values.get("destination")??wl(n);return{kind:e==="copy-item"?"copy":"move",source:n,destination:l,options:{force:t,...r,recursive:e==="copy-item"&&o.switches.has("recurse"),overwritePossible:!0}}}if(e==="rename-item"){let l=o.values.get("newname");return!n||!l||/[\\/]/.test(l)?void 0:{kind:"rename",source:n,destination:hl(n,l),options:{force:t,...r}}}if(e==="new-item"||e==="ni"){let l=o.values.get("name"),c=l?yl(o.values.get("path")??".",l):o.values.get("path"),d=o.values.get("itemtype"),u=d?{force:t,...r,itemType:d}:{force:t,...r};return c?{kind:"create",target:c,options:u}:void 0}let i=e==="out-file"?Fs(o,"filepath","literalpath"):n;if(i)return e==="remove-item"?{kind:"delete",target:i,options:{force:t,...r,recursive:o.switches.has("recurse")}}:{kind:"write",target:i,options:{force:t,...r,append:e==="add-content"||o.switches.has("append")}}}a(dl,"buildOperation");function Fs(e,...o){let n=o.map(t=>e.values.get(t)).filter(t=>!!t);return n.length===1?n[0]:void 0}a(Fs,"pathValue");function ul(e){return"target"in e?[e.target]:[e.source,e.destination]}a(ul,"operationPaths");function fl(e){return/[,*?`$]|@\(|[{}]/.test(e)||pl(e)}a(fl,"isAmbiguousPathExpression");function ml(e){return["path","filepath","destination","newname","name"].some(o=>/[\[\]]/.test(e.values.get(o)??""))}a(ml,"hasUnmodelledBracketWildcard");function pl(e){return/^[a-z]:[\\/]/i.test(e)?!1:/^[a-z][a-z0-9_.-]*:/i.test(e)}a(pl,"isPowerShellProviderPath");function gl(e){if(e===void 0||/^\$?true$|^1$/i.test(e))return!0;if(/^\$?false$|^0$/i.test(e))return!1}a(gl,"parseSwitchValue");function wl(e){let o=/^[a-z]:|\\/i.test(e)?Ge.win32:Ge.posix;return o.join(".",o.basename(e))}a(wl,"defaultDestination");function hl(e,o){let n=/^[a-z]:|\\/i.test(e)?Ge.win32:Ge.posix;return n.join(n.dirname(e),o)}a(hl,"joinSourceParent");function yl(e,o){return(/^[a-z]:|\\/i.test(e)?Ge.win32:Ge.posix).join(e,o)}a(yl,"joinPath");function vl(e){return e.replace(/\\/g,"/").split("/").at(-1)?.toLowerCase()??""}a(vl,"commandName");function go(e,o,n){return{complete:!1,values:e,switches:o,reason:n}}a(go,"failed");function Be(e){return{status:"incomplete",operations:[],reason:e}}a(Be,"incomplete");var kl=W.join(".agent","plan_mode_doc.md"),Zo=new Map,Qo=null;function Sl(e){if(!e||!e.trim())return!1;let o=e.trim().replace(/\s+/g," ").toLowerCase();for(let n of bs)if(o===n||o.startsWith(n+" ")){if(n==="sed"&&o.split(/\s+/).some(i=>i.startsWith("-i")||i==="--in-place"))return!1;if(n==="awk"){let r=o.split(/\s+/);if(r.includes("-f")||r.includes("--file"))return!1}if(["node","npm","yarn","pnpm","tsc","python","pip","go","cargo","rustc","ruby","perl"].includes(n)){let r=o.split(/\s+/).slice(1);if(r.length>0&&!r.every(i=>/^(-v|--version|-h|--help)$/.test(i)))return!1}return!0}return!1}a(Sl,"isSingleBashReadCommand");var $l=/^[a-zA-Z0-9]+$/;function bl(e){let o=e.trim();if(!o.endsWith("--help")||o.includes('"')||o.includes("'"))return!1;let n=!1;for(let t of o.split(/\s+/))if(t.startsWith("-"))if(t==="--help")n=!0;else return!1;else if(!$l.test(t))return!1;return n}a(bl,"isHelpCommand");function rt(e){if(!e||!e.trim())return!1;if(bl(e))return!0;let o=e.trim().replace(/\\\r?\n/g," "),n=mo(o);if(n.unparseable||n.statements.length===0)return!1;let t=n.statements.length>1||(n.statements[0]?.stages.length??0)>1;for(let r of n.statements){if(r.precedingOp!==null&&r.precedingOp!=="&&")return!1;for(let i of r.stages){for(let c of i.redirections)if(c.input||!Qn(c.target))return!1;let l=i.argv.join(" ");if(l&&!(t&&i.argv[0]?.toLowerCase()==="cd"&&i.argv.length>=2)&&!Sl(l))return!1}}return!0}a(rt,"isBashReadCommand");function xl(e){let o=e.trim();return o?rt(o)?null:"[Blocked] Direct !command execution only supports safe read-only commands. Use the bash tool for commands that write files, invoke shells, or require confirmation.":"[Shell: No command provided]"}a(xl,"getDirectShellBypassBlockReason");var Vs=new Set(["remove-item","set-content","add-content","out-file","new-item","copy-item","move-item","rename-item","ni"]),Al={bash:new Set(["-c"]),dash:new Set(["-c"]),sh:new Set(["-c"]),zsh:new Set(["-c"]),cmd:new Set(["/c"]),powershell:new Set(["-command","-c"]),pwsh:new Set(["-command","-c"])};function ot(e){let o=e[0]?.replace(/\\/g,"/"),n=o?.slice(o.lastIndexOf("/")+1).replace(/\.exe$/i,"").toLowerCase();if(!n)return;let t=Al[n];if(!t)return;let r=e.findIndex((i,l)=>l>0&&t.has(i.toLowerCase()));return r>=0?e[r+1]:void 0}a(ot,"getNestedShellCommand");function st(e){return Ys(e,0)}a(st,"isBashWriteCommand");function Ys(e,o){if(!e||!e.trim())return!1;let n=mo(e);if(n.unparseable)return!1;for(let t of n.statements)for(let r of t.stages){let i=r.argv.map(c=>c.toLowerCase());if(i.length>0){let c=i[0],d=i.length>=2?`${i[0]} ${i[1]}`:null;for(let u of $s)if(u===c||d!==null&&u===d)return!0}for(let c of i)if(Vs.has(c))return!0;for(let c of r.redirections)if(!c.input&&!Qn(c.target))return!0;let l=o<3?ot(r.argv):void 0;if(l!==void 0&&Ys(l,o+1))return!0}return!1}a(Ys,"isBashWriteCommandAtDepth");function it(e){let o=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\((.+)\)$/);return o?{tool:o[1].toLowerCase(),pattern:o[2]}:{tool:e.toLowerCase(),pattern:null}}a(it,"parseAllowedToolPattern");function Rl(e,o){if(o==="*")return!1;if(o.endsWith(":*")){let n=o.slice(0,-2);return e.startsWith(n)}return e===o}a(Rl,"matchesBashPatternLegacy");function El(e,o){if(o==="*")return!1;if(o.endsWith(":*")){let n=o.slice(0,-2);return e===n}return e===o}a(El,"matchesBashPatternByExtractedPrefix");async function at(e,o,n,t,r){if(e.toLowerCase()!=="bash")return!1;let i=o.command??"",l=[];for(let c of n){let d=it(c);if(d.tool==="bash"){if(d.pattern===null)return!0;l.push({pattern:d.pattern})}}if(l.length===0)return!1;if(t){let c;try{c=await t.extract(i,r)}catch{return!1}if(c.kind!=="prefix")return!1;for(let{pattern:d}of l)if(d&&El(c.value,d))return!0;return!1}for(let{pattern:c}of l)if(c&&Rl(i,c))return!0;return!1}a(at,"isToolCallAllowed");function lt(e,o,n){if(e.toLowerCase()!=="bash")return"";let t=o.command??"",r=t.split(" ");return r.length>1?`Bash(${r.slice(0,2).join(" ")}:*)`:`Bash(${t})`}a(lt,"generateSavePattern");function ho(e,o){try{let n=W.resolve(e),t=W.resolve(o),r=Ne(),i=W.join(t,".kodax");return D(n,i)||D(n,r)?!0:!(D(n,t)||ni().some(c=>D(n,c)))}catch{return!1}}a(ho,"isAlwaysConfirmPath");function Gs(e){return!e||e.startsWith("-")?!1:/^\.\.?[/\\]/.test(e)||e.startsWith("~/")||e.startsWith("~\\")||/^[a-zA-Z]:[/\\]/.test(e)?!0:e.startsWith("/")&&e.length>1?!(process.platform==="win32"&&nt.test(e)):!!(e.startsWith(".")&&/[/\\]/.test(e)||e.split(/[/\\]+/).includes(".."))}a(Gs,"looksLikePath");var nt=/^\/[A-Za-z][A-Za-z0-9]*(?::[A-Za-z0-9]+)?$/,zs={python:new Set(["-c"]),py:new Set(["-c"]),node:new Set(["-e","--eval","-p","--print"]),ruby:new Set(["-e"]),perl:new Set(["-e"])},Cl=new Set(["rg","ripgrep","grep","egrep","fgrep","findstr","select-string","sed","awk"]),Il=new Set(["-e","--regexp","--regex","-pattern"]),Tl=new Set(["-f","--file"]),qs=new Set(["-g","--glob","--iglob","-r","--replace"]),et=new Set(["--include","--exclude","--exclude-dir"]),_l={rg:qs,ripgrep:qs,grep:et,egrep:et,fgrep:et,awk:new Set(["-v","--assign"]),"select-string":new Set(["-inputobject"])},Pl={rg:new Set(["--ignore-file"]),ripgrep:new Set(["--ignore-file"]),grep:new Set(["--exclude-from"]),egrep:new Set(["--exclude-from"]),fgrep:new Set(["--exclude-from"]),"select-string":new Set(["-path","-literalpath"])};function ct(e){let o=e.replace(/\\/g,"/");return(o.split("/").pop()??o).toLowerCase().replace(/\.exe$/,"")}a(ct,"commandBasename");function Ll(){return{sourceIndexes:new Set,pathIndexes:new Set,pathValues:new Set}}a(Ll,"createCommandArgumentRoles");function ze(e,o,n,t){let r=e[o];r!==void 0&&(n.add(o),t?.add(r))}a(ze,"addIndexedValue");function en(e,o){let n=e.toLowerCase();if(o.startsWith("--")){let t=`${o}=`;return n.startsWith(t)?e.slice(t.length):void 0}return n.startsWith(o)&&e.length>o.length?e.slice(o.length):void 0}a(en,"attachedOptionValue");function Ml(e,o,n){for(let t=1;t<e.length;t+=1){let r=e[t]??"",i=r.toLowerCase();for(let l of o){if(i===l){ze(e,t+1,n.sourceIndexes);break}if(en(r,l)!==void 0){n.sourceIndexes.add(t);break}}}}a(Ml,"collectScriptSourceRoles");function Ks(e,o,n,t){if(o)for(let r=1;r<e.length;r+=1){let i=e[r]??"";if(i==="--")break;let l=i.toLowerCase();for(let c of o){if(l===c){ze(e,r+1,n,t);break}let d=en(i,c);if(d!==void 0){n.add(r),t?.add(d);break}}}}a(Ks,"collectFlagValueRoles");function Wl(e,o){let n=ct(e[0]??"");Ks(e,_l[n],o.sourceIndexes),Ks(e,Pl[n],o.pathIndexes,o.pathValues);let t=!1;for(let i=1;i<e.length;i+=1){let l=e[i]??"";if(l==="--")break;let c=l.toLowerCase();if(n==="findstr"&&c.startsWith("/c:")){o.sourceIndexes.add(i),t=!0;continue}if(n==="findstr"&&c.startsWith("/g:")){o.pathIndexes.add(i),o.pathValues.add(l.slice(3)),t=!0;continue}for(let d of Il){if(c===d){ze(e,i+1,o.sourceIndexes),t=!0;break}if(en(l,d)!==void 0){o.sourceIndexes.add(i),t=!0;break}}for(let d of Tl){if(c===d){ze(e,i+1,o.pathIndexes,o.pathValues),t=!0;break}let u=en(l,d);if(u!==void 0){o.pathValues.add(u),t=!0;break}}}if(!t){let i=!1;for(let l=1;l<e.length;l+=1){let c=e[l]??"";if(c==="--"){i=!0;continue}if(!(o.sourceIndexes.has(l)||o.pathIndexes.has(l))&&!(!i&&c.startsWith("-"))&&!(n==="findstr"&&nt.test(c))){ze(e,l,o.sourceIndexes);break}}}let r=!1;for(let i=1;i<e.length;i+=1){let l=e[i]??"";if(l==="--"){r=!0;continue}!r&&l.startsWith("-")||o.sourceIndexes.has(i)||o.pathIndexes.has(i)||n==="findstr"&&nt.test(l)||ze(e,i,o.pathIndexes,o.pathValues)}}a(Wl,"collectRegexArgumentRoles");function Js(e){let o=Ll(),n=ct(e[0]??""),t=/^python(?:\d+(?:\.\d+)*)?$/.test(n)?zs.python:zs[n];return t&&Ml(e,t,o),Cl.has(n)&&Wl(e,o),o}a(Js,"collectCommandArgumentRoles");function Zs(e){let o=[],n=[],t="",r=-1,i,l=a(d=>{r<0||(n.push({value:t,start:r,end:d}),t="",r=-1)},"finishWord"),c=a(()=>{n.length>0&&o.push(n),n=[]},"finishStage");for(let d=0;d<e.length;d+=1){let u=e[d];if(i){u===i?i=void 0:i==='"'&&u==="\\"&&e[d+1]==='"'?(t+=`${u}${e[d+1]}`,d+=1):t+=u;continue}u==='"'||u==="'"?(r<0&&(r=d),i=u):/\s/.test(u)?l(d):u==="|"||u==="&"||u===";"?(l(d),c()):(r<0&&(r=d),t+=u)}return i?[]:(l(e.length),c(),o)}a(Zs,"tokenizeRawCommandStages");function Qs(e){let o=e.split("");for(let n of Zs(e)){let t=Js(n.map(r=>r.value));for(let r of t.sourceIndexes){let i=n[r];if(i)for(let l=i.start;l<i.end;l+=1)o[l]=" "}}return o.join("")}a(Qs,"maskRawInlineSources");function Ol(e){let o=[],n;for(let i of[/"([A-Za-z]:\\[^"\r\n]+)"/g,/'([A-Za-z]:\\[^'\r\n]+)'/g])for(;(n=i.exec(e))!==null;)o.push(n[1]);let t=/(?:^|\s)(\.\.?\/[^\s]+|\.\.?\\[^\s]+|~\/[^\s]+|\.[^\s]*[/\\][^\s]*)/g;for(;(n=t.exec(e))!==null;)o.push(n[1]);let r=/(?:^|[\s:=<>])([a-zA-Z]:\\[^\s"'|;&<>]+)/g;for(;(n=r.exec(e))!==null;)o.push(n[1]);return o}a(Ol,"legacyRegexPathScan");function nn(e){let o=new Set,n=mo(e);if(!n.unparseable)for(let t of n.statements)for(let r of t.stages){let i=Js(r.argv);for(let l of i.pathValues)o.add(l);for(let l=0;l<r.argv.length;l+=1){let c=r.argv[l];i.sourceIndexes.has(l)||i.pathIndexes.has(l)||Gs(c)&&o.add(c)}for(let l of r.redirections)Gs(l.target)&&o.add(l.target)}for(let t of Ol(Qs(e)))o.add(t);return Array.from(o)}a(nn,"extractPathsFromCommand");function Nl(e,o,n=o){let t=nn(e);for(let r of t){let i=Do(r,n);if(ho(i,o))return!0}return!1}a(Nl,"isCommandOnProtectedPath");function Xs(e){let o=W.normalize(e);return process.platform==="win32"?o.toLowerCase():o}a(Xs,"normalizePathForComparison");function Dl(e,o){return Xs(e)===Xs(o)}a(Dl,"pathsEqual");function dt(e,o){try{let n=W.resolve(o),t=W.resolve(n,oi(ei(e)));return D(t,n)}catch{return!1}}a(dt,"isPathInsideProject");function Ul(e){let o=e.match(/[A-Za-z]:[\\/][^\s;|&<>(){}'"]+|\/[^\s;|&<>(){}'"]+/g);return o?o.filter(n=>!/^(?:\/dev\/|\/proc\/)/i.test(n)):[]}a(Ul,"collectAbsolutePathCandidates");function ut(e){let o=W.resolve(e),n=Zo.get(o);if(n)return n;if(Jo.existsSync(o)){let c=Jo.realpathSync.native(o);return Zo.set(o,c),c}let t=[],r=o;for(;!Jo.existsSync(r);){let c=W.dirname(r);if(c===r)return Zo.set(o,o),o;t.unshift(W.basename(r)),r=c}let i=Jo.realpathSync.native(r),l=W.join(i,...t);return Zo.set(o,l),l}a(ut,"resolveExistingPathPrefix");function ei(e){return e==="~"?wo.homedir():e.startsWith(`~${W.sep}`)||e.startsWith("~/")||e.startsWith("~\\")?W.join(wo.homedir(),e.slice(2)):e}a(ei,"expandHomeDirectory");function oi(e){let o=wo.tmpdir(),n=[[/^%temp%/i,o],[/^%tmp%/i,o],[/^\$env:temp\b/i,o],[/^\$env:tmp\b/i,o],[/^\$tmpdir\b/i,o],[/^\$temp\b/i,o],[/^\$tmp\b/i,o]];for(let[t,r]of n)if(t.test(e))return e.replace(t,r);return e}a(oi,"expandSystemTempAlias");function jl(e,o,n=o){let t=W.resolve(n??o??process.cwd()),r=oi(ei(e)),i=W.isAbsolute(r)?W.resolve(r):W.resolve(t,r);return ut(i)}a(jl,"resolvePermissionPath");function ni(){if(Qo)return Qo;let e=new Set,o=[wo.tmpdir(),process.env.TEMP,process.env.TMP,process.env.TMPDIR].filter(n=>typeof n=="string"&&n.trim().length>0);for(let n of o)try{e.add(ut(n))}catch{}return Qo=Array.from(e),Qo}a(ni,"getSystemTempDirectories");function ft(e){let o=ut(e??process.cwd());return{projectPlanDoc:W.join(o,kl),systemTempDirs:ni()}}a(ft,"getPlanModeAllowedWritablePaths");function tt(e,o,n=o){let t=jl(e,o,n),{projectPlanDoc:r,systemTempDirs:i}=ft(o);return Dl(t,r)?!0:i.some(l=>D(t,l))}a(tt,"isPlanModeAllowedPath");function Fl(e){let{projectPlanDoc:o,systemTempDirs:n}=ft(e),t=n[0]??wo.tmpdir();return`${o} or the system temp directory (${t})`}a(Fl,"formatPlanModeAllowedLocations");var Hl=new Set(["-a","--append","-i","--ignore-interrupts"]);function Bl(e){let o=[];for(let n=1;n<e.argv.length;n+=1){let t=e.argv[n];Hl.has(t)||t.startsWith("-")||o.push(t)}return o}a(Bl,"collectTeeTargets");function Gl(e){let o=Bs(e.argv),n=[];for(let t of o.operations)"target"in t?n.push(t.target):t.kind==="copy"?n.push(t.destination):n.push(t.source,t.destination);return n}a(Gl,"collectPowerShellWriteTargets");function qe(e){return on(e,0,!0)}a(qe,"collectBashWriteTargets");function ti(e){return on(e,0,!1)}a(ti,"collectDeterministicBashWriteTargets");var zl=new Set(["rm","rmdir","mkdir","touch","mv","move","ren","del","erase","rd"]),ql=new Set(["cp","copy"]);function Kl(e,o=1){let n=[],t=!1;for(let r=o;r<e.length;r+=1){let i=e[r];i==="--"?t=!0:(t||!i.startsWith("-"))&&n.push(i)}return n}a(Kl,"collectPositionalArgs");function Xl(e){let o=ct(e.argv[0]??""),n=Kl(e.argv);if(zl.has(o))return n;if(ql.has(o)){let t=e.argv.findIndex(i=>i==="-t"||i==="--target-directory");if(t>=0){let i=e.argv[t+1];return i?[i]:[]}let r=e.argv.find(i=>i.startsWith("--target-directory="));return r?[r.slice(19)]:n.slice(-1)}if(o==="chmod"||o==="chown")return n.slice(1);if(o==="dd"){let t=e.argv.find(r=>r.startsWith("of="));return t?[t.slice(3)]:[]}return[]}a(Xl,"collectDirectCommandWriteTargets");function Vl(e){let o=[],n=Qs(e),t;for(let r=0;r<n.length;r+=1){let i=n[r];if(t!==void 0){i===t?t=void 0:i==="\\"&&t==='"'&&(r+=1);continue}if(i==='"'||i==="'"){t=i;continue}if(i==="\\"){r+=1;continue}if(i!==">")continue;for(n[r+1]===">"&&(r+=1);/\s/.test(n[r+1]??"");)r+=1;let l=n[r+1],c=r+(l==='"'||l==="'"?2:1),d=c;for(;d<n.length;){let u=n[d];if(l==='"'||l==="'"){if(u===l)break}else if(/\s|[|;&<>]/.test(u))break;d+=1}d>c&&o.push(n.slice(c,d)),r=d}return o}a(Vl,"collectRawOutputRedirectionTargets");function on(e,o,n){let t=new Set,r=a(l=>{let c=l?.trim();c&&t.add(c)},"pushTarget");if(n)for(let l of nn(e))r(l);else for(let l of Vl(e))r(l);let i=mo(e);if(i.unparseable){if(o<3)for(let l of Zs(e)){let c=ot(l.map(d=>d.value));if(c!==void 0)for(let d of on(c,o+1,n))r(d)}return Array.from(t)}for(let l of i.statements)for(let c of l.stages){for(let f of c.redirections)f.input||r(f.target);let d=c.argv[0]?.toLowerCase();if(!d)continue;if(d==="tee")for(let f of Bl(c))r(f);else if(Vs.has(d))for(let f of Gl(c))r(f);if(!n)for(let f of Xl(c))r(f);let u=o<3?ot(c.argv):void 0;if(u!==void 0)for(let f of on(u,o+1,n))r(f)}return Array.from(t)}a(on,"collectBashWriteTargetsAtDepth");function ri(e,o){if(!st(e))return{dangerous:!1};let n=new Set([...qe(e),...Ul(e)]);for(let t of n)if(!dt(t,o))return{dangerous:!0,reason:`Command may modify file outside project: ${t}`};return{dangerous:!1}}a(ri,"getBashOutsideProjectWriteRisk");function si(e,o,n,t=n){let r=Fl(n);if(Yr(e))return null;if(uo.has(e)){let i=typeof o.path=="string"?o.path:"";return i?tt(i,n,t)?null:`[Blocked] Plan mode only allows file modifications in ${r}. Requested path: ${i}`:`[Blocked] Tool '${e}' is not allowed in plan mode unless it targets ${r}.`}if(e==="bash"){let i=o.command??"";if(!st(i))return null;let l=qe(i);if(l.length===0)return`[Blocked] Plan mode only allows bash write operations when every target is either ${r}. Could not determine a safe target from: ${i.slice(0,80)}${i.length>80?"...":""}`;let c=l.find(d=>!tt(d,n,t));return c?`[Blocked] Plan mode only allows bash write operations in ${r}. Blocked target: ${c}`:null}return`[Blocked] Tool '${e}' has side effects and is not permitted in plan mode. Switch to accept-edits or auto mode to use it, or work within ${r}.`}a(si,"getPlanModeBlockReason");import tn from"node:path";import pt from"node:os";function ai(){try{return Ne()}catch{return}}a(ai,"safeGetAgentConfigHome");function mt(e,o){let n=process.platform==="win32"?/^(?:\$\{home\}|\$home|\$env:(?:home|userprofile)|%userprofile%)(?=$|[\\/])/i:/^(?:\$\{HOME\}|\$HOME)(?=$|[\\/])/;return Do(e.replace(n,pt.homedir()),o)}a(mt,"resolveShellWriteTarget");function ii(e,o){let n=ai();if(n&&D(e,n))return"user-kodax";let t=tn.join(tn.resolve(o),".kodax");if(D(e,t))return"project-kodax"}a(ii,"resolveProtectedZone");function Yl(){let e=new Set;try{e.add(pt.tmpdir())}catch{}for(let o of["TEMP","TMP","TMPDIR"]){let n=process.env[o];n&&n.length>0&&e.add(n)}return Array.from(e)}a(Yl,"getSystemTempDirs");var Jl=new Set(["bash"]),Zl={toolNames:Jl,collect(e,o,n=o){let t=typeof e.input.command=="string"?e.input.command:"";if(!t||!o)return[];let r=[],i=new Set,l=new Set,c=Yl(),d=tn.resolve(o);for(let u of nn(t)){let f;try{f=mt(u,n)}catch{continue}let m=ii(f,o);if(m){i.has(f)||(i.add(f),r.push({kind:"protected_path",path:u,zone:m}));continue}if(ho(f,o)){let v=c.some(y=>D(f,y)),k=D(f,d);!v&&!k&&!l.has(f)&&(l.add(f),r.push({kind:"outside_project",path:u}))}}for(let u of qe(t)){let f;try{f=mt(u,n)}catch{continue}ii(f,o)||D(f,d)||c.some(k=>D(f,k))||r.push({kind:"shell_redirect_outside",target:u})}return r}},cp=a((e,o,n)=>{if(e.name!=="bash")return{denied:!1};let t=typeof e.input.command=="string"?e.input.command:"",r=new Set([tn.join(pt.homedir(),".kodax")]),i=ai();i&&r.add(i);for(let l of ti(t)){let c=mt(l,n);if([...r].some(d=>D(c,d)))return{denied:!0,patternId:"user_kodax_write",reason:`Shell write to credential-zone path \`${l}\` (under ~/.kodax/) is permanently denied. KodaX config edits must use the \`kodax config\` CLI or SDK config API.`}}return{denied:!1}},"replBashUserKodaxWriteDeny");var sn=B("config.json");function ui(){return di.join(process.cwd(),".kodax","config.local.json")}a(ui,"getProjectConfigFile");function xp(e=process.env){let o=yo(sn);return Ql({settings:o.autoMode,env:e})}a(xp,"loadAutoModeSettings");function Ql(e={}){let o=e.settings??{},n=e.env??{},t=n.KODAX_AUTO_MODE_ENGINE?.trim(),r=t==="llm"||t==="rules"?t:void 0,i=o.engine==="llm"||o.engine==="rules"?o.engine:void 0,l=r??i??"llm",c=ci(o.classifierModel),d=ci(n.KODAX_AUTO_MODE_CLASSIFIER_MODEL),u=n.KODAX_AUTO_MODE_TIMEOUT_MS?.trim(),f=u!==void 0?Number(u):NaN,m=Number.isFinite(f)&&f>0?Math.floor(f):void 0,v=typeof o.timeoutMs=="number"&&o.timeoutMs>0?Math.floor(o.timeoutMs):void 0,k=li(n.KODAX_AUTO_SPECULATIVE_WINDOW_MS?.trim()),y=typeof o.speculativeWindowMs=="number"?li(String(o.speculativeWindowMs)):void 0;return{engine:l,classifierModel:c,classifierModelEnv:d,timeoutMs:m??v,speculativeWindowMs:k??y}}a(Ql,"resolveAutoModeSettings");function li(e){if(e===void 0||e==="")return;let o=Number(e);if(Number.isFinite(o))return o<0?0:Math.floor(o)}a(li,"parseSpeculativeWindow");function ci(e){if(typeof e!="string")return;let o=e.trim();return o.length===0?void 0:o}a(ci,"nonEmptyString");function yo(e){try{if(rn.existsSync(e))return JSON.parse(rn.readFileSync(e,"utf-8"))}catch{}return{}}a(yo,"readJsonFile");function fi(e,o){rn.mkdirSync(di.dirname(e),{recursive:!0}),rn.writeFileSync(e,JSON.stringify(o,null,2))}a(fi,"writeJsonFile");function gt(e){let o=yo(sn);fi(sn,{...o,permissionMode:e})}a(gt,"savePermissionModeUser");function Ap(){let e=yo(sn),o=yo(ui()),n=e.alwaysAllowTools??[],t=o.alwaysAllowTools??[];return[...new Set([...n,...t])]}a(Ap,"loadAlwaysAllowTools");function Rp(e,o,n=!1){let t=lt(e,o,n);if(!t)return;let r=ui(),i=yo(r),l=i.alwaysAllowTools??[];l.includes(t)||fi(r,{...i,alwaysAllowTools:[...l,t]})}a(Rp,"saveAlwaysAllowToolPattern");var wt=["ama","sa"];function mi(e){let o=wt.indexOf(e);return wt[(o+1)%wt.length]??"ama"}a(mi,"nextAgentMode");var ge=class{static{a(this,"CommandRegistry")}commands=new Map;aliases=new Map;register(o){let n=o.name.toLowerCase();if(this.commands.has(n))throw new Error(`Command "${o.name}" is already registered`);if(this.aliases.has(n)){let r=this.aliases.get(n);throw new Error(`Command "${o.name}" conflicts with existing alias for "${r}"`)}let t=new Set;for(let r of o.aliases??[]){let i=r.toLowerCase();if(i!==n){if(t.has(i))throw new Error(`Alias "${r}" is duplicated within command "${o.name}"`);if(this.commands.has(i))throw new Error(`Alias "${r}" conflicts with existing command "${i}"`);if(this.aliases.has(i)){let l=this.aliases.get(i);throw new Error(`Alias "${r}" is already registered for "${l}"`)}t.add(i)}}if(this.commands.set(n,{...o,source:o.source??"builtin"}),o.aliases)for(let r of o.aliases){let i=r.toLowerCase();i!==n&&this.aliases.set(i,n)}}unregister(o){let n=o.toLowerCase(),t=this.aliases.get(n)??n;if(!this.commands.has(t))return!1;let r=this.commands.get(t);if(r?.aliases)for(let i of r.aliases)this.aliases.delete(i.toLowerCase());return this.commands.delete(t),!0}get(o){let n=o.toLowerCase(),t=this.aliases.get(n)??n;return this.commands.get(t)}has(o){let n=o.toLowerCase(),t=this.aliases.get(n)??n;return this.commands.has(t)}getAll(o){let n=new Map;for(let[t,r]of this.commands)o&&r.source!==o||n.has(t)||n.set(t,{name:r.name,aliases:r.aliases,description:r.description,source:r.source??"builtin",usage:r.usage,priority:r.priority,location:r.location,path:r.path,userInvocable:r.userInvocable,disableModelInvocation:r.disableModelInvocation,allowedTools:r.allowedTools,context:r.context,agent:r.agent,argumentHint:r.argumentHint,model:r.model});return Array.from(n.values()).sort((t,r)=>t.name.localeCompare(r.name))}getBySource(o){return this.getAll(o)}getNames(){return Array.from(this.commands.keys()).sort()}clear(){this.commands.clear(),this.aliases.clear()}get size(){return this.commands.size}get aliasCount(){return this.aliases.size}},ec=new ge;function ht(e){return[`ready=${e.ready}`,`new=${e.newlyActive}`,`attention=${e.attention}`,`active=${e.active}`].join(" ")}a(ht,"formatLearningStatus");function Lp(e){if(e.ready+e.newlyActive+e.attention!==0)return`Learning recovery: ${ht(e)} [/learn]`}a(Lp,"formatLearningRecoverySummary");import K from"chalk";import{Buffer as hi}from"node:buffer";import{spawn as oc}from"node:child_process";import pi from"node:process";var Ae="\x1B",nc="\x07",yt=`${Ae}\\`;function gi(e,o){return e.SSH_CONNECTION?!1:o==="win32"||o==="darwin"||o==="linux"}a(gi,"shouldPreferNativeClipboard");function tc(e,o){let n=hi.from(e,"utf8").toString("base64"),t=o.TERM==="xterm-kitty"?yt:nc,r=`${Ae}]52;c;${n}${t}`;return o.TMUX?`${Ae}Ptmux;${r.replaceAll(Ae,`${Ae}${Ae}`)}${yt}`:o.STY?`${Ae}P${r}${yt}`:r}a(tc,"buildOscSequence");async function an(e,o,n){return new Promise((t,r)=>{let i=oc(e,o,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),l="";i.on("error",r),i.stderr?.on("data",c=>{l+=c.toString()}),i.on("close",c=>{if(c===0){t(!0);return}r(new Error(l.trim()||`${e} exited with code ${c??"unknown"}`))}),i.stdin?.write(n),i.stdin?.end()})}a(an,"execClipboardCommand");function rc(e){let o="$stream = [Console]::OpenStandardInput(); $buffer = New-Object byte[] 8192; $memory = New-Object System.IO.MemoryStream; while (($read = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) { $memory.Write($buffer, 0, $read) }; $text = [System.Text.Encoding]::UTF8.GetString($memory.ToArray()); Set-Clipboard -Value $text",n=hi.from(e,"utf8");return[["powershell",["-NoProfile","-NonInteractive","-Command",o],n],["pwsh",["-NoProfile","-NonInteractive","-Command",o],n],["cmd",["/c","chcp 65001 >nul & clip"],n]]}a(rc,"buildWindowsClipboardCandidates");async function wi(e,o,n){if(o.SSH_CONNECTION)return!1;switch(n){case"win32":{let t=rc(e);for(let[r,i,l]of t)try{if(await an(r,i,l))return!0}catch{}return!1}case"darwin":return an("pbcopy",[],e);case"linux":{let t=[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]];for(let[r,i]of t)try{if(await an(r,i,e))return!0}catch{}return!1}default:return!1}}a(wi,"tryNativeClipboard");async function sc(e,o){if(!o.TMUX)return!1;let n=o.LC_TERMINAL==="iTerm2"?["load-buffer","-"]:["load-buffer","-w","-"];try{return await an("tmux",n,e)}catch{return!1}}a(sc,"tryTmuxClipboard");async function yi(e,o={}){let n=o.env??pi.env,t=o.platform??pi.platform,r=e.trimEnd(),i=tc(r,n);if(!r)throw new Error("Nothing to copy.");if(gi(n,t))try{if(await wi(r,n,t))return{path:"native"}}catch{}if(await sc(r,n))return{path:"tmux-buffer"};if(o.terminalWrite?.(i))return{path:"osc52"};if(!gi(n,t))try{if(await wi(r,n,t))return{path:"native"}}catch{}throw new Error("Unable to access any clipboard path.")}a(yi,"copyTextToClipboard");var vt;(function(e){e.Idle="idle",e.Responding="responding",e.WaitingForConfirmation="waiting_for_confirmation"})(vt||(vt={}));var z;(function(e){e.Scheduled="scheduled",e.Validating="validating",e.AwaitingApproval="awaiting_approval",e.Executing="executing",e.Success="success",e.Error="error",e.Cancelled="cancelled"})(z||(z={}));var Fp={[z.Scheduled]:"\u25CB",[z.Validating]:"\u25CC",[z.AwaitingApproval]:"?",[z.Executing]:"\u25CB",[z.Success]:"\u2713",[z.Error]:"\u2717",[z.Cancelled]:"-"},vi;(function(e){e[e.Low=-100]="Low",e[e.Normal=0]="Normal",e[e.High=100]="High",e[e.Critical=200]="Critical"})(vi||(vi={}));var Hp={streamingState:vt.Idle,currentResponse:"",history:[],pendingToolCalls:[],sessionId:"",provider:"",model:"",isLoading:!1};var ic="[redacted]",ki="[truncated]";function ae(e,o=2e3){return e.length>o?`${e.slice(0,o-3)}...`:e}a(ae,"truncateToolReplayText");function ac(e){let o=e.toLowerCase().replace(/[\s_-]/g,"");return o.includes("token")||o.includes("password")||o.includes("secret")||o.includes("apikey")||o.includes("accesstoken")||o==="authorization"||o==="cookie"||o==="setcookie"}a(ac,"isSensitiveToolInputKey");function Si(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Si,"isRecord");function kt(e,o=0,n=new WeakSet){if(e===null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string")return ae(e);if(o>=6)return ki;if(typeof e=="object"&&e!==null){if(n.has(e))return ki;if(n.add(e),Array.isArray(e))return e.slice(0,50).map(r=>kt(r,o+1,n));if(!Si(e))return ae(String(e));let t={};for(let[r,i]of Object.entries(e).slice(0,50))t[r]=ac(r)?ic:kt(i,o+1,n);return t}return ae(String(e))}a(kt,"sanitizeToolJsonValue");function $i(e){if(!e)return;let o=kt(e);return Si(o)?o:void 0}a($i,"sanitizeToolInput");function bi(e){if(e!==void 0){if(typeof e=="string")return ae(e);try{return ae(JSON.stringify(e))}catch{return ae(String(e))}}}a(bi,"stringifyToolReplayValue");function Xp(e){return e.type==="tool_summary"||e.type==="task_completed"?{type:"event",text:e.text,icon:"tool",...e.timestamp===void 0?{}:{timestamp:e.timestamp}}:e.type==="tool_group"?{type:"tool_group",tools:e.tools.map(gc),...e.timestamp===void 0?{}:{timestamp:e.timestamp}}:e}a(Xp,"seedToHistoryItem");var lc="[Thinking]",cc="[/Thinking]",dc="Untitled Session",xi=50,uc=60,Ri="...",Ei=["[Managed Task]","[Managed Task Protocol Retry]","Assigned native agent identity:","Tool policy:","Blocked tools:","Allowed shell patterns:","Dependency handoff artifacts:","Dependency summary preview:","Preferred agent:","Read structured bundle first:","Read human summary next:"],Ci=[/(?:^|\n)You are the [^\n]+ role for a managed KodaX task\./,/(?:^|\n)Primary task:/,/(?:^|\n)Work intent:/,/(?:^|\n)Complexity:/,/(?:^|\n)Risk:/,/(?:^|\n)Harness:/,/(?:^|\n)Brainstorm required:/],fc=/(^|\r?\n)\[Thinking\]\r?\n([\s\S]*?)\r?\n\[\/Thinking\](?=\r?\n|$)/g,mc="Session ended before the tool completed.";function pc(e){switch(e){case"success":return z.Success;case"error":return z.Error;case"cancelled":return z.Cancelled;case"awaiting_approval":return z.AwaitingApproval;default:return e}}a(pc,"toolCallSeedToHistoryToolStatus");function gc(e){return{id:e.id,name:e.name,status:pc(e.status),...e.input!==void 0?{input:e.input}:{},...e.preview!==void 0?{preview:e.preview}:{},...e.output!==void 0?{output:e.output}:{},...e.error!==void 0?{error:e.error}:{},startTime:e.startTime??Date.now(),...e.endTime!==void 0?{endTime:e.endTime}:{}}}a(gc,"toolCallSeedToHistoryToolCall");function wc(e){let o=-1;for(let n of Ei){let t=e.indexOf(n);t>=0&&(o===-1||t<o)&&(o=t)}for(let n of Ci){let t=n.exec(e);t&&t.index>=0&&(o===-1||t.index<o)&&(o=t.index)}return o}a(wc,"findControlPlaneCutIndex");function hc(e){return Ei.some(o=>e.includes(o))||Ci.some(o=>o.test(e))}a(hc,"hasControlPlaneSignal");function Ii(e){let o=[];for(let n of e)n&&typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&o.push(String(n.text));return o}a(Ii,"collectTextBlocks");function cn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(cn,"isRecord");function yc(e){if(typeof e=="string")return ae(e);if(e===void 0)return"";try{return bi(e)??""}catch{return ae(String(e))}}a(yc,"toolResultContentToString");function vc(e){let o=yc(e.content),n=o.trimStart(),t=e.is_error===!0||n.startsWith("[Tool Error]")||n.startsWith("[Error]"),r=n.startsWith("[Cancelled]")||n.startsWith("[Blocked]");return t?{status:"error",error:o}:r?{status:"cancelled",error:o}:{status:"success",output:o}}a(vc,"inferToolResultSeed");function kc(e){let o=new Map;if(!e||e.role!=="user"||!Array.isArray(e.content))return o;for(let n of e.content)!cn(n)||n.type!=="tool_result"||typeof n.tool_use_id!="string"||o.set(n.tool_use_id,vc(n));return o}a(kc,"collectToolResultSeeds");function Sc(e,o){if(e.type!=="tool_use"||typeof e.id!="string"||typeof e.name!="string")return;let n=o.get(e.id)??{status:"cancelled",error:mc};return{id:e.id,name:e.name,status:n.status,...e.input!==void 0?{input:$i(cn(e.input)?e.input:{})??{}}:{},...n.output!==void 0?{output:n.output}:{},...n.error!==void 0?{error:n.error}:{}}}a(Sc,"buildToolCallSeed");function $c(e){return typeof e=="string"?e:Array.isArray(e)?Ii(e).join(`
3
3
  `):""}a($c,"extractAssistantTextOnly");function ko(e,o,n){n.trim().length!==0&&e.push({type:o,text:n})}a(ko,"pushSeed");function Ai(e){return e.replace(/^\n+/,"").replace(/\n+$/,"")}a(Ai,"stripLegacyTagBoundaryNewlines");function bc(e){let o=e.name,n=e.input;if(!n)return`\u26A1 ${o}`;let t=o==="bash"?vo(String(n.command??"")):o==="read"||o==="write"||o==="edit"?vo(String(n.file_path??n.path??"")):o==="grep"||o==="glob"?vo(String(n.pattern??"")):o==="web_search"||o==="web_fetch"?vo(String(n.query??n.url??"")):void 0;return t?`\u26A1 ${o}(${t})`:`\u26A1 ${o}`}a(bc,"formatToolUseSummary");function vo(e,o=60){let n=e.replace(/\s+/g," ").trim();return n.length>o?`${n.slice(0,o)}...`:n}a(vo,"truncateToolHint");function xc(e){if(!e.includes(lc)||!e.includes(cc))return e.trim().length>0?[{type:"assistant",text:e}]:[];let o=[],n=0;for(let t of e.matchAll(fc)){let r=t.index??-1,i=t[1]??"",l=t[2]??"";if(r<0)continue;let c=r+i.length;ko(o,"assistant",Ai(e.slice(n,c))),ko(o,"thinking",l),n=r+t[0].length}return ko(o,"assistant",Ai(e.slice(n))),o.length===0?e.trim().length>0?[{type:"assistant",text:e}]:[]:o}a(xc,"parseLegacyAssistantContent");function Ti(e,o){if(typeof e=="string")return xc(e);if(!Array.isArray(e))return[];let n=[],t=[],r=[],i=a(()=>{t.length!==0&&(ko(n,"assistant",t.join(`
4
4
  `)),t.length=0)},"flushAssistantBuffer"),l=a(()=>{r.length!==0&&(n.push({type:"tool_group",tools:[...r]}),r.length=0)},"flushToolBuffer");for(let c of e)if(!(!cn(c)||typeof c.type!="string"))switch(c.type){case"text":l(),"text"in c&&t.push(String(c.text));break;case"thinking":i(),l(),"thinking"in c&&ko(n,"thinking",String(c.thinking));break;case"tool_use":if(i(),o){let d=Sc(c,o);d&&r.push(d)}else if(typeof c.name=="string"){let d=bc({name:c.name,...cn(c.input)?{input:c.input}:{}});d&&n.push({type:"tool_summary",text:d})}break;case"tool_result":case"redacted_thinking":break;default:break}return l(),i(),n}a(Ti,"extractAssistantHistorySeeds");var Ac=["You are the Scout role","You are the Generator role","You are the Planner role","You are the Evaluator role"],Rc=/\r?\n?\`\`\`kodax[\w-]*[\s\S]*?\`\`\`\s*/g;function Ec(e){return Ac.some(o=>e.includes(o))}a(Ec,"isManagedWorkerPrompt");function _i(e){return e.replace(Rc,"").trim()}a(_i,"stripManagedProtocolBlocks");function Cc(e){switch(e.role){case"assistant":return Ti(e.content).flatMap(n=>{if(n.type!=="assistant")return[n];let t=_i(n.text);return t.length>0&&t.trim()!=="..."?[{...n,text:t}]:[]});case"user":{if(e._source==="sidecar-verifier"){let n=ln(e.content).trim();return n?[{type:"sidecar",text:n,verdict:"revise"}]:[]}if(e._source==="agent-completed"||e._source==="task-completed"){let n=ln(e.content).trim();return n?[{type:"task_completed",text:n}]:[]}if(e._synthetic)return[];let o=ln(e.content);return o.trim().length===0||Ec(o)?[]:[{type:"user",text:o}]}case"system":return[];default:return[]}}a(Cc,"extractHistorySeedsFromMessageWithoutTimestamp");function Pi(e,o){if(o===void 0)return[...e];let n=Date.parse(o);return!Number.isFinite(n)||n<0?[...e]:e.map(t=>({...t,timestamp:n}))}a(Pi,"withMessageTimestamp");function Ic(e){return Pi(Cc(e),e.timestamp)}a(Ic,"extractHistorySeedsFromMessage");function Vp(e){let o=[];for(let n=0;n<e.length;n+=1){let t=e[n];if(t){if(t.role==="assistant"){let r=kc(e[n+1]),i=Pi(Ti(t.content,r),t.timestamp);o.push(...i.map(l=>l.type==="assistant"?{...l,text:_i(l.text)}:l).filter(l=>l.type!=="assistant"||l.text.length>0&&l.text.trim()!=="..."));continue}o.push(...Ic(t))}}return o}a(Vp,"extractHistorySeedsFromMessages");function ln(e){return typeof e=="string"?e:Array.isArray(e)?Ii(e).join(`
5
5
  `):""}a(ln,"extractTextContent");function Tc(e){let o=e.replace(/\s+/g," ").trim();return o?o.length>xi?`${o.slice(0,xi)}${Ri}`:o:dc}a(Tc,"formatSessionTitle");function _c(e){if(e.role!=="user")return!1;let o=e.content;return!Array.isArray(o)||o.length===0?!1:o.every(n=>!!n&&typeof n=="object"&&"type"in n&&n.type==="tool_result")}a(_c,"isPureToolResultUserMessage");function St(e){for(let o=e.length-1;o>=0;o--){let n=e[o];if(n){if(n.role==="assistant"){let t=$c(n.content);return t&&t.trim()!=="..."?t:""}if(!_c(n))return""}}return""}a(St,"extractLastAssistantText");function Yp(e,o,n,t){let r=[St(e),o.trim(),n?.trim()??"",t?.trim()??""];for(let i of r){let l=Li(i);if(l)return l}return""}a(Yp,"resolveCompletedAssistantText");function Li(e){let o=e.trim();if(!o||o==="...")return"";let n=wc(o);return n===0?"":(n>0?o.slice(0,n):o).trim()}a(Li,"sanitizeUserFacingAssistantText");function Jp(e){let o=e.trim();return o.length>0&&Li(o).length===0&&hc(o)}a(Jp,"isControlPlaneOnlyAssistantText");function Zp(e){let o=e.find(t=>t.role==="user"),n=o?ln(o.content):"";return Tc(n)}a(Zp,"extractTitle");function Qp(e,o=uc){let n=e.replace(/\n/g," "),t=n.length>o?Ri:"";return n.slice(0,o)+t}a(Qp,"formatMessagePreview");var $t={name:"copy",description:"Copy last assistant message to clipboard",usage:"/copy",handler:a(async(e,o)=>{let n=St(o.messages);if(!n){console.log(K.yellow(`
@@ -619,4 +619,4 @@ Available Skills:
619
619
  [Skill "${t}" is not user-invocable]`)),!1;console.log(s.cyan(`
620
620
  [Invoking skill: ${t}]`)),i.argumentHint&&console.log(s.dim(`Arguments: ${r||"(none)"}`)),console.log();let l=await n.loadFull(t),c={workingDirectory:process.cwd(),projectRoot:o.gitRoot??void 0,sessionId:o.sessionId,environment:{},executeDynamicContext:o.skillDynamicContext?.execute,disableDynamicContext:o.skillDynamicContext?.disable},d=await Or(l,r,c);return console.log(s.green(`Skill activated: ${t}`)),console.log(s.dim("The skill context has been prepared for the AI.")),console.log(),{invocation:{prompt:d.content,source:"skill",displayName:t,path:l.skillFilePath,disableModelInvocation:d.disableModelInvocation,userInvocable:l.userInvocable,allowedTools:l.allowedTools,context:l.context,agent:l.agent,argumentHint:l.argumentHint,model:l.model,hooks:l.hooks,skillInvocation:{name:t,path:l.skillFilePath,description:l.description,arguments:r||void 0,allowedTools:l.allowedTools,context:l.context,agent:l.agent,argumentHint:l.argumentHint,model:l.model,hookEvents:l.hooks?Object.entries(l.hooks).filter(([,u])=>Array.isArray(u)&&u.length>0).map(([u])=>u):void 0,expandedContent:d.content}}}}catch(i){return console.log(s.red(`
621
621
  [Error invoking skill: ${i instanceof Error?i.message:String(i)}]`)),!1}}a(mr,"executeSkillCommand");var Wn=class{static{a(this,"SkillCompleter")}gitRoot;constructor(o){this.gitRoot=o}canComplete(o,n){return this.parseTrigger(o.slice(0,n))!==void 0}async getCompletions(o,n){let t=this.parseTrigger(o.slice(0,n));if(!t)return[];let r=t.partial.toLowerCase();return(await this.getSkills()).filter(l=>{let c=l.name.toLowerCase();return c.includes(r)||this.fuzzyIncludes(r,c)}).map(l=>({text:`${t.invocationPrefix}${l.name}`,display:l.name,description:this.truncateDescription(l.description),type:"skill"})).sort((l,c)=>{let d=l.display.toLowerCase().startsWith(r),u=c.display.toLowerCase().startsWith(r);return d&&!u?-1:!d&&u?1:l.display.length-c.display.length})}setGitRoot(o){this.gitRoot!==o&&(this.gitRoot=o)}parseTrigger(o){let n=o.match(/(^|\s)\/skill:([^\s]*)$/);if(n)return{partial:n[2]??"",invocationPrefix:"/skill:"};let t=o.match(/(^|\s)\/([^\s]*)$/);if(t)return{partial:t[2]??"",invocationPrefix:"/"}}async getSkills(){try{let o=Se(this.gitRoot);return o.size===0&&await De(this.gitRoot),o.listUserInvocable()}catch{return[]}}fuzzyIncludes(o,n){let t=0;for(let r=0;r<n.length&&t<o.length;r+=1)n[r]===o[t]&&(t+=1);return t===o.length}truncateDescription(o,n=50){return o.length<=n?o:o.slice(0,n-3)+"..."}};import{exec as Of}from"node:child_process";import*as no from"node:path";import{promisify as Nf}from"node:util";var Na=Nf(Of);function Df(e){let o=e.slice(3);if(!o)return;let n=o.indexOf(" -> ");return(n===-1?o:o.slice(n+4)).replace(/^"(.*)"$/,"$1").trim()||void 0}a(Df,"pathFromPorcelainLine");async function Da(e,o=10){try{let[{stdout:n},{stdout:t}]=await Promise.all([Na("git rev-parse --show-toplevel",{cwd:e,windowsHide:!0}),Na("git status --porcelain=v1 -uall",{cwd:e,windowsHide:!0})]),r=n.trim(),i=[],l=new Set;for(let c of t.split(`
622
- `)){if(!c.trim())continue;let d=Df(c);if(!d)continue;let u=no.resolve(r,d),f=no.relative(e,u).split(no.sep).join("/");if(!(!f||f.startsWith("..")||l.has(f))&&(l.add(f),i.push(f),i.length>=o))break}return i}catch{return[]}}a(Da,"getRecentWorkingSetFiles");function to(e){let o=e.lastIndexOf("/");if(o===-1)return-1;for(;o>0&&!/\s/.test(e[o-1]??"");)if(o=e.lastIndexOf("/",o-1),o===-1)return-1;return o}a(to,"findCommandSlashIndex");var wr=class{static{a(this,"FileCompleter")}cwdSource;cache=new Map;cacheTimeout=5e3;recentCache=new Map;recentFilesProvider;constructor(o,n=Da){this.cwdSource=o,this.recentFilesProvider=n}canComplete(o,n){let t=o.slice(0,n),r=t.lastIndexOf("@");return!(r===-1||r>0&&!/\s/.test(t[r-1]??"")||t.slice(r+1).includes(" "))}async getCompletions(o,n){let t=o.slice(0,n),r=t.lastIndexOf("@");if(r===-1)return[];let i=t.slice(r+1),l=[],c=this.resolveCwd(),d=i.lastIndexOf("/"),u=d===-1?c:Mo.join(c,i.slice(0,d)),f=d===-1?i:i.slice(d+1);try{let v=(await this.readdir(u)).filter(k=>k.toLowerCase().startsWith(f.toLowerCase()));for(let k of v){let y=Mo.join(u,k),$=await this.isDirectory(y),g=d===-1?k:i.slice(0,d+1)+k;l.push({text:"@"+g+($?"/":""),display:k+($?"/":""),description:$?"directory":"file",type:"file"})}}catch{}if(d===-1){let m=await this.getRecentFiles(c),v=new Set(l.map($=>$.text)),k=f.toLowerCase(),y=[];for(let $ of m){if(f&&!Mo.basename($).toLowerCase().startsWith(k))continue;let g="@"+$;v.has(g)||(v.add(g),y.push({text:g,display:$,description:"recent",type:"file"}))}l.unshift(...y)}return l}async getRecentFiles(o){let n=Date.now(),t=this.recentCache.get(o);if(t&&t.expiresAt>n)return t.files;let r=await this.recentFilesProvider(o);return this.recentCache.set(o,{files:r,expiresAt:Date.now()+this.cacheTimeout}),r}resolveCwd(){return typeof this.cwdSource=="function"?this.cwdSource():this.cwdSource??process.cwd()}async readdir(o){let n=Date.now(),t=this.cache.get(o);return t&&t.expiresAt>n?t.entries:(t&&this.cache.delete(o),new Promise(r=>{On.readdir(o,(i,l)=>{i?r([]):(this.cache.set(o,{entries:l,expiresAt:Date.now()+this.cacheTimeout}),r(l))})}))}async isDirectory(o){return new Promise(n=>{On.stat(o,(t,r)=>{n(!t&&r.isDirectory())})})}},hr=class{static{a(this,"CommandCompleter")}commands;constructor(){this.commands=new Map,this.loadCommands()}loadCommands(){for(let n of Lo().getAll())n.userInvocable!==!1&&this.commands.set(n.name,{description:n.description,aliases:n.aliases??[]});let o=se();for(let n of o?.listCommands()??[])n.metadata?.userInvocable!==!1&&this.commands.set(n.name,{description:n.description,aliases:n.aliases??[]})}canComplete(o,n){let t=o.slice(0,n),r=to(t);return r===-1?!1:!t.slice(r).includes(" ")}async getCompletions(o,n){let t=o.slice(0,n),r=to(t);if(r===-1)return[];this.commands.clear(),this.loadCommands();let i=t.slice(r+1).toLowerCase(),l=[];for(let[c,d]of this.commands){this.fuzzyMatch(i,c)&&l.push({text:"/"+c,display:"/"+c,description:d.description,type:"command"});for(let u of d.aliases)u!==c&&this.fuzzyMatch(i,u)&&l.push({text:"/"+u,display:"/"+u,description:`Alias for /${c}: ${d.description}`,type:"command"})}return l}fuzzyMatch(o,n){if(!o)return!0;let t=o.toLowerCase(),r=n.toLowerCase(),i=0;for(let l=0;l<r.length&&i<t.length;l++)r[l]===t[i]&&i++;return i===t.length}};function ev(e){let o=new wr(e),n=new Wn,t=new hr;return async r=>{let i=r.includes("@"),l=r.includes("/");if(!i&&!l)return[[],r];let c=[];if(l){let u=await Uf(r,r.length);c.push(...u)}if(l&&n.canComplete(r,r.length)){let u=await n.getCompletions(r,r.length);c.push(...u)}if(l&&t.canComplete(r,r.length)){let u=await t.getCompletions(r,r.length);c.push(...u)}if(i&&o.canComplete(r,r.length)){let u=await o.getCompletions(r,r.length);c.push(...u)}return[c.map(u=>jf(r,u)),r]}}a(ev,"createCompleter");async function Uf(e,o){let{ArgumentCompleter:n}=await import("./argument-completer-GHWEWPVQ.js"),t=new n;return t.canComplete(e,o)?t.getCompletions(e,o):[]}a(Uf,"getArgumentCompletions");function jf(e,o){if(o.type!=="argument")return o.text;let n=to(e);if(n!==-1&&!/\s/.test(e.slice(n)))return`${e} ${o.text}`;let r=e.match(/\S+$/)?.[0]??"";return`${r?e.slice(0,e.length-r.length):e}${o.text}`}a(jf,"formatReadlineCompletion");import{existsSync as Nn,readdirSync as Ha,readFileSync as Ba}from"node:fs";import{join as Dn}from"node:path";var Ff=[{name:"plan",description:"Read-only planning mode - blocks all modifications",type:"enum"},{name:"accept-edits",description:"File edits auto-approved, bash requires confirmation",type:"enum"},{name:"auto",description:"Use auto-mode classifier for tool permissions",type:"enum"}],ro=[{name:"none",description:"Disable reasoning when the model supports it",type:"enum"},{name:"auto",description:"Clear the explicit effort override",type:"enum"},{name:"low",description:"Use low reasoning effort",type:"enum"},{name:"medium",description:"Use medium reasoning effort",type:"enum"},{name:"high",description:"Use high reasoning effort",type:"enum"},{name:"xhigh",description:"Use extra-high reasoning effort",type:"enum"},{name:"max",description:"Use maximum reasoning effort",type:"enum"}];function Hf(e){if(e&&e.includes("/")){let o=e.indexOf("/"),n=e.slice(0,o),t=e.slice(o+1);if(We(n))try{return He(n).filter(i=>!t||i.toLowerCase().includes(t.toLowerCase())).map(i=>({name:`${n}/${i}`,description:i,type:"enum"}))}catch{}return[]}return Oe().map(o=>({name:o,description:`Switch to ${o} provider`,type:"enum"}))}a(Hf,"getModelArgs");var yr=[{name:"workspace",description:"Inspect current workspace/runtime truth in more detail",type:"enum"},{name:"runtime",description:"Alias for workspace runtime inspection",type:"enum"},{name:"worktree",description:"Alias for workspace runtime inspection",type:"enum"}],vr=[{name:"all",description:"Delete ALL sessions",type:"enum"}],Bf=[{name:"status",description:"Show MCP server status",type:"enum"},{name:"refresh",description:"Refresh MCP server catalogs",type:"enum"}],Gf=[{name:"status",description:"Show child-task fallback order",type:"enum"},{name:"off",description:"Disable child-task fallback providers",type:"enum"}],zf=[{name:"llm",description:"Use LLM classifier for auto mode",type:"enum"},{name:"rules",description:"Use rules-only auto mode",type:"enum"}],Ua=[{name:"ama",description:"Use AMA agent mode",type:"enum"},{name:"sa",description:"Use single-agent mode",type:"enum"},{name:"toggle",description:"Cycle to the next agent mode",type:"enum"}],ja=[{name:"on",description:"Enable logging",type:"enum"},{name:"off",description:"Disable logging",type:"enum"}],qf=[{name:"list",description:"List project memory files",type:"enum"},{name:"pending",description:"List pending memory proposals",type:"enum"},{name:"show",description:"Preview a memory proposal",type:"enum"},{name:"approve",description:"Approve a memory proposal",type:"enum"},{name:"reject",description:"Reject a memory proposal",type:"enum"},{name:"curate",description:"Report memory governance findings",type:"enum"},{name:"rebuild",description:"Rebuild MEMORY.md index",type:"enum"},{name:"open",description:"Print the memory entrypoint path",type:"enum"},{name:"help",description:"Show memory help",type:"enum"}],Kf=[{name:"status",description:"Show current persistent goal",type:"enum"},{name:"pause",description:"Pause the active goal",type:"enum"},{name:"resume",description:"Resume a paused goal",type:"enum"},{name:"clear",description:"Clear the current goal",type:"enum"},{name:"help",description:"Show goal help",type:"enum"},{name:"--tokens",description:"Set an optional goal token budget",type:"enum"}],Xf=[{name:"show",description:"Show a captured paste by id",type:"enum"},{name:"list",description:"List captured pastes",type:"enum"}],Vf=[{name:"--lean",description:"Add a minimal-diff/YAGNI review pass",type:"enum"},{name:"--workflow",description:"Review through a dynamic workflow",type:"enum"},{name:"base",description:"Review changes against the detected base branch",type:"enum"},{name:"sha",description:"Review a specific commit",type:"enum"},{name:"help",description:"Show review help",type:"enum"}],Yf=[{name:"init",description:"Create AGENTS.md in the target project if absent",type:"enum"},{name:"lean",description:"Initialize or LLM-review AGENTS.md for Lean Mode guidance",type:"enum"},{name:"help",description:"Show agents help",type:"enum"}],Jf=[{name:"status",description:"Inspect the current repo-intelligence runtime state",type:"enum"},{name:"mode",description:"Switch repo-intelligence runtime mode",type:"enum"},{name:"trace",description:"Toggle repo-intelligence trace output",type:"enum"}],Zf=[{name:"auto",description:"Let KodaX pick the best repo-intelligence engine",type:"enum"},{name:"full",description:"Prefer the full repo-intelligence engine",type:"enum"},{name:"light",description:"Use the light repo-intelligence engine",type:"enum"},{name:"off",description:"Disable repo-intelligence injection",type:"enum"}],Qf=[{name:"on",description:"Enable repo-intelligence trace output",type:"enum"},{name:"off",description:"Disable repo-intelligence trace output",type:"enum"},{name:"toggle",description:"Toggle repo-intelligence trace output",type:"enum"}],em=[{name:"status",description:"Deprecated alias for /repo-intel status",type:"enum"}],om=[{name:"list",description:"List built-in and saved workflows",type:"enum"},{name:"create",description:"Generate and run a workflow from a request",type:"enum"},{name:"runs",description:"List active and recent workflow runs",type:"enum"},{name:"show",description:"Show latest run or a specific workflow run",type:"enum"},{name:"pause",description:"Pause future child launches for a run",type:"enum"},{name:"resume",description:"Resume a paused run",type:"enum"},{name:"stop",description:"Stop an active workflow run",type:"enum"},{name:"delete",description:"Delete one persisted workflow run or generated saved capsule",type:"enum"},{name:"prune",description:"Preview or delete old terminal workflow runs",type:"enum"},{name:"rerun",description:"Rerun a run id or saved workflow name",type:"enum"},{name:"save",description:"Save a generated run as a workflow capsule",type:"enum"},{name:"rename",description:"Rename a run display name or saved workflow capsule",type:"enum"},{name:"revise",description:"Generate a revised workflow capsule",type:"enum"},{name:"help",description:"Show workflow help",type:"enum"}],nm=new Set(["show","pause","resume","stop","delete","rerun","save","rename","revise"]),tm=new Set(["show","delete","rerun","save","rename","revise"]),rm=[{name:"--all",description:"Show all persisted workflow runs",type:"enum"},{name:"--limit",description:"Show at most N persisted workflow runs",type:"enum"}],sm=[{name:"--dry-run",description:"Preview cleanup without deleting runs",type:"enum"},{name:"--keep",description:"Keep the newest N terminal runs",type:"enum"},{name:"--older-than",description:"Delete terminal runs older than Nd or Nh",type:"enum"}],im=[{name:"--force",description:"Delete stale non-terminal run records",type:"enum"},{name:"--run",description:"Treat the target as a workflow run record",type:"enum"},{name:"--saved",description:"Treat the target as a generated saved workflow capsule",type:"enum"}],am=[".workflow.json",".ts",".mjs",".js"];function lm(e,o){switch(e){case"pause":return o==="running";case"resume":return o==="paused";case"stop":return o==="running"||o==="paused";case"delete":return o!=="running"&&o!=="paused";default:return!0}}a(lm,"workflowRunMatchesSubcommand");function Un(e){return/^[a-zA-Z0-9._-]{1,120}$/.test(e)&&!e.startsWith(".")&&!e.includes("..")}a(Un,"isWorkflowRunEntryName");function cm(e,o){let n=Dn(e,"workflow-metadata.json");if(Nn(n))try{let r=JSON.parse(Ba(n,"utf8"));if(typeof r=="object"&&r!==null){let i=r.displayName;if(typeof i=="string"&&Un(i.trim()))return i.trim()}}catch{}let t=o.displayName;return typeof t=="string"&&Un(t.trim())?t.trim():void 0}a(cm,"readWorkflowRunDisplayName");function dm(){let e=Ee(process.cwd()).key,o=B("workflow-runs",e);if(!Nn(o))return[];let n=[];for(let t of Ha(o)){if(!Un(t))continue;let r=Dn(o,t,"run.json");if(Nn(r))try{let i=JSON.parse(Ba(r,"utf8")),l=typeof i.workflow=="string"?i.workflow:"?",c=typeof i.status=="string"?i.status:"?",d=typeof i.endedAt=="number"?i.endedAt:0;n.push({arg:{name:t,description:`${l} - ${c}`,type:"string"},endedAt:d});let u=cm(Dn(o,t),i);u&&u!==t&&n.push({arg:{name:u,description:`${l} alias for ${t} - ${c}`,type:"string"},endedAt:d})}catch{}}return n.sort((t,r)=>r.endedAt-t.endedAt).map(t=>t.arg)}a(dm,"getPersistedWorkflowRunIdArgs");function jn(e){let o=Fe().list().filter(r=>lm(e,r.status)).map(r=>({name:r.runId,description:`${r.workflow} - ${r.status}`,type:"string"})),n=tm.has(e)?dm():[],t=new Set;return[...o,...n].filter(r=>t.has(r.name)?!1:(t.add(r.name),!0))}a(jn,"getWorkflowRunIdArgs");function um(e){for(let o of am)if(e.endsWith(o)){let n=e.slice(0,-o.length);return Un(n)?n:void 0}}a(um,"savedWorkflowNameFromFile");function Wo(e={}){let o=[{path:B("workflows"),source:"personal"},{path:Dn(process.cwd(),".kodax","workflows"),source:"project"}],n=new Map;for(let t of o)if(Nn(t.path))try{for(let r of Ha(t.path)){if(e.generatedOnly===!0&&!r.endsWith(".workflow.json"))continue;let i=um(r);i&&n.set(i,{name:i,description:`${t.source} saved workflow`,type:"enum"})}}catch{}return[...n.values()].sort((t,r)=>t.name.localeCompare(r.name))}a(Wo,"getSavedWorkflowNameArgs");function fm(){let e=new Map;for(let o of jn("rerun"))e.set(o.name,{...o,description:`recent run: ${o.description}`,type:"string"});for(let o of Wo()){let n=e.get(o.name);if(n){e.set(o.name,{...n,description:`${n.description}; also ${o.description}`});continue}e.set(o.name,{...o,description:o.description,type:"string"})}return[...e.values()]}a(fm,"getWorkflowRerunArgs");function kr(e){let o=new Map;for(let n of jn(e))o.set(n.name,{...n,description:`workflow run: ${n.description}`,type:"string"});for(let n of Wo({generatedOnly:e==="delete"})){let t=o.get(n.name);if(t){o.set(n.name,{...t,description:`${t.description}; also ${n.description}`});continue}o.set(n.name,{...n,description:n.description,type:"string"})}return[...o.values()]}a(kr,"getWorkflowRunOrSavedNameArgs");function Fa(e){let o=new Set(e.slice(1).filter(n=>n.startsWith("--")));return o.has("--saved")?Wo({generatedOnly:!0}):o.has("--run")?jn("delete"):kr("delete")}a(Fa,"getWorkflowDeleteTargetArgs");function mm(e){let[o=""]=e,n=o.toLowerCase(),t=e.length===1&&e[0]===""?0:e.length;if(t<=1)return[...om,...qo().map(r=>({name:r.name,description:r.description,type:"enum"})),...Wo()];if(n==="rerun"&&t<=2)return fm();if(n==="rename"&&t<=2)return kr("rename");if(n==="delete"&&t<=2)return[...im,...Fa(e)];if(n==="delete"&&t<=3&&e.slice(1).some(r=>r.startsWith("--")))return Fa(e);if(n==="revise"){if(t<=2)return[{name:"--replace",description:"Replace a saved workflow after confirmation",type:"enum"},...kr("revise")];if(e[1]==="--replace"&&t<=3)return Wo()}return nm.has(n)&&t<=2?jn(n):n==="runs"&&t<=2?rm:n==="prune"&&t<=2?sm:[]}a(mm,"getWorkflowArgs");function pm(e){let[o=""]=e,n=o.toLowerCase(),t=e.length===1&&e[0]===""?0:e.length;return t<=1?Jf:t>2?[]:n==="mode"?Zf:n==="trace"?Qf:[]}a(pm,"getRepoIntelArgs");var gm=new Map([["mode",Ff],["thinking",ro],["think",ro],["t",ro],["reasoning",ro],["reason",ro],["effort",ro],["status",yr],["info",yr],["ctx",yr],["mcp",Bf],["fallback",Gf],["auto-engine",zf],["agent-mode",Ua],["am",Ua],["verifier-log",ja],["stall-log",ja],["memory",qf],["goal",Kf],["paste",Xf],["review",Vf],["agents",Yf],["delete",vr],["rm",vr],["del",vr]]),wm=new Set(["model","m","provider"]),hm=new Set(["repo-intel"]),ym=new Set(["repointel","ri"]),vm=new Set(["workflow"]);function Sr(e,o,n=[]){let t=e.toLowerCase();return wm.has(t)?Hf(o):hm.has(t)?pm(n):ym.has(t)?n.length<=1?em:[]:vm.has(t)?mm(n):gm.get(t)??[]}a(Sr,"getCommandArguments");var $r=class{static{a(this,"ArgumentCompleter")}canComplete(o,n){let t=o.slice(0,n),r=to(t);if(r===-1)return!1;let i=t.slice(r),l=i.split(/\s+/);if(l.length>=2&&l[0]!=="")return!0;let c=i.slice(1).toLowerCase();return Sr(c).length>0}async getCompletions(o,n){let t=o.slice(0,n),r=to(t);if(r===-1)return[];let i=t.slice(r),l=i.indexOf(" "),c=(l===-1?i.slice(1):i.slice(1,l)).toLowerCase(),d=l===-1?"":i.slice(l+1),u=d?d.split(/\s+/):[""],f=u.length-1,m=(u[f]??"").toLowerCase(),v=Sr(c,m,u);if(!v||v.length===0)return[];let k=new Set(u.slice(0,-1).map($=>$.toLowerCase()));return v.filter($=>!k.has($.name.toLowerCase())).filter($=>!m||$.name.includes("/")?!0:$.name.toLowerCase().includes(m)).map($=>({text:$.name,display:$.name,description:$.description,type:"argument"})).sort(($,g)=>{if(!m)return 0;let x=$.display.toLowerCase().startsWith(m),T=g.display.toLowerCase().startsWith(m);return x&&!T?-1:!x&&T?1:$.display.length-g.display.length})}};function mv(){return new $r}a(mv,"createArgumentCompleter");export{vt as a,z as b,Fp as c,vi as d,Hp as e,Yo as f,bm as g,Xa as h,xm as i,uo as j,xs as k,As as l,fo as m,mo as n,Dm as o,Bs as p,rt as q,xl as r,st as s,at as t,lt as u,ho as v,nn as w,Nl as x,dt as y,qe as z,ti as A,ri as B,si as C,Zl as D,cp as E,xp as F,Ql as G,gt as H,Ap as I,Rp as J,mi as K,Lp as L,yi as M,ae as N,$i as O,bi as P,Xp as Q,gc as R,Ic as S,Vp as T,ln as U,St as V,Yp as W,Li as X,Jp as Y,Zp as Z,Qp as _,xg as $,Ag as aa,Rg as ba,Fi as ca,Rt as da,Hi as ea,Ee as fa,Pg as ga,bo as ha,Pt as ia,Te as ja,Xd as ka,Vd as la,aa as ma,rw as na,sw as oa,lu as pa,oh as qa,nh as ra,th as sa,$h as ta,bh as ua,xh as va,Ah as wa,Rh as xa,ka as ya,Ph as za,Lh as Aa,$a as Ba,Mh as Ca,Qh as Da,ba as Ea,Lo as Fa,Uy as Ga,jy as Ha,Wn as Ia,$r as Ja,mv as Ka,to as La,wr as Ma,hr as Na,ev as Oa};
622
+ `)){if(!c.trim())continue;let d=Df(c);if(!d)continue;let u=no.resolve(r,d),f=no.relative(e,u).split(no.sep).join("/");if(!(!f||f.startsWith("..")||l.has(f))&&(l.add(f),i.push(f),i.length>=o))break}return i}catch{return[]}}a(Da,"getRecentWorkingSetFiles");function to(e){let o=e.lastIndexOf("/");if(o===-1)return-1;for(;o>0&&!/\s/.test(e[o-1]??"");)if(o=e.lastIndexOf("/",o-1),o===-1)return-1;return o}a(to,"findCommandSlashIndex");var wr=class{static{a(this,"FileCompleter")}cwdSource;cache=new Map;cacheTimeout=5e3;recentCache=new Map;recentFilesProvider;constructor(o,n=Da){this.cwdSource=o,this.recentFilesProvider=n}canComplete(o,n){let t=o.slice(0,n),r=t.lastIndexOf("@");return!(r===-1||r>0&&!/\s/.test(t[r-1]??"")||t.slice(r+1).includes(" "))}async getCompletions(o,n){let t=o.slice(0,n),r=t.lastIndexOf("@");if(r===-1)return[];let i=t.slice(r+1),l=[],c=this.resolveCwd(),d=i.lastIndexOf("/"),u=d===-1?c:Mo.join(c,i.slice(0,d)),f=d===-1?i:i.slice(d+1);try{let v=(await this.readdir(u)).filter(k=>k.toLowerCase().startsWith(f.toLowerCase()));for(let k of v){let y=Mo.join(u,k),$=await this.isDirectory(y),g=d===-1?k:i.slice(0,d+1)+k;l.push({text:"@"+g+($?"/":""),display:k+($?"/":""),description:$?"directory":"file",type:"file"})}}catch{}if(d===-1){let m=await this.getRecentFiles(c),v=new Set(l.map($=>$.text)),k=f.toLowerCase(),y=[];for(let $ of m){if(f&&!Mo.basename($).toLowerCase().startsWith(k))continue;let g="@"+$;v.has(g)||(v.add(g),y.push({text:g,display:$,description:"recent",type:"file"}))}l.unshift(...y)}return l}async getRecentFiles(o){let n=Date.now(),t=this.recentCache.get(o);if(t&&t.expiresAt>n)return t.files;let r=await this.recentFilesProvider(o);return this.recentCache.set(o,{files:r,expiresAt:Date.now()+this.cacheTimeout}),r}resolveCwd(){return typeof this.cwdSource=="function"?this.cwdSource():this.cwdSource??process.cwd()}async readdir(o){let n=Date.now(),t=this.cache.get(o);return t&&t.expiresAt>n?t.entries:(t&&this.cache.delete(o),new Promise(r=>{On.readdir(o,(i,l)=>{i?r([]):(this.cache.set(o,{entries:l,expiresAt:Date.now()+this.cacheTimeout}),r(l))})}))}async isDirectory(o){return new Promise(n=>{On.stat(o,(t,r)=>{n(!t&&r.isDirectory())})})}},hr=class{static{a(this,"CommandCompleter")}commands;constructor(){this.commands=new Map,this.loadCommands()}loadCommands(){for(let n of Lo().getAll())n.userInvocable!==!1&&this.commands.set(n.name,{description:n.description,aliases:n.aliases??[]});let o=se();for(let n of o?.listCommands()??[])n.metadata?.userInvocable!==!1&&this.commands.set(n.name,{description:n.description,aliases:n.aliases??[]})}canComplete(o,n){let t=o.slice(0,n),r=to(t);return r===-1?!1:!t.slice(r).includes(" ")}async getCompletions(o,n){let t=o.slice(0,n),r=to(t);if(r===-1)return[];this.commands.clear(),this.loadCommands();let i=t.slice(r+1).toLowerCase(),l=[];for(let[c,d]of this.commands){this.fuzzyMatch(i,c)&&l.push({text:"/"+c,display:"/"+c,description:d.description,type:"command"});for(let u of d.aliases)u!==c&&this.fuzzyMatch(i,u)&&l.push({text:"/"+u,display:"/"+u,description:`Alias for /${c}: ${d.description}`,type:"command"})}return l}fuzzyMatch(o,n){if(!o)return!0;let t=o.toLowerCase(),r=n.toLowerCase(),i=0;for(let l=0;l<r.length&&i<t.length;l++)r[l]===t[i]&&i++;return i===t.length}};function ev(e){let o=new wr(e),n=new Wn,t=new hr;return async r=>{let i=r.includes("@"),l=r.includes("/");if(!i&&!l)return[[],r];let c=[];if(l){let u=await Uf(r,r.length);c.push(...u)}if(l&&n.canComplete(r,r.length)){let u=await n.getCompletions(r,r.length);c.push(...u)}if(l&&t.canComplete(r,r.length)){let u=await t.getCompletions(r,r.length);c.push(...u)}if(i&&o.canComplete(r,r.length)){let u=await o.getCompletions(r,r.length);c.push(...u)}return[c.map(u=>jf(r,u)),r]}}a(ev,"createCompleter");async function Uf(e,o){let{ArgumentCompleter:n}=await import("./argument-completer-3NHIKB4N.js"),t=new n;return t.canComplete(e,o)?t.getCompletions(e,o):[]}a(Uf,"getArgumentCompletions");function jf(e,o){if(o.type!=="argument")return o.text;let n=to(e);if(n!==-1&&!/\s/.test(e.slice(n)))return`${e} ${o.text}`;let r=e.match(/\S+$/)?.[0]??"";return`${r?e.slice(0,e.length-r.length):e}${o.text}`}a(jf,"formatReadlineCompletion");import{existsSync as Nn,readdirSync as Ha,readFileSync as Ba}from"node:fs";import{join as Dn}from"node:path";var Ff=[{name:"plan",description:"Read-only planning mode - blocks all modifications",type:"enum"},{name:"accept-edits",description:"File edits auto-approved, bash requires confirmation",type:"enum"},{name:"auto",description:"Use auto-mode classifier for tool permissions",type:"enum"}],ro=[{name:"none",description:"Disable reasoning when the model supports it",type:"enum"},{name:"auto",description:"Clear the explicit effort override",type:"enum"},{name:"low",description:"Use low reasoning effort",type:"enum"},{name:"medium",description:"Use medium reasoning effort",type:"enum"},{name:"high",description:"Use high reasoning effort",type:"enum"},{name:"xhigh",description:"Use extra-high reasoning effort",type:"enum"},{name:"max",description:"Use maximum reasoning effort",type:"enum"}];function Hf(e){if(e&&e.includes("/")){let o=e.indexOf("/"),n=e.slice(0,o),t=e.slice(o+1);if(We(n))try{return He(n).filter(i=>!t||i.toLowerCase().includes(t.toLowerCase())).map(i=>({name:`${n}/${i}`,description:i,type:"enum"}))}catch{}return[]}return Oe().map(o=>({name:o,description:`Switch to ${o} provider`,type:"enum"}))}a(Hf,"getModelArgs");var yr=[{name:"workspace",description:"Inspect current workspace/runtime truth in more detail",type:"enum"},{name:"runtime",description:"Alias for workspace runtime inspection",type:"enum"},{name:"worktree",description:"Alias for workspace runtime inspection",type:"enum"}],vr=[{name:"all",description:"Delete ALL sessions",type:"enum"}],Bf=[{name:"status",description:"Show MCP server status",type:"enum"},{name:"refresh",description:"Refresh MCP server catalogs",type:"enum"}],Gf=[{name:"status",description:"Show child-task fallback order",type:"enum"},{name:"off",description:"Disable child-task fallback providers",type:"enum"}],zf=[{name:"llm",description:"Use LLM classifier for auto mode",type:"enum"},{name:"rules",description:"Use rules-only auto mode",type:"enum"}],Ua=[{name:"ama",description:"Use AMA agent mode",type:"enum"},{name:"sa",description:"Use single-agent mode",type:"enum"},{name:"toggle",description:"Cycle to the next agent mode",type:"enum"}],ja=[{name:"on",description:"Enable logging",type:"enum"},{name:"off",description:"Disable logging",type:"enum"}],qf=[{name:"list",description:"List project memory files",type:"enum"},{name:"pending",description:"List pending memory proposals",type:"enum"},{name:"show",description:"Preview a memory proposal",type:"enum"},{name:"approve",description:"Approve a memory proposal",type:"enum"},{name:"reject",description:"Reject a memory proposal",type:"enum"},{name:"curate",description:"Report memory governance findings",type:"enum"},{name:"rebuild",description:"Rebuild MEMORY.md index",type:"enum"},{name:"open",description:"Print the memory entrypoint path",type:"enum"},{name:"help",description:"Show memory help",type:"enum"}],Kf=[{name:"status",description:"Show current persistent goal",type:"enum"},{name:"pause",description:"Pause the active goal",type:"enum"},{name:"resume",description:"Resume a paused goal",type:"enum"},{name:"clear",description:"Clear the current goal",type:"enum"},{name:"help",description:"Show goal help",type:"enum"},{name:"--tokens",description:"Set an optional goal token budget",type:"enum"}],Xf=[{name:"show",description:"Show a captured paste by id",type:"enum"},{name:"list",description:"List captured pastes",type:"enum"}],Vf=[{name:"--lean",description:"Add a minimal-diff/YAGNI review pass",type:"enum"},{name:"--workflow",description:"Review through a dynamic workflow",type:"enum"},{name:"base",description:"Review changes against the detected base branch",type:"enum"},{name:"sha",description:"Review a specific commit",type:"enum"},{name:"help",description:"Show review help",type:"enum"}],Yf=[{name:"init",description:"Create AGENTS.md in the target project if absent",type:"enum"},{name:"lean",description:"Initialize or LLM-review AGENTS.md for Lean Mode guidance",type:"enum"},{name:"help",description:"Show agents help",type:"enum"}],Jf=[{name:"status",description:"Inspect the current repo-intelligence runtime state",type:"enum"},{name:"mode",description:"Switch repo-intelligence runtime mode",type:"enum"},{name:"trace",description:"Toggle repo-intelligence trace output",type:"enum"}],Zf=[{name:"auto",description:"Let KodaX pick the best repo-intelligence engine",type:"enum"},{name:"full",description:"Prefer the full repo-intelligence engine",type:"enum"},{name:"light",description:"Use the light repo-intelligence engine",type:"enum"},{name:"off",description:"Disable repo-intelligence injection",type:"enum"}],Qf=[{name:"on",description:"Enable repo-intelligence trace output",type:"enum"},{name:"off",description:"Disable repo-intelligence trace output",type:"enum"},{name:"toggle",description:"Toggle repo-intelligence trace output",type:"enum"}],em=[{name:"status",description:"Deprecated alias for /repo-intel status",type:"enum"}],om=[{name:"list",description:"List built-in and saved workflows",type:"enum"},{name:"create",description:"Generate and run a workflow from a request",type:"enum"},{name:"runs",description:"List active and recent workflow runs",type:"enum"},{name:"show",description:"Show latest run or a specific workflow run",type:"enum"},{name:"pause",description:"Pause future child launches for a run",type:"enum"},{name:"resume",description:"Resume a paused run",type:"enum"},{name:"stop",description:"Stop an active workflow run",type:"enum"},{name:"delete",description:"Delete one persisted workflow run or generated saved capsule",type:"enum"},{name:"prune",description:"Preview or delete old terminal workflow runs",type:"enum"},{name:"rerun",description:"Rerun a run id or saved workflow name",type:"enum"},{name:"save",description:"Save a generated run as a workflow capsule",type:"enum"},{name:"rename",description:"Rename a run display name or saved workflow capsule",type:"enum"},{name:"revise",description:"Generate a revised workflow capsule",type:"enum"},{name:"help",description:"Show workflow help",type:"enum"}],nm=new Set(["show","pause","resume","stop","delete","rerun","save","rename","revise"]),tm=new Set(["show","delete","rerun","save","rename","revise"]),rm=[{name:"--all",description:"Show all persisted workflow runs",type:"enum"},{name:"--limit",description:"Show at most N persisted workflow runs",type:"enum"}],sm=[{name:"--dry-run",description:"Preview cleanup without deleting runs",type:"enum"},{name:"--keep",description:"Keep the newest N terminal runs",type:"enum"},{name:"--older-than",description:"Delete terminal runs older than Nd or Nh",type:"enum"}],im=[{name:"--force",description:"Delete stale non-terminal run records",type:"enum"},{name:"--run",description:"Treat the target as a workflow run record",type:"enum"},{name:"--saved",description:"Treat the target as a generated saved workflow capsule",type:"enum"}],am=[".workflow.json",".ts",".mjs",".js"];function lm(e,o){switch(e){case"pause":return o==="running";case"resume":return o==="paused";case"stop":return o==="running"||o==="paused";case"delete":return o!=="running"&&o!=="paused";default:return!0}}a(lm,"workflowRunMatchesSubcommand");function Un(e){return/^[a-zA-Z0-9._-]{1,120}$/.test(e)&&!e.startsWith(".")&&!e.includes("..")}a(Un,"isWorkflowRunEntryName");function cm(e,o){let n=Dn(e,"workflow-metadata.json");if(Nn(n))try{let r=JSON.parse(Ba(n,"utf8"));if(typeof r=="object"&&r!==null){let i=r.displayName;if(typeof i=="string"&&Un(i.trim()))return i.trim()}}catch{}let t=o.displayName;return typeof t=="string"&&Un(t.trim())?t.trim():void 0}a(cm,"readWorkflowRunDisplayName");function dm(){let e=Ee(process.cwd()).key,o=B("workflow-runs",e);if(!Nn(o))return[];let n=[];for(let t of Ha(o)){if(!Un(t))continue;let r=Dn(o,t,"run.json");if(Nn(r))try{let i=JSON.parse(Ba(r,"utf8")),l=typeof i.workflow=="string"?i.workflow:"?",c=typeof i.status=="string"?i.status:"?",d=typeof i.endedAt=="number"?i.endedAt:0;n.push({arg:{name:t,description:`${l} - ${c}`,type:"string"},endedAt:d});let u=cm(Dn(o,t),i);u&&u!==t&&n.push({arg:{name:u,description:`${l} alias for ${t} - ${c}`,type:"string"},endedAt:d})}catch{}}return n.sort((t,r)=>r.endedAt-t.endedAt).map(t=>t.arg)}a(dm,"getPersistedWorkflowRunIdArgs");function jn(e){let o=Fe().list().filter(r=>lm(e,r.status)).map(r=>({name:r.runId,description:`${r.workflow} - ${r.status}`,type:"string"})),n=tm.has(e)?dm():[],t=new Set;return[...o,...n].filter(r=>t.has(r.name)?!1:(t.add(r.name),!0))}a(jn,"getWorkflowRunIdArgs");function um(e){for(let o of am)if(e.endsWith(o)){let n=e.slice(0,-o.length);return Un(n)?n:void 0}}a(um,"savedWorkflowNameFromFile");function Wo(e={}){let o=[{path:B("workflows"),source:"personal"},{path:Dn(process.cwd(),".kodax","workflows"),source:"project"}],n=new Map;for(let t of o)if(Nn(t.path))try{for(let r of Ha(t.path)){if(e.generatedOnly===!0&&!r.endsWith(".workflow.json"))continue;let i=um(r);i&&n.set(i,{name:i,description:`${t.source} saved workflow`,type:"enum"})}}catch{}return[...n.values()].sort((t,r)=>t.name.localeCompare(r.name))}a(Wo,"getSavedWorkflowNameArgs");function fm(){let e=new Map;for(let o of jn("rerun"))e.set(o.name,{...o,description:`recent run: ${o.description}`,type:"string"});for(let o of Wo()){let n=e.get(o.name);if(n){e.set(o.name,{...n,description:`${n.description}; also ${o.description}`});continue}e.set(o.name,{...o,description:o.description,type:"string"})}return[...e.values()]}a(fm,"getWorkflowRerunArgs");function kr(e){let o=new Map;for(let n of jn(e))o.set(n.name,{...n,description:`workflow run: ${n.description}`,type:"string"});for(let n of Wo({generatedOnly:e==="delete"})){let t=o.get(n.name);if(t){o.set(n.name,{...t,description:`${t.description}; also ${n.description}`});continue}o.set(n.name,{...n,description:n.description,type:"string"})}return[...o.values()]}a(kr,"getWorkflowRunOrSavedNameArgs");function Fa(e){let o=new Set(e.slice(1).filter(n=>n.startsWith("--")));return o.has("--saved")?Wo({generatedOnly:!0}):o.has("--run")?jn("delete"):kr("delete")}a(Fa,"getWorkflowDeleteTargetArgs");function mm(e){let[o=""]=e,n=o.toLowerCase(),t=e.length===1&&e[0]===""?0:e.length;if(t<=1)return[...om,...qo().map(r=>({name:r.name,description:r.description,type:"enum"})),...Wo()];if(n==="rerun"&&t<=2)return fm();if(n==="rename"&&t<=2)return kr("rename");if(n==="delete"&&t<=2)return[...im,...Fa(e)];if(n==="delete"&&t<=3&&e.slice(1).some(r=>r.startsWith("--")))return Fa(e);if(n==="revise"){if(t<=2)return[{name:"--replace",description:"Replace a saved workflow after confirmation",type:"enum"},...kr("revise")];if(e[1]==="--replace"&&t<=3)return Wo()}return nm.has(n)&&t<=2?jn(n):n==="runs"&&t<=2?rm:n==="prune"&&t<=2?sm:[]}a(mm,"getWorkflowArgs");function pm(e){let[o=""]=e,n=o.toLowerCase(),t=e.length===1&&e[0]===""?0:e.length;return t<=1?Jf:t>2?[]:n==="mode"?Zf:n==="trace"?Qf:[]}a(pm,"getRepoIntelArgs");var gm=new Map([["mode",Ff],["thinking",ro],["think",ro],["t",ro],["reasoning",ro],["reason",ro],["effort",ro],["status",yr],["info",yr],["ctx",yr],["mcp",Bf],["fallback",Gf],["auto-engine",zf],["agent-mode",Ua],["am",Ua],["verifier-log",ja],["stall-log",ja],["memory",qf],["goal",Kf],["paste",Xf],["review",Vf],["agents",Yf],["delete",vr],["rm",vr],["del",vr]]),wm=new Set(["model","m","provider"]),hm=new Set(["repo-intel"]),ym=new Set(["repointel","ri"]),vm=new Set(["workflow"]);function Sr(e,o,n=[]){let t=e.toLowerCase();return wm.has(t)?Hf(o):hm.has(t)?pm(n):ym.has(t)?n.length<=1?em:[]:vm.has(t)?mm(n):gm.get(t)??[]}a(Sr,"getCommandArguments");var $r=class{static{a(this,"ArgumentCompleter")}canComplete(o,n){let t=o.slice(0,n),r=to(t);if(r===-1)return!1;let i=t.slice(r),l=i.split(/\s+/);if(l.length>=2&&l[0]!=="")return!0;let c=i.slice(1).toLowerCase();return Sr(c).length>0}async getCompletions(o,n){let t=o.slice(0,n),r=to(t);if(r===-1)return[];let i=t.slice(r),l=i.indexOf(" "),c=(l===-1?i.slice(1):i.slice(1,l)).toLowerCase(),d=l===-1?"":i.slice(l+1),u=d?d.split(/\s+/):[""],f=u.length-1,m=(u[f]??"").toLowerCase(),v=Sr(c,m,u);if(!v||v.length===0)return[];let k=new Set(u.slice(0,-1).map($=>$.toLowerCase()));return v.filter($=>!k.has($.name.toLowerCase())).filter($=>!m||$.name.includes("/")?!0:$.name.toLowerCase().includes(m)).map($=>({text:$.name,display:$.name,description:$.description,type:"argument"})).sort(($,g)=>{if(!m)return 0;let x=$.display.toLowerCase().startsWith(m),T=g.display.toLowerCase().startsWith(m);return x&&!T?-1:!x&&T?1:$.display.length-g.display.length})}};function mv(){return new $r}a(mv,"createArgumentCompleter");export{vt as a,z as b,Fp as c,vi as d,Hp as e,Yo as f,bm as g,Xa as h,xm as i,uo as j,xs as k,As as l,fo as m,mo as n,Dm as o,Bs as p,rt as q,xl as r,st as s,at as t,lt as u,ho as v,nn as w,Nl as x,dt as y,qe as z,ti as A,ri as B,si as C,Zl as D,cp as E,xp as F,Ql as G,gt as H,Ap as I,Rp as J,mi as K,Lp as L,yi as M,ae as N,$i as O,bi as P,Xp as Q,gc as R,Ic as S,Vp as T,ln as U,St as V,Yp as W,Li as X,Jp as Y,Zp as Z,Qp as _,xg as $,Ag as aa,Rg as ba,Fi as ca,Rt as da,Hi as ea,Ee as fa,Pg as ga,bo as ha,Pt as ia,Te as ja,Xd as ka,Vd as la,aa as ma,rw as na,sw as oa,lu as pa,oh as qa,nh as ra,th as sa,$h as ta,bh as ua,xh as va,Ah as wa,Rh as xa,ka as ya,Ph as za,Lh as Aa,$a as Ba,Mh as Ca,Qh as Da,ba as Ea,Lo as Fa,Uy as Ga,jy as Ha,Wn as Ia,$r as Ja,mv as Ka,to as La,wr as Ma,hr as Na,ev as Oa};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{m as f}from"./chunk-OGL227XV.js";import{a as h}from"./chunk-ONUPGMER.js";import{createHash as R}from"node:crypto";function O(i){return new y(i)}h(O,"createMemoryAgent");var y=class{static{h(this,"DefaultMemoryAgent")}options;constructor(e){this.options=e}async startSession(e){let t=this.options.initialMemoryPack??await this.options.controlPlane.buildMemoryPack({task:e.objective,identity:e.identity,maxCandidates:12,maxHints:5});return new g(e,t.memoryRevision,t.candidates,this.options)}},g=class{static{h(this,"DefaultMemorySession")}input;memoryRevision;candidates;options;observations=new Map;consumedReminderKeys=new Set;lastSequence=0;closed=!1;completion;prefetchGeneration=0;prefetch;readyPrefetch;queryByEpoch=new Map;injectedReceiptIds=[];constructor(e,t,n,c){this.input=e,this.memoryRevision=t,this.candidates=n,this.options=c}observe(e){if(this.assertOpen(),v(e.summary))return;let t=K(e,this.options.sourcePolicy),n=this.observations.get(e.id);if(n!==void 0){if(n.sequence===t.sequence&&w(n)===w(t))return;throw new Error(`conflicting duplicate memory observation: ${e.id}`)}if(!Number.isSafeInteger(e.sequence)||e.sequence<=this.lastSequence)throw new Error(`memory observation sequence must be strictly monotonic after ${this.lastSequence}`);if(e.summary.trim().length===0)throw new Error("memory observation summary must not be empty");this.observations.set(e.id,t),this.lastSequence=e.sequence}recall(e){this.assertOpen();let t=[...this.observations.values()].filter(d=>d.sequence<=e.throughSequence).filter(d=>I(d,e)).sort((d,l)=>l.sequence-d.sequence).slice(0,3),n=this.candidates.filter(d=>P(d,e)).slice(0,Math.max(0,3-t.length)),c=this.prefetchKey(e),s=this.consumeReadyPrefetch(c).filter(d=>!n.some(l=>l.ref.id===d.ref.id)).slice(0,Math.max(0,3-t.length-n.length)),a=m([...t.flatMap(d=>d.evidence.map(l=>l.ref)),...n.map(d=>d.ref.id),...s.map(d=>d.ref.id)]),r=k([...t.length>0||n.length>0?["exact"]:[],...s.length>0?["semantic_prefetch"]:[]]);if(t.length===0&&n.length===0&&s.length===0){this.startPrefetch(c,e),this.emitDecisionReceipt(e,[],[],r);return}let o=[...t.map(d=>d.summary.trim()),...n.map(d=>d.bodySnippet??d.hook),...s.map(d=>d.bodySnippet??d.hook)].join(`
2
+ import{m as f}from"./chunk-Y3AMP22L.js";import{a as h}from"./chunk-ONUPGMER.js";import{createHash as R}from"node:crypto";function O(i){return new y(i)}h(O,"createMemoryAgent");var y=class{static{h(this,"DefaultMemoryAgent")}options;constructor(e){this.options=e}async startSession(e){let t=this.options.initialMemoryPack??await this.options.controlPlane.buildMemoryPack({task:e.objective,identity:e.identity,maxCandidates:12,maxHints:5});return new g(e,t.memoryRevision,t.candidates,this.options)}},g=class{static{h(this,"DefaultMemorySession")}input;memoryRevision;candidates;options;observations=new Map;consumedReminderKeys=new Set;lastSequence=0;closed=!1;completion;prefetchGeneration=0;prefetch;readyPrefetch;queryByEpoch=new Map;injectedReceiptIds=[];constructor(e,t,n,c){this.input=e,this.memoryRevision=t,this.candidates=n,this.options=c}observe(e){if(this.assertOpen(),v(e.summary))return;let t=K(e,this.options.sourcePolicy),n=this.observations.get(e.id);if(n!==void 0){if(n.sequence===t.sequence&&w(n)===w(t))return;throw new Error(`conflicting duplicate memory observation: ${e.id}`)}if(!Number.isSafeInteger(e.sequence)||e.sequence<=this.lastSequence)throw new Error(`memory observation sequence must be strictly monotonic after ${this.lastSequence}`);if(e.summary.trim().length===0)throw new Error("memory observation summary must not be empty");this.observations.set(e.id,t),this.lastSequence=e.sequence}recall(e){this.assertOpen();let t=[...this.observations.values()].filter(d=>d.sequence<=e.throughSequence).filter(d=>I(d,e)).sort((d,l)=>l.sequence-d.sequence).slice(0,3),n=this.candidates.filter(d=>P(d,e)).slice(0,Math.max(0,3-t.length)),c=this.prefetchKey(e),s=this.consumeReadyPrefetch(c).filter(d=>!n.some(l=>l.ref.id===d.ref.id)).slice(0,Math.max(0,3-t.length-n.length)),a=m([...t.flatMap(d=>d.evidence.map(l=>l.ref)),...n.map(d=>d.ref.id),...s.map(d=>d.ref.id)]),r=k([...t.length>0||n.length>0?["exact"]:[],...s.length>0?["semantic_prefetch"]:[]]);if(t.length===0&&n.length===0&&s.length===0){this.startPrefetch(c,e),this.emitDecisionReceipt(e,[],[],r);return}let o=[...t.map(d=>d.summary.trim()),...n.map(d=>d.bodySnippet??d.hook),...s.map(d=>d.bodySnippet??d.hook)].join(`
3
3
  `),b=u(`${a.join("\0")}\0${e.actionSignature??e.decisionIntent}`);if(this.consumedReminderKeys.has(b)){this.emitDecisionReceipt(e,a,[],r);return}return this.consumedReminderKeys.add(b),this.emitDecisionReceipt(e,a,a,r),{content:o,evidenceRefs:a}}query(e){this.assertOpen();let t=p(e.decisionRevision,e.throughSequence),n=E(e.need),c=u([t,this.memoryRevision,n??"",e.actionSignature??"",f].join("\0")),s=this.queryByEpoch.get(t);if(s!==void 0)return s.key===c?s.result:Promise.resolve(void 0);let a=n===void 0?Promise.resolve(void 0):this.queryOnce(e,n);return this.queryByEpoch.set(t,{key:c,result:a}),n===void 0&&this.emitDecisionReceipt(e,[],[],["deliberate_query"]),a}rewind(e){if(this.assertOpen(),!Number.isSafeInteger(e.throughSequence)||e.throughSequence<0)throw new Error("rewind sequence must be a non-negative safe integer");for(let[t,n]of this.observations)n.sequence>e.throughSequence&&this.observations.delete(t);for(this.lastSequence=e.throughSequence,this.consumedReminderKeys.clear(),this.queryByEpoch.clear();this.injectedReceiptIds.length>0;)this.injectedReceiptIds.pop();this.cancelPrefetch("rewind")}complete(e){return this.assertOpen(),this.completion!==void 0?this.completion:(this.completion=this.completeOnce(e),this.completion)}async close(e={}){this.cancelPrefetch("close"),e.drain!==!1&&this.completion!==void 0&&await this.completion,this.closed=!0}async completeOnce(e){if(e.status==="cancelled"||v(e.summary))return;let t=j(this.input,[...this.observations.values()],{...e,status:e.status,evidence:e.evidence.map(n=>q(n,this.options.sourcePolicy))},this.options.now?.()??new Date().toISOString(),this.injectedReceiptIds);await this.options.persistOutcomeDigest?.(t),await this.reviewWithTimeout(t)}async reviewWithTimeout(e){let t=this.options.reviewEpisode;if(t===void 0)return;let n=new AbortController,c=Math.max(1,this.options.reviewTimeoutMs??3e4),s,a=await Promise.race([t(e,n.signal).then(()=>!1),new Promise(r=>{s=setTimeout(()=>{n.abort(),r(!0)},c)})]);s!==void 0&&clearTimeout(s),a&&this.options.onTrace?.({type:"review.timed_out",key:e.reviewKey,detail:`${c}ms`})}assertOpen(){if(this.closed)throw new Error("memory session is closed")}prefetchKey(e){return u([e.decisionRevision,e.decisionIntent,e.actionSignature??"",String(e.throughSequence),this.memoryRevision,this.candidates.map(t=>t.ref.id).join(",")].join("\0"))}async queryOnce(e,t){try{let n=await this.options.controlPlane.buildMemoryPack({task:this.input.objective,identity:this.input.identity,decisionIntent:t,...e.actionSignature!==void 0?{actionSignature:e.actionSignature}:{},maxCandidates:3,maxHints:3,includeSnippets:!0,purpose:"deliberate_query"}),c=n.promptHints.filter(M).filter(o=>o.bodySnippet!==void 0&&o.bodySnippet.trim().length>0).slice(0,3),s=c.map(o=>o.ref.id),a=x(c.map(o=>o.bodySnippet??"")),r=a.length===0?[]:s;return this.emitDecisionReceipt(e,s,r,["deliberate_query"],n.candidates.map(o=>o.ref.id)),a.length===0?void 0:{content:a,evidenceRefs:s}}catch(n){this.emitDecisionReceipt(e,[],[],["deliberate_query"]),this.options.onTrace?.({type:"query.failed",key:p(e.decisionRevision,e.throughSequence),detail:n instanceof Error?n.message:String(n)});return}}emitDecisionReceipt(e,t,n,c,s=this.candidates.map(a=>a.ref.id)){let a=p(e.decisionRevision,e.throughSequence),r=u(s.join("\0")),o={id:`memory-decision:${u([a,f,r,t.join(","),n.join(","),c.join(",")].join("\0")).slice(0,24)}`,decisionEpoch:a,decisionRevision:e.decisionRevision,policyVersion:f,candidateSetFingerprint:r,candidateRefs:[...s],selectedRefs:[...t],injectedRefs:[...n],selectionModes:[...c],...e.actionSignature!==void 0?{actionSignature:e.actionSignature}:{},throughSequence:e.throughSequence};n.length>0&&!this.injectedReceiptIds.includes(o.id)&&this.injectedReceiptIds.push(o.id),this.options.onTrace?.({type:"memory.decision",receipt:o})}consumeReadyPrefetch(e){if(this.readyPrefetch?.key!==e)return[];let t=new Set(this.readyPrefetch.refIds);return this.readyPrefetch=void 0,this.candidates.filter(n=>t.has(n.ref.id))}startPrefetch(e,t){let n=this.options.recallRunner;if(n===void 0||this.candidates.length===0||this.prefetch?.key===e)return;this.cancelPrefetch("superseded");let c=new AbortController,s=++this.prefetchGeneration;this.prefetch={key:e,controller:c};let a=new Set(this.candidates.map(r=>r.ref.id));n({objective:t.objective,decisionContext:t.decisionContext,decisionIntent:t.decisionIntent,candidates:this.candidates.map(r=>({refId:r.ref.id,claim:r.bodySnippet??r.hook,...r.ref.claimKind!==void 0?{claimKind:r.ref.claimKind}:{}})),signal:c.signal}).then(r=>{if(c.signal.aborted||s!==this.prefetchGeneration||this.prefetch?.key!==e){this.options.onTrace?.({type:"recall.prefetch.discarded",key:e});return}this.readyPrefetch={key:e,refIds:m(r.selectedRefIds.filter(o=>a.has(o)))},this.prefetch=void 0,this.options.onTrace?.({type:"recall.prefetch.completed",key:e})}).catch(r=>{c.signal.aborted||(s===this.prefetchGeneration&&(this.prefetch=void 0),this.options.onTrace?.({type:"recall.prefetch.failed",key:e,detail:r instanceof Error?r.message:String(r)}))})}cancelPrefetch(e){if(this.prefetch===void 0)return;let t=this.prefetch.key;this.prefetch.controller.abort(),this.prefetch=void 0,this.prefetchGeneration+=1,this.options.onTrace?.({type:"recall.prefetch.discarded",key:t,detail:e})}};function I(i,e){return i.actionSignature!==void 0&&e.actionSignature!==void 0?i.actionSignature===e.actionSignature:i.claimKey!==void 0&&i.claimKey===e.decisionIntent}h(I,"exactObservationMatch");function P(i,e){return i.ref.actionSignature!==void 0&&e.actionSignature!==void 0?i.ref.actionSignature===e.actionSignature:i.ref.claimKey!==void 0&&i.ref.claimKey===e.decisionIntent}h(P,"exactCandidateMatch");function j(i,e,t,n,c){let s=[...e].reverse().find(o=>o.kind==="outcome"),a=e.at(-1)?.sequence??0,r=u([i.identity.sessionId,String(a),t.status,t.summary].join("\0"));return{id:`memory-outcome:${r.slice(0,24)}`,reviewKey:r,sessionId:i.identity.sessionId,branchId:i.identity.sessionId,sequence:a,objective:i.objective,...s?.actionSignature!==void 0?{actionSignature:s.actionSignature}:{},approach:s?.summary??"episode completion",outcome:t.status,summary:t.summary.trim(),evidenceRefs:m(t.evidence.map(o=>o.ref)),evidence:t.evidence.map(o=>({ref:o.ref,grade:o.requestedGrade,source:o.source,observedAt:o.observedAt})),...c.length>0?{memoryInfluence:m(c).map(o=>({decisionReceiptRef:o,grade:"exposed"}))}:{},visibility:s?.visibility??"prompt_safe",createdAt:n}}h(j,"buildOutcomeDigest");function E(i){let e=i.replace(/\s+/g," ").trim();if(!(e.length===0||S(e)>512||v(e))&&!/^(?:list|show|dump|enumerate)\s+(?:all|every)\s+(?:the\s+)?memor(?:y|ies)\b/i.test(e)&&!/\b(?:all|every)\s+(?:project|workspace|tenant|user|agent)(?:s|'s)?\b/i.test(e))return e}h(E,"normalizeQueryNeed");function S(i){let e=0,t=0;for(let n of i)n.codePointAt(0)<=127?e+=1:t+=1;return Math.ceil(e/4)+t}h(S,"estimateMemoryTokens");function M(i){return i.ref.visibility==="prompt_safe"&&i.ref.authority!=="proposal_only"&&(i.ref.lifecycle==="active"||i.ref.lifecycle==="trusted"||i.ref.lifecycle==="readonly")}h(M,"isGovernedQueryHint");function x(i){let e=i.map(n=>n.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"").replace(/<\/?[^>]+>/g,"").replace(/[<>]/g,"").replace(/\s+/g," ").trim()).filter(n=>n.length>0),t=e.join(`
4
4
  `);for(;S(t)>512&&e.length>1;)e.pop(),t=e.join(`
5
5
  `);return S(t)<=512?t:""}h(x,"boundedQueryContent");function p(i,e){return u(`${i}\0${e}`).slice(0,24)}h(p,"decisionEpoch");function k(i){return[...new Set(i)]}h(k,"uniqueModes");function K(i,e){return Object.freeze({...i,evidence:Object.freeze(i.evidence.map(t=>Object.freeze(q(t,e)))),...i.metadata!==void 0?{metadata:Object.freeze({...i.metadata})}:{}})}h(K,"freezeObservation");function q(i,e){let t=e?.(i)??"inferred";return{...i,requestedGrade:_(i.requestedGrade,t)}}h(q,"applySourcePolicy");function _(i,e){let t=["inferred","observed","corroborated","verified","authoritative"];return t[Math.min(t.indexOf(i),t.indexOf(e))]??"inferred"}h(_,"lowerEvidenceGrade");function w(i){return JSON.stringify(i)}h(w,"stableObservation");function m(i){return[...new Set(i)]}h(m,"unique");function u(i){return R("sha256").update(i).digest("hex")}h(u,"digest");function v(i){return/(?:-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|authorization:\s*bearer\s+\S+|(?:api[_-]?key|password|secret|token)\s*[:=]\s*\S+)/i.test(i)}h(v,"isRestrictedMemoryContent");export{O as a};