@kodax-ai/kodax 0.7.92 → 0.7.93

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 (39) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +9 -0
  3. package/README_CN.md +9 -0
  4. package/dist/chunks/{agent-YHHFIH7N.js → agent-R7HVNARP.js} +1 -1
  5. package/dist/chunks/argument-completer-JHXUJWHC.js +2 -0
  6. package/dist/chunks/{chunk-PKPBII4F.js → chunk-3YOZIFSJ.js} +2 -2
  7. package/dist/chunks/{chunk-OSQIYUGD.js → chunk-4BY53JTF.js} +2 -2
  8. package/dist/chunks/{chunk-X75UGXP3.js → chunk-7QBWHCIZ.js} +1 -1
  9. package/dist/chunks/chunk-A3ZQE2BX.js +519 -0
  10. package/dist/chunks/{chunk-FBL7IVMK.js → chunk-BHE66SP3.js} +14 -14
  11. package/dist/chunks/chunk-D27EY4XC.js +383 -0
  12. package/dist/chunks/{chunk-5CIKWSCA.js → chunk-HLZWPB32.js} +2 -2
  13. package/dist/chunks/{chunk-RJIYXB62.js → chunk-JJ2YDBSN.js} +2 -2
  14. package/dist/chunks/{chunk-AGZNXFHZ.js → chunk-JTZKC4TV.js} +4 -4
  15. package/dist/chunks/{chunk-QPBN3J4E.js → chunk-PRASABCC.js} +2 -2
  16. package/dist/chunks/{chunk-QKLS4BYA.js → chunk-SMVC3Q3U.js} +4 -4
  17. package/dist/chunks/{chunk-THZVJ6R7.js → chunk-XTWIGVUL.js} +1 -1
  18. package/dist/chunks/{construction-bootstrap-QVLJPFTL.js → construction-bootstrap-474QPSYB.js} +1 -1
  19. package/dist/chunks/{dist-XC5M7UYX.js → dist-H4PT2QAV.js} +1 -1
  20. package/dist/chunks/{dist-WNMK42WE.js → dist-ITTXQHRJ.js} +1 -1
  21. package/dist/chunks/{host-B3TK2U43.js → host-OR3IO2A4.js} +1 -1
  22. package/dist/chunks/{run-manager-5AV3MR4W.js → run-manager-MNOTWIFX.js} +1 -1
  23. package/dist/chunks/{utils-HPVZCR2J.js → utils-5J4BHNBV.js} +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/kodax_bootstrap.js +1 -1
  26. package/dist/kodax_cli.js +1035 -1035
  27. package/dist/runtime-worker.js +1007 -1007
  28. package/dist/sandbox-workspace-session.js +1 -1
  29. package/dist/sdk-a2a.js +1 -1
  30. package/dist/sdk-coding.js +1 -1
  31. package/dist/sdk-llm.js +1 -1
  32. package/dist/sdk-repl.js +1 -1
  33. package/dist/sdk-runtime.js +1 -1
  34. package/dist/sdk-sandbox.js +1 -1
  35. package/dist/sdk-session.js +1 -1
  36. package/package.json +1 -1
  37. package/dist/chunks/argument-completer-6ZTRBNZM.js +0 -2
  38. package/dist/chunks/chunk-A6GNPNGB.js +0 -383
  39. package/dist/chunks/chunk-BV3SVH36.js +0 -519
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{a as vu,b as xu,c as ku,d as Eu,e as _u,f as Su,g as xs}from"./chunk-GH3KBC2H.js";import{a as ks,b as Nn,c as Tu}from"./chunk-YVG6OKN7.js";import{C as Pn,Ja as gs,Pa as ys,S as uo,Sa as Jd,e as fs,f as ps,g as ms,ka as fo,ma as hs}from"./chunk-FBL7IVMK.js";import{$a as Mn,Aa as he,Bb as au,Bc as yo,Hd as wo,Ia as Ae,Id as bo,Ja as on,Ka as ke,Nd as pu,Q as Zd,Rd as vs,Sb as cu,Sd as vo,Ud as xo,Uf as hu,Wa as tu,Xa as bs,Xf as gu,Zb as lu,_ as eu,aa as rn,ac as go,ah as wu,b as ws,c as yr,ch as bu,db as wr,eb as Pt,fb as nu,gc as du,gg as yu,ib as Ce,jb as mo,kb as Ln,l as J,lb as ru,mb as ho,mc as uu,nb as ou,ob as iu,pb as su,r as po,t as T,ue as et,v as Qd,ve as mu,zc as fu}from"./chunk-7XSZVOG7.js";import{h as Mt,j as je}from"./chunk-QFV6YCIH.js";import{a as i}from"./chunk-ONUPGMER.js";import br from"node:fs";import Es from"node:os";import re from"node:path";var jb=new Set(["runtime","mcp-tokens","mcp-clients","integrations","sandbox-runtime","processes","learned",".ssh",".aws",".azure",".gnupg",".kube",".docker",".agents",".codex",".claude",".gemini",".direnv",".terraform.d",".password-store"]),Fb=new Set(["config.json","auth.json","custom-providers.json","trusted-project-rules.json",".env",".envrc",".pgpass",".npmrc",".pypirc",".netrc",".git-credentials","credentials","credentials.json","application_default_credentials.json","id_rsa","id_ed25519",".gitconfig",".gitmodules",".terraformrc",".condarc",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".bash_history",".zsh_history"]),Ub=new Set([".env.example",".env.sample",".env.template"]);function jn(e){return(e==="~"?Es.homedir():/^~[\\/]/.test(e)?re.join(Es.homedir(),e.slice(2)):e).replace(/^(?:\$\{HOME\}|\$HOME|\$env:(?:home|userprofile)|%userprofile%)(?=$|[\\/])/i,Es.homedir())}i(jn,"expandHome");function ge(e,t=process.cwd()){if(!e.trim()||e.includes("\0"))return;let n=jn(e);if(process.platform==="win32"&&/^[a-z]:[^\\/]/i.test(n))return;let r=[],o=re.resolve(t,n);for(;;){try{br.lstatSync(o)}catch(s){if(s.code!=="ENOENT")return;let a=re.dirname(o);if(a===o)return;r.unshift(re.basename(o)),o=a;continue}try{return re.join(br.realpathSync.native(o),...r)}catch{return}}}i(ge,"canonicalizeAgentHomePolicyPath");function vr(e,t){let n=re.relative(t,e);if(!(!n||n.startsWith("..")||re.isAbsolute(n)))return n.split(/[\\/]+/).map(r=>{let o=r.toLowerCase();if(process.platform!=="win32")return o;let s=o.indexOf(":");return(s>=0?o.slice(0,s):o).replace(/[ .]+$/g,"")}).join("/")}i(vr,"normalizedRelative");function Au(e){let t=e.split("/"),n=t.at(-1)??"";return t.some(r=>jb.has(r))||t.some(r=>Fb.has(r))||!Ub.has(n)&&(n===".env"||n.startsWith(".env."))||t.some(r=>/^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$/.test(r))?!0:t.some((r,o)=>r===".git"&&["config","config.worktree"].includes(t[o+1]??"")||r===".config"&&t[o+1]==="git"&&t[o+2]==="config"||r===".cargo"&&t[o+1]==="credentials.toml"||r===".m2"&&["settings.xml","settings-security.xml"].includes(t[o+1]??"")||r===".gradle"&&t[o+1]==="gradle.properties"||r===".nuget"&&t.slice(o+1).includes("nuget.config")||r===".pip"&&t[o+1]==="pip.conf"||r===".huggingface"&&t[o+1]==="token"||r===".cache"&&t[o+1]==="huggingface"&&t[o+2]==="token"||r===".config"&&["gcloud","gh","openai","anthropic"].includes(t[o+1]??"")||r===".config"&&t[o+1]==="pip"&&t[o+2]==="pip.conf"||r===".config"&&t[o+1]==="rclone"&&t[o+2]==="rclone.conf"||r===".config"&&t[o+1]==="pypoetry"&&t[o+2]==="auth.toml"||r===".config"&&t[o+1]==="fish"&&["config.fish","fish_variables"].includes(t[o+2]??"")||r===".local"&&t[o+1]==="share"&&t[o+2]==="keyrings"||r==="library"&&t[o+1]==="keychains"||r==="appdata"&&["local","roaming"].includes(t[o+1]??"")&&t[o+2]==="microsoft"&&["credentials","protect","vault"].includes(t[o+3]??""))}i(Au,"isProtectedRelativePath");function _s(e,t){let n=vr(e,t);return n!==void 0&&!Au(n)}i(_s,"isAutoWritableAgentHomePath");function qb(e,t){let n=vr(e,t);if(n===void 0)return!1;if(n==="custom-providers.json")return!0;if(n==="runtime"||n==="runtime/permission-grants.json"||n.startsWith("runtime/daemon/"))return!1;let r=n.startsWith("runtime/")?n.slice(8):n;return!Au(r)}i(qb,"isAutoReadableAgentHomePath");function WP(e,t=process.cwd()){let n;try{n=Ae()}catch{return!0}let r=re.resolve(n),o=re.resolve(t,jn(e)),s=ge(n)??r,a=ge(e,t);return a===void 0?ke(o,r):ke(a,s)&&!qb(a,s)}i(WP,"isProtectedAgentHomeReadTarget");function Wb(e,t=process.cwd()){let n;try{n=Ae()}catch{return!1}let r=re.resolve(n),o=re.resolve(t,jn(e)),s=ge(n)??r,a=ge(e,t);return a===void 0?ke(o,r):ke(a,s)&&!_s(a,s)}i(Wb,"isProtectedAgentHomeMutationTarget");function Dn(e,t=process.cwd()){let n;try{n=Ae()}catch{return!1}let r=re.resolve(n),o=re.resolve(t,jn(e));if(ke(o,r)){let l=vr(o,r);if(Ss(l))return!0}let s=ge(n)??r,a=ge(e,t);if(a===void 0)return ke(o,r);if(!ke(a,s))return!1;let c=vr(a,s);return Ss(c)}i(Dn,"isAgentHomeHardMutationTarget");function Ss(e){return e===void 0||e==="runtime"||e.startsWith("runtime/")||e==="processes"||e.startsWith("processes/")||e==="learned"||e.startsWith("learned/")}i(Ss,"isHardAgentHomeRelativePath");function Cu(e,t=process.cwd()){let n;try{n=Ae()}catch{return!1}let r=re.resolve(t,jn(e));try{if(!br.lstatSync(r).isSymbolicLink()){let a=re.resolve(n),c=ge(n)??a,l=ge(r);return ke(a,r)||l!==void 0&&ke(c,l)?!0:Dn(e,t)}}catch(a){return a.code!=="ENOENT"?!0:Dn(e,t)}let o=re.resolve(n);if(!ke(r,o))return!1;let s=vr(r,o);return Ss(s)}i(Cu,"isAgentHomeHardRemovalTarget");function BP(e,t=process.cwd()){let n;try{n=Ae()}catch{return!0}let r=re.resolve(n),o=ge(n)??r,s=re.resolve(t,jn(e)),a=ge(s);return ke(r,s)||a!==void 0&&ke(o,a)||Wb(s,t)?!0:Bb(s,o)}i(BP,"isProtectedAgentHomeRemovalTarget");function Bb(e,t){let n;try{n=br.lstatSync(e)}catch(a){return a.code!=="ENOENT"}let r=n.isSymbolicLink()?re.resolve(e):ge(e);if(r===void 0||ke(r,t)&&!_s(r,t))return!0;if(n.isSymbolicLink()||!n.isDirectory())return!1;let o=[e],s=0;for(;o.length>0;){let a=o.pop(),c;try{c=br.readdirSync(a,{withFileTypes:!0})}catch{return!0}for(let l of c){if(++s>2e4)return!0;let d=re.join(a,l.name),u=l.isSymbolicLink()?re.resolve(d):ge(d);if(u===void 0||ke(u,t)&&!_s(u,t))return!0;l.isDirectory()&&o.push(d)}}return!1}i(Bb,"removalTreeContainsProtectedPath");import{randomUUID as Pu}from"node:crypto";import{mkdir as Hb,readFile as Mu,rename as Kb,rm as Rs,writeFile as Lu}from"node:fs/promises";import So from"node:path";var ko=new Map,zb=3e4,Gb=1e3,Xb=3e4,Eo=3,Vb="model-filesystem-effects.json",Yb="model-filesystem-effects.lock",Ru,Iu=!1;function Nu(){return Iu||(Ru=wr(process.pid),Iu=!0),Ru}i(Nu,"getEffectOwnerStartIdentity");var Ou=process.env.VITEST_WORKER_ID===void 0?void 0:`${process.env.VITEST_WORKER_ID}-${process.pid}`.replace(/[^a-z0-9_-]/gi,"_");function $u(e,t){return So.join(e,"runtime",...Ou===void 0?[]:[`test-filesystem-effects-${Ou}`],t)}i($u,"effectRuntimePath");function Jb(){let e=process.platform==="win32"?So.join(So.resolve(process.env.PROGRAMDATA??"C:\\ProgramData"),"KodaX","sandbox-runtime"):Ae();return{coordinatorPath:$u(e,Yb),statePath:$u(e,Vb)}}i(Jb,"captureEffectLeaseStorage");function Ts(e){if(typeof e!="object"||e===null)return!1;let t=e;return Number.isInteger(t.pid)&&typeof t.token=="string"&&(t.effectPid===void 0||Number.isInteger(t.effectPid))&&(t.effectProcessStartIdentity===void 0||typeof t.effectProcessStartIdentity=="string")&&(t.effectFinished===void 0||typeof t.effectFinished=="boolean")&&(t.processStartIdentity===void 0||typeof t.processStartIdentity=="string")&&(t.sandboxPolicyKey===void 0||typeof t.sandboxPolicyKey=="string")&&(t.posixProcessGroup===void 0||typeof t.posixProcessGroup=="boolean")&&(t.windowsJobContained===void 0||typeof t.windowsJobContained=="boolean")}i(Ts,"isEffectLeaseOwner");async function xr(e){let t;try{t=await Mu(e.statePath,"utf8")}catch(s){if(s.code==="ENOENT")return{direct:[],namespaces:[],shells:[]};throw s}let n=JSON.parse(t);if(typeof n!="object"||n===null)throw new Error("Invalid filesystem effect lease state.");let r=n;if(!Array.isArray(r.direct)||!r.direct.every(Ts))throw new Error("Invalid direct filesystem effect state.");if(!Array.isArray(r.shells)||!r.shells.every(Ts))throw new Error("Invalid shell filesystem effect state.");let o=r.namespaces??[];if(!Array.isArray(o)||!o.every(Ts))throw new Error("Invalid namespace filesystem effect state.");return{direct:r.direct,namespaces:o,shells:r.shells}}i(xr,"readEffectLeaseState");function Qb(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}i(Qb,"isProcessAlive");function Du(e){if(!Qb(e.pid))return!1;let t=e.pid===process.pid?Nu():wr(e.pid);return e.processStartIdentity===void 0||t===void 0||t===e.processStartIdentity}i(Du,"isEffectLeaseOwnerAlive");function Zb(e,t){if(e.effectFinished===!0)return"absent";if(e.effectPid===void 0)return t?"unknown":"absent";if(e.posixProcessGroup===!0)try{return process.kill(-e.effectPid,0),"alive"}catch(r){return r.code==="ESRCH"?"absent":"unknown"}let n=wr(e.effectPid);return n!==void 0&&(e.effectProcessStartIdentity===void 0||n===e.effectProcessStartIdentity)?"alive":process.platform!=="win32"||e.windowsJobContained===!0||!t?"absent":"unknown"}i(Zb,"modelEffectTreeState");function ev(e,t,n){let r=new Map;for(let a of[...e.direct,...e.namespaces,...e.shells])r.set(a,Du(a));let o=i(a=>n.has(a.token)&&(a.effectPid===void 0||a.effectFinished===!0),"hasReleaseProof"),s=i(a=>!o(a)&&(r.get(a)===!0||Zb(a,t)!=="absent"),"keepExternalEffect");return{direct:e.direct.filter(a=>!o(a)&&r.get(a)===!0),namespaces:e.namespaces.filter(s),shells:e.shells.filter(s)}}i(ev,"removeStaleEffectLeases");function Is(e,t){return`${e.statePath}.${Buffer.from(t,"utf8").toString("base64url")}.released`}i(Is,"effectReleaseMarkerPath");async function tv(e,t){let n=new Set,r=[...t.direct,...t.namespaces,...t.shells];return await Promise.all(r.map(async o=>{try{(await Mu(Is(e,o.token),"utf8")).trim()===o.token&&n.add(o.token)}catch(s){if(s.code!=="ENOENT")throw s}})),n}i(tv,"releasedEffectTokens");async function As(e,t){try{await Rs(Is(e,t),{force:!0})}catch(n){T({source:"coding.filesystem-effect-coordinator",level:"warn",message:"Failed to remove a settled filesystem-effect release marker.",detail:n})}}i(As,"removeEffectReleaseMarkerBestEffort");async function nv(e){return await kr(e,async()=>{let r=await xr(e);return[...r.namespaces,...r.shells].some(o=>!Du(o))})?(await ru()).skipped>0:!0}i(nv,"reconcileAbandonedManagedEffects");async function _o(e,t){let{statePath:n}=e;if(t.direct.length===0&&t.namespaces.length===0&&t.shells.length===0){await Rs(n,{force:!0});return}await Hb(So.dirname(n),{recursive:!0});let r=`${n}.${process.pid}.${Pu()}.tmp`;await Lu(r,`${JSON.stringify(t)}
2
+ import{a as vu,b as xu,c as ku,d as Eu,e as _u,f as Su,g as xs}from"./chunk-GH3KBC2H.js";import{a as ks,b as Nn,c as Tu}from"./chunk-YVG6OKN7.js";import{C as Pn,Ja as gs,Pa as ys,S as uo,Sa as Jd,e as fs,f as ps,g as ms,ka as fo,ma as hs}from"./chunk-BHE66SP3.js";import{$a as Mn,Aa as he,Bb as au,Bc as yo,Hd as wo,Ia as Ae,Id as bo,Ja as on,Ka as ke,Nd as pu,Q as Zd,Rd as vs,Sb as cu,Sd as vo,Ud as xo,Uf as hu,Wa as tu,Xa as bs,Xf as gu,Zb as lu,_ as eu,aa as rn,ac as go,ah as wu,b as ws,c as yr,ch as bu,db as wr,eb as Pt,fb as nu,gc as du,gg as yu,ib as Ce,jb as mo,kb as Ln,l as J,lb as ru,mb as ho,mc as uu,nb as ou,ob as iu,pb as su,r as po,t as T,ue as et,v as Qd,ve as mu,zc as fu}from"./chunk-7XSZVOG7.js";import{h as Mt,j as je}from"./chunk-QFV6YCIH.js";import{a as i}from"./chunk-ONUPGMER.js";import br from"node:fs";import Es from"node:os";import re from"node:path";var jb=new Set(["runtime","mcp-tokens","mcp-clients","integrations","sandbox-runtime","processes","learned",".ssh",".aws",".azure",".gnupg",".kube",".docker",".agents",".codex",".claude",".gemini",".direnv",".terraform.d",".password-store"]),Fb=new Set(["config.json","auth.json","custom-providers.json","trusted-project-rules.json",".env",".envrc",".pgpass",".npmrc",".pypirc",".netrc",".git-credentials","credentials","credentials.json","application_default_credentials.json","id_rsa","id_ed25519",".gitconfig",".gitmodules",".terraformrc",".condarc",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".bash_history",".zsh_history"]),Ub=new Set([".env.example",".env.sample",".env.template"]);function jn(e){return(e==="~"?Es.homedir():/^~[\\/]/.test(e)?re.join(Es.homedir(),e.slice(2)):e).replace(/^(?:\$\{HOME\}|\$HOME|\$env:(?:home|userprofile)|%userprofile%)(?=$|[\\/])/i,Es.homedir())}i(jn,"expandHome");function ge(e,t=process.cwd()){if(!e.trim()||e.includes("\0"))return;let n=jn(e);if(process.platform==="win32"&&/^[a-z]:[^\\/]/i.test(n))return;let r=[],o=re.resolve(t,n);for(;;){try{br.lstatSync(o)}catch(s){if(s.code!=="ENOENT")return;let a=re.dirname(o);if(a===o)return;r.unshift(re.basename(o)),o=a;continue}try{return re.join(br.realpathSync.native(o),...r)}catch{return}}}i(ge,"canonicalizeAgentHomePolicyPath");function vr(e,t){let n=re.relative(t,e);if(!(!n||n.startsWith("..")||re.isAbsolute(n)))return n.split(/[\\/]+/).map(r=>{let o=r.toLowerCase();if(process.platform!=="win32")return o;let s=o.indexOf(":");return(s>=0?o.slice(0,s):o).replace(/[ .]+$/g,"")}).join("/")}i(vr,"normalizedRelative");function Au(e){let t=e.split("/"),n=t.at(-1)??"";return t.some(r=>jb.has(r))||t.some(r=>Fb.has(r))||!Ub.has(n)&&(n===".env"||n.startsWith(".env."))||t.some(r=>/^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$/.test(r))?!0:t.some((r,o)=>r===".git"&&["config","config.worktree"].includes(t[o+1]??"")||r===".config"&&t[o+1]==="git"&&t[o+2]==="config"||r===".cargo"&&t[o+1]==="credentials.toml"||r===".m2"&&["settings.xml","settings-security.xml"].includes(t[o+1]??"")||r===".gradle"&&t[o+1]==="gradle.properties"||r===".nuget"&&t.slice(o+1).includes("nuget.config")||r===".pip"&&t[o+1]==="pip.conf"||r===".huggingface"&&t[o+1]==="token"||r===".cache"&&t[o+1]==="huggingface"&&t[o+2]==="token"||r===".config"&&["gcloud","gh","openai","anthropic"].includes(t[o+1]??"")||r===".config"&&t[o+1]==="pip"&&t[o+2]==="pip.conf"||r===".config"&&t[o+1]==="rclone"&&t[o+2]==="rclone.conf"||r===".config"&&t[o+1]==="pypoetry"&&t[o+2]==="auth.toml"||r===".config"&&t[o+1]==="fish"&&["config.fish","fish_variables"].includes(t[o+2]??"")||r===".local"&&t[o+1]==="share"&&t[o+2]==="keyrings"||r==="library"&&t[o+1]==="keychains"||r==="appdata"&&["local","roaming"].includes(t[o+1]??"")&&t[o+2]==="microsoft"&&["credentials","protect","vault"].includes(t[o+3]??""))}i(Au,"isProtectedRelativePath");function _s(e,t){let n=vr(e,t);return n!==void 0&&!Au(n)}i(_s,"isAutoWritableAgentHomePath");function qb(e,t){let n=vr(e,t);if(n===void 0)return!1;if(n==="custom-providers.json")return!0;if(n==="runtime"||n==="runtime/permission-grants.json"||n.startsWith("runtime/daemon/"))return!1;let r=n.startsWith("runtime/")?n.slice(8):n;return!Au(r)}i(qb,"isAutoReadableAgentHomePath");function WP(e,t=process.cwd()){let n;try{n=Ae()}catch{return!0}let r=re.resolve(n),o=re.resolve(t,jn(e)),s=ge(n)??r,a=ge(e,t);return a===void 0?ke(o,r):ke(a,s)&&!qb(a,s)}i(WP,"isProtectedAgentHomeReadTarget");function Wb(e,t=process.cwd()){let n;try{n=Ae()}catch{return!1}let r=re.resolve(n),o=re.resolve(t,jn(e)),s=ge(n)??r,a=ge(e,t);return a===void 0?ke(o,r):ke(a,s)&&!_s(a,s)}i(Wb,"isProtectedAgentHomeMutationTarget");function Dn(e,t=process.cwd()){let n;try{n=Ae()}catch{return!1}let r=re.resolve(n),o=re.resolve(t,jn(e));if(ke(o,r)){let l=vr(o,r);if(Ss(l))return!0}let s=ge(n)??r,a=ge(e,t);if(a===void 0)return ke(o,r);if(!ke(a,s))return!1;let c=vr(a,s);return Ss(c)}i(Dn,"isAgentHomeHardMutationTarget");function Ss(e){return e===void 0||e==="runtime"||e.startsWith("runtime/")||e==="processes"||e.startsWith("processes/")||e==="learned"||e.startsWith("learned/")}i(Ss,"isHardAgentHomeRelativePath");function Cu(e,t=process.cwd()){let n;try{n=Ae()}catch{return!1}let r=re.resolve(t,jn(e));try{if(!br.lstatSync(r).isSymbolicLink()){let a=re.resolve(n),c=ge(n)??a,l=ge(r);return ke(a,r)||l!==void 0&&ke(c,l)?!0:Dn(e,t)}}catch(a){return a.code!=="ENOENT"?!0:Dn(e,t)}let o=re.resolve(n);if(!ke(r,o))return!1;let s=vr(r,o);return Ss(s)}i(Cu,"isAgentHomeHardRemovalTarget");function BP(e,t=process.cwd()){let n;try{n=Ae()}catch{return!0}let r=re.resolve(n),o=ge(n)??r,s=re.resolve(t,jn(e)),a=ge(s);return ke(r,s)||a!==void 0&&ke(o,a)||Wb(s,t)?!0:Bb(s,o)}i(BP,"isProtectedAgentHomeRemovalTarget");function Bb(e,t){let n;try{n=br.lstatSync(e)}catch(a){return a.code!=="ENOENT"}let r=n.isSymbolicLink()?re.resolve(e):ge(e);if(r===void 0||ke(r,t)&&!_s(r,t))return!0;if(n.isSymbolicLink()||!n.isDirectory())return!1;let o=[e],s=0;for(;o.length>0;){let a=o.pop(),c;try{c=br.readdirSync(a,{withFileTypes:!0})}catch{return!0}for(let l of c){if(++s>2e4)return!0;let d=re.join(a,l.name),u=l.isSymbolicLink()?re.resolve(d):ge(d);if(u===void 0||ke(u,t)&&!_s(u,t))return!0;l.isDirectory()&&o.push(d)}}return!1}i(Bb,"removalTreeContainsProtectedPath");import{randomUUID as Pu}from"node:crypto";import{mkdir as Hb,readFile as Mu,rename as Kb,rm as Rs,writeFile as Lu}from"node:fs/promises";import So from"node:path";var ko=new Map,zb=3e4,Gb=1e3,Xb=3e4,Eo=3,Vb="model-filesystem-effects.json",Yb="model-filesystem-effects.lock",Ru,Iu=!1;function Nu(){return Iu||(Ru=wr(process.pid),Iu=!0),Ru}i(Nu,"getEffectOwnerStartIdentity");var Ou=process.env.VITEST_WORKER_ID===void 0?void 0:`${process.env.VITEST_WORKER_ID}-${process.pid}`.replace(/[^a-z0-9_-]/gi,"_");function $u(e,t){return So.join(e,"runtime",...Ou===void 0?[]:[`test-filesystem-effects-${Ou}`],t)}i($u,"effectRuntimePath");function Jb(){let e=process.platform==="win32"?So.join(So.resolve(process.env.PROGRAMDATA??"C:\\ProgramData"),"KodaX","sandbox-runtime"):Ae();return{coordinatorPath:$u(e,Yb),statePath:$u(e,Vb)}}i(Jb,"captureEffectLeaseStorage");function Ts(e){if(typeof e!="object"||e===null)return!1;let t=e;return Number.isInteger(t.pid)&&typeof t.token=="string"&&(t.effectPid===void 0||Number.isInteger(t.effectPid))&&(t.effectProcessStartIdentity===void 0||typeof t.effectProcessStartIdentity=="string")&&(t.effectFinished===void 0||typeof t.effectFinished=="boolean")&&(t.processStartIdentity===void 0||typeof t.processStartIdentity=="string")&&(t.sandboxPolicyKey===void 0||typeof t.sandboxPolicyKey=="string")&&(t.posixProcessGroup===void 0||typeof t.posixProcessGroup=="boolean")&&(t.windowsJobContained===void 0||typeof t.windowsJobContained=="boolean")}i(Ts,"isEffectLeaseOwner");async function xr(e){let t;try{t=await Mu(e.statePath,"utf8")}catch(s){if(s.code==="ENOENT")return{direct:[],namespaces:[],shells:[]};throw s}let n=JSON.parse(t);if(typeof n!="object"||n===null)throw new Error("Invalid filesystem effect lease state.");let r=n;if(!Array.isArray(r.direct)||!r.direct.every(Ts))throw new Error("Invalid direct filesystem effect state.");if(!Array.isArray(r.shells)||!r.shells.every(Ts))throw new Error("Invalid shell filesystem effect state.");let o=r.namespaces??[];if(!Array.isArray(o)||!o.every(Ts))throw new Error("Invalid namespace filesystem effect state.");return{direct:r.direct,namespaces:o,shells:r.shells}}i(xr,"readEffectLeaseState");function Qb(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}i(Qb,"isProcessAlive");function Du(e){if(!Qb(e.pid))return!1;let t=e.pid===process.pid?Nu():wr(e.pid);return e.processStartIdentity===void 0||t===void 0||t===e.processStartIdentity}i(Du,"isEffectLeaseOwnerAlive");function Zb(e,t){if(e.effectFinished===!0)return"absent";if(e.effectPid===void 0)return t?"unknown":"absent";if(e.posixProcessGroup===!0)try{return process.kill(-e.effectPid,0),"alive"}catch(r){return r.code==="ESRCH"?"absent":"unknown"}let n=wr(e.effectPid);return n!==void 0&&(e.effectProcessStartIdentity===void 0||n===e.effectProcessStartIdentity)?"alive":process.platform!=="win32"||e.windowsJobContained===!0||!t?"absent":"unknown"}i(Zb,"modelEffectTreeState");function ev(e,t,n){let r=new Map;for(let a of[...e.direct,...e.namespaces,...e.shells])r.set(a,Du(a));let o=i(a=>n.has(a.token)&&(a.effectPid===void 0||a.effectFinished===!0),"hasReleaseProof"),s=i(a=>!o(a)&&(r.get(a)===!0||Zb(a,t)!=="absent"),"keepExternalEffect");return{direct:e.direct.filter(a=>!o(a)&&r.get(a)===!0),namespaces:e.namespaces.filter(s),shells:e.shells.filter(s)}}i(ev,"removeStaleEffectLeases");function Is(e,t){return`${e.statePath}.${Buffer.from(t,"utf8").toString("base64url")}.released`}i(Is,"effectReleaseMarkerPath");async function tv(e,t){let n=new Set,r=[...t.direct,...t.namespaces,...t.shells];return await Promise.all(r.map(async o=>{try{(await Mu(Is(e,o.token),"utf8")).trim()===o.token&&n.add(o.token)}catch(s){if(s.code!=="ENOENT")throw s}})),n}i(tv,"releasedEffectTokens");async function As(e,t){try{await Rs(Is(e,t),{force:!0})}catch(n){T({source:"coding.filesystem-effect-coordinator",level:"warn",message:"Failed to remove a settled filesystem-effect release marker.",detail:n})}}i(As,"removeEffectReleaseMarkerBestEffort");async function nv(e){return await kr(e,async()=>{let r=await xr(e);return[...r.namespaces,...r.shells].some(o=>!Du(o))})?(await ru()).skipped>0:!0}i(nv,"reconcileAbandonedManagedEffects");async function _o(e,t){let{statePath:n}=e;if(t.direct.length===0&&t.namespaces.length===0&&t.shells.length===0){await Rs(n,{force:!0});return}await Hb(So.dirname(n),{recursive:!0});let r=`${n}.${process.pid}.${Pu()}.tmp`;await Lu(r,`${JSON.stringify(t)}
3
3
  `,"utf8");try{await Kb(r,n)}catch(o){try{await Rs(r,{force:!0})}catch(s){throw new AggregateError([o,s],"Filesystem effect state update and cleanup both failed.")}throw o}}i(_o,"writeEffectLeaseState");async function kr(e,t){let n=await yo(e.coordinatorPath,zb);try{return await t()}finally{await n()}}i(kr,"withEffectLeaseCoordinator");function rv(e,t){return e.sandboxPolicyKey===void 0||t===void 0?!0:e.sandboxPolicyKey!==t}i(rv,"namespaceConflictsWithShell");function Cs(e,t){return t===void 0||e.sandboxPolicyKey===void 0?!0:e.sandboxPolicyKey!==t}i(Cs,"shellConflictsWithNamespace");async function To(e,t){let n=Jb(),r=Pu(),o=Nu(),s={pid:process.pid,token:r,...o===void 0?{}:{processStartIdentity:o},...t===void 0?{}:{sandboxPolicyKey:t}},a=Date.now()+Gb,c=Date.now()+Xb,l=await nv(n);for(;;){let k=await kr(n,async()=>{let S=await xr(n),D=await tv(n,S),C=ev(S,l,D),K=new Set([...C.direct,...C.namespaces,...C.shells].map(N=>N.token));return(e==="shell"?C.direct.length>0||C.namespaces.some(N=>rv(N,t)):e==="direct"?C.shells.length>0||C.namespaces.length>0:C.direct.length>0||C.namespaces.length>0||C.shells.some(N=>Cs(N,t)))?t!==void 0&&(e==="namespace"?C.namespaces.some(Q=>Q.sandboxPolicyKey!==t)||C.shells.some(Q=>Cs(Q,t)):e==="shell"&&C.namespaces.some(Q=>Q.sandboxPolicyKey!==void 0&&Q.sandboxPolicyKey!==t))?"sandbox-policy-conflict":C.direct.length===0&&(e==="namespace"?t!==void 0&&C.shells.every(Q=>!Cs(Q,t))&&C.namespaces.length>0&&C.namespaces.every(Q=>Q.sandboxPolicyKey===t):e==="shell"&&t===void 0&&C.namespaces.length>0&&C.namespaces.every(Q=>Q.sandboxPolicyKey!==void 0))?"sandbox-acl-transition":!1:(await _o(n,e==="shell"?{direct:C.direct,namespaces:C.namespaces,shells:[...C.shells,s]}:e==="direct"?{direct:[...C.direct,s],namespaces:C.namespaces,shells:C.shells}:{direct:C.direct,namespaces:[...C.namespaces,s],shells:C.shells}),await Promise.all([...D].filter(N=>!K.has(N)).map(N=>As(n,N))),!0)});if(k===!0)break;if(k==="sandbox-policy-conflict")throw new Error("A different sandbox policy is already active.");let L=k==="sandbox-acl-transition"?c:a;if(Date.now()>=L)throw new Error("A model filesystem effect is already active; retry after it finishes.");await new Promise(S=>setTimeout(S,20))}let d=!1,u=!1,f,p=!1,m=!1,h=!1,y=!1,w=i(()=>kr(n,async()=>{let k=await xr(n),L=(e==="shell"?k.shells:e==="direct"?k.direct:k.namespaces).find(S=>S.token===r);if(L===void 0){if(u||m){await As(n,r);return}throw new Error("Filesystem effect lease ownership was lost.")}if(L.effectPid!==void 0&&L.effectFinished!==!0)throw new Error("Filesystem effect process tree has not been proven drained.");m=!0,await _o(n,e==="shell"?{direct:k.direct,namespaces:k.namespaces,shells:k.shells.filter(S=>S.token!==r)}:e==="direct"?{direct:k.direct.filter(S=>S.token!==r),namespaces:k.namespaces,shells:k.shells}:{direct:k.direct,namespaces:k.namespaces.filter(S=>S.token!==r),shells:k.shells}),await As(n,r)}),"releaseOnce"),g=i(()=>{if(d||p)return;p=!0;let k=i(()=>{setTimeout(()=>{w().then(()=>{d=!0,p=!1}).catch(()=>{k()})},250).unref?.()},"retry");k()},"scheduleBackgroundRelease"),b=i(async()=>{let k;if(!u&&(!h||y))try{await Lu(Is(n,r),`${r}
4
4
  `,"utf8"),u=!0}catch(S){k=S}let L;for(let S=1;S<=Eo;S+=1)try{await w(),k!==void 0&&T({source:"coding.filesystem-effect-coordinator",level:"warn",message:"Filesystem-effect release converged without a durable release marker.",detail:k});return}catch(D){L=D,S<Eo&&await new Promise(C=>setTimeout(C,20))}throw g(),k===void 0?L:new AggregateError([k,L],"Filesystem-effect release marker and coordinator cleanup both failed.")},"releaseReliably"),v=i(async()=>{d||(f??=b().then(()=>{d=!0}).finally(()=>{f=void 0}),await f)},"release"),x=i(async(k,L)=>{if(!Number.isInteger(k)||k<=0)throw new Error(`Invalid filesystem effect process id: ${k}`);await kr(n,async()=>{let S=await xr(n);if(!(e==="shell"?S.shells:e==="direct"?S.direct:S.namespaces).some(N=>N.token===r))throw new Error("Filesystem effect lease ownership was lost before process binding.");let C=wr(k),K={...s,effectPid:k,effectFinished:!1,...C===void 0?{}:{effectProcessStartIdentity:C},posixProcessGroup:process.platform!=="win32",windowsJobContained:L},ee=i(N=>N.token===r?K:N,"replaceOwner");await _o(n,{direct:e==="direct"?S.direct.map(ee):S.direct,namespaces:e==="namespace"?S.namespaces.map(ee):S.namespaces,shells:e==="shell"?S.shells.map(ee):S.shells})}),h=!0,y=!1},"bindEffectProcess"),I,_=!1,M=i(()=>kr(n,async()=>{let k=await xr(n),L=i(D=>D.token===r?{...D,effectFinished:!0}:D,"replaceOwner");if(!(e==="shell"?k.shells:e==="direct"?k.direct:k.namespaces).some(D=>D.token===r))throw new Error("Filesystem effect lease ownership was lost before tree completion.");await _o(n,{direct:e==="direct"?k.direct.map(L):k.direct,namespaces:e==="namespace"?k.namespaces.map(L):k.namespaces,shells:e==="shell"?k.shells.map(L):k.shells})}),"finishEffectProcessOnce"),P=i(()=>{if(y||_)return;_=!0;let k=i(()=>{setTimeout(()=>{M().then(()=>{y=!0,_=!1}).catch(()=>{k()})},250).unref?.()},"retry");k()},"scheduleBackgroundFinish");return Object.assign(v,{bindEffectProcess:x,finishEffectProcess:i(async()=>{y||(I??=(async()=>{let k;for(let L=1;L<=Eo;L+=1)try{await M(),y=!0;return}catch(S){k=S,L<Eo&&await new Promise(D=>setTimeout(D,20))}throw P(),k})().finally(()=>{I=void 0}),await I)},"finishEffectProcess")})}i(To,"acquireEffectLease");function ju(e){return To("shell",e)}i(ju,"acquireFileSystemMutationLease");function JP(e){return To("namespace",e)}i(JP,"acquireExclusiveFileSystemEffectLease");function ov(){return To("direct")}i(ov,"acquireDirectFileMutationLease");async function iv(e){let t=await ov();try{return await e()}finally{await t()}}i(iv,"withHostFileSystemMutation");async function Os(e){let t=await To("namespace");try{return await e(t.bindEffectProcess,t.finishEffectProcess)}finally{await t()}}i(Os,"withHostFileSystemNamespaceMutation");function Lt(e,t,n){let r=ge(t);if(r===void 0)throw new Error(`Cannot identify backup path: ${t}`);e.delete(r),e.set(r,n)}i(Lt,"recordFileBackup");function sv(){let e=process.env.KODAX_PATH_KEY_PLATFORM;return e==="win32"?!0:e==="posix"?!1:process.platform==="win32"}i(sv,"isWindowsPathPlatform");function Ao(e){if(typeof e!="string"||e.length===0)return"";let t=e.replace(/\\/g,"/");return t.startsWith("//")?t="//"+t.slice(2).replace(/\/+/g,"/"):t=t.replace(/\/+/g,"/"),sv()?t=t.toLowerCase():t.length>=2&&/^[A-Za-z]:/.test(t)&&(t=t[0].toLowerCase()+t.slice(1)),t.length>1&&t.endsWith("/")&&(t=t.replace(/\/+$/g,"")),t}i(Ao,"normalizePathForKey");async function B(e,t){let n=Ao(e),o=(ko.get(n)??Promise.resolve()).catch(()=>{}).then(async()=>iv(async()=>{if(Dn(e))throw new Error(`Mutation targets protected KodaX state: ${e}`);return await t()})),s=o.catch(()=>{}).finally(()=>{ko.get(n)===s&&ko.delete(n)});return ko.set(n,s),o}i(B,"withFileMutation");import{createHash as av}from"node:crypto";import Fu from"node:path";var Uu=32,cv=4096,qu=128,lv=65536,dv=262144,uv=65536,Wu=64,fv=6e5,pv=6e4,mv=new Set(["pwsh","powershell","cmd","bash","zsh"]),hv=new Set(["default","none","login","interactive","login-interactive"]),Bu=3e4,Ps=1e4;function Ms(e){let t=Er(e,"shellExecution");if(Co(t,["version","shell","environment","cache","probeTimeoutMs"],"shellExecution"),t.version!==1)throw new Error("shellExecution.version must be 1");let n=Er(t.shell,"shellExecution.shell");if(Co(n,["kind","executable","args","profile"],"shellExecution.shell"),!mv.has(n.kind))throw new Error("shellExecution.shell.kind is not supported");let r=n.kind,o=zu(n.executable,"shellExecution.shell.executable",4096);if(o!==void 0&&!Fu.isAbsolute(o)&&!Fu.win32.isAbsolute(o)&&/[\\/]/.test(o))throw new Error("shellExecution.shell.executable must be absolute or a bare executable name");let s=gv(n.args,r),a=bv(n.profile,r),c=vv(t.environment),l=Ev(t.cache),d=Ku(t.probeTimeoutMs,"shellExecution.probeTimeoutMs",100,pv);return{version:1,shell:{kind:r,...o!==void 0?{executable:o}:{},...s!==void 0?{args:s}:{},...a!==void 0?{profile:a}:{}},...c!==void 0?{environment:c}:{},...l!==void 0?{cache:l}:{},...d!==void 0?{probeTimeoutMs:d}:{}}}i(Ms,"normalizeShellExecutionContract");function Hu(e){return av("sha256").update($s(Ms(e))).digest("hex")}i(Hu,"shellExecutionContractFingerprint");function Ro(e){let t=e.toUpperCase();return t==="KODAX_PROVIDER_CREDENTIAL"||t==="KODAX_API_KEY"||/(?:^|_)(?:API_?KEY|KEY|TOKEN|SECRET|PASSWORD|CREDENTIALS?)$/.test(t)||/(?:^|_)(?:SECRET|CREDENTIAL)(?:_|$)/.test(t)}i(Ro,"isSensitiveShellEnvironmentName");function gv(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length>Uu)throw new Error(`shellExecution.shell.args must contain at most ${Uu} strings`);let n=e.map((o,s)=>Ls(o,`shellExecution.shell.args[${s}]`,cv)),r=wv(t);if(n.some(o=>yv(t,o,r)))throw new Error("shellExecution.shell.args cannot override KodaX command or persistence flags");return n}i(gv,"normalizeShellArgs");function yv(e,t,n){let r=t.trim().toLowerCase();if(e==="cmd")return r==="/?"||r.startsWith("/c")||r.startsWith("/k");if(e==="pwsh"||e==="powershell"){let o=r.startsWith("/")?`-${r.slice(1)}`:r;if(!o.startsWith("-")||o.length<2)return!1;let s=o.split(/[:=]/,1)[0]??o;return n.has(s)||[...n].some(a=>a.startsWith(s))}return n.has(r)?!0:e==="bash"||e==="zsh"?/^-[^-]*[cilf]/.test(r):!1}i(yv,"isShellControlArgument");function wv(e){return e==="cmd"?new Set(["/c","/k"]):e==="pwsh"||e==="powershell"?new Set(["-command","-commandwithargs","-encodedcommand","-file","-help","-h","-?","-interactive","-login","-noexit","-noninteractive","-noprofile","-sshservermode","-version","-wd","-workingdirectory"]):new Set(["-c","--command","-i","--interactive","-f","-l","-il","-li","--login","--noprofile","--norc"])}i(wv,"commandControlArgs");function bv(e,t){if(e===void 0)return;if(!hv.has(e))throw new Error("shellExecution.shell.profile is not supported");let n=e;if(t==="cmd"&&n!=="default"&&n!=="none")throw new Error("cmd supports only default or none profile mode");if(t==="powershell"&&n!=="default"&&n!=="none")throw new Error("Windows PowerShell supports only default or none profile mode");return n}i(bv,"normalizeProfileMode");function vv(e){if(e===void 0)return;let t=Er(e,"shellExecution.environment");Co(t,["inherit","set","denyPatterns","setup","windowsPath"],"shellExecution.environment");let n=t.inherit;if(n!==void 0&&n!=="filtered"&&n!=="none")throw new Error("shellExecution.environment.inherit must be filtered or none");let r=xv(t.set),o=kv(t.denyPatterns),s=zu(t.setup,"shellExecution.environment.setup",uv),a=t.windowsPath;if(a!==void 0&&a!=="process"&&a!=="registry")throw new Error("shellExecution.environment.windowsPath must be process or registry");return{...n!==void 0?{inherit:n}:{},...r!==void 0?{set:r}:{},...o!==void 0?{denyPatterns:o}:{},...s!==void 0?{setup:s}:{},...a!==void 0?{windowsPath:a}:{}}}i(vv,"normalizeEnvironment");function xv(e){if(e===void 0)return;let t=Object.entries(Er(e,"shellExecution.environment.set"));if(t.length>qu)throw new Error(`shellExecution.environment.set must contain at most ${qu} entries`);let n=0,r={};for(let[o,s]of t){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))throw new Error(`invalid shell environment variable name: ${o}`);if(Ro(o))throw new Error(`shellExecution.environment.set cannot contain sensitive variable ${o}`);if(o.toUpperCase()==="NODE_OPTIONS")throw new Error(`shellExecution.environment.set cannot contain execution-control variable ${o}`);let a=_v(s,`shellExecution.environment.set.${o}`,lv);if(n+=o.length+a.length,n>dv)throw new Error("shellExecution.environment.set exceeds the size limit");r[o]=a}return r}i(xv,"normalizeEnvironmentSet");function kv(e){if(e!==void 0){if(!Array.isArray(e)||e.length>Wu)throw new Error(`shellExecution.environment.denyPatterns must contain at most ${Wu} strings`);return e.map((t,n)=>{let r=Ls(t,`shellExecution.environment.denyPatterns[${n}]`,256);if(!/^[A-Za-z0-9_*?-]+$/.test(r))throw new Error(`invalid shell environment deny pattern: ${r}`);return r})}}i(kv,"normalizeDenyPatterns");function Ev(e){if(e===void 0)return;let t=Er(e,"shellExecution.cache");Co(t,["ttlMs","refreshToken"],"shellExecution.cache");let n=Ku(t.ttlMs,"shellExecution.cache.ttlMs",0,fv),r=t.refreshToken;if(r!==void 0&&typeof r!="string"&&typeof r!="number")throw new Error("shellExecution.cache.refreshToken must be a string or number");if(typeof r=="number"&&(!Number.isSafeInteger(r)||!Number.isFinite(r)))throw new Error("shellExecution.cache.refreshToken number must be a safe integer");if(typeof r=="string"&&r.length>256)throw new Error("shellExecution.cache.refreshToken exceeds the size limit");return{...n!==void 0?{ttlMs:n}:{},...r!==void 0?{refreshToken:r}:{}}}i(Ev,"normalizeCache");function Ku(e,t,n,r){if(e!==void 0){if(!Number.isSafeInteger(e)||Number(e)<n||Number(e)>r)throw new Error(`${t} must be a safe integer between ${n} and ${r}`);return Number(e)}}i(Ku,"optionalInteger");function zu(e,t,n){return e===void 0?void 0:Ls(e,t,n)}i(zu,"optionalBoundedString");function Ls(e,t,n){if(typeof e!="string"||e.length===0||e.length>n||e.includes("\0"))throw new Error(`${t} must be a non-empty string of at most ${n} characters`);return e}i(Ls,"boundedString");function _v(e,t,n){if(typeof e!="string"||e.length>n||e.includes("\0"))throw new Error(`${t} must be a string of at most ${n} characters`);return e}i(_v,"boundedStringAllowEmpty");function Er(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}i(Er,"requireRecord");function Co(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o!==void 0)throw new Error(`${n} contains unknown field ${o}`)}i(Co,"assertOnlyKeys");function $s(e){if(e===null||typeof e!="object")return JSON.stringify(e)??"undefined";if(Array.isArray(e))return`[${e.map($s).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${$s(t[n])}`).join(",")}}`}i($s,"stableSerialize");import Gu from"node:path";var Sv=new Set(["COMSPEC","HOMEDRIVE","HOMEPATH","HOME","LOCALAPPDATA","OS","PATH","PATHEXT","PROGRAMDATA","PROGRAMFILES","PROGRAMFILES(X86)","SYSTEMDRIVE","SYSTEMROOT","TEMP","TMP","USERPROFILE","WINDIR"]),Tv=new Set(["HOME","LANG","LC_ALL","LOGNAME","PATH","SHELL","TERM","TMPDIR","USER"]),Av=new Set(["BASH_ENV","NODE_OPTIONS","RIPGREP_CONFIG_PATH"]),Cv=4096,Rv=2*1024*1024;function Oo(e,t,n=process.platform,r=[],o,s=[]){let a={...e};for(let c of Object.keys(a)){let l=Iv(c,s,n);(Us(c)||!l&&(Ro(c)||r.some(d=>d.toUpperCase()===c.toUpperCase())))&&Ov(a,c,n)}return js(a,n,o),n!=="win32"||t!=="cmd"||Fe(a,"NoDefaultCurrentDirectoryInExePath","1",n),a}i(Oo,"hardenShellCommandEnvironment");function $o(e){return e?_r(e.split(",")):[]}i($o,"parseSandboxEnvironmentPass");function _r(e){return Array.isArray(e)?[...new Set(e.filter(t=>typeof t=="string").map(t=>t.trim()).filter(t=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)))]:[]}i(_r,"normalizeSandboxEnvironmentPass");function Vu(e,t,n,r=process.platform){let o={...t};for(let s of n){if(Us(s))continue;let a=Object.keys(e).find(c=>Yu(c,s,r));a===void 0||e[a]===void 0||Fe(o,a,e[a],r)}return o}i(Vu,"applyShellEnvironmentPass");function Iv(e,t,n){return t.some(r=>Yu(e,r,n))}i(Iv,"environmentNameIsListed");function Yu(e,t,n){return n==="win32"?e.toUpperCase()===t.toUpperCase():e===t}i(Yu,"environmentNamesEqual");function js(e,t,n){let r=Object.keys(e).find(l=>l.toUpperCase()==="PATH");if(!r||e[r]===void 0)return;let o=t==="win32"?Gu.win32:Gu.posix,s=t==="win32"?";":":",a=n===void 0?void 0:o.resolve(n),c=e[r].split(s).filter(l=>{let d=l.replace(/^"|"$/g,"");if(!o.isAbsolute(d))return!1;if(a===void 0)return!0;let u=o.relative(a,o.resolve(d));return u.startsWith("..")||o.isAbsolute(u)});e[r]=c.join(s)}i(js,"sanitizeCommandPath");function Ov(e,t,n){let r=n==="win32"?Object.keys(e).filter(o=>o.toUpperCase()===t.toUpperCase()):[t];for(let o of r)delete e[o]}i(Ov,"deleteEnvironmentValue");function Fs(e,t,n,r=process.platform,o=[],s){let a=t.environment?.inherit??"filtered",c=r==="win32"?Sv:Tv,l={};for(let[d,u]of Object.entries(e))u===void 0||Io(d,t,o)||a==="none"&&!c.has(d.toUpperCase())||Fe(l,d,u,r);for(let[d,u]of Object.entries(t.environment?.set??{})){if(o.some(f=>f.toUpperCase()===d.toUpperCase()))throw new Error(`shellExecution.environment.set cannot contain active Provider credential variable ${d}`);if(Io(d,t,o))throw new Error(`shellExecution.environment.set cannot contain denied variable ${d}`);Fe(l,d,u,r)}return n!==void 0&&!Io("KODAX_SESSION_TMP",t,o)&&Fe(l,"KODAX_SESSION_TMP",n,r),js(l,r,s),ef(l),l}i(Fs,"buildShellProbeEnvironment");function Ju(e,t,n=process.platform,r=[],o){let s={};for(let[a,c]of Object.entries(e))Io(a,t,r)||Fe(s,a,c,n);return js(s,n,o),ef(s),s}i(Ju,"sanitizeResolvedShellEnvironment");function Io(e,t,n=[]){return Ro(e)||Us(e)||n.some(r=>r.toUpperCase()===e.toUpperCase())?!0:(t.environment?.denyPatterns??[]).some(r=>$v(e,r))}i(Io,"isDeniedEnvironmentName");function Us(e){return Av.has(e.toUpperCase())||/^BASH_FUNC_.+(?:%%|\(\))$/i.test(e)}i(Us,"isExecutionControlEnvironmentName");function $v(e,t){let n="^";for(let r of t.toUpperCase())r==="*"?n+=".*":r==="?"?n+=".":n+=r.replace(/[\\^$.[\]{}()+|]/g,"\\$&");return new RegExp(`${n}$`,"i").test(e)}i($v,"environmentNameMatchesPattern");function Qu(e){let t={};for(let n of e.split(/\r?\n/)){let r=/^\s*(.+?)\s+REG_(?:EXPAND_)?SZ(?:\s+(.*?))?\s*$/i.exec(n),o=r?.[1]?.trim();o===void 0||o.length===0||o==="(Default)"||o.includes("=")||o.includes("\0")||(t[o]=r?.[2]??"")}return t}i(Qu,"parseWindowsRegistryEnvironment");function Zu(e,t,n){let r=Xu(t,"PATH"),o=Xu(n,"PATH");if(r===void 0&&o===void 0)return{...e};let s={...e};Ds(s,t),Ds(s,n);let a={...e};Ds(a,t),Fe(a,"PATH","","win32");let c=r===void 0?"":Ns(r,a),l={...s};Fe(l,"PATH",c,"win32");for(let[m,h]of[...Object.entries(t),...Object.entries(n)])m.toUpperCase()!=="PATH"&&Fe(s,m,Ns(h,l),"win32");let d={...s};Fe(d,"PATH",c,"win32");let u=o===void 0?"":Ns(o,d),p=/%PATH%/i.test(o??"")?u:[c,u].filter(m=>m.length>0).join(";");return Fe(s,"PATH",p,"win32"),s}i(Zu,"mergeWindowsRegistryEnvironment");function Ns(e,t){let n=new Map(Object.entries(t).filter(o=>o[1]!==void 0).map(([o,s])=>[o.toUpperCase(),s])),r=e;for(let o=0;o<16;o+=1){let s=r.replace(/%([^%]+)%/g,(a,c)=>n.get(c.toUpperCase())??a);if(s===r)return r;r=s}return r}i(Ns,"expandWindowsEnvironmentReferences");function Ds(e,t){for(let[n,r]of Object.entries(t))n.toUpperCase()!=="PATH"&&Fe(e,n,r,"win32")}i(Ds,"overlayWindowsRegistryValues");function Xu(e,t){return Object.entries(e).find(([n])=>n.toUpperCase()===t.toUpperCase())?.[1]}i(Xu,"recordEnvironmentValue");function Fe(e,t,n,r){if(r==="win32"){let o=Object.keys(e).find(s=>s.toUpperCase()===t.toUpperCase());o!==void 0&&o!==t&&delete e[o]}e[t]=n}i(Fe,"setEnvironmentValue");function ef(e){let t=Object.entries(e);if(t.length>Cv)throw new Error("resolved shell environment contains too many variables");if(t.reduce((r,[o,s])=>r+Buffer.byteLength(o)+Buffer.byteLength(s??""),0)>Rv)throw new Error("resolved shell environment exceeds the size limit")}i(ef,"validateEnvironmentSize");import{spawn as Pv}from"node:child_process";import{randomBytes as Mv}from"node:crypto";import{accessSync as Lv,constants as tf,realpathSync as Nv,statSync as Dv}from"node:fs";import{delimiter as jv,isAbsolute as nf,join as Mo,resolve as df,win32 as qs}from"node:path";import Ws from"iconv-lite";var Fv=3*1024*1024,Uv=64,qv=[`delete process.env.${bs};`,"const s=process.argv[1];","process.stdout.write(s+Buffer.from(JSON.stringify(process.env)).toString('base64')+s);"].join(""),Wv=`eval(Buffer.from('${Buffer.from(qv).toString("base64")}','base64').toString())`,Nt=new Map,dt=new Map,uf=0;function gM(){uf+=1,Nt.clear();for(let e of dt.values())e.controller.abort();dt.clear()}i(gM,"clearShellExecutionEnvironmentCache");async function ff(e,t,n,r=[],o){if(o?.aborted)throw tt();let s=Ms(e),a=df(t),c=sf(a),l=Hu(s),d=n===void 0?"":sf(n),u=[...r].map(g=>g.toUpperCase()).sort().join("\0"),f=[uf,l,c,d,u].join("\0"),p=Nt.get(f);if(p!==void 0&&p.expiresAt>Date.now())return p.value;p!==void 0&&Nt.delete(f);let m=dt.get(f);if(m?.controller.signal.aborted&&(dt.get(f)===m&&dt.delete(f),m=void 0),m!==void 0)return rf(m,o);let h=new AbortController,y,w=Bv(s,l,a,n,r,h.signal).then(g=>{if(h.signal.aborted||dt.get(f)!==y)throw tt();let b=s.cache?.ttlMs??Bu;return b>0&&rx(f,g,b),g}).finally(()=>{y.settled=!0,dt.get(f)===y&&dt.delete(f)});return y={controller:h,promise:w,waiters:0,settled:!1},dt.set(f,y),rf(y,o)}i(ff,"resolveShellExecution");function rf(e,t){return t?.aborted?(e.waiters===0&&!e.settled&&e.controller.abort(),Promise.reject(tt())):(e.waiters+=1,new Promise((n,r)=>{let o=!1,s=i(()=>(t?.removeEventListener("abort",c),e.waiters-=1,e.waiters===0&&!e.settled),"releaseWaiter"),a=i(l=>{o||(o=!0,s()&&e.controller.abort(),"value"in l?n(l.value):r(l.error))},"finish"),c=i(()=>{if(o)return;if(o=!0,!s()){r(tt());return}e.controller.abort(),e.promise.then(()=>r(tt()),()=>r(tt()))},"onAbort");t?.addEventListener("abort",c,{once:!0}),e.promise.then(l=>a({value:l}),l=>a({error:l})),t?.aborted&&c()}))}i(rf,"waitForInFlightResolution");function tt(){return Object.assign(new Error("shell environment resolution cancelled"),{name:"AbortError"})}i(tt,"shellResolutionAbortError");function pf(e,t,n){let r=n===void 0?$o(process.env.KODAX_SANDBOX_ENV_PASS):_r(n),o=Oo(e.env,e.contract.shell.kind,process.platform,[]);return{executable:e.executable,args:[...e.commandArgs,e.contract.shell.kind==="cmd"&&t.trimStart().startsWith('"')?`"${t.trimStart()}"`:t],env:Vu(process.env,o,r,process.platform),...e.contract.shell.kind==="cmd"?{windowsVerbatimArguments:!0}:{}}}i(pf,"createShellCommandInvocation");async function Bv(e,t,n,r,o=[],s){let a=e.shell.profile??"default";if(process.platform==="win32"&&e.shell.kind==="pwsh"&&(a==="login"||a==="login-interactive"))throw new Error("pwsh login profile mode is supported only on Linux and macOS");let c=Fs(process.env,e,r,process.platform,o,n);e.shell.kind==="bash"&&a==="none"&&(c=ox(c,"BASH_ENV")),process.platform==="win32"&&e.environment?.windowsPath==="registry"&&(c=await tx(c,n,e,s),c=Fs(c,e,r,process.platform,o,n));let l=Jv(e,c),d=await Hv(l,e,n,c,s);return{executable:l,commandArgs:Vv(e.shell.kind,e.shell.args),env:Ju(d,e,process.platform,o),contract:e,contractFingerprint:t}}i(Bv,"resolveFreshShellExecution");async function Hv(e,t,n,r,o){let s=`__KODAX_ENV_${Mv(16).toString("hex")}__`,a=zv(t.shell.kind,s),c=t.environment?.setup,l=Gv(t.shell.kind,c,a),d=Xv(t.shell.kind,t.shell.args,t.shell.profile??"default",l),u=await Hs({executable:e,args:d,cwd:n,env:r,timeoutMs:t.probeTimeoutMs??Ps,kind:"shell-environment-probe",windowsVerbatimArguments:t.shell.kind==="cmd",signal:o});return Kv(u.stdout,s)}i(Hv,"probeShellEnvironment");function Kv(e,t){let n=Buffer.from(t),r=e.indexOf(n),o=r<0?-1:e.indexOf(n,r+n.length);if(r<0||o<0)throw new Error("shell environment probe did not return a valid framed payload");let s=e.subarray(r+n.length,o).toString("ascii");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(s))throw new Error("shell environment probe returned an invalid payload encoding");let a;try{a=JSON.parse(Buffer.from(s,"base64").toString("utf8"))}catch{throw new Error("shell environment probe returned invalid JSON")}if(a===null||typeof a!="object"||Array.isArray(a))throw new Error("shell environment probe returned a non-object environment");let c={};for(let[l,d]of Object.entries(a)){if(l.length===0||l.length>32767||l.includes("=")||l.includes("\0")||typeof d!="string")throw new Error("shell environment probe returned an invalid environment entry");c[l]=d}return c}i(Kv,"parseEnvironmentProbeOutput");function zv(e,t,n=process.execPath,r=process.versions.electron!==void 0,o=process.env.KODAX_BUNDLED==="true"){let s=Mn({args:["-e",Wv,t],env:{},executable:n,isBundled:o,isElectron:r}),a;e==="pwsh"||e==="powershell"?a=`& ${cf(s.command)} ${s.args.map(cf).join(" ")}`:e==="cmd"?a=[lf(s.command),...s.args.map(lf)].join(" "):a=[af(s.command),...s.args.map(af)].join(" ");let c=[bs,tu].filter(l=>s.env[l]==="1");return c.length===0?a:e==="pwsh"||e==="powershell"?`& { ${c.map(d=>`$env:${d} = '1';`).join(" ")} ${a} }`:e==="cmd"?`${c.map(d=>`set "${d}=1"`).join(" && ")} && ${a}`:`${c.map(l=>`${l}=1`).join(" ")} ${a}`}i(zv,"buildNodeEnvironmentHelper");function Gv(e,t,n){return t===void 0?e==="cmd"?`"${n}"`:n:e==="pwsh"||e==="powershell"?`$ErrorActionPreference='Stop'; ${t}
5
5
  ${n}`:e==="cmd"?`(${t}) && ${n}`:`set -e
@@ -35,7 +35,7 @@ ${t.join(`
35
35
  `),sources:[{label:"session storage",path:"packages/repl/src/interactive/storage.ts"}],nextTopics:["compaction","memory","commands","troubleshooting"]},{id:"compaction",title:"Context compaction",aliases:["compact","automatic compaction","context compression","\u4E0A\u4E0B\u6587\u538B\u7F29","\u81EA\u52A8\u538B\u7F29"],summary:"Always-on large compaction thresholds, protected tail, query retention, and events.",body:["Automatic large context compaction is always enabled. The legacy `enabled:false`","setting is accepted for compatibility but cannot turn it off.","`compaction.triggerPercent` defaults to 75 and is clamped to 15..90.","`compaction.triggerTokens` is an optional absolute token threshold; omitted or 0","disables only that absolute threshold. The smaller percentage, positive absolute,","and physical provider-capacity threshold wins.","","The protected recent tail is 20% of the effective trigger, not 20% of the model","context window. One major-compaction wave summarizes the complete eligible prefix","once and preserves the recent tail atomically; it does not repeatedly compact only","the oldest chunk in one turn. A mechanical user-query ledger retains every genuine","user request and correction across later compactions.","","Large compaction is checked at request boundaries, never by a background timer.","Manual `/compact` and Runtime `sessions.compact()` bypass only the trigger comparison","and use the same effective policy and protected budget. SDK hosts can set per-run","`options.compaction` or Session `compactionTriggerPercent` /","`compactionTriggerTokens`; setting the Session absolute value to 0 removes it.","","A successful transition emits one post-commit `context.compaction.finished` fact.","Failed, stale, unchanged, or physically invalid fallback candidates do not emit a","successful compact result and do not partially replace canonical history.","","Before compacted raw bodies are evicted from memory, the root Session host durably","persists their exact lineage. The island sidecar is flushed before the slim main","Session replaces it; stable entry IDs deduplicate their overlap on load. A failed","sidecar or main write keeps an exact live or persisted copy and exposes a diagnostic.","The commit callback is awaited before the next model request or canonical finished","event. Runtime becomes the persistence owner across embedded and daemon boundaries.","Sessions already reduced to `[compacted]` by an older build cannot reconstruct bytes","that were never persisted, but all later compactions use the durable ordering.","","When a later request depends on an omitted detail, a root Agent can use","`session_history_search` and then bounded `session_history_read` instead of guessing","from the summary. Search covers exact persisted user, assistant, tool-result, and","child-task evidence, excludes hidden reasoning/system/checkpoint content, and binds","reads to a revision. SDK hosts use `sessions.transcriptSearch()` and then","`transcriptEntryChunk()` with the returned transcript revision and entry index."].join(`
36
36
  `),sources:[{label:"v0.7.74 design",path:"docs/features/v0.7.74.md"},{label:"compaction config",path:"packages/coding/src/compaction-config.ts"},{label:"shared policy",path:"packages/agent/src/session-lineage/compaction/policy.ts"},{label:"history recovery",path:"packages/agent/src/session-lineage/history-retrieval.ts"},{label:"durable storage",path:"packages/repl/src/interactive/storage.ts"},{label:"SDK guide",path:"docs/SDK_EMBEDDER_GUIDE.md"}],nextTopics:["config","sessions","sdk"]},{id:"memory",title:"Governed memory",aliases:["memory","remember","recall","memory agent","memory_recall","memory_intent","\u8BB0\u5FC6","\u8BB0\u4F4F","\u4E0B\u6B21\u8BB0\u5F97","\u56DE\u5FC6"],summary:"F228 memory governance, automatic recall, deliberate query, and the experimental SDK.",body:["Top-level coding runs use the existing F228 Memory Control Plane. At session start KodaX","builds an exact-scoped memory pack; passive recall stays on the zero-wait hot path. When","the current context cannot answer a specific question about prior execution experience or","a user preference, the Action LLM may call the read-only memory_recall tool. Current","repository facts must still come from current tools, not memory.","","Memory management is conversation-first. When the user asks what KodaX remembers, or","explicitly asks it to remember, correct, or forget something, the root Action LLM calls","memory_intent. Mutations carry an exact quote from the current user turn. Safe explicit","requests apply immediately through the governed preview/fingerprint/apply controller and","do not create a duplicate episode review. Ordinary narration, quoted examples, temporary","task instructions, ambiguous targets, and sensitive content are not silently stored.","Ambiguous, conflicting, broad, or sensitive requests return clarification or an explained","decision. Autonomous episode review remains separate: verified low-risk changes may","auto-apply, while exceptional inferred changes remain reviewable and restart-recoverable.","","Recalled text is low-authority evidence, never an instruction override. Scope, secret","filtering, source evidence, lifecycle, and mutation protection are deterministic code gates.","Use /memory list|remember|forget|decisions|show|approve|reject|doctor|open as an advanced","escape hatch. MEMORY.md is a derived projection; open launches an external application and","the hidden rebuild command only repairs that projection. Durable changes still pass the","proposal/preview/fingerprint/apply controller;","KodaX does not expose filesystem memory actions or auto-edit prompts, policy, code, or weights.","","For `tool_failure`, `verification_failure`, or a durably committed `context_compacted`","event, `MemorySession.intervene()` rebuilds a closed prompt-safe candidate set and may","inject at most three low-authority evidence items before the next Action-LLM request.","Deterministic exact matches run without a model call. An in-process host may opt into the","bounded `memoryRecallRunner`; malformed, unknown, stale, timed-out, cancelled, or failed","selector output fails silent. The default runtime makes no selector call, and daemon DTOs","reject this function binding.","","SDK hosts can opt into @kodax-ai/kodax/experimental-memory. MemorySession.recall() is","synchronous; query() is deliberate and read-only; observe(), complete(), rewind(), and close()","provide bounded episode lifecycle. Decision receipts are trace-only and do not store hidden","reasoning. This subpath is experimental; the F228 control plane remains the only durable store."].join(`
37
37
  `),sources:[{label:"coding memory runtime",path:"packages/coding/src/agent-runtime/run-substrate.ts"},{label:"memory recall tool",path:"packages/coding/src/tools/memory-recall.ts"},{label:"memory intent tool",path:"packages/coding/src/tools/memory-intent.ts"},{label:"memory command",path:"packages/repl/src/commands/memory-command.ts"},{label:"experimental memory SDK",path:"packages/agent/src/experimental-memory/"}],nextTopics:["sessions","tools","sdk"]},{id:"doctor",title:"kodax doctor",aliases:["doctor","diagnose","health check","ping","\u8BCA\u65AD","\u4F53\u68C0"],summary:"Diagnose config/provider/credential issues; --ping live reachability.",body:["Run `kodax doctor` to print a health report: configured provider(s), credential/config","state, and storage directories. Add `kodax doctor --ping` to live-probe whether each","configured provider is reachable with the current key. This is the first stop for",'connection / 401 / 429 / "provider not working" problems.'].join(`
38
- `),sources:[{label:"doctor CLI",path:"src/kodax_doctor.ts"}],nextTopics:["troubleshooting","providers","config"]},{id:"sdk",title:"SDK",aliases:["embed","library","api","sdk\u5165\u95E8","\u5D4C\u5165"],summary:"Published subpaths, shared Runtime hosting, packaged Electron, A2A, and memory.",body:["The source monorepo has 4 workspace packages: @kodax-ai/llm, @kodax-ai/agent,","@kodax-ai/coding, and @kodax-ai/repl. The published @kodax-ai/kodax bundle exposes","12 SDK subpaths: /agent, /llm, /coding, /media, /repl, /skills, /mcp, /session,","/runtime, /sandbox, /a2a, and /experimental-memory.","Use @kodax-ai/kodax/coding for coding tasks; @kodax-ai/kodax/runtime for embedded,","Worker-hosted, or local-daemon sessions/runs/events/permissions;","@kodax-ai/kodax/sandbox for explicit host-owned ASRT containment;","@kodax-ai/kodax/a2a for the A2A 1.0 JSON-RPC/SSE client/server edge; and","@kodax-ai/kodax/experimental-memory for the opt-in MemoryAgent/MemorySession contract.","For an A2A server, listen() waits for durable recovery; a host wiring handle() directly","can await server.whenReady() before accepting traffic.","External Agent owner planes bound close to a 30-second default across admitted work","and executor disposal; hosts may set a positive finite `closeTimeoutMs` override.","","The shared local daemon is authoritative for one Coder profile. Join a session atomically","with sessions.observe(); replace local projection after runtime change/resync_required.","Use sessions.status() for the authoritative Session lifecycle projection and","captureRuntimeSessionDiagnostics() / sessions.diagnostics() for one bounded, read-only","support record. Diagnostics never take ownership, resume, repair, or migrate the Session.","Use sessions.conversation(), sessions.conversationPage(), and","sessions.conversationEntryChunk() for the same immutable ordinary-conversation projection","across embedded and daemon modes; require conversationHistory:1 when that contract is needed.","Control mutations use durable operation identities and settings/permission revisions.","AskUser and permissions are transport-safe. Provider credentials are requested just in","time and scoped to a run/provider; run-bound Host Tools never leak into unrelated CLI","runs. Daemon/inline ownership is fenced, and inline rollback remains sticky. Partner","products keep their separate private embedded Runtime.","The v0.7.90 stabilization keeps these ownership boundaries while making workspace","timeout retirement orderly, preserving direct clone provenance, and normalizing","run-scoped tool schemas before provider dispatch.","The v0.7.91 SDK adds `runtimeExitSettlement:1` and the public","`settleKodaXRuntimeExit({ configHome, profile, runtime? })` transaction.","Pass the connected Runtime for an orderly host exit; after relaunch, call it","with `configHome` and `profile` to resume an exact prepared ticket. `clean`","means verified orderly shutdown, `recovered` means identity-scoped repair","was proven safe, and `blocked` supplies a bounded next action. The API never","accepts short caller timeouts and never exposes bare-PID kill or raw ACL deletion.","The v0.7.92 SDK advertises `sandboxRuntime:4` and `crashOutcomeModel:2`.","Filesystem-effect tickets share an operation token with the coordinator lock;","a stale same-PID ticket is reclaimed only when it no longer owns that lock.","Managed `onComplete` is not terminal authority; the executor Promise is.","`KodaXFileLockTimeoutError` means the filesystem-effect coordinator was","unavailable, not that a learning job holds the lock. Do not delete ProgramData","lock files by hand.","Resume reconstruction uses canonical Session messages as the ordinary","conversation; uiHistory may overlay display metadata but cannot hide that","transcript. Presentation-only agent-completed and task-completed events","stay host-owned when a non-empty CLI uiHistory exists.","The same release requires `liveOutputSegments:1` for new daemon consumers and","bundles lazy Anthropic/OpenAI SDK dependency graphs in standalone binaries.","AskUser and permission prompts have independent bounded deadlines and owner AbortSignals. On expiry, Runtime accepts only a validated default; otherwise it dismisses the request. MCP reverse elicitation cancels through the same signal. `reclaimStaleKodaXFileLock` is the public Agent helper for an explicitly identified stale learning lock; it is not a general lock deletion primitive.","Configure `userInputTimeoutMs` independently from `permissionTimeoutMs`; both are validated before embedded, Worker, or daemon startup. Permission timeout 0 retains its timer-disable meaning.","","Require `learningCenter:1` and `skillLearningLoop:1` when a host depends on the complete","F263 project-canary contract. `runtime.learning` exposes list/get/snapshot/events/subscribe","plus explicit acknowledge, snooze, reject, disable, rollback, review, trust, and user-scope","promotion controls. Inventory and lifecycle state remain Runtime-owned; clients render","the Learning Center and never infer activation from files alone.","","Packaged/asar Electron hosts may use daemon auto-start when the default-enabled","RunAsNode fuse is available. `homeDir` is the CLI-style base directory that owns","`.kodax`; `KODAX_HOME` is the lower-level `.kodax` path. ELECTRON_RUN_AS_NODE exists","only at the detached child exec boundary and is removed before daemon or user child","code loads. If the fuse is disabled, start the daemon with ordinary Node/CLI and use","attach-only mode; KodaX does not reopen the GUI or silently fall back to inline mode.","","Windows child cleanup identity-checks observed processes and exposes indeterminate outcomes","instead of using bare-PID success. Snapshot ancestry is not Job Object containment: an","intermediate parent can exit before a later snapshot and hide a running descendant. Until","Issue 256 is resolved with spawn-time Job Object assignment and a host-issued Worker owner","lease, do not treat Runtime/Worker close as proof that every descendant terminated.","","Runtime Auto Mode is a durable Session setting, not a UI-side classifier. Query","sessions.getAutoModeStats() for current state and configure the engine/model/timeout","through Session settings. A missing LLM classifier model is a recoverable typed error,","not a fallback to rules or a permission prompt. Permission requests can include opaque","`grantSuggestions`; return a suggestion id for allow_session/allow_always rather than","building a scope. `RuntimePermissionMatcher` describes the Runtime-generated exact","command/path/call matcher, while persistent grants are revisioned through","permissions.listGrants() and revokeGrant(). Daemon capability","`runtimeAutoModeGuardrail` v4 advertises this concrete-grant and intent-aligned fallback contract.","Daemon auto-start requires v4 and safely replaces an idle v3 owner; v4 reports","`fallbackPersistsEngine:false`, so classifier degradation cannot silently select Rules.","","Hosts that depend on bounded source-level streaming batches can require","`runtimeEventCoalescing:1`. Auto-start safely upgrades an idle legacy daemon; busy or","otherwise unsafe owners fail closed instead of being stopped. Text and reasoning deltas","remain reconstructable and each accumulated merge stays within 8 KiB before sequence","allocation, durable event persistence, and subscriber delivery.","","Persisted Actor Sessions have one exclusive Runtime owner. Current owners publish a","loopback identity challenge in addition to their PID, so an unrelated process that reuses","the PID cannot pin crashed ownership. Ambiguous probes and legacy owners remain fail-closed.","","Model `wait_agent` and SDK `runtime.agents.wait()` are intentionally different.","The model tool waits for mailbox/user/interruption/timeout activity and receives only","an acknowledgement. SDK hosts use `runtime.agents.events()` for Actor event snapshots","and `runtime.agents.wait(sessionId, afterSequence, timeoutMs)` for sequence-based","telemetry long-poll; progress remains observable without resampling the action model.","For user input during an active Run, require `interruptInput:1` and call","`runtime.runs.submitInput()`; the Runtime delivers the ordered batch at a safe Runner","boundary rather than creating a continuation Run. A terminal candidate closes the input","window atomically, drains every already-accepted item, and reserves one same-Run model","turn even at the iteration limit. Failure, cancellation, and terminal cleanup keep the","window closed so undelivered input cannot leak into another Run.","","For a Runtime-owned Session, every delivered interrupt is first persisted as its own","canonical user entry. `runtime.runs.get().interruptInputs` and `run.input.delivered` expose","the delivered item's `entryId`, an exact canonical session-entry reference; compaction,","event replay, and Runtime restart preserve it. Treat the field as absent only for legacy","records and never invent an entry id: missing/ambiguous provenance or required persistence","failure fails the current delivery closed.","Since v0.7.82, submitInput resolves the admitted authoritative Run before reading mutable","Session history. Active interrupt and after-turn admission therefore avoid transient","`data_changed`; after-turn still waits for predecessor settlement and an exact operation","id produces one admission and one queue item.","An observed daemon Stop is cooperative: it fences later provider retries, continuations,","guardrails, tools, and Run-admitted Actor work while preserving turns already admitted.","Trusted Stop/Abort causality is classified before credential redaction; completion races","and independent failures remain factual terminal outcomes.","Since v0.7.83, a Windows daemon starts suspended and is assigned to a kill-on-close","Job Object before user code runs. An out-of-Job supervisor waits for daemon exit and","Job emptiness. `waitForRuntimeDaemonShutdown()` requires the exact durable cleanup","outcome plus daemon and supervisor exit; the `daemonShutdownVerification:1` capability","advertises this contract. A legacy daemon without containment is not reported as verified","and cannot be migrated safely in place for this requirement: stop and relaunch it.","This daemon-owned slice narrows Issue 256 but does not close its Worker owner-lease gap,","which remains open after v0.7.87; this release assigns no replacement target.","Since v0.7.84, Agent progress persistence is bounded to one in-flight","durable projection plus one latest replacement, so terminal settlement does not","wait behind an unbounded progress backlog. If Actor durability becomes unknown,","a same-owner Stop can reconcile and validate the late snapshot, quiesce remaining","turns, and retry the repair. Promise terminal facts outrank fallback callbacks","after repair; foreign owners and unresolved stores remain fail-closed. A no-op","quiesce does not rewrite the Session.","","Since v0.7.85, Runtime event order belongs to one Session journal. Every event","carries a { sessionId, journalEpoch, seq } cursor, and events.subscribe()/replay()","require sessionId or runId; numeric Runtime-global sequences are not resumable.","A2A binds one Runtime Session to each Task, daemon clients require","sessionEventJournal:1, and corrupt journal indexes or ambiguous retention evidence","fail closed. A terminal Run with authoritative status and no queued interrupt input","is restored at startup without replaying its complete event journal.","The semantic repo-intelligence Worker retires after its idle warm-cache window;","a later cache miss starts a fresh Worker.","","F289/F290 keep Memory review draining and lesson/verdict admission bounded and","observable. F292 makes explicit Memory management conversation-first: safe explicit","remember, correction, forget, and recall requests are host-governed, while","ambiguous or inferred changes remain reviewable. The experimental SDK exposes","MemoryManagementAgent only when the supplied controller supports that capability.","","Since v0.7.86, inline daemon-enable recovery removes only a provably abandoned","owner fence; live, malformed, legacy, and ambiguous owners remain fail-closed.","Runtime owner and learning-file lock records include an OS process-start identity,","so PID reuse cannot preserve stale ownership. Windows sandbox ACL owner markers are","durable and recovery is serialized across Runtime profiles. Sandbox stop waits for","process-tree termination proof before ACL recovery; missing attestation fences later","filesystem effects and never replays the command. Spawn, lease-release, and cleanup","failures remain combined in a lifecycle safety diagnostic. POSIX workspace sessions","initialize fresh KODAX_HOME policy roots before identity capture, settle only workspace-local","warm-up within the Shell abort/deadline, retire","invalid cached sessions after lease-cleanup failure, and block replacement after unconfirmed","process-tree or cleanup failure. Issue 256 remains open","after v0.7.87; this release assigns no replacement target.","","Coding hosts may pass `memoryRecallRunner` to opt into F275 semantic candidate selection;","without it, sparse governed intervention remains deterministic and adds zero selector calls.","Because the runner is a function binding, Worker/daemon DTO options reject it; configure it","inside the Runtime owner or use inline mode.","","The SDK is ESM-only. Capability queries such as per-model context/limits, credential","verification, and agent discovery can support embedder UIs without starting a coding run."].join(`
38
+ `),sources:[{label:"doctor CLI",path:"src/kodax_doctor.ts"}],nextTopics:["troubleshooting","providers","config"]},{id:"sdk",title:"SDK",aliases:["embed","library","api","sdk\u5165\u95E8","\u5D4C\u5165"],summary:"Published subpaths, shared Runtime hosting, packaged Electron, A2A, and memory.",body:["The source monorepo has 4 workspace packages: @kodax-ai/llm, @kodax-ai/agent,","@kodax-ai/coding, and @kodax-ai/repl. The published @kodax-ai/kodax bundle exposes","12 SDK subpaths: /agent, /llm, /coding, /media, /repl, /skills, /mcp, /session,","/runtime, /sandbox, /a2a, and /experimental-memory.","Use @kodax-ai/kodax/coding for coding tasks; @kodax-ai/kodax/runtime for embedded,","Worker-hosted, or local-daemon sessions/runs/events/permissions;","@kodax-ai/kodax/sandbox for explicit host-owned ASRT containment;","@kodax-ai/kodax/a2a for the A2A 1.0 JSON-RPC/SSE client/server edge; and","@kodax-ai/kodax/experimental-memory for the opt-in MemoryAgent/MemorySession contract.","For an A2A server, listen() waits for durable recovery; a host wiring handle() directly","can await server.whenReady() before accepting traffic.","External Agent owner planes bound close to a 30-second default across admitted work","and executor disposal; hosts may set a positive finite `closeTimeoutMs` override.","","The shared local daemon is authoritative for one Coder profile. Join a session atomically","with sessions.observe(); replace local projection after runtime change/resync_required.","Use sessions.status() for the authoritative Session lifecycle projection and","captureRuntimeSessionDiagnostics() / sessions.diagnostics() for one bounded, read-only","support record. Diagnostics never take ownership, resume, repair, or migrate the Session.","Use sessions.conversation(), sessions.conversationPage(), and","sessions.conversationEntryChunk() for the same immutable ordinary-conversation projection","across embedded and daemon modes; require conversationHistory:1 when that contract is needed.","Control mutations use durable operation identities and settings/permission revisions.","AskUser and permissions are transport-safe. Provider credentials are requested just in","time and scoped to a run/provider; run-bound Host Tools never leak into unrelated CLI","runs. Daemon/inline ownership is fenced, and inline rollback remains sticky. Partner","products keep their separate private embedded Runtime.","The v0.7.90 stabilization keeps these ownership boundaries while making workspace","timeout retirement orderly, preserving direct clone provenance, and normalizing","run-scoped tool schemas before provider dispatch.","The v0.7.91 SDK adds `runtimeExitSettlement:1` and the public","`settleKodaXRuntimeExit({ configHome, profile, runtime? })` transaction.","Pass the connected Runtime for an orderly host exit; after relaunch, call it","with `configHome` and `profile` to resume an exact prepared ticket. `clean`","means verified orderly shutdown, `recovered` means identity-scoped repair","was proven safe, and `blocked` supplies a bounded next action. The API never","accepts short caller timeouts and never exposes bare-PID kill or raw ACL deletion.","The v0.7.93 SDK keeps `sandboxRuntime:4` and `crashOutcomeModel:2`.","A durable Windows failed shutdown outcome ends the 170-second orderly","exit wait and enters exact recovery immediately.","After a verified boot change, previous-boot shared ACL markers may be","recovered under the machine lock before they are cleared.","Anthropic and OpenAI abort wrappers are classified by isolated SDK class","identity when the request signal is already aborted.","The v0.7.92 SDK advertises `sandboxRuntime:4` and `crashOutcomeModel:2`.","Filesystem-effect tickets share an operation token with the coordinator lock;","a stale same-PID ticket is reclaimed only when it no longer owns that lock.","Managed `onComplete` is not terminal authority; the executor Promise is.","`KodaXFileLockTimeoutError` means the filesystem-effect coordinator was","unavailable, not that a learning job holds the lock. Do not delete ProgramData","lock files by hand.","Resume reconstruction uses canonical Session messages as the ordinary","conversation; uiHistory may overlay display metadata but cannot hide that","transcript. Presentation-only agent-completed and task-completed events","stay host-owned when a non-empty CLI uiHistory exists.","The same release requires `liveOutputSegments:1` for new daemon consumers and","bundles lazy Anthropic/OpenAI SDK dependency graphs in standalone binaries.","AskUser and permission prompts have independent bounded deadlines and owner AbortSignals. On expiry, Runtime accepts only a validated default; otherwise it dismisses the request. MCP reverse elicitation cancels through the same signal. `reclaimStaleKodaXFileLock` is the public Agent helper for an explicitly identified stale learning lock; it is not a general lock deletion primitive.","Configure `userInputTimeoutMs` independently from `permissionTimeoutMs`; both are validated before embedded, Worker, or daemon startup. Permission timeout 0 retains its timer-disable meaning.","","Require `learningCenter:1` and `skillLearningLoop:1` when a host depends on the complete","F263 project-canary contract. `runtime.learning` exposes list/get/snapshot/events/subscribe","plus explicit acknowledge, snooze, reject, disable, rollback, review, trust, and user-scope","promotion controls. Inventory and lifecycle state remain Runtime-owned; clients render","the Learning Center and never infer activation from files alone.","","Packaged/asar Electron hosts may use daemon auto-start when the default-enabled","RunAsNode fuse is available. `homeDir` is the CLI-style base directory that owns","`.kodax`; `KODAX_HOME` is the lower-level `.kodax` path. ELECTRON_RUN_AS_NODE exists","only at the detached child exec boundary and is removed before daemon or user child","code loads. If the fuse is disabled, start the daemon with ordinary Node/CLI and use","attach-only mode; KodaX does not reopen the GUI or silently fall back to inline mode.","","Windows child cleanup identity-checks observed processes and exposes indeterminate outcomes","instead of using bare-PID success. Snapshot ancestry is not Job Object containment: an","intermediate parent can exit before a later snapshot and hide a running descendant. Until","Issue 256 is resolved with spawn-time Job Object assignment and a host-issued Worker owner","lease, do not treat Runtime/Worker close as proof that every descendant terminated.","","Runtime Auto Mode is a durable Session setting, not a UI-side classifier. Query","sessions.getAutoModeStats() for current state and configure the engine/model/timeout","through Session settings. A missing LLM classifier model is a recoverable typed error,","not a fallback to rules or a permission prompt. Permission requests can include opaque","`grantSuggestions`; return a suggestion id for allow_session/allow_always rather than","building a scope. `RuntimePermissionMatcher` describes the Runtime-generated exact","command/path/call matcher, while persistent grants are revisioned through","permissions.listGrants() and revokeGrant(). Daemon capability","`runtimeAutoModeGuardrail` v4 advertises this concrete-grant and intent-aligned fallback contract.","Daemon auto-start requires v4 and safely replaces an idle v3 owner; v4 reports","`fallbackPersistsEngine:false`, so classifier degradation cannot silently select Rules.","","Hosts that depend on bounded source-level streaming batches can require","`runtimeEventCoalescing:1`. Auto-start safely upgrades an idle legacy daemon; busy or","otherwise unsafe owners fail closed instead of being stopped. Text and reasoning deltas","remain reconstructable and each accumulated merge stays within 8 KiB before sequence","allocation, durable event persistence, and subscriber delivery.","","Persisted Actor Sessions have one exclusive Runtime owner. Current owners publish a","loopback identity challenge in addition to their PID, so an unrelated process that reuses","the PID cannot pin crashed ownership. Ambiguous probes and legacy owners remain fail-closed.","","Model `wait_agent` and SDK `runtime.agents.wait()` are intentionally different.","The model tool waits for mailbox/user/interruption/timeout activity and receives only","an acknowledgement. SDK hosts use `runtime.agents.events()` for Actor event snapshots","and `runtime.agents.wait(sessionId, afterSequence, timeoutMs)` for sequence-based","telemetry long-poll; progress remains observable without resampling the action model.","For user input during an active Run, require `interruptInput:1` and call","`runtime.runs.submitInput()`; the Runtime delivers the ordered batch at a safe Runner","boundary rather than creating a continuation Run. A terminal candidate closes the input","window atomically, drains every already-accepted item, and reserves one same-Run model","turn even at the iteration limit. Failure, cancellation, and terminal cleanup keep the","window closed so undelivered input cannot leak into another Run.","","For a Runtime-owned Session, every delivered interrupt is first persisted as its own","canonical user entry. `runtime.runs.get().interruptInputs` and `run.input.delivered` expose","the delivered item's `entryId`, an exact canonical session-entry reference; compaction,","event replay, and Runtime restart preserve it. Treat the field as absent only for legacy","records and never invent an entry id: missing/ambiguous provenance or required persistence","failure fails the current delivery closed.","Since v0.7.82, submitInput resolves the admitted authoritative Run before reading mutable","Session history. Active interrupt and after-turn admission therefore avoid transient","`data_changed`; after-turn still waits for predecessor settlement and an exact operation","id produces one admission and one queue item.","An observed daemon Stop is cooperative: it fences later provider retries, continuations,","guardrails, tools, and Run-admitted Actor work while preserving turns already admitted.","Trusted Stop/Abort causality is classified before credential redaction; completion races","and independent failures remain factual terminal outcomes.","Since v0.7.83, a Windows daemon starts suspended and is assigned to a kill-on-close","Job Object before user code runs. An out-of-Job supervisor waits for daemon exit and","Job emptiness. `waitForRuntimeDaemonShutdown()` requires the exact durable cleanup","outcome plus daemon and supervisor exit; the `daemonShutdownVerification:1` capability","advertises this contract. A legacy daemon without containment is not reported as verified","and cannot be migrated safely in place for this requirement: stop and relaunch it.","This daemon-owned slice narrows Issue 256 but does not close its Worker owner-lease gap,","which remains open after v0.7.87; this release assigns no replacement target.","Since v0.7.84, Agent progress persistence is bounded to one in-flight","durable projection plus one latest replacement, so terminal settlement does not","wait behind an unbounded progress backlog. If Actor durability becomes unknown,","a same-owner Stop can reconcile and validate the late snapshot, quiesce remaining","turns, and retry the repair. Promise terminal facts outrank fallback callbacks","after repair; foreign owners and unresolved stores remain fail-closed. A no-op","quiesce does not rewrite the Session.","","Since v0.7.85, Runtime event order belongs to one Session journal. Every event","carries a { sessionId, journalEpoch, seq } cursor, and events.subscribe()/replay()","require sessionId or runId; numeric Runtime-global sequences are not resumable.","A2A binds one Runtime Session to each Task, daemon clients require","sessionEventJournal:1, and corrupt journal indexes or ambiguous retention evidence","fail closed. A terminal Run with authoritative status and no queued interrupt input","is restored at startup without replaying its complete event journal.","The semantic repo-intelligence Worker retires after its idle warm-cache window;","a later cache miss starts a fresh Worker.","","F289/F290 keep Memory review draining and lesson/verdict admission bounded and","observable. F292 makes explicit Memory management conversation-first: safe explicit","remember, correction, forget, and recall requests are host-governed, while","ambiguous or inferred changes remain reviewable. The experimental SDK exposes","MemoryManagementAgent only when the supplied controller supports that capability.","","Since v0.7.86, inline daemon-enable recovery removes only a provably abandoned","owner fence; live, malformed, legacy, and ambiguous owners remain fail-closed.","Runtime owner and learning-file lock records include an OS process-start identity,","so PID reuse cannot preserve stale ownership. Windows sandbox ACL owner markers are","durable and recovery is serialized across Runtime profiles. Sandbox stop waits for","process-tree termination proof before ACL recovery; missing attestation fences later","filesystem effects and never replays the command. Spawn, lease-release, and cleanup","failures remain combined in a lifecycle safety diagnostic. POSIX workspace sessions","initialize fresh KODAX_HOME policy roots before identity capture, settle only workspace-local","warm-up within the Shell abort/deadline, retire","invalid cached sessions after lease-cleanup failure, and block replacement after unconfirmed","process-tree or cleanup failure. Issue 256 remains open","after v0.7.87; this release assigns no replacement target.","","Coding hosts may pass `memoryRecallRunner` to opt into F275 semantic candidate selection;","without it, sparse governed intervention remains deterministic and adds zero selector calls.","Because the runner is a function binding, Worker/daemon DTO options reject it; configure it","inside the Runtime owner or use inline mode.","","The SDK is ESM-only. Capability queries such as per-model context/limits, credential","verification, and agent discovery can support embedder UIs without starting a coding run."].join(`
39
39
  `),sources:[{label:"published exports",path:"package.json"},{label:"Runtime facade",path:"src/sdk-runtime.ts"},{label:"A2A facade",path:"src/sdk-a2a.ts"},{label:"SDK embedder guide",path:"public_docs/sdk/embedder-guide.md"},{label:"known issues",path:"docs/KNOWN_ISSUES.md"}],nextTopics:["providers","agents","tools"]},{id:"troubleshooting",title:"Troubleshooting",aliases:["error","problem","401","429","fix","\u6392\u969C","\u62A5\u9519","\u95EE\u9898"],summary:"First run kodax doctor; provider 401/429, network, Windows paths, Node/npm.",body:["First: run `kodax doctor --ping` to localize the problem.","- 401 / unauthorized: key missing/invalid \u2014 check provider env var or config.json.","- 429 / rate limit: back off, or set KODAX_FALLBACK_PROVIDERS for cross-provider fallback.","- Network: corporate proxy / region blocks can fail provider endpoints.","- Windows: paths use forward slashes internally; case-insensitive workspace match is handled.","- Node/npm: ensure Node >= 20; reinstall the global package if the CLI is stale.","- Daemon exits before healthy: inspect ~/.kodax/runtime/daemon/<profile>/bootstrap.log.","- Integration degraded: validate only the named integrations/*.json domain. The core"," daemon remains usable and hot-recovers; do not delete config.json or the whole directory."].join(`
40
40
  `),sources:[{label:"doctor CLI",path:"src/kodax_doctor.ts"}],nextTopics:["doctor","providers","config"]}],Ef=Object.freeze(Object.fromEntries(Ex.map(e=>[e.id,e])));var _x="KodaX";function Sx(e){return{id:String(e.id??""),title:String(e.title??""),aliases:e.aliases??[],summary:String(e.summary??""),body:String(e.body??""),sources:e.sources??[],nextTopics:e.nextTopics??[]}}i(Sx,"normalizeInjected");function Tx(e,t){let n=new Map,r=[],o=t??kf;for(let s of o){if(n.has(s))continue;let a=Ef[s];a&&(n.set(s,a),r.push(s))}for(let s of e??[])n.has(s.id)||r.push(s.id),n.set(s.id,Sx(s));return{ids:r,byId:n}}i(Tx,"buildEntries");function Ax(e,t){return`(${t} ${e} manual \u2014 about ${t} itself, not Claude Code or Codex CLI.`+(t==="KodaX"?" KodaX config lives in ~/.kodax/config.json + KODAX_* env vars.)":")")}i(Ax,"scopeAnchor");function Tf(e){return e.toLowerCase().split(/[^a-z0-9一-鿿]+/u).filter(t=>t.length>0)}i(Tf,"tokenize");function Cx(e,t,n){return e.includes(n)?t.get(n):void 0}i(Cx,"findByExactId");function Rx(e,t,n){let r=n.trim().toLowerCase();if(r.length!==0)for(let o of e){let s=t.get(o);if(s.aliases.some(a=>a.toLowerCase()===r))return s}}i(Rx,"findByAlias");function Ix(e,t,n){if(t.length===0)return 0;let r=new Set(Tf([e.id,e.title,e.summary,...e.aliases].join(" "))),o=0;for(let s of t)r.has(s)&&(o+=1);for(let s of e.aliases){let a=s.trim().toLowerCase();/[一-鿿]/u.test(a)&&n.includes(a)&&(o+=2)}return o}i(Ix,"scoreTopic");function _f(e,t,n){let r=Tf(n),o=n.toLowerCase();return e.map(s=>t.get(s)).map(s=>({topic:s,score:Ix(s,r,o)})).filter(s=>s.score>0).sort((s,a)=>a.score-s.score).map(s=>s.topic)}i(_f,"rankByQuery");function Sf(e,t){return{matchedTopic:e.id,title:e.title,content:`${Ax(e.id,t)}
41
41
 
@@ -376,7 +376,7 @@ LSP errors detected in this file, please fix:
376
376
  ${u}`:""}async getDefinition(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.definition(_e.resolve(t),n).catch(()=>[]);return Vi(s,"No definition found at that position.")}async getHover(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.hover(_e.resolve(t),n).catch(()=>null);return Aw(s)}async getReferences(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.references(_e.resolve(t),n).catch(()=>[]);return Vi(s,"No references found at that position.")}async getDocumentSymbols(t,n={}){let r=await this.navClient(t,n);if(r.kind!=="client")return r.message;let o=await r.client.documentSymbols(_e.resolve(t)).catch(()=>[]);return Cw(o,"No symbols found in this file.")}async getWorkspaceSymbols(t,n={}){let r=await this.workspaceClients(n);if(r.length===0)return"No language server is available for workspace symbol search.";let o=await Promise.all(r.map(s=>s.workspaceSymbols(t).catch(()=>[])));return Rw(o.flat(),"No workspace symbols found for that query.")}async getImplementation(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.implementation(_e.resolve(t),n).catch(()=>[]);return Vi(s,"No implementation found at that position.")}async getPrepareCallHierarchy(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.prepareCallHierarchy(_e.resolve(t),n).catch(()=>[]);return Ow(s,"No call hierarchy item found at that position.")}async getIncomingCalls(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=_e.resolve(t),a=await o.client.prepareCallHierarchy(s,n).catch(()=>[]);if(a.length===0)return"No call hierarchy item found at that position.";let c=await Promise.all(a.map(l=>o.client.incomingCalls(l).catch(()=>[])));return $w(c.flat(),"No incoming calls found for that symbol.")}async getOutgoingCalls(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=_e.resolve(t),a=await o.client.prepareCallHierarchy(s,n).catch(()=>[]);if(a.length===0)return"No call hierarchy item found at that position.";let c=await Promise.all(a.map(l=>o.client.outgoingCalls(l).catch(()=>[])));return Pw(c.flat(),"No outgoing calls found for that symbol.")}async navClient(t,n){let r=ks(t);if(!r)return{kind:"message",message:`No language server is configured for ${_e.basename(t)}.`};let o=this.servers.filter(c=>c.languageIds.includes(r));if(o.length===0)return{kind:"message",message:`No language server is configured for ${_e.basename(t)}.`};let s=_e.resolve(t),a=n.gitRoot??_e.dirname(s);for(let c of o){let l=_d(s,c.rootMarkers,a),d=await this.getClient(c,l,n);if(d)return await d.notifyOpenOrChange(s).catch(()=>{}),{kind:"client",client:d}}return{kind:"message",message:o.map(c=>c.installGuidance).join(`
377
377
  `)}}async workspaceClients(t){let n=_e.resolve(t.gitRoot??process.cwd()),r=[];for(let o of this.servers){let s=await this.getClient(o,n,t);s&&r.push(s)}return r}async shutdownAll(){this.shuttingDown=!0;try{await Promise.all([...this.spawning.values()].map(n=>n.catch(()=>{})));let t=[...this.clients.values()];this.clients.clear(),this.broken.clear(),await Promise.all(t.map(n=>n.shutdown().catch(()=>{})))}finally{this.shuttingDown=!1}}killAllSync(){for(let t of this.clients.values())t.killSync();this.clients.clear()}resetBroken(t){t?this.broken.delete(t):this.broken.clear()}async getClient(t,n,r){let o=`${Nn(n)}|${t.id}`,s=this.clients.get(o);if(s)return s;if(this.broken.has(o))return;let a=this.spawning.get(o);if(a)return a;let c=this.spawnClient(t,n,o,r);this.spawning.set(o,c);try{return await c}finally{this.spawning.delete(o)}}async spawnClient(t,n,r,o){try{let s=t.discover({root:n,moduleUrl:this.config.moduleUrl});if(s||(s=await this.acquireIfEnabled(t,n,o)),!s){this.broken.add(r),this.config.debug?.(`${t.id} not installed at ${n} \u2014 ${t.installGuidance}`);return}o.onProgress?.(`Starting ${t.id} language server\u2026`);let c=await(this.config.createClient??(await import("./client-OVYKC3ND.js")).createLspClient)({serverId:t.id,root:n,launch:s,debug:this.config.debug});if(this.shuttingDown){await c.shutdown().catch(()=>{});return}return this.clients.set(r,c),c}catch(s){this.broken.add(r),this.config.debug?.(`${t.id} failed to start at ${n}: ${s.message}`);return}}async acquireIfEnabled(t,n,r){if(!(!t.acquire||!Sd()))try{return await t.acquire({root:n,signal:r.signal,onProgress:r.onProgress,debug:this.config.debug})}catch(o){this.config.debug?.(`${t.id} auto-install failed: ${o.message}`);return}}},ao,Mw=!1;function Lw(){let e=uo()?.lsp;if(!(e===!1||e===void 0&&process.env.KODAX_LSP==="0"))return ao||(ao=new Rd({moduleUrl:import.meta.url,debug:process.env.KODAX_DEBUG_LSP?t=>T({source:"coding:lsp",level:"debug",message:t}):void 0}),!Mw&&!Pt()&&(Mw=!0,process.once("exit",()=>ao?.killAllSync()))),ao}i(Lw,"getDefaultLspService");async function _z(){await ao?.shutdownAll()}i(_z,"shutdownDefaultLspService");import{createHash as sP}from"node:crypto";import{execFileSync as _$}from"child_process";import{randomUUID as S$}from"node:crypto";import T$ from"fs/promises";import zw from"os";function Nw(e,t,n){let r=e?.provider?.trim()||process.env[t]?.trim()||void 0,o=e?.model?.trim()||process.env[n]?.trim()||void 0;if(!(!r&&!o))return{provider:r,model:o}}i(Nw,"resolveTier");function Id(e,t){let n=uo()?.modelTiers;if(e==="fast")return t?Nw(n?.fast,"KODAX_FAST_PROVIDER","KODAX_FAST_MODEL"):void 0;if(e==="deep")return Nw(n?.deep,"KODAX_DEEP_PROVIDER","KODAX_DEEP_MODEL")}i(Id,"resolveModelHintTier");function m$(){let e=process.env.KODAX_FALLBACK_PROVIDERS?.trim();return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}i(m$,"resolveFallbackChain");function Dw(e){return e instanceof ps||e instanceof ms||e instanceof fs}i(Dw,"isFallbackEligibleError");function h$(e){return e instanceof ps?"rate-limit exhausted":e instanceof ms?"network error":e instanceof fs?"provider error":e instanceof Error?e.message:String(e)}i(h$,"errorReason");async function Od(e,t,n,r){let o=e.provider??"anthropic";try{return await n(e,t)}catch(s){if(e.abortSignal?.aborted||!Dw(s))throw s;let a=m$().filter(l=>l!==o&&(r?.isProviderAllowed?.(l)??!0)),c=s;for(let l of a){r?.onFallback?.({fromProvider:o,toProvider:l,reason:h$(c)});try{return await n({...e,provider:l,model:void 0},t)}catch(d){if(e.abortSignal?.aborted||!Dw(d))throw d;c=d}}throw c}}i(Od,"invokeChildWithFallback");function g$(e){if(!e.trim())return[];let t=[],n=/(^|\s)\/skill:([\w](?:[\w.\-:]*[\w])?)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"",s=r[2]??"";if(!s)continue;let a=r.index+o.length,c=`/skill:${s}`;t.push({name:s,raw:c,start:a,end:a+c.length})}return t}i(g$,"parseInlineSkillReferences");function y$(e){if(!e.trim())return[];let t=[],n=/(^|\s)\/(?!skill:)([\w](?:[\w.\-:]*[\w])?)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"",s=r[2]??"";if(!s)continue;let a=r.index+o.length,c=`/${s}`;t.push({name:s,raw:c,start:a,end:a+c.length})}return t}i(y$,"parseBareInlineSlashReferences");function jw(e){return Array.from(new Set(g$(e).map(t=>t.name)))}i(jw,"uniqueInlineSkillNames");function Fw(e){return Array.from(new Set(y$(e).map(t=>t.name)))}i(Fw,"uniqueBareInlineSlashNames");function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(at,"isRecord");function w$(e){return e instanceof Error?e.message:String(e)}i(w$,"errorMessage");function Zi(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}i(Zi,"safeStringify");function Uw(e,t){switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number";case"integer":return typeof e=="number"&&Number.isInteger(e);case"boolean":return typeof e=="boolean";case"object":return at(e);case"array":return Array.isArray(e);case"null":return e===null;default:return!0}}i(Uw,"matchesType");function b$(e,t){return e.some(n=>n===t?!0:typeof n!="object"||typeof t!="object"?!1:Zi(n)===Zi(t))}i(b$,"enumMatches");function Yi(e,t){return e?`${e}.${t}`:t}i(Yi,"joinPath");function Ji(e,t,n=""){if(!at(t))return[];let r=[],o=n||"(root)",s=t.type;if(typeof s=="string"&&!Uw(e,s))return[`${o}: expected type ${s}`];if(Array.isArray(s)&&!s.some(a=>typeof a=="string"&&Uw(e,a)))return[`${o}: expected one of types ${s.join("|")}`];if(Array.isArray(t.enum)&&!b$(t.enum,e)&&r.push(`${o}: value is not one of the allowed enum values`),Array.isArray(t.oneOf)){let a=t.oneOf.filter(c=>Ji(e,c,n).length===0).length;a!==1&&r.push(`${o}: value must match exactly one of the ${t.oneOf.length} oneOf variants (matched ${a})`)}if(at(e)){let a=at(t.properties)?t.properties:void 0;if(Array.isArray(t.required))for(let c of t.required)typeof c=="string"&&!(c in e)&&r.push(`${Yi(n,c)}: required field is missing`);if(a){for(let[c,l]of Object.entries(e))c in a&&r.push(...Ji(l,a[c],Yi(n,c)));if(t.additionalProperties===!1)for(let c of Object.keys(e))c in a||r.push(`${Yi(n,c)}: unexpected property (additionalProperties is false)`)}}return Array.isArray(e)&&at(t.items)&&e.forEach((a,c)=>{r.push(...Ji(a,t.items,`${o}[${c}]`))}),r}i(Ji,"validateAgainstSchema");var v$=["$ref","$defs","definitions","allOf","anyOf","not","if","then","else","const","patternProperties","propertyNames","dependencies","dependentSchemas","dependentRequired","contains","unevaluatedProperties","unevaluatedItems","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties"];function Qi(e,t,n){if(at(e)){for(let r of v$)r in e&&!n.has(r)&&n.set(r,t||"(root)");if(at(e.properties))for(let[r,o]of Object.entries(e.properties))Qi(o,Yi(t,r),n);if(at(e.items)&&Qi(e.items,`${t||"(root)"}[]`,n),Array.isArray(e.oneOf))for(let r of e.oneOf)Qi(r,`${t||"(root)"}(oneOf)`,n);at(e.additionalProperties)&&!n.has("additionalProperties (schema form)")&&n.set("additionalProperties (schema form)",t||"(root)")}}i(Qi,"collectUnsupportedKeywords");function Lz(e){if(!at(e))return;let t=new Map;if(Qi(e,"",t),t.size===0)return;let n=[...t.entries()].map(([r,o])=>`\`${r}\` (at ${o})`).join(", ");throw new Error(`outputSchema uses unsupported JSON-Schema keyword(s): ${n}. The workflow validator supports only type, enum, required, properties, items, oneOf, and additionalProperties: false (nested object arrays included). Inline the referenced shapes, drop value-constraint keywords, and use that subset.`)}i(Lz,"assertSupportedOutputSchema");function x$(e){let t=e.indexOf("{"),n=e.indexOf("[");return t<0?n:n<0?t:Math.min(t,n)}i(x$,"firstStructureStart");function qw(e){let t=x$(e);if(t<0)return;let n=e[t],r=n==="{"?"}":"]",o=0,s=!1,a=!1;for(let c=t;c<e.length;c+=1){let l=e[c];if(s){a?a=!1:l==="\\"?a=!0:l==='"'&&(s=!1);continue}if(l==='"'){s=!0;continue}if(l===n)o+=1;else if(l===r&&(o-=1,o===0))return e.slice(t,c+1)}}i(qw,"balancedStructure");function k$(e){if(typeof e!="string"||e.trim().length===0)return;let t=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(n=t.exec(e))!==null;){let o=n[1]?.trim();o&&(r=o)}return r?qw(r)??r:qw(e)}i(k$,"extractJsonCandidate");function $d(e,t){let n=k$(e);if(n===void 0)return{ok:!1,errors:["no JSON value was found in the output"]};let r;try{r=JSON.parse(n)}catch(s){return{ok:!1,errors:[`output was not valid JSON: ${w$(s)}`]}}let o=Ji(r,t);return{ok:o.length===0,value:r,errors:o}}i($d,"evaluateStructuredOutput");function Ww(e){return["## Required Output Format","After your analysis, end your response with a single fenced ```json code block containing ONLY a JSON value that matches the JSON Schema below. Put nothing after the closing fence.","Schema:","```json",Zi(e),"```"].join(`
378
378
  `)}i(Ww,"buildStructuredOutputInstruction");function Bw(e,t){return["Your previous response did not produce a valid result object for the workflow.","Problems:",...e.map(n=>`- ${n}`),"Re-emit ONLY a single fenced ```json code block containing a JSON value that matches this schema. No prose, nothing after the closing fence.","Schema:","```json",Zi(t),"```"].join(`
379
- `)}i(Bw,"buildStructuredOutputRepairPrompt");var Hw={type:"object",additionalProperties:!1,required:["schemaVersion","outcomes","assertedCoverage"],properties:{schemaVersion:{type:"number",enum:[1]},outcomes:{type:"array",items:{type:"object",additionalProperties:!1,required:["target","disposition","evidenceRefs"],properties:{target:{oneOf:[{type:"object",additionalProperties:!1,required:["actorPath","turnId"],properties:{actorPath:{type:"string"},turnId:{type:"string"}}},{type:"object",additionalProperties:!1,required:["evidenceRef"],properties:{evidenceRef:{type:"string"}}}]},disposition:{type:"string",enum:["confirmed","refuted","unresolved"]},evidenceRefs:{type:"array",items:{type:"string"}}}}},assertedCoverage:{type:"array",items:{type:"string"}}}};function ns(e){if(!ts(e)||!Pd(e,["schemaVersion","outcomes","assertedCoverage"])||e.schemaVersion!==1||!Array.isArray(e.outcomes)||e.outcomes.length>50||!Array.isArray(e.assertedCoverage)||e.assertedCoverage.length>50)return;let t=Kw(e.assertedCoverage);if(t===void 0)return;let n=[];for(let r of e.outcomes){let o=E$(r);if(o===void 0)return;n.push(o)}return{schemaVersion:1,outcomes:n,assertedCoverage:[...new Set(t)]}}i(ns,"parsePatternDispositionEnvelope");function mr(e){if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e;if(Array.isArray(e)){let n=[];for(let r of e){let o=mr(r);if(o===void 0)return;n.push(o)}return n}if(!ts(e))return;let t={};for(let[n,r]of Object.entries(e)){let o=mr(r);if(o===void 0)return;t[n]=o}return t}i(mr,"toAgentMetadataValue");function E$(e){if(!ts(e)||!Pd(e,["target","disposition","evidenceRefs"])||!ts(e.target)||!Pd(e.target,["actorPath","turnId","evidenceRef"])||e.disposition!=="confirmed"&&e.disposition!=="refuted"&&e.disposition!=="unresolved"||!Array.isArray(e.evidenceRefs)||e.evidenceRefs.length>20)return;let t=Kw(e.evidenceRefs);if(t===void 0)return;let n=es(e.target.actorPath),r=es(e.target.turnId),o=es(e.target.evidenceRef),s=n!==void 0&&r!==void 0;if(s!==(o!==void 0)&&!(!s&&(e.target.actorPath!==void 0||e.target.turnId!==void 0)))return{target:s?{actorPath:n,turnId:r}:{evidenceRef:o},disposition:e.disposition,evidenceRefs:[...new Set(t)]}}i(E$,"parseOutcome");function Kw(e){let t=[];for(let n of e){let r=es(n);if(r===void 0)return;t.push(r)}return t}i(Kw,"stringArray");function es(e){if(typeof e!="string")return;let t=e.trim();return t.length>0&&t.length<=512?t:void 0}i(es,"boundedString");function ts(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ts,"isRecord");function Pd(e,t){let n=new Set(t);return Object.keys(e).every(r=>n.has(r))}i(Pd,"hasOnlyKeys");var Md,rs;async function Jw(){if(Md)return Md;if(!rs){let e="./agent.js";rs=import("./agent-YHHFIH7N.js").then(t=>{let n=t.runKodaX;if(typeof n!="function")throw new Error("[child-executor] Agent module loaded but `runKodaX` export is missing or not a function. This indicates an API break in packages/coding/src/agent.ts. Check that `export { runKodaX }` is still present.");return Md=n,n}).catch(t=>{if(rs=void 0,t instanceof Error&&t.message.startsWith("[child-executor]"))throw t;let n=t instanceof Error?t.message:String(t);throw new Error(`[child-executor] Failed to lazy-load agent module (\`${e}\`) for a nested Agent turn. This usually means the @kodax-ai/coding build is broken or out of date. Underlying cause: ${n}`)})}return rs}i(Jw,"getRunKodaX");var A$=["You are summarizing your own just-completed child-agent report for a parent workflow.","Do not use tools. Do not continue investigation. Produce only the digest."].join(`
379
+ `)}i(Bw,"buildStructuredOutputRepairPrompt");var Hw={type:"object",additionalProperties:!1,required:["schemaVersion","outcomes","assertedCoverage"],properties:{schemaVersion:{type:"number",enum:[1]},outcomes:{type:"array",items:{type:"object",additionalProperties:!1,required:["target","disposition","evidenceRefs"],properties:{target:{oneOf:[{type:"object",additionalProperties:!1,required:["actorPath","turnId"],properties:{actorPath:{type:"string"},turnId:{type:"string"}}},{type:"object",additionalProperties:!1,required:["evidenceRef"],properties:{evidenceRef:{type:"string"}}}]},disposition:{type:"string",enum:["confirmed","refuted","unresolved"]},evidenceRefs:{type:"array",items:{type:"string"}}}}},assertedCoverage:{type:"array",items:{type:"string"}}}};function ns(e){if(!ts(e)||!Pd(e,["schemaVersion","outcomes","assertedCoverage"])||e.schemaVersion!==1||!Array.isArray(e.outcomes)||e.outcomes.length>50||!Array.isArray(e.assertedCoverage)||e.assertedCoverage.length>50)return;let t=Kw(e.assertedCoverage);if(t===void 0)return;let n=[];for(let r of e.outcomes){let o=E$(r);if(o===void 0)return;n.push(o)}return{schemaVersion:1,outcomes:n,assertedCoverage:[...new Set(t)]}}i(ns,"parsePatternDispositionEnvelope");function mr(e){if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e;if(Array.isArray(e)){let n=[];for(let r of e){let o=mr(r);if(o===void 0)return;n.push(o)}return n}if(!ts(e))return;let t={};for(let[n,r]of Object.entries(e)){let o=mr(r);if(o===void 0)return;t[n]=o}return t}i(mr,"toAgentMetadataValue");function E$(e){if(!ts(e)||!Pd(e,["target","disposition","evidenceRefs"])||!ts(e.target)||!Pd(e.target,["actorPath","turnId","evidenceRef"])||e.disposition!=="confirmed"&&e.disposition!=="refuted"&&e.disposition!=="unresolved"||!Array.isArray(e.evidenceRefs)||e.evidenceRefs.length>20)return;let t=Kw(e.evidenceRefs);if(t===void 0)return;let n=es(e.target.actorPath),r=es(e.target.turnId),o=es(e.target.evidenceRef),s=n!==void 0&&r!==void 0;if(s!==(o!==void 0)&&!(!s&&(e.target.actorPath!==void 0||e.target.turnId!==void 0)))return{target:s?{actorPath:n,turnId:r}:{evidenceRef:o},disposition:e.disposition,evidenceRefs:[...new Set(t)]}}i(E$,"parseOutcome");function Kw(e){let t=[];for(let n of e){let r=es(n);if(r===void 0)return;t.push(r)}return t}i(Kw,"stringArray");function es(e){if(typeof e!="string")return;let t=e.trim();return t.length>0&&t.length<=512?t:void 0}i(es,"boundedString");function ts(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ts,"isRecord");function Pd(e,t){let n=new Set(t);return Object.keys(e).every(r=>n.has(r))}i(Pd,"hasOnlyKeys");var Md,rs;async function Jw(){if(Md)return Md;if(!rs){let e="./agent.js";rs=import("./agent-R7HVNARP.js").then(t=>{let n=t.runKodaX;if(typeof n!="function")throw new Error("[child-executor] Agent module loaded but `runKodaX` export is missing or not a function. This indicates an API break in packages/coding/src/agent.ts. Check that `export { runKodaX }` is still present.");return Md=n,n}).catch(t=>{if(rs=void 0,t instanceof Error&&t.message.startsWith("[child-executor]"))throw t;let n=t instanceof Error?t.message:String(t);throw new Error(`[child-executor] Failed to lazy-load agent module (\`${e}\`) for a nested Agent turn. This usually means the @kodax-ai/coding build is broken or out of date. Underlying cause: ${n}`)})}return rs}i(Jw,"getRunKodaX");var A$=["You are summarizing your own just-completed child-agent report for a parent workflow.","Do not use tools. Do not continue investigation. Produce only the digest."].join(`
380
380
  `),C$=["Create a short user-facing digest of your previous report for the parent workflow.","Return only 2-4 bullet lines.","Each bullet must be concrete: a finding, decision, risk, evidence pointer, unresolved question, or next action.","Use the same natural language as the user request or your report.","Do not include a title, table, generic preamble, or workflow handoff markers."].join(`
381
381
  `),Qw=4,Zw=1e4,R$=45e3,I$=40;function eb(e,t){return e.historyStorage?{id:`worker-${S$()}`,scope:"managed-task-worker",storage:e.historyStorage,...t&&t.length>0?{initialMessages:[...t]}:{}}:t&&t.length>0?{initialMessages:[...t]}:void 0}i(eb,"buildChildRunSession");function is(e){let t={};return e.parentOptions.repoIntelligenceMode!==void 0&&(t.repoIntelligenceMode=e.parentOptions.repoIntelligenceMode),e.parentOptions.repoIntelligenceTrace!==void 0&&(t.repoIntelligenceTrace=e.parentOptions.repoIntelligenceTrace),t}i(is,"inheritRepoIntelligenceContext");async function tb(e,t,n){if(e.length===0)return Yw;let r=e.filter(f=>f.readOnly),o=e.filter(f=>!f.readOnly),s=iP(o,n.parentRole,n.parentHarness),a=[...r,...s];if(a.length===0)return Yw;let c=[],l=[],d=n.onProgress??(()=>{});d(`Starting ${a.length} child tasks in parallel`);let u=await au({bundles:a,runOne:i(f=>f.readOnly?X$(f,t,n):Y$(f,t,n),"runOne"),maxParallel:n.maxParallel,abortSignal:n.abortSignal,onProgress:i((f,p)=>{f.kind==="start"?d(`[${p.completedCount}/${p.totalCount}] Running: ${f.bundle.id}`):f.kind==="item-done"&&d(`[${p.completedCount}/${p.totalCount}] Done: ${f.bundle.id} \u2192 ${f.result.status}`)},"onProgress")});for(let f of u.results)f.status==="fulfilled"?c.push(f.value):c.push(On(f.bundle,`[Crash] ${f.reason.message}`,"failed"));for(let f of u.cancelled)l.push(f.id);return oP(a,c,l)}i(tb,"executeChildAgents");function nb(e,t){let n=[...t?.bindingConstraints??[],...e.constraints];return{...t,delegatedObjective:e.objective,bindingConstraints:n,...e.scopeSummary!==void 0?{scopeHint:e.scopeSummary}:{},readOnly:t?.readOnly===!0||e.readOnly}}i(nb,"buildChildPermissionIntent");var O$=["list_dispatchable_agents","spawn_agent","run_workflow","send_message","followup_task","wait_agent","interrupt_agent","list_agents","agent_output","emit_managed_protocol"];function $$(e,t){if(!t)return e;let n=new Set(t.tools),r=n.has("*"),o=new Set(e);for(let s of Qt()){let a=!r&&!n.has(s.name),c=!t.network&&(s.sideEffect==="reads-network"||s.sideEffect==="mutates-network"),l=!t.canAskUser&&s.name==="ask_user_question";(a||c||l)&&o.add(s.name)}return[...o]}i($$,"restrictToolsForActor");function rb(e,t,n){let r=$$(e,t);return n!==void 0?r:[...new Set([...r,...O$])]}i(rb,"restrictToolsForChildRuntime");function ss(e,t){return t.contextAgentId??e.id}i(ss,"childContextAgentId");function as(e,t){return t.contextParentAgentId??(t.actorControl!==void 0?t.actorParentAgentId:e.currentAgentId)}i(as,"childContextParentAgentId");function os(e,t,n){if(t.includes(e))return!1;let r=Qt().find(o=>o.name===e);return r?n.toolVisibilityPolicy?.({name:r.name,sideEffect:r.sideEffect,planModeAllowed:r.planModeAllowed===!0})??!0:!1}i(os,"isChildToolVisible");function Ld(e,t){return t===void 0||t.providers.includes("*")||t.providers.includes(e)}i(Ld,"isProviderAllowed");function ob(e,t){if(!Ld(e,t))throw new Error(`Child Actor is not authorized to use provider ${e}.`)}i(ob,"assertChildProviderAllowed");function P$(e){let t=JSON.parse(e);if(typeof t!="object"||t===null||!("path"in t))throw new Error("worktree_create returned an invalid payload");let n=t.path;if(typeof n!="string"||n.length===0)throw new Error("worktree_create returned an invalid path");return n}i(P$,"readWorktreePath");async function ib(e,t){if(e.isolation!=="worktree")return{ctx:t};let n=await tg({description:`workflow-${e.id}`},t),r=P$(n);return{ctx:{...t,gitRoot:r,executionCwd:r},worktreePath:r}}i(ib,"prepareChildIsolationScope");function sb(e,t){return t.worktreePath?[`[Workflow worktree: ${t.worktreePath}]`,e].join(`
382
382
  `):e}i(sb,"annotateWorktreeSummary");async function Gw(e,t){if(e.worktreePath)try{await rg(e.worktreePath,t);return}catch(n){return`[Workflow worktree cleanup failed: ${n instanceof Error?n.message:String(n)}]`}}i(Gw,"cleanupChildIsolationScope");function M$(e,t){return t?{...e,summary:`${e.summary}
@@ -411,4 +411,4 @@ ${Oe(o)}
411
411
  ${Oe(e.content)}
412
412
  </agent-completed>`}return`<agent-message id="${Oe(e.messageId)}" from="${Oe(e.senderPath)}" classification="${e.classification}">
413
413
  ${Oe(e.content)}
414
- </agent-message>`}i(Ud,"renderMailboxMessage");function bP(e,t){if(!(!t||e.actor.capabilities.providers.includes("*"))&&!e.actor.capabilities.providers.includes(t))throw new Error(`Actor ${e.actor.path} is not authorized to use provider ${t}.`)}i(bP,"assertProviderAuthority");function Oe(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}i(Oe,"escapeXml");function vP(e){return{async admit(t){return e.spentBudget+t.units>e.totalBudget?{admitted:!1,fact:{code:"agent_budget_exhausted",retryable:!1,reason:`shared root work budget exhausted (${e.spentBudget}/${e.totalBudget})`}}:(e.spentBudget+=t.units,{admitted:!0})},async refund(){e.spentBudget=Math.max(0,e.spentBudget-1)},snapshot:i(()=>({...e}),"snapshot")}}i(vP,"managedWorkBudgetPort");function xP(e,t){let n=Ke(e.specialistName);if(n)return n;let r=Ke(e.agentId);if(!(!r||t.actor.kind==="native"))throw new Error(`Agent selector ${r} was not resolved before execution.`)}i(xP,"specialistName");function kP(e){return e==="fast"||e==="balanced"||e==="deep"?e:void 0}i(kP,"modelHint");function EP(e){let t=Ke(e);if(!t)return;let n=Pn(t);return n==="auto"?void 0:n}i(EP,"effort");function Ke(e){return typeof e=="string"&&e.length>0?e:void 0}i(Ke,"metadataString");function Sb(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}i(Sb,"metadataStringArray");import Cb from"node:path";var _P=80;function SP(e){let t=e.trim().replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,_P);return!t||t==="."||t===".."?"session":t}i(SP,"sanitizeScratchSessionId");function Rb(e){let t=e.session?.id?.trim();if(!t)return;let n=e.context?.gitRoot?.trim(),r=n?Cb.resolve(n):ye(e.context);return Cb.resolve(r,".agent","tmp","sessions",SP(t))}i(Rb,"getSessionScratchDir");var TP="emit_managed_protocol",TG="kodax-task-contract",AP="kodax-task-verdict",AG="kodax-task-scout",CG="kodax-task-handoff";function CP(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}i(CP,"asRecord");function Ib(e){return e.trim().toLowerCase()===TP}i(Ib,"isManagedProtocolToolName");function Ob(e,t){if(!(!e&&!t))return{verdict:t?.verdict?{...e?.verdict??{},...t.verdict}:e?.verdict}}i(Ob,"mergeManagedProtocolPayload");function RP(e){let t=e.trim().toLowerCase();if(!t)return;let r=t.replace(/[`"'()[\]{}<>]+/g,"").replace(/[.:;!?]+$/g,"").replace(/[_\s-]+/g," ").trim().split(/\s+/,1)[0]??"";if(r){if(/^accept(?:ed|s|ing)?$/.test(r)||r==="approve"||r==="approved")return"accept";if(/^revis(?:e|ed|es|ing)?$/.test(r))return"revise";if(/^block(?:ed|ing)?$/.test(r))return"blocked"}}i(RP,"normalizeManagedVerdictStatus");function IP(e){let t=e.trim();if(!t)return;let n=t.replace(/[`"'()[\]{}<>]+/g,"").replace(/[.:;!?]+$/g,"").replace(/[\s-]+/g,"_").trim().toUpperCase();if(n==="H1_EXECUTE_EVAL"||n==="H1")return"H1_EXECUTE_EVAL";if(n==="H2_PLAN_EXECUTE_EVAL"||n==="H2")return"H2_PLAN_EXECUTE_EVAL"}i(IP,"normalizeManagedNextHarness");function OP(e){return Array.isArray(e)?e.map(t=>String(t).trim()).filter(Boolean):typeof e=="string"?e.split(/\r?\n/).map(t=>t.replace(/^-+\s*/,"").trim()).filter(Boolean):[]}i(OP,"normalizeStringListValue");function RG(e,t,n=""){let r=CP(t);if(!r||e!=="evaluator")return;let o=typeof r.status=="string"?RP(r.status):void 0;if(o)return{verdict:{source:"evaluator",status:o,reason:typeof r.reason=="string"&&r.reason.trim()||void 0,followups:OP(r.followup??r.followups),userFacingText:n,userAnswer:typeof r.user_answer=="string"?r.user_answer.trim()||void 0:typeof r.userAnswer=="string"&&r.userAnswer.trim()||void 0,nextHarness:typeof(r.next_harness??r.nextHarness)=="string"?IP(String(r.next_harness??r.nextHarness)):void 0,budgetRequest:typeof(r.budget_request??r.budgetRequest)=="string"&&String(r.budget_request??r.budgetRequest).trim()||void 0}}}i(RG,"coerceManagedProtocolToolPayload");function IG(e){if(e==="evaluator")return AP}i(IG,"getManagedBlockNameForRole");function OG(e,t){return e&&t==="evaluator"?!!e.verdict:!1}i(OG,"hasManagedProtocolForRole");function $G(e,t){return new RegExp(String.raw`\`\`\`${t}\s*[\s\S]*?\`\`\``,"i").test(e)}i($G,"textContainsManagedBlock");function $b(e,t){if(!t||t.length===0)return e;let n=new Set(t);return e.filter(r=>!n.has(r))}i($b,"filterExcludedTools");function Pb(e,t,n){return t?e.filter(r=>{let o=qe(r)??n?.get(r);return o?t({name:o.name,sideEffect:o.sideEffect,planModeAllowed:o.planModeAllowed===!0}):!1}):e}i(Pb,"applyToolVisibilityPolicy");function $P(e,t,n=!1,r,o=!1){let s=ic(t)==="off"?id(e):e;return n||(s=sd(s)),s=Gl(s,r),s=td(s,r),o||(s=s.filter(a=>a!=="list_dispatchable_agents")),s}i($P,"getRuntimeActiveToolNames");function qG(e,t,n=!1,r=!1,o,s,a,c=!1,l){let d=od(),u=new Set(d.map(m=>m.name)),f=[...d,...(l??[]).filter(m=>!u.has(m.name)).map(qi)];if(e.length===0)return[];let p=new Set($P(e,t,r,o,c));return f.filter(m=>p.has(m.name)&&(n||!Ib(m.name))).map(m=>{let h=Fo(m,a);if(!Wi(h.name)||s&&s.has(h.name))return h;let y=An[h.name];return y?{...h,description:y}:h})}i(qG,"getActiveToolDefinitions");import{join as PP}from"node:path";function MP(e,t){if(t&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return PP(e,t)}i(MP,"resolveResumeFromRunDir");function eX(e){let{options:t,runtime:n,managedProtocolPayloadRef:r,sessionId:o}=e,s=t.events??{},a=ye(t.context),c=Rb(t),l=Pb($b([...Gt],t.context?.excludeTools),t.context?.toolVisibilityPolicy),d=Gt.every(f=>l.includes(f))?$c({sessionId:o,currentAgentId:t.context?.currentAgentId,sessionScope:t.session?.scope,storage:t.session?.storage}):void 0,u={backups:new Map,actorControl:t.context?.actorControl,actorQueueAgentId:t.context?.actorQueueAgentId,contextIdentitySessionId:t.context?.contextIdentitySessionId??o,actorHost:t.context?.actorHost,managedWorkBudget:t.context?.managedWorkBudget,permissionIntent:t.context?.permissionIntent,gitRoot:t.context?.gitRoot??void 0,sessionId:o,...d!==void 0?{loadSessionHistory:d}:{},taskSurface:t.context?.taskSurface,agentProfile:t.context?.agentProfile,agentScope:t.context?.agentScope,agentExecutorPlane:t.context?.agentExecutorPlane,selfManual:t.selfManual,skillDynamicContext:t.skillDynamicContext,skillRegistry:t.context?.skillRegistry,admitLearnedSkillInvocation:t.context?.admitLearnedSkillInvocation,skillScriptRunner:t.context?.skillScriptRunner,assertReadablePath:t.context?.assertReadablePath,toolVisibilityPolicy:t.context?.toolVisibilityPolicy,excludeTools:t.context?.excludeTools,lspService:t.context?.lspService??Lw(),executionCwd:a,shellExecution:t.context?.shellExecution,sandbox:t.sandbox,shellSandbox:t.context?.shellSandbox,providerCredentialEnvironmentNames:Jd(),sessionScratchDir:c,extensionRuntime:n,askUser:s.askUser,askUserMulti:s.askUserMulti,askUserInput:s.askUserInput,exitPlanMode:s.exitPlanMode,abortSignal:t.abortSignal,managedProtocolRole:t.context?.managedProtocolEmission?.enabled?t.context.managedProtocolEmission.role:void 0,emitManagedProtocol:t.context?.managedProtocolEmission?.enabled?f=>{r.current=Ob(r.current,f)}:void 0,mutationTracker:t.context?.mutationTracker,planModeBlockCheck:t.context?.planModeBlockCheck,guardrails:t.guardrails,parentAgentConfig:{provider:t.provider,model:t.modelOverride??t.model,reasoningMode:t.reasoningMode,effort:t.effort,repoIntelligenceMode:t.context?.repoIntelligenceMode,repoIntelligenceTrace:t.context?.repoIntelligenceTrace,...t.compaction!==void 0?{compaction:{...t.compaction}}:{},...t.context?.contextDiagnostics!==void 0?{contextDiagnostics:t.context.contextDiagnostics}:{},...t.disablePromptCache!==void 0?{disablePromptCache:t.disablePromptCache}:{},...t.context?.shellExecution!==void 0?{shellExecution:t.context.shellExecution}:{},...t.sandbox!==void 0?{sandbox:t.sandbox}:{},...t.context?.permissionIntent!==void 0?{permissionIntent:t.context.permissionIntent}:{}},parentEvents:s,onChildProgress:void 0,currentAgentId:t.context?.currentAgentId,parentAgentId:t.context?.parentAgentId,sendMessageTurnCounter:{count:0},goalContext:t.context?.goalRuntime?.goalContext};if(!u.actorControl&&(t.agentMode==="ama"||t.context?.actorSession)){let f=t.context?.actorSession??new co({maxConcurrentThreadsPerSession:t.maxConcurrentThreadsPerSession,sessionId:o});u.actorHost=f,u.actorControl=f.attach(u,t)}return u.workflowHost=NP(t,o,u.actorControl,u.actorHost),u}i(eX,"buildToolExecutionContext");function LP(e,t){return{...t?{sessionId:t}:{},...e.context?.agentProfile?.surface?{surface:e.context.agentProfile.surface}:{},...e.context?.taskSurface?{taskSurface:e.context.taskSurface}:{},...e.context?.gitRoot?{projectRoot:e.context.gitRoot}:{}}}i(LP,"buildWorkflowHostMetadata");function NP(e,t,n,r){let o=e.workflowRunsBaseDir;if(process.env.KODAX_DEBUG_WORKFLOW_GATE){let a=o===void 0?"no-host: workflowRunsBaseDir undefined":e.agentMode!=="ama"?`no-host: agentMode=${String(e.agentMode)} (need ama)`:e.context?.workflowIntent!=="explicit"?"no-host: explicit Workflow intent absent":"host wired";T({source:"coding:workflow-gate",level:"debug",message:"Workflow host gate evaluated.",detail:{agentMode:e.agentMode,runsBaseDir:o,decision:a}})}if(o===void 0||e.agentMode!=="ama"||e.context?.workflowIntent!=="explicit")return;let s=i(async({manifest:a,source:c,args:l,resumeFromRunId:d,signal:u})=>{let[{startManagedWorkflow:f},{getDefaultWorkflowRunManager:p}]=await Promise.all([import("./host-B3TK2U43.js"),import("./run-manager-5AV3MR4W.js")]),m=[e.abortSignal,u].filter(v=>v!==void 0),h=m.length===0?void 0:m.length===1?m[0]:AbortSignal.any(m),y=n&&r?{...e,context:{...e.context,actorControl:n,actorHost:r}}:e,w=await f({source:{kind:"inline",manifest:a,source:c},args:l,options:y,runsBaseDir:o,manager:p(),...(()=>{let v=MP(o,d);return v?{resumeFromRunDir:v}:{}})(),...h?{signal:h}:{},processMetadata:{hostMetadata:LP(e,t)}});if(w.kind==="declined")return{kind:"declined",reason:w.reason};let g=w.qualityWarnings?.map(v=>`${v.code}: ${v.message}`),b=w.managed.done.then(v=>{let x=w.managed.getSnapshot?.(),I=v.kind==="completed"?v.state.events.reduce((_,M)=>{if(M.type==="agent_unverified"){let P=M.data?.name??M.data?.taskId;_.push(typeof P=="string"&&P.length>0?P:"agent")}return _},[]):[];return{kind:"started",runId:w.runId,...x?.status!==void 0?{status:x.status}:{},...x?.resultText!==void 0?{resultText:x.resultText}:{},...x?.error!==void 0?{error:x.error}:{},...I.length>0?{verificationWarnings:I}:{},...g&&g.length>0?{workflowQualityWarnings:g}:{}}});return{kind:"started",runId:w.runId,done:b,...g&&g.length>0?{workflowQualityWarnings:g}:{}}},"startInline");return{startInline:s,runInline:i(async a=>{let c=await s(a);return c.kind==="declined"?{kind:"declined",reason:c.reason}:await c.done},"runInline")}}i(NP,"buildWorkflowToolHost");export{ye as a,X as b,ge as c,_s as d,qb as e,WP as f,Wb as g,Dn as h,Cu as i,BP as j,JP as k,B as l,Ms as m,Hu as n,Oo as o,$o as p,_r as q,gM as r,ff as s,pf as t,AM as u,CM as v,RM as w,IM as x,Ks as y,zs as z,zt as A,WS as B,_c as C,S0 as D,yf as E,Fn as F,Lo as G,Gs as H,Xs as I,nt as J,Sr as K,Tr as L,lx as M,No as N,sn as O,Js as P,Wr as Q,TF as R,AF as S,Br as T,$F as U,PF as V,MF as W,jF as X,BT as Y,FF as Z,kf as _,j0 as $,Ef as aa,Af as ba,ea as ca,Fo as da,xh as ea,GF as fa,kh as ga,XF as ha,VF as ia,YF as ja,JF as ka,xi as la,eU as ma,Eh as na,Y0 as oa,na as pa,oa as qa,Qx as ra,Zx as sa,ia as ta,fa as ua,pa as va,Qf as wa,$r as xa,Ir as ya,Rr as za,sa as Aa,Xf as Ba,ba as Ca,va as Da,Pr as Ea,ka as Fa,Ea as Ga,ft as Ha,Vn as Ia,_D as Ja,qp as Ka,Ma as La,La as Ma,Wp as Na,Na as Oa,Da as Pa,ja as Qa,Fa as Ra,qa as Sa,Wa as Ta,Ba as Ua,Ha as Va,Nr as Wa,me as Xa,O_ as Ya,ic as Za,vj as _a,xj as $a,kj as ab,jr as bb,ui as cb,fi as db,Fr as eb,z_ as fb,G_ as gb,Ej as hb,sc as ib,ac as jb,cc as kb,lc as lb,pn as mb,uc as nb,mi as ob,fc as pb,Fm as qb,ie as rb,mc as sb,hc as tb,gc as ub,yc as vb,fF as wb,pF as xb,mF as yb,MS as zb,yi as Ab,hF as Bb,Xr as Cb,Ve as Db,_i as Eb,fw as Fb,YR as Gb,JR as Hb,zr as Ib,sg as Jb,tl as Kb,nl as Lb,A1 as Mb,kg as Nb,Eg as Ob,$1 as Pb,_g as Qb,D1 as Rb,j1 as Sb,F1 as Tb,U1 as Ub,q1 as Vb,W1 as Wb,Sg as Xb,Rg as Yb,ul as Zb,MC as _b,CI as $b,RH as ac,ad as bc,qi as cc,IH as dc,An as ec,Wi as fc,PH as gc,qy as hc,Wy as ic,$I as jc,Xy as kc,Vy as lc,ro as mc,eO as nc,md as oc,hd as pc,ZH as qc,rO as rc,oO as sc,eK as tc,Gr as uc,Ii as vc,Vt as wc,bt as xc,hl as yc,El as zc,Yr as Ac,Jr as Bc,Gg as Cc,Xg as Dc,Tl as Ec,vt as Fc,iR as Gc,Rl as Hc,ar as Ic,cr as Jc,lR as Kc,Qr as Lc,pR as Mc,bR as Nc,vR as Oc,xn as Pc,Zr as Qc,eo as Rc,AR as Sc,Dl as Tc,kn as Uc,En as Vc,RR as Wc,IR as Xc,OR as Yc,DR as Zc,FR as _c,HR as $c,ji as ad,cy as bd,GR as cd,XR as dd,gd as ed,yd as fd,hK as gd,gK as hd,yK as id,wK as jd,bK as kd,oo as ld,Hi as md,ow as nd,aw as od,wI as pd,lr as qd,bI as rd,ur as sd,qe as td,_n as ud,vI as vd,rd as wd,xI as xd,kI as yd,Qt as zd,EI as Ad,_I as Bd,SI as Cd,TI as Dd,AI as Ed,Et as Fd,od as Gd,PO as Hd,gl as Id,Cy as Jd,Ry as Kd,lI as Ld,dI as Md,pI as Nd,mI as Od,hI as Pd,KO as Qd,mw as Rd,hw as Sd,Rb as Td,TP as Ud,TG as Vd,AP as Wd,AG as Xd,CG as Yd,Ib as Zd,Ob as _d,RG as $d,IG as ae,OG as be,$G as ce,gw as de,Sw as ee,Rd as fe,Lw as ge,_z as he,jw as ie,Fw as je,Ji as ke,Lz as le,ns as me,tb as ne,aG as oe,co as pe,yG as qe,wG as re,$b as se,Pb as te,$P as ue,qG as ve,eX as we};
414
+ </agent-message>`}i(Ud,"renderMailboxMessage");function bP(e,t){if(!(!t||e.actor.capabilities.providers.includes("*"))&&!e.actor.capabilities.providers.includes(t))throw new Error(`Actor ${e.actor.path} is not authorized to use provider ${t}.`)}i(bP,"assertProviderAuthority");function Oe(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}i(Oe,"escapeXml");function vP(e){return{async admit(t){return e.spentBudget+t.units>e.totalBudget?{admitted:!1,fact:{code:"agent_budget_exhausted",retryable:!1,reason:`shared root work budget exhausted (${e.spentBudget}/${e.totalBudget})`}}:(e.spentBudget+=t.units,{admitted:!0})},async refund(){e.spentBudget=Math.max(0,e.spentBudget-1)},snapshot:i(()=>({...e}),"snapshot")}}i(vP,"managedWorkBudgetPort");function xP(e,t){let n=Ke(e.specialistName);if(n)return n;let r=Ke(e.agentId);if(!(!r||t.actor.kind==="native"))throw new Error(`Agent selector ${r} was not resolved before execution.`)}i(xP,"specialistName");function kP(e){return e==="fast"||e==="balanced"||e==="deep"?e:void 0}i(kP,"modelHint");function EP(e){let t=Ke(e);if(!t)return;let n=Pn(t);return n==="auto"?void 0:n}i(EP,"effort");function Ke(e){return typeof e=="string"&&e.length>0?e:void 0}i(Ke,"metadataString");function Sb(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}i(Sb,"metadataStringArray");import Cb from"node:path";var _P=80;function SP(e){let t=e.trim().replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,_P);return!t||t==="."||t===".."?"session":t}i(SP,"sanitizeScratchSessionId");function Rb(e){let t=e.session?.id?.trim();if(!t)return;let n=e.context?.gitRoot?.trim(),r=n?Cb.resolve(n):ye(e.context);return Cb.resolve(r,".agent","tmp","sessions",SP(t))}i(Rb,"getSessionScratchDir");var TP="emit_managed_protocol",TG="kodax-task-contract",AP="kodax-task-verdict",AG="kodax-task-scout",CG="kodax-task-handoff";function CP(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}i(CP,"asRecord");function Ib(e){return e.trim().toLowerCase()===TP}i(Ib,"isManagedProtocolToolName");function Ob(e,t){if(!(!e&&!t))return{verdict:t?.verdict?{...e?.verdict??{},...t.verdict}:e?.verdict}}i(Ob,"mergeManagedProtocolPayload");function RP(e){let t=e.trim().toLowerCase();if(!t)return;let r=t.replace(/[`"'()[\]{}<>]+/g,"").replace(/[.:;!?]+$/g,"").replace(/[_\s-]+/g," ").trim().split(/\s+/,1)[0]??"";if(r){if(/^accept(?:ed|s|ing)?$/.test(r)||r==="approve"||r==="approved")return"accept";if(/^revis(?:e|ed|es|ing)?$/.test(r))return"revise";if(/^block(?:ed|ing)?$/.test(r))return"blocked"}}i(RP,"normalizeManagedVerdictStatus");function IP(e){let t=e.trim();if(!t)return;let n=t.replace(/[`"'()[\]{}<>]+/g,"").replace(/[.:;!?]+$/g,"").replace(/[\s-]+/g,"_").trim().toUpperCase();if(n==="H1_EXECUTE_EVAL"||n==="H1")return"H1_EXECUTE_EVAL";if(n==="H2_PLAN_EXECUTE_EVAL"||n==="H2")return"H2_PLAN_EXECUTE_EVAL"}i(IP,"normalizeManagedNextHarness");function OP(e){return Array.isArray(e)?e.map(t=>String(t).trim()).filter(Boolean):typeof e=="string"?e.split(/\r?\n/).map(t=>t.replace(/^-+\s*/,"").trim()).filter(Boolean):[]}i(OP,"normalizeStringListValue");function RG(e,t,n=""){let r=CP(t);if(!r||e!=="evaluator")return;let o=typeof r.status=="string"?RP(r.status):void 0;if(o)return{verdict:{source:"evaluator",status:o,reason:typeof r.reason=="string"&&r.reason.trim()||void 0,followups:OP(r.followup??r.followups),userFacingText:n,userAnswer:typeof r.user_answer=="string"?r.user_answer.trim()||void 0:typeof r.userAnswer=="string"&&r.userAnswer.trim()||void 0,nextHarness:typeof(r.next_harness??r.nextHarness)=="string"?IP(String(r.next_harness??r.nextHarness)):void 0,budgetRequest:typeof(r.budget_request??r.budgetRequest)=="string"&&String(r.budget_request??r.budgetRequest).trim()||void 0}}}i(RG,"coerceManagedProtocolToolPayload");function IG(e){if(e==="evaluator")return AP}i(IG,"getManagedBlockNameForRole");function OG(e,t){return e&&t==="evaluator"?!!e.verdict:!1}i(OG,"hasManagedProtocolForRole");function $G(e,t){return new RegExp(String.raw`\`\`\`${t}\s*[\s\S]*?\`\`\``,"i").test(e)}i($G,"textContainsManagedBlock");function $b(e,t){if(!t||t.length===0)return e;let n=new Set(t);return e.filter(r=>!n.has(r))}i($b,"filterExcludedTools");function Pb(e,t,n){return t?e.filter(r=>{let o=qe(r)??n?.get(r);return o?t({name:o.name,sideEffect:o.sideEffect,planModeAllowed:o.planModeAllowed===!0}):!1}):e}i(Pb,"applyToolVisibilityPolicy");function $P(e,t,n=!1,r,o=!1){let s=ic(t)==="off"?id(e):e;return n||(s=sd(s)),s=Gl(s,r),s=td(s,r),o||(s=s.filter(a=>a!=="list_dispatchable_agents")),s}i($P,"getRuntimeActiveToolNames");function qG(e,t,n=!1,r=!1,o,s,a,c=!1,l){let d=od(),u=new Set(d.map(m=>m.name)),f=[...d,...(l??[]).filter(m=>!u.has(m.name)).map(qi)];if(e.length===0)return[];let p=new Set($P(e,t,r,o,c));return f.filter(m=>p.has(m.name)&&(n||!Ib(m.name))).map(m=>{let h=Fo(m,a);if(!Wi(h.name)||s&&s.has(h.name))return h;let y=An[h.name];return y?{...h,description:y}:h})}i(qG,"getActiveToolDefinitions");import{join as PP}from"node:path";function MP(e,t){if(t&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return PP(e,t)}i(MP,"resolveResumeFromRunDir");function eX(e){let{options:t,runtime:n,managedProtocolPayloadRef:r,sessionId:o}=e,s=t.events??{},a=ye(t.context),c=Rb(t),l=Pb($b([...Gt],t.context?.excludeTools),t.context?.toolVisibilityPolicy),d=Gt.every(f=>l.includes(f))?$c({sessionId:o,currentAgentId:t.context?.currentAgentId,sessionScope:t.session?.scope,storage:t.session?.storage}):void 0,u={backups:new Map,actorControl:t.context?.actorControl,actorQueueAgentId:t.context?.actorQueueAgentId,contextIdentitySessionId:t.context?.contextIdentitySessionId??o,actorHost:t.context?.actorHost,managedWorkBudget:t.context?.managedWorkBudget,permissionIntent:t.context?.permissionIntent,gitRoot:t.context?.gitRoot??void 0,sessionId:o,...d!==void 0?{loadSessionHistory:d}:{},taskSurface:t.context?.taskSurface,agentProfile:t.context?.agentProfile,agentScope:t.context?.agentScope,agentExecutorPlane:t.context?.agentExecutorPlane,selfManual:t.selfManual,skillDynamicContext:t.skillDynamicContext,skillRegistry:t.context?.skillRegistry,admitLearnedSkillInvocation:t.context?.admitLearnedSkillInvocation,skillScriptRunner:t.context?.skillScriptRunner,assertReadablePath:t.context?.assertReadablePath,toolVisibilityPolicy:t.context?.toolVisibilityPolicy,excludeTools:t.context?.excludeTools,lspService:t.context?.lspService??Lw(),executionCwd:a,shellExecution:t.context?.shellExecution,sandbox:t.sandbox,shellSandbox:t.context?.shellSandbox,providerCredentialEnvironmentNames:Jd(),sessionScratchDir:c,extensionRuntime:n,askUser:s.askUser,askUserMulti:s.askUserMulti,askUserInput:s.askUserInput,exitPlanMode:s.exitPlanMode,abortSignal:t.abortSignal,managedProtocolRole:t.context?.managedProtocolEmission?.enabled?t.context.managedProtocolEmission.role:void 0,emitManagedProtocol:t.context?.managedProtocolEmission?.enabled?f=>{r.current=Ob(r.current,f)}:void 0,mutationTracker:t.context?.mutationTracker,planModeBlockCheck:t.context?.planModeBlockCheck,guardrails:t.guardrails,parentAgentConfig:{provider:t.provider,model:t.modelOverride??t.model,reasoningMode:t.reasoningMode,effort:t.effort,repoIntelligenceMode:t.context?.repoIntelligenceMode,repoIntelligenceTrace:t.context?.repoIntelligenceTrace,...t.compaction!==void 0?{compaction:{...t.compaction}}:{},...t.context?.contextDiagnostics!==void 0?{contextDiagnostics:t.context.contextDiagnostics}:{},...t.disablePromptCache!==void 0?{disablePromptCache:t.disablePromptCache}:{},...t.context?.shellExecution!==void 0?{shellExecution:t.context.shellExecution}:{},...t.sandbox!==void 0?{sandbox:t.sandbox}:{},...t.context?.permissionIntent!==void 0?{permissionIntent:t.context.permissionIntent}:{}},parentEvents:s,onChildProgress:void 0,currentAgentId:t.context?.currentAgentId,parentAgentId:t.context?.parentAgentId,sendMessageTurnCounter:{count:0},goalContext:t.context?.goalRuntime?.goalContext};if(!u.actorControl&&(t.agentMode==="ama"||t.context?.actorSession)){let f=t.context?.actorSession??new co({maxConcurrentThreadsPerSession:t.maxConcurrentThreadsPerSession,sessionId:o});u.actorHost=f,u.actorControl=f.attach(u,t)}return u.workflowHost=NP(t,o,u.actorControl,u.actorHost),u}i(eX,"buildToolExecutionContext");function LP(e,t){return{...t?{sessionId:t}:{},...e.context?.agentProfile?.surface?{surface:e.context.agentProfile.surface}:{},...e.context?.taskSurface?{taskSurface:e.context.taskSurface}:{},...e.context?.gitRoot?{projectRoot:e.context.gitRoot}:{}}}i(LP,"buildWorkflowHostMetadata");function NP(e,t,n,r){let o=e.workflowRunsBaseDir;if(process.env.KODAX_DEBUG_WORKFLOW_GATE){let a=o===void 0?"no-host: workflowRunsBaseDir undefined":e.agentMode!=="ama"?`no-host: agentMode=${String(e.agentMode)} (need ama)`:e.context?.workflowIntent!=="explicit"?"no-host: explicit Workflow intent absent":"host wired";T({source:"coding:workflow-gate",level:"debug",message:"Workflow host gate evaluated.",detail:{agentMode:e.agentMode,runsBaseDir:o,decision:a}})}if(o===void 0||e.agentMode!=="ama"||e.context?.workflowIntent!=="explicit")return;let s=i(async({manifest:a,source:c,args:l,resumeFromRunId:d,signal:u})=>{let[{startManagedWorkflow:f},{getDefaultWorkflowRunManager:p}]=await Promise.all([import("./host-OR3IO2A4.js"),import("./run-manager-MNOTWIFX.js")]),m=[e.abortSignal,u].filter(v=>v!==void 0),h=m.length===0?void 0:m.length===1?m[0]:AbortSignal.any(m),y=n&&r?{...e,context:{...e.context,actorControl:n,actorHost:r}}:e,w=await f({source:{kind:"inline",manifest:a,source:c},args:l,options:y,runsBaseDir:o,manager:p(),...(()=>{let v=MP(o,d);return v?{resumeFromRunDir:v}:{}})(),...h?{signal:h}:{},processMetadata:{hostMetadata:LP(e,t)}});if(w.kind==="declined")return{kind:"declined",reason:w.reason};let g=w.qualityWarnings?.map(v=>`${v.code}: ${v.message}`),b=w.managed.done.then(v=>{let x=w.managed.getSnapshot?.(),I=v.kind==="completed"?v.state.events.reduce((_,M)=>{if(M.type==="agent_unverified"){let P=M.data?.name??M.data?.taskId;_.push(typeof P=="string"&&P.length>0?P:"agent")}return _},[]):[];return{kind:"started",runId:w.runId,...x?.status!==void 0?{status:x.status}:{},...x?.resultText!==void 0?{resultText:x.resultText}:{},...x?.error!==void 0?{error:x.error}:{},...I.length>0?{verificationWarnings:I}:{},...g&&g.length>0?{workflowQualityWarnings:g}:{}}});return{kind:"started",runId:w.runId,done:b,...g&&g.length>0?{workflowQualityWarnings:g}:{}}},"startInline");return{startInline:s,runInline:i(async a=>{let c=await s(a);return c.kind==="declined"?{kind:"declined",reason:c.reason}:await c.done},"runInline")}}i(NP,"buildWorkflowToolHost");export{ye as a,X as b,ge as c,_s as d,qb as e,WP as f,Wb as g,Dn as h,Cu as i,BP as j,JP as k,B as l,Ms as m,Hu as n,Oo as o,$o as p,_r as q,gM as r,ff as s,pf as t,AM as u,CM as v,RM as w,IM as x,Ks as y,zs as z,zt as A,WS as B,_c as C,S0 as D,yf as E,Fn as F,Lo as G,Gs as H,Xs as I,nt as J,Sr as K,Tr as L,lx as M,No as N,sn as O,Js as P,Wr as Q,TF as R,AF as S,Br as T,$F as U,PF as V,MF as W,jF as X,BT as Y,FF as Z,kf as _,j0 as $,Ef as aa,Af as ba,ea as ca,Fo as da,xh as ea,GF as fa,kh as ga,XF as ha,VF as ia,YF as ja,JF as ka,xi as la,eU as ma,Eh as na,Y0 as oa,na as pa,oa as qa,Qx as ra,Zx as sa,ia as ta,fa as ua,pa as va,Qf as wa,$r as xa,Ir as ya,Rr as za,sa as Aa,Xf as Ba,ba as Ca,va as Da,Pr as Ea,ka as Fa,Ea as Ga,ft as Ha,Vn as Ia,_D as Ja,qp as Ka,Ma as La,La as Ma,Wp as Na,Na as Oa,Da as Pa,ja as Qa,Fa as Ra,qa as Sa,Wa as Ta,Ba as Ua,Ha as Va,Nr as Wa,me as Xa,O_ as Ya,ic as Za,vj as _a,xj as $a,kj as ab,jr as bb,ui as cb,fi as db,Fr as eb,z_ as fb,G_ as gb,Ej as hb,sc as ib,ac as jb,cc as kb,lc as lb,pn as mb,uc as nb,mi as ob,fc as pb,Fm as qb,ie as rb,mc as sb,hc as tb,gc as ub,yc as vb,fF as wb,pF as xb,mF as yb,MS as zb,yi as Ab,hF as Bb,Xr as Cb,Ve as Db,_i as Eb,fw as Fb,YR as Gb,JR as Hb,zr as Ib,sg as Jb,tl as Kb,nl as Lb,A1 as Mb,kg as Nb,Eg as Ob,$1 as Pb,_g as Qb,D1 as Rb,j1 as Sb,F1 as Tb,U1 as Ub,q1 as Vb,W1 as Wb,Sg as Xb,Rg as Yb,ul as Zb,MC as _b,CI as $b,RH as ac,ad as bc,qi as cc,IH as dc,An as ec,Wi as fc,PH as gc,qy as hc,Wy as ic,$I as jc,Xy as kc,Vy as lc,ro as mc,eO as nc,md as oc,hd as pc,ZH as qc,rO as rc,oO as sc,eK as tc,Gr as uc,Ii as vc,Vt as wc,bt as xc,hl as yc,El as zc,Yr as Ac,Jr as Bc,Gg as Cc,Xg as Dc,Tl as Ec,vt as Fc,iR as Gc,Rl as Hc,ar as Ic,cr as Jc,lR as Kc,Qr as Lc,pR as Mc,bR as Nc,vR as Oc,xn as Pc,Zr as Qc,eo as Rc,AR as Sc,Dl as Tc,kn as Uc,En as Vc,RR as Wc,IR as Xc,OR as Yc,DR as Zc,FR as _c,HR as $c,ji as ad,cy as bd,GR as cd,XR as dd,gd as ed,yd as fd,hK as gd,gK as hd,yK as id,wK as jd,bK as kd,oo as ld,Hi as md,ow as nd,aw as od,wI as pd,lr as qd,bI as rd,ur as sd,qe as td,_n as ud,vI as vd,rd as wd,xI as xd,kI as yd,Qt as zd,EI as Ad,_I as Bd,SI as Cd,TI as Dd,AI as Ed,Et as Fd,od as Gd,PO as Hd,gl as Id,Cy as Jd,Ry as Kd,lI as Ld,dI as Md,pI as Nd,mI as Od,hI as Pd,KO as Qd,mw as Rd,hw as Sd,Rb as Td,TP as Ud,TG as Vd,AP as Wd,AG as Xd,CG as Yd,Ib as Zd,Ob as _d,RG as $d,IG as ae,OG as be,$G as ce,gw as de,Sw as ee,Rd as fe,Lw as ge,_z as he,jw as ie,Fw as je,Ji as ke,Lz as le,ns as me,tb as ne,aG as oe,co as pe,yG as qe,wG as re,$b as se,Pb as te,$P as ue,qG as ve,eX as we};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Eb as Ke,Fb as Le,Ib as ze,Jb as Je,ke as ge,le as Ge,ne as Xe,oe as Ye,pe as Ze,we as Qe}from"./chunk-AGZNXFHZ.js";import{Q as Ne}from"./chunk-FBL7IVMK.js";import{Bg as pe,Cg as B,Dg as we,Eg as Ue,Lg as Ve,Mg as Be,Ng as He,lg as re,og as De,pg as je,rg as Z,t as fe,vg as me}from"./chunk-7XSZVOG7.js";import{a as i}from"./chunk-ONUPGMER.js";import{basename as kr,dirname as vr}from"node:path";import{execFile as Qt}from"node:child_process";import oe from"node:path";import{promisify as en}from"node:util";var tn=en(Qt),nn=1e4,at=2,et=new Set(["write","edit","multi_edit","insert_after_anchor"]),tt=new Set(["read"]);function rn(e,t){if(t.includes("*"))return e;if(e.includes("*"))return t;let n=new Set(t);return e.filter(r=>n.has(r))}i(rn,"intersectWorkflowToolCeilings");var on=/^\s*(?:let me|i will|i'll|i am going to)\b[\s\S]{0,120}\b(?:start|create|implement|write|build|plan)\b|^\s*(?:我将|让我|接下来)[\s\S]{0,80}(?:开始|创建|编写|实现|制定)/i;function an(e){if(e?.timeoutMs!==void 0){if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)throw new Error("workflow wait timeoutMs must be a positive number");return Math.floor(e.timeoutMs)}}i(an,"normalizeWaitTimeoutMs");function he(e){return e?.requiresMutation===!0||(e?.requiredChangedPaths?.length??0)>0}i(he,"hasVerificationWork");function H(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").trim()}i(H,"normalizeWorkspacePath");function ye(e,t){let n=t.gitRoot?oe.resolve(t.gitRoot):void 0,r=oe.isAbsolute(e)&&n?oe.relative(n,oe.resolve(e)):e;return H(r)}i(ye,"normalizeRequiredPath");function sn(e){let t=(e.readOnly??!1)===!1?{enforcement:"warn",requiresMutation:!0,rejectPreparatoryFinalText:!0}:void 0;if(e.verification!==void 0){let n={...t??{},...e.verification,enforcement:e.verification.enforcement??"hard"},r=e.verification.requiredChangedPaths;return{verification:{...n,...r!==void 0&&r.length>0&&n.requiresMutation===void 0?{requiresMutation:!0}:{}}}}return{verification:t}}i(sn,"resolveVerificationForInput");function cn(e,t){if(t===!0&&e.readOnly===!1)throw new Error(`workflow manifest readOnly=true cannot spawn write-capable child "${e.name}"; set the workflow manifest readOnly=false or use child readOnly:true`);let n=e.readOnly??t??!1;return e.readOnly===n?e:{...e,readOnly:n}}i(cn,"resolveSpawnAgentInput");function st(e){let t=e.trim();return t.length>0&&on.test(t)}i(st,"isPreparatoryOnlyText");function dn(e,t){let n=e.trim(),r=t?.trim();return r&&(n.length===0||st(n))?r:e}i(dn,"selectWorkflowFinalText");async function ie(e,t){return(await tn("git",[...e],{cwd:t,timeout:nn,windowsHide:!0,maxBuffer:4194304})).stdout.toString()}i(ie,"runGit");async function un(e){let t=e.gitRoot??e.executionCwd??process.cwd(),n=(await ie(["rev-parse","--show-toplevel"],t)).trim(),r=await Promise.all([ie(["diff","--name-only","--"],n),ie(["diff","--cached","--name-only","--"],n),ie(["ls-files","--others","--exclude-standard"],n)]);return[...new Set(r.flatMap(a=>a.split(/\r?\n/)).map(H).filter(a=>a.length>0))]}i(un,"listGitChangedFiles");async function ke(e,t){try{return{paths:(await t(e)).map(H).filter(r=>r.length>0)}}catch(n){return{paths:[],error:n instanceof Error?n.message:String(n)}}}i(ke,"captureChangedPaths");function ln(){return{toolNameById:new Map,toolPathById:new Map,succeededToolCalls:[],succeededPaths:[],readPathById:new Map,succeededReadPaths:[]}}i(ln,"createMutationRecorder");function nt(e){if(e)for(let t of["path","file_path","target_path"]){let n=e[t];if(typeof n=="string"&&n.trim().length>0)return H(n)}}i(nt,"readMutationPath");function fn(e,t){return{...e??{},onToolUseStart:i((n,r)=>{if(et.has(n.name)){t.toolNameById.set(n.id,n.name);let a=nt(n.input);a!==void 0&&t.toolPathById.set(n.id,a)}if(tt.has(n.name)){let a=nt(n.input);a!==void 0&&t.readPathById.set(n.id,a)}e?.onToolUseStart?.(n,r)},"onToolUseStart"),onToolResult:i((n,r)=>{let a=t.toolNameById.get(n.id)??n.name;if(et.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){t.succeededToolCalls.push(a);let o=t.toolPathById.get(n.id);o!==void 0&&t.succeededPaths.push(o)}if(tt.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){let o=t.readPathById.get(n.id);o!==void 0&&t.succeededReadPaths.push(o)}e?.onToolResult?.(n,r)},"onToolResult")}}i(fn,"wrapEventsForMutationRecording");function ae(e){return[...new Set(e.filter(t=>t.trim().length>0))]}i(ae,"uniqueItems");function rt(e){let t=e.verification;if(!t)return;let n=[],r=new Set(e.before.paths.map(H)),a=ae(e.after.paths.map(H)),o=a.filter(m=>!r.has(m)),s=ae(e.mutationRecorder.succeededToolCalls),d=e.acceptToolMutationEvidence?s:[],g=e.acceptToolMutationEvidence?ae(e.mutationRecorder.succeededPaths.map(H)):[],h=o.length>0||d.length>0,y=t.enforcement??"hard",p=(t.requiredChangedPaths??[]).map(m=>ye(m,e.ctx)),b=ae(e.mutationRecorder.succeededReadPaths.map(m=>ye(m,e.ctx))),v=(t.requiredReadPaths??[]).map(m=>ye(m,e.ctx));t.requiresMutation===!0&&(e.before.error!==void 0||e.after.error!==void 0?n.push(`workspace mutation verification could not read changed files: ${e.after.error??e.before.error}`):h||n.push(e.acceptToolMutationEvidence||s.length===0?"expected file mutations, but no new workspace changes or successful write tools were observed":"write tools ran in an isolated worktree, but no main workspace changes were present after cleanup")),e.term.limitReached===!0&&!h&&n.push("workflow child reached its iteration limit before satisfying the task");for(let m of p)!a.includes(m)&&!g.includes(m)&&n.push(`required changed path was not present in workspace changes: ${m}`);for(let m of v)b.includes(m)||n.push(`required review evidence was not read: ${m}`);let W=t.minFinalTextChars;return W!==void 0&&!h&&e.term.finalText.trim().length<W&&n.push(`finalText was shorter than the required ${W} characters`),t.rejectPreparatoryFinalText===!0&&!h&&st(e.term.finalText)&&n.push("finalText looks preparatory instead of terminal"),{ok:n.length===0,enforcement:y,reasons:n,changedPaths:a,mutationToolCalls:s,mutationEvidence:h,...b.length>0?{readPaths:b}:{}}}i(rt,"evaluateVerification");function ve(e,t){if(t.ok)return e;let r=[t.enforcement==="warn"?"[Workflow task completed without verification]":"[Workflow task verification failed]",...t.reasons.map(a=>`- ${a}`)].join(`
2
+ import{Eb as Ke,Fb as Le,Ib as ze,Jb as Je,ke as ge,le as Ge,ne as Xe,oe as Ye,pe as Ze,we as Qe}from"./chunk-JTZKC4TV.js";import{Q as Ne}from"./chunk-BHE66SP3.js";import{Bg as pe,Cg as B,Dg as we,Eg as Ue,Lg as Ve,Mg as Be,Ng as He,lg as re,og as De,pg as je,rg as Z,t as fe,vg as me}from"./chunk-7XSZVOG7.js";import{a as i}from"./chunk-ONUPGMER.js";import{basename as kr,dirname as vr}from"node:path";import{execFile as Qt}from"node:child_process";import oe from"node:path";import{promisify as en}from"node:util";var tn=en(Qt),nn=1e4,at=2,et=new Set(["write","edit","multi_edit","insert_after_anchor"]),tt=new Set(["read"]);function rn(e,t){if(t.includes("*"))return e;if(e.includes("*"))return t;let n=new Set(t);return e.filter(r=>n.has(r))}i(rn,"intersectWorkflowToolCeilings");var on=/^\s*(?:let me|i will|i'll|i am going to)\b[\s\S]{0,120}\b(?:start|create|implement|write|build|plan)\b|^\s*(?:我将|让我|接下来)[\s\S]{0,80}(?:开始|创建|编写|实现|制定)/i;function an(e){if(e?.timeoutMs!==void 0){if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)throw new Error("workflow wait timeoutMs must be a positive number");return Math.floor(e.timeoutMs)}}i(an,"normalizeWaitTimeoutMs");function he(e){return e?.requiresMutation===!0||(e?.requiredChangedPaths?.length??0)>0}i(he,"hasVerificationWork");function H(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").trim()}i(H,"normalizeWorkspacePath");function ye(e,t){let n=t.gitRoot?oe.resolve(t.gitRoot):void 0,r=oe.isAbsolute(e)&&n?oe.relative(n,oe.resolve(e)):e;return H(r)}i(ye,"normalizeRequiredPath");function sn(e){let t=(e.readOnly??!1)===!1?{enforcement:"warn",requiresMutation:!0,rejectPreparatoryFinalText:!0}:void 0;if(e.verification!==void 0){let n={...t??{},...e.verification,enforcement:e.verification.enforcement??"hard"},r=e.verification.requiredChangedPaths;return{verification:{...n,...r!==void 0&&r.length>0&&n.requiresMutation===void 0?{requiresMutation:!0}:{}}}}return{verification:t}}i(sn,"resolveVerificationForInput");function cn(e,t){if(t===!0&&e.readOnly===!1)throw new Error(`workflow manifest readOnly=true cannot spawn write-capable child "${e.name}"; set the workflow manifest readOnly=false or use child readOnly:true`);let n=e.readOnly??t??!1;return e.readOnly===n?e:{...e,readOnly:n}}i(cn,"resolveSpawnAgentInput");function st(e){let t=e.trim();return t.length>0&&on.test(t)}i(st,"isPreparatoryOnlyText");function dn(e,t){let n=e.trim(),r=t?.trim();return r&&(n.length===0||st(n))?r:e}i(dn,"selectWorkflowFinalText");async function ie(e,t){return(await tn("git",[...e],{cwd:t,timeout:nn,windowsHide:!0,maxBuffer:4194304})).stdout.toString()}i(ie,"runGit");async function un(e){let t=e.gitRoot??e.executionCwd??process.cwd(),n=(await ie(["rev-parse","--show-toplevel"],t)).trim(),r=await Promise.all([ie(["diff","--name-only","--"],n),ie(["diff","--cached","--name-only","--"],n),ie(["ls-files","--others","--exclude-standard"],n)]);return[...new Set(r.flatMap(a=>a.split(/\r?\n/)).map(H).filter(a=>a.length>0))]}i(un,"listGitChangedFiles");async function ke(e,t){try{return{paths:(await t(e)).map(H).filter(r=>r.length>0)}}catch(n){return{paths:[],error:n instanceof Error?n.message:String(n)}}}i(ke,"captureChangedPaths");function ln(){return{toolNameById:new Map,toolPathById:new Map,succeededToolCalls:[],succeededPaths:[],readPathById:new Map,succeededReadPaths:[]}}i(ln,"createMutationRecorder");function nt(e){if(e)for(let t of["path","file_path","target_path"]){let n=e[t];if(typeof n=="string"&&n.trim().length>0)return H(n)}}i(nt,"readMutationPath");function fn(e,t){return{...e??{},onToolUseStart:i((n,r)=>{if(et.has(n.name)){t.toolNameById.set(n.id,n.name);let a=nt(n.input);a!==void 0&&t.toolPathById.set(n.id,a)}if(tt.has(n.name)){let a=nt(n.input);a!==void 0&&t.readPathById.set(n.id,a)}e?.onToolUseStart?.(n,r)},"onToolUseStart"),onToolResult:i((n,r)=>{let a=t.toolNameById.get(n.id)??n.name;if(et.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){t.succeededToolCalls.push(a);let o=t.toolPathById.get(n.id);o!==void 0&&t.succeededPaths.push(o)}if(tt.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){let o=t.readPathById.get(n.id);o!==void 0&&t.succeededReadPaths.push(o)}e?.onToolResult?.(n,r)},"onToolResult")}}i(fn,"wrapEventsForMutationRecording");function ae(e){return[...new Set(e.filter(t=>t.trim().length>0))]}i(ae,"uniqueItems");function rt(e){let t=e.verification;if(!t)return;let n=[],r=new Set(e.before.paths.map(H)),a=ae(e.after.paths.map(H)),o=a.filter(m=>!r.has(m)),s=ae(e.mutationRecorder.succeededToolCalls),d=e.acceptToolMutationEvidence?s:[],g=e.acceptToolMutationEvidence?ae(e.mutationRecorder.succeededPaths.map(H)):[],h=o.length>0||d.length>0,y=t.enforcement??"hard",p=(t.requiredChangedPaths??[]).map(m=>ye(m,e.ctx)),b=ae(e.mutationRecorder.succeededReadPaths.map(m=>ye(m,e.ctx))),v=(t.requiredReadPaths??[]).map(m=>ye(m,e.ctx));t.requiresMutation===!0&&(e.before.error!==void 0||e.after.error!==void 0?n.push(`workspace mutation verification could not read changed files: ${e.after.error??e.before.error}`):h||n.push(e.acceptToolMutationEvidence||s.length===0?"expected file mutations, but no new workspace changes or successful write tools were observed":"write tools ran in an isolated worktree, but no main workspace changes were present after cleanup")),e.term.limitReached===!0&&!h&&n.push("workflow child reached its iteration limit before satisfying the task");for(let m of p)!a.includes(m)&&!g.includes(m)&&n.push(`required changed path was not present in workspace changes: ${m}`);for(let m of v)b.includes(m)||n.push(`required review evidence was not read: ${m}`);let W=t.minFinalTextChars;return W!==void 0&&!h&&e.term.finalText.trim().length<W&&n.push(`finalText was shorter than the required ${W} characters`),t.rejectPreparatoryFinalText===!0&&!h&&st(e.term.finalText)&&n.push("finalText looks preparatory instead of terminal"),{ok:n.length===0,enforcement:y,reasons:n,changedPaths:a,mutationToolCalls:s,mutationEvidence:h,...b.length>0?{readPaths:b}:{}}}i(rt,"evaluateVerification");function ve(e,t){if(t.ok)return e;let r=[t.enforcement==="warn"?"[Workflow task completed without verification]":"[Workflow task verification failed]",...t.reasons.map(a=>`- ${a}`)].join(`
3
3
  `);return e.trim().length>0?`${e}
4
4
 
5
5
  ${r}`:r}i(ve,"appendVerificationFailure");function ot(){return{ok:!1,enforcement:"warn",reasons:["workflow child reached its iteration limit before satisfying the task"],mutationEvidence:!1}}i(ot,"limitReachedWarningVerification");function mn(e){return e.entry.bundle.readOnly!==!0&&e.entry.repairAttempts<at&&e.term.status==="completed"&&e.verification!==void 0&&e.verification.ok!==!0&&e.verification.enforcement!=="warn"}i(mn,"shouldRepairVerificationFailure");function pn(e){let t=e.verification.reasons.map(r=>`- ${r}`).join(`
@@ -13,7 +13,7 @@ ${s.text}`),rubric:t.rubric??vn}))).text,findings:r,degraded:a}}i(Pn,"runParalle
13
13
  `).trim().replace(/[\t\n\f\r ]+/g," ")}i(j,"normalizeText");function lt(e){return j(e).replace(/\\/g,"/")}i(lt,"normalizeLocation");function se(e){return[...new Set(e.map(j).filter(Boolean))].sort((t,n)=>t<n?-1:t>n?1:0)}i(se,"uniqueSorted");function An(e,t,n){return Mn("sha256").update(`${e}\0${lt(t)}\0${j(n)}`,"utf8").digest("hex")}i(An,"findingId");function ft(e,t,n){if(!t&&n.specVerdict!=="not-verifiable")throw new Error('review result must use specVerdict "not-verifiable" when requirements are absent');return{specVerdict:n.specVerdict,qualityVerdict:n.qualityVerdict,findings:n.findings.map(r=>{let a=lt(r.location),o=j(r.claim),s=j(r.evidence);return{findingId:An(e,a,o),severity:r.severity,location:a,claim:o,evidence:s,...r.suggestedFix?{suggestedFix:j(r.suggestedFix)}:{}}}).sort((r,a)=>r.findingId<a.findingId?-1:r.findingId>a.findingId?1:0),unverifiedRequirements:se(n.unverifiedRequirements)}}i(ft,"normalizeScopedReviewResult");var ut={low:0,medium:1,high:2,critical:3};function En(e){return e.reduce((t,n)=>ut[n]>ut[t]?n:t,"low")}i(En,"maxSeverity");function mt(e){if(e.length===0)throw new Error("at least one primary review result is required");let t=new Map;for(let a of e)for(let o of a.findings)t.set(o.findingId,[...t.get(o.findingId)??[],o]);let n=[...t.entries()].map(([a,o])=>({findingId:a,severity:En(o.map(s=>s.severity)),location:o[0].location,claim:o[0].claim,evidence:se(o.map(s=>s.evidence)),suggestedFixes:se(o.flatMap(s=>s.suggestedFix?[s.suggestedFix]:[]))})).sort((a,o)=>a.findingId<o.findingId?-1:a.findingId>o.findingId?1:0);return{specVerdict:e.some(a=>a.specVerdict==="issues")?"issues":e.some(a=>a.specVerdict==="not-verifiable")?"not-verifiable":"compliant",qualityVerdict:e.some(a=>a.qualityVerdict==="needs-fixes")?"needs-fixes":"approved",findings:n,unverifiedRequirements:se(e.flatMap(a=>a.unverifiedRequirements))}}i(mt,"mergeScopedReviewResults");function pt(e,t){let n=new Set(e.findings.map(s=>s.findingId)),r=new Set;for(let s of t.findings){if(!n.has(s.findingId)||r.has(s.findingId))throw new Error("verifier must return every input findingId exactly once");r.add(s.findingId)}if(r.size!==n.size)throw new Error("verifier must return every input findingId exactly once");let a=new Map(t.findings.map(s=>[s.findingId,s])),o=e.findings.flatMap(s=>{let d=a.get(s.findingId);if(d.disposition==="refuted")return[];let g=d.severityReason?.trim(),h=d.effectiveSeverity!==void 0&&!!g;return[{...s,disposition:d.disposition,severity:h?d.effectiveSeverity:s.severity,verificationEvidence:j(d.evidence),...g?{severityReason:j(g)}:{}}]});return{specVerdict:e.specVerdict,qualityVerdict:e.qualityVerdict,unverifiedRequirements:e.unverifiedRequirements,actionable:o,audit:t,unqualifiedApprovalAllowed:o.length===0&&e.unverifiedRequirements.length===0&&e.specVerdict==="compliant"&&e.qualityVerdict==="approved"}}i(pt,"applyFindingVerification");var Wn={type:"object",additionalProperties:!1,required:["summary"],properties:{summary:{type:"string"}}};function gt(e){return[e.packetPath,...e.evidenceChunks.map(t=>t.path)]}i(gt,"evidencePaths");function Fn(e){let t=ge(e,Se);if(t.length>0)throw new Error(`primary reviewer structured result is invalid: ${t.join("; ")}`);return e}i(Fn,"rawReview");function On(e){let t=ge(e,Re);if(t.length>0)throw new Error(`finding verifier structured result is invalid: ${t.join("; ")}`);return e}i(On,"rawVerification");function be(e,t){if(e===null||e.status!=="completed")throw new Error(`${t} did not complete; no verdict was accepted`);if(e.verification!==void 0&&!e.verification.ok)throw new Error(`${t} did not read every required packet path; no verdict was accepted`);return e}i(be,"resultOrThrow");function qn(e,t,n){return["Review one immutable KodaX packet as an independent third-party reviewer.",`Packet manifest: ${e.packetPath}`,...e.evidenceChunks.map(r=>`Evidence chunk: ${r.path}`),`This packet has binding requirements: ${e.requirementsPresent?"yes":"no"}.`,t?"This is the additional high-risk primary. Actively seek a disagreement with the first reader; do not assume it was correct.":"Own both specification and implementation-quality verdicts for this scope.",n.lean?"Also identify unnecessary additions, but never remove validation, security, data-loss protection, accessibility, or requested behavior.":"",n.reviewFocus?`Additional user focus: ${n.reviewFocus}`:"","Read the manifest and every listed chunk with the read tool before deciding.","Begin with the required JSON result. No preamble or process narration.","The findings array contains only actionable defects, never approval evidence or positive observations.","When the scope is compliant and approved with no actionable defect, findings must be empty.","If a named requirement cannot be proven compliant or violated from surfaced evidence, use specVerdict not-verifiable, list it in unverifiedRequirements, and emit no finding for that uncertainty; absence of evidence is not proof of a defect.","If requirements are absent, specVerdict must be not-verifiable."].filter(Boolean).join(`
14
14
  `)}i(qn,"buildScopedReviewPrimaryPrompt");function Cn(e,t){return["Independently attempt to refute every candidate finding in this batch.",`Packet manifest: ${e.packetPath}`,...e.evidenceChunks.map(n=>`Evidence chunk: ${n.path}`),`Canonical candidates: ${JSON.stringify(t.findings)}`,"Read the packet evidence. You may run one focused check after naming the concrete doubt.","Return every findingId exactly once. A severity change requires severityReason.","Begin with the required JSON result; no preamble."].join(`
15
15
  `)}i(Cn,"buildScopedReviewVerificationPrompt");function $n(e){return["Synthesize the structured review results below without rereading packet bodies.","Lead with confirmed findings, keep unresolved findings visibly unresolved, omit refuted findings from the actionable list, and never silently downgrade severity.","Cite locations and state explicitly when no actionable issue was confirmed.",JSON.stringify(e)].join(`
16
- `)}i($n,"buildScopedReviewFinalPrompt");async function wt(e,t,n,r){let a=be(await e.runAgent({name:`${n?"high-risk-":""}primary-${t.partitionKey}`,phase:"primary-review",prompt:qn(t,n,r),scopeSummary:`${t.partitionKey}: ${t.scopePaths.join(", ")}`,constraints:["read every required packet path","return both verdicts","cite evidence at each finding"],readOnly:!0,modelHint:n?"deep":"balanced",verification:{enforcement:"hard",requiredReadPaths:gt(t)},outputSchema:Se,terseResult:!0}),"primary reviewer");return e.log({message:`primary read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"primary",contentHash:t.contentHash}}),Fn(a.structured)}i(wt,"runPrimary");async function _n(e,t,n){if(n.findings.length===0)return{specVerdict:n.specVerdict,qualityVerdict:n.qualityVerdict,unverifiedRequirements:n.unverifiedRequirements,actionable:[],audit:{findings:[]},unqualifiedApprovalAllowed:n.unverifiedRequirements.length===0&&n.specVerdict==="compliant"&&n.qualityVerdict==="approved"};let r=be(await e.runAgent({name:`verify-${t.partitionKey}`,phase:"verifier",prompt:Cn(t,n),scopeSummary:`verify ${n.findings.length} candidate finding(s) in ${t.partitionKey}`,constraints:["fresh context","attempt refutation","one disposition per findingId"],readOnly:!0,modelHint:"deep",verification:{enforcement:"hard",requiredReadPaths:gt(t)},outputSchema:Re,terseResult:!0}),"finding verifier");return e.log({message:`verification read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"verification",contentHash:t.contentHash,reason:"candidate findings"}}),pt(n,On(r.structured))}i(_n,"verifyFindings");async function Nn(e,t,n){let r=[await wt(e,t,!1,n)];t.riskFlags.includes("routing-high")&&r.push(await wt(e,t,!0,n));let a=r.map(d=>ft(t.contentHash,t.requirementsPresent,d)),o=mt(a),s=await _n(e,t,o);return e.log({message:`quality gate completed for ${t.partitionKey}`,data:{kind:"review_quality_gate",contentHash:t.contentHash,actionableFindings:s.actionable.length,unresolvedFindings:s.actionable.filter(d=>d.disposition==="unresolved").length,unqualifiedApprovalAllowed:s.unqualifiedApprovalAllowed}}),{contentHash:t.contentHash,result:s}}i(Nn,"reviewPacket");async function Dn(e,t){if(!Array.isArray(t.packets)||t.packets.length===0)throw new Error("scoped-review requires at least one review packet");let n=await e.parallel(t.packets.map(d=>()=>Nn(e,d,t)),{concurrency:4});if(n.some(d=>d===null))throw new Error("one or more scope packets failed review; no final verdict was accepted");let r=n.filter(d=>d!==null);await e.artifact("scoped-review-audit",r);let a=be(await e.runAgent({name:"final-review-synthesis",phase:"final-synthesis",prompt:$n(r),scopeSummary:`cross-scope synthesis for ${r.length} packet(s)`,constraints:["preserve severity","preserve unresolved uncertainty","do not invent evidence"],readOnly:!0,modelHint:"deep",outputSchema:Wn,terseResult:!0}),"final synthesis"),o=a.structured;return{summary:typeof o?.summary=="string"?o.summary:a.finalText,packetResults:r}}i(Dn,"runScopedReview");var ht={meta:{name:"scoped-review",description:"Review immutable scope packets once, verify only candidate findings, then synthesize.",readOnly:!0,phases:["primary-review","verifier","final-synthesis"],maxAgents:64,maxConcurrency:4},run:Dn};function yt(e){return{meta:e.meta,run:i((t,n)=>e.run(t,n),"run")}}i(yt,"erase");var kt=[yt(dt),yt(ht)];function vt(e){return kt.find(t=>t.meta.name===e)}i(vt,"getBuiltinWorkflow");function no(){return kt.map(e=>e.meta)}i(no,"listBuiltinWorkflows");import{mkdir as Tt,readdir as jn,readFile as Q,rename as Un,unlink as Pe,writeFile as Me}from"node:fs/promises";import{basename as Vn,dirname as Ie,join as K}from"node:path";import{pathToFileURL as Bn}from"node:url";var It=[".workflow.json",".ts",".mjs",".js"],ee="0.7.49";function Pt(){return"0.7.92"}i(Pt,"currentKodaxWorkflowVersion");function Hn(e){return e.endsWith(".workflow.json")?"capability-generated":"trusted-local"}i(Hn,"executionForPath");function Kn(e){let t=It.find(n=>e.endsWith(n));return t?e.slice(0,-t.length):void 0}i(Kn,"stripWorkflowSuffix");function Ae(e){let t=e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").slice(0,80);if(!t||t==="."||t==="..")throw new Error("workflow name must contain at least one safe filename character");return t}i(Ae,"safeWorkflowName");function Ee(e){return typeof e=="object"&&e!==null}i(Ee,"isRecord");function xt(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`workflow run.json missing ${t}`);return n}i(xt,"readRequiredString");async function St(e,t){if(!e)return[];let n;try{n=await jn(e)}catch{return[]}let r=new Map;for(let a of It)for(let o of n){if(!o.endsWith(a))continue;let s=Kn(o);if(!s||s.length===0||r.has(s))continue;let d=K(e,o);r.set(s,{name:s,path:d,source:t,execution:Hn(d)})}return[...r.values()]}i(St,"scanDir");async function te(e){let t=await St(e.personal,"personal"),n=await St(e.project,"project"),r=new Map;for(let a of t)r.set(a.name,a);for(let a of n)r.set(a.name,a);return[...r.values()].sort((a,o)=>a.name.localeCompare(o.name))}i(te,"discoverSavedWorkflows");function Ln(e){return typeof e=="object"&&e!==null&&"meta"in e&&"run"in e&&typeof e.run=="function"}i(Ln,"isWorkflowModule");function zn(e){let t=e.default;if(Ln(t))return t;let n=typeof t=="function"?t:e.run,r=e.workflow??e.meta;if(typeof n=="function"&&typeof r=="object"&&r!==null&&"name"in r)return{meta:r,run:n};throw new Error("invalid workflow module: expected a `{ meta, run }` default export, or `export const workflow = {...}` + a default run function")}i(zn,"normalizeWorkflowModule");function Jn(e){let t=JSON.parse(e);if(!Ee(t))throw new Error("generated workflow file must be an object");if(t.format!==void 0&&t.format!=="kodax.workflow")throw new Error(`unsupported workflow capsule format: ${String(t.format)}`);if(t.format==="kodax.workflow"){let a=pe(t);return{manifest:a.manifest,source:a.source,capsule:a,legacy:!1}}let n=t.source;if(typeof n!="string"||n.trim().length===0)throw new Error("generated workflow file source must be a non-empty string");let r=Z(t.manifest);return{manifest:r,source:n,capsule:B({minKodaxVersion:ee,manifest:r,source:n}),legacy:!0}}i(Jn,"parseGeneratedWorkflowFile");async function We(e){let t=Jn(await Q(e,"utf8"));return t.capsule??B({minKodaxVersion:ee,manifest:t.manifest,source:t.source})}i(We,"loadSavedWorkflowCapsule");async function Mt(e){if(e.endsWith(".workflow.json"))return we(await We(e));let t=await import(Bn(e).href);return zn(t)}i(Mt,"loadSavedWorkflow");function Fe(e){if(e.mayUseWorktree===!0)return{environment:["git-repo","worktree-capable"]}}i(Fe,"deriveRequirements");function ce(e,t){me(t,{filename:`${e.name}.workflow.js`,requireAsyncRun:!0})}i(ce,"assertGeneratedCapsuleSource");async function Gn(e){let t=Ae(e.name),n=Z(e.manifest);ce(n,e.source);let r=e.requires??Fe(n),a=B({minKodaxVersion:e.minKodaxVersion??ee,manifest:n,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...r!==void 0?{requires:r}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}});await Tt(e.dir,{recursive:!0});let o=K(e.dir,`${t}.workflow.json`);return await Me(o,`${JSON.stringify(a,null,2)}
16
+ `)}i($n,"buildScopedReviewFinalPrompt");async function wt(e,t,n,r){let a=be(await e.runAgent({name:`${n?"high-risk-":""}primary-${t.partitionKey}`,phase:"primary-review",prompt:qn(t,n,r),scopeSummary:`${t.partitionKey}: ${t.scopePaths.join(", ")}`,constraints:["read every required packet path","return both verdicts","cite evidence at each finding"],readOnly:!0,modelHint:n?"deep":"balanced",verification:{enforcement:"hard",requiredReadPaths:gt(t)},outputSchema:Se,terseResult:!0}),"primary reviewer");return e.log({message:`primary read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"primary",contentHash:t.contentHash}}),Fn(a.structured)}i(wt,"runPrimary");async function _n(e,t,n){if(n.findings.length===0)return{specVerdict:n.specVerdict,qualityVerdict:n.qualityVerdict,unverifiedRequirements:n.unverifiedRequirements,actionable:[],audit:{findings:[]},unqualifiedApprovalAllowed:n.unverifiedRequirements.length===0&&n.specVerdict==="compliant"&&n.qualityVerdict==="approved"};let r=be(await e.runAgent({name:`verify-${t.partitionKey}`,phase:"verifier",prompt:Cn(t,n),scopeSummary:`verify ${n.findings.length} candidate finding(s) in ${t.partitionKey}`,constraints:["fresh context","attempt refutation","one disposition per findingId"],readOnly:!0,modelHint:"deep",verification:{enforcement:"hard",requiredReadPaths:gt(t)},outputSchema:Re,terseResult:!0}),"finding verifier");return e.log({message:`verification read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"verification",contentHash:t.contentHash,reason:"candidate findings"}}),pt(n,On(r.structured))}i(_n,"verifyFindings");async function Nn(e,t,n){let r=[await wt(e,t,!1,n)];t.riskFlags.includes("routing-high")&&r.push(await wt(e,t,!0,n));let a=r.map(d=>ft(t.contentHash,t.requirementsPresent,d)),o=mt(a),s=await _n(e,t,o);return e.log({message:`quality gate completed for ${t.partitionKey}`,data:{kind:"review_quality_gate",contentHash:t.contentHash,actionableFindings:s.actionable.length,unresolvedFindings:s.actionable.filter(d=>d.disposition==="unresolved").length,unqualifiedApprovalAllowed:s.unqualifiedApprovalAllowed}}),{contentHash:t.contentHash,result:s}}i(Nn,"reviewPacket");async function Dn(e,t){if(!Array.isArray(t.packets)||t.packets.length===0)throw new Error("scoped-review requires at least one review packet");let n=await e.parallel(t.packets.map(d=>()=>Nn(e,d,t)),{concurrency:4});if(n.some(d=>d===null))throw new Error("one or more scope packets failed review; no final verdict was accepted");let r=n.filter(d=>d!==null);await e.artifact("scoped-review-audit",r);let a=be(await e.runAgent({name:"final-review-synthesis",phase:"final-synthesis",prompt:$n(r),scopeSummary:`cross-scope synthesis for ${r.length} packet(s)`,constraints:["preserve severity","preserve unresolved uncertainty","do not invent evidence"],readOnly:!0,modelHint:"deep",outputSchema:Wn,terseResult:!0}),"final synthesis"),o=a.structured;return{summary:typeof o?.summary=="string"?o.summary:a.finalText,packetResults:r}}i(Dn,"runScopedReview");var ht={meta:{name:"scoped-review",description:"Review immutable scope packets once, verify only candidate findings, then synthesize.",readOnly:!0,phases:["primary-review","verifier","final-synthesis"],maxAgents:64,maxConcurrency:4},run:Dn};function yt(e){return{meta:e.meta,run:i((t,n)=>e.run(t,n),"run")}}i(yt,"erase");var kt=[yt(dt),yt(ht)];function vt(e){return kt.find(t=>t.meta.name===e)}i(vt,"getBuiltinWorkflow");function no(){return kt.map(e=>e.meta)}i(no,"listBuiltinWorkflows");import{mkdir as Tt,readdir as jn,readFile as Q,rename as Un,unlink as Pe,writeFile as Me}from"node:fs/promises";import{basename as Vn,dirname as Ie,join as K}from"node:path";import{pathToFileURL as Bn}from"node:url";var It=[".workflow.json",".ts",".mjs",".js"],ee="0.7.49";function Pt(){return"0.7.93"}i(Pt,"currentKodaxWorkflowVersion");function Hn(e){return e.endsWith(".workflow.json")?"capability-generated":"trusted-local"}i(Hn,"executionForPath");function Kn(e){let t=It.find(n=>e.endsWith(n));return t?e.slice(0,-t.length):void 0}i(Kn,"stripWorkflowSuffix");function Ae(e){let t=e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").slice(0,80);if(!t||t==="."||t==="..")throw new Error("workflow name must contain at least one safe filename character");return t}i(Ae,"safeWorkflowName");function Ee(e){return typeof e=="object"&&e!==null}i(Ee,"isRecord");function xt(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`workflow run.json missing ${t}`);return n}i(xt,"readRequiredString");async function St(e,t){if(!e)return[];let n;try{n=await jn(e)}catch{return[]}let r=new Map;for(let a of It)for(let o of n){if(!o.endsWith(a))continue;let s=Kn(o);if(!s||s.length===0||r.has(s))continue;let d=K(e,o);r.set(s,{name:s,path:d,source:t,execution:Hn(d)})}return[...r.values()]}i(St,"scanDir");async function te(e){let t=await St(e.personal,"personal"),n=await St(e.project,"project"),r=new Map;for(let a of t)r.set(a.name,a);for(let a of n)r.set(a.name,a);return[...r.values()].sort((a,o)=>a.name.localeCompare(o.name))}i(te,"discoverSavedWorkflows");function Ln(e){return typeof e=="object"&&e!==null&&"meta"in e&&"run"in e&&typeof e.run=="function"}i(Ln,"isWorkflowModule");function zn(e){let t=e.default;if(Ln(t))return t;let n=typeof t=="function"?t:e.run,r=e.workflow??e.meta;if(typeof n=="function"&&typeof r=="object"&&r!==null&&"name"in r)return{meta:r,run:n};throw new Error("invalid workflow module: expected a `{ meta, run }` default export, or `export const workflow = {...}` + a default run function")}i(zn,"normalizeWorkflowModule");function Jn(e){let t=JSON.parse(e);if(!Ee(t))throw new Error("generated workflow file must be an object");if(t.format!==void 0&&t.format!=="kodax.workflow")throw new Error(`unsupported workflow capsule format: ${String(t.format)}`);if(t.format==="kodax.workflow"){let a=pe(t);return{manifest:a.manifest,source:a.source,capsule:a,legacy:!1}}let n=t.source;if(typeof n!="string"||n.trim().length===0)throw new Error("generated workflow file source must be a non-empty string");let r=Z(t.manifest);return{manifest:r,source:n,capsule:B({minKodaxVersion:ee,manifest:r,source:n}),legacy:!0}}i(Jn,"parseGeneratedWorkflowFile");async function We(e){let t=Jn(await Q(e,"utf8"));return t.capsule??B({minKodaxVersion:ee,manifest:t.manifest,source:t.source})}i(We,"loadSavedWorkflowCapsule");async function Mt(e){if(e.endsWith(".workflow.json"))return we(await We(e));let t=await import(Bn(e).href);return zn(t)}i(Mt,"loadSavedWorkflow");function Fe(e){if(e.mayUseWorktree===!0)return{environment:["git-repo","worktree-capable"]}}i(Fe,"deriveRequirements");function ce(e,t){me(t,{filename:`${e.name}.workflow.js`,requireAsyncRun:!0})}i(ce,"assertGeneratedCapsuleSource");async function Gn(e){let t=Ae(e.name),n=Z(e.manifest);ce(n,e.source);let r=e.requires??Fe(n),a=B({minKodaxVersion:e.minKodaxVersion??ee,manifest:n,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...r!==void 0?{requires:r}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}});await Tt(e.dir,{recursive:!0});let o=K(e.dir,`${t}.workflow.json`);return await Me(o,`${JSON.stringify(a,null,2)}
17
17
  `,"utf8"),{name:t,path:o,source:"project",execution:"capability-generated"}}i(Gn,"saveGeneratedWorkflow");async function Rt(e,t){await Me(e,`${JSON.stringify(t,null,2)}
18
18
  `,"utf8")}i(Rt,"writeCapsuleFile");async function Xn(e){try{return await Q(e,"utf8"),!0}catch{return!1}}i(Xn,"fileExists");async function uo(e){let t=(await te(e.dirs)).filter(d=>d.name===e.name).filter(d=>e.source===void 0||d.source===e.source);if(t.length===0)throw new Error(`saved workflow not found: ${e.name}`);if(t.length>1)throw new Error(`ambiguous saved workflow name: ${e.name}`);let n=t[0];if(!n.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be renamed");let r=Ae(e.newName),a=K(Ie(n.path),`${r}.workflow.json`);if(a!==n.path&&await Xn(a))throw new Error(`saved workflow already exists: ${r}`);let o=await We(n.path);ce(o.manifest,o.source);let s=B({minKodaxVersion:o.minKodaxVersion,manifest:{...o.manifest,name:r},source:o.source,...o.intent!==void 0?{intent:o.intent}:{},...o.inputs!==void 0?{inputs:o.inputs}:{},...o.requires!==void 0?{requires:o.requires}:{},...o.provenance!==void 0?{provenance:o.provenance}:{}});return await Me(a,`${JSON.stringify(s,null,2)}
19
19
  `,"utf8"),a!==n.path&&await Pe(n.path),{name:r,path:a,source:n.source,execution:"capability-generated"}}i(uo,"renameSavedWorkflow");async function lo(e){let t=(await te(e.dirs)).filter(r=>r.name===e.name).filter(r=>e.source===void 0||r.source===e.source);if(t.length===0)throw new Error(`saved workflow not found: ${e.name}`);if(t.length>1)throw new Error(`ambiguous saved workflow name: ${e.name}`);let n=t[0];if(!n.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be deleted");return await Pe(n.path),n}i(lo,"deleteSavedWorkflow");async function fo(e){let t=Ae(e.name),n=(await te(e.dirs)).filter(v=>v.name===t).filter(v=>e.savedSource===void 0||v.source===e.savedSource);if(n.length===0)throw new Error(`saved workflow not found: ${t}`);if(n.length>1)throw new Error(`ambiguous saved workflow name: ${t}`);let r=n[0];if(!r.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be replaced");let a=Z({...e.manifest,name:t});ce(a,e.source);let o=e.requires??Fe(a),s=B({minKodaxVersion:e.minKodaxVersion??ee,manifest:a,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...o!==void 0?{requires:o}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}}),d=await We(r.path),g=new Date().toISOString().replace(/[:.]/g,"-"),h=K(Ie(r.path),".revisions",t),y=`${g}-${process.hrtime.bigint().toString(36)}`,p=K(h,`${t}-${y}.workflow.json`),b=K(Ie(r.path),`.${t}.${process.pid}.${Date.now().toString(36)}.tmp`);await Tt(h,{recursive:!0}),await Rt(p,d);try{await Rt(b,s),await Un(b,r.path)}catch(v){try{await Pe(b)}catch{}throw v}return{name:t,path:r.path,source:r.source,execution:"capability-generated",previousPath:p}}i(fo,"replaceSavedWorkflow");function Yn(e){if(!Ee(e))return;let t=e.request;if(typeof t=="string"&&t.trim().length>0)return t;let n=e.question;if(typeof n=="string"&&n.trim().length>0)return n}i(Yn,"readOptionalOriginalRequest");function At(e){return Zn(e)}i(At,"buildCapsuleFromRun");async function Zn(e){let t=JSON.parse(await Q(K(e.runDir,"run.json"),"utf8"));if(!Ee(t))throw new Error("workflow run.json must be an object");let n=xt(t,"scriptSnapshotPath"),r=xt(t,"manifestSnapshotPath"),a=await Q(n,"utf8"),o=Z(JSON.parse(await Q(r,"utf8")));ce(o,a);let s=typeof t.runId=="string"&&t.runId.length>0?t.runId:Vn(e.runDir),d=Yn(t.args),g=Fe(o),h=Ue(o,d!==void 0?{originalRequest:d}:{}),y={description:"Provide new workflow args matching the generated request shape.",..."args"in t?{examples:[t.args]}:{}};return B({minKodaxVersion:ee,manifest:o,source:a,intent:h,inputs:y,...g!==void 0?{requires:g}:{},provenance:{fromRunId:s,createdAt:new Date().toISOString(),kodaxVersion:Pt()}})}i(Zn,"readCapsuleFromRun");async function mo(e){let t=await At(e);return{capsule:t,module:we(t)}}i(mo,"loadGeneratedWorkflowFromRun");async function po(e){let t=await At(e);return Gn({dir:e.targetDir,name:e.name,manifest:t.manifest,source:t.source,...t.intent!==void 0?{intent:t.intent}:{},...t.inputs!==void 0?{inputs:t.inputs}:{},...t.requires!==void 0?{requires:t.requires}:{},...t.provenance!==void 0?{provenance:t.provenance}:{},minKodaxVersion:t.minKodaxVersion})}i(po,"saveGeneratedWorkflowFromRun");function U(e,t,n,r){e.push({severity:t,requirement:n,message:r})}i(U,"addRequirementIssue");function bt(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e.trim());if(t)return[Number(t[1]),Number(t[2]),Number(t[3])]}i(bt,"parseSemver");function Qn(e,t){for(let n=0;n<3;n+=1){let r=e[n]-t[n];if(r!==0)return r}return 0}i(Qn,"compareSemver");function er(e,t,n){let r=bt(t),a=bt(n);if(!r){U(e,"error","kodax:min-version",`workflow minKodaxVersion is not valid semver: ${t}`);return}if(!a){U(e,"warning","kodax:min-version",`cannot verify workflow minKodaxVersion ${t}; current version is unknown`);return}Qn(a,r)<0&&U(e,"error","kodax:min-version",`workflow requires KodaX >= ${t}, current version is ${n}`)}i(er,"addMinVersionIssue");function Te(e,t,n,r){if(!n)return;if(!r){for(let o of n)U(e,"warning",`${t}:${o}`,`workflow requires ${t}:${o}, but no ${t} inventory was provided`);return}let a=new Set(r);for(let o of n)a.has(o)||U(e,"error",`${t}:${o}`,`missing required workflow ${t}: ${o}`)}i(Te,"addMissingItems");function wo(e,t={}){let n=pe(e),r=[],a=n.requires;er(r,n.minKodaxVersion,t.kodaxVersion??Pt()),a?.environment?.includes("git-repo")&&t.isGitRepo===!1&&U(r,"error","environment:git-repo","workflow requires a git repository"),a?.environment?.includes("worktree-capable")&&t.worktreeCapable===!1&&U(r,"error","environment:worktree-capable","workflow may request git worktree isolation");try{me(n.source,{filename:`${n.manifest.name}.workflow.js`,requireAsyncRun:!0})}catch(o){let s=o instanceof Error?o.message:String(o);U(r,"error","workflow:source",s)}return Te(r,"tools",a?.tools,t.availableTools),Te(r,"mcp",a?.mcp,t.availableMcp),Te(r,"skills",a?.skills,t.availableSkills),{ok:!r.some(o=>o.severity==="error"),issues:r}}i(wo,"preflightWorkflowCapsule");function nr(e){return{project:Et(e,".kodax","workflows"),personal:Et(tr(),".kodax","workflows")}}i(nr,"defaultSavedWorkflowDirs");async function rr(e,t){let r=(await te(t)).find(a=>a.name===e);if(r)return Mt(r.path)}i(rr,"resolveSavedByName");function Wt(e){let t=nr(e);return async n=>vt(n)??await rr(n,t)}i(Wt,"createNestedWorkflowResolver");import{existsSync as or,mkdirSync as ir,readFileSync as ar,writeFileSync as Ft}from"node:fs";import{join as ne}from"node:path";var Ot="results";function qt(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}i(qt,"safeKey");function Ct(e,t){let n=ne(e,t);if(or(n))try{return JSON.parse(ar(n,"utf8"))}catch{return}}i(Ct,"readResult");function $t(e,t={}){let n=ne(e,Ot);ir(n,{recursive:!0});let r=t.readFrom?ne(t.readFrom,Ot):void 0;return{get:i(a=>{let o=`${qt(a)}.json`,s=Ct(n,o);if(s!==void 0)return s;if(r===void 0)return;let d=Ct(r,o);if(d!==void 0){try{Ft(ne(n,o),JSON.stringify(d),"utf8")}catch{}return d}},"get"),set:i((a,o)=>{try{Ft(ne(n,`${qt(a)}.json`),JSON.stringify(o),"utf8")}catch{}},"set")}}i($t,"createFsResultCache");import{mkdirSync as sr,appendFileSync as cr,writeFileSync as ue}from"node:fs";import{join as J}from"node:path";function de(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}i(de,"record");function F(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0}i(F,"finiteNumber");function _t(e){let t=new Map,n=new Set,r=[],a=[],o=new Set,s=[],d=[],g=0,h=0,y=0,p=0,b=0,v=0,W=0,m=0,T={},$=[];for(let C of e){let M=C.data??{};if(C.type==="agent_spawned"){let u=typeof M.taskId=="string"?M.taskId:void 0;u&&t.set(u,M),M.role==="primary-review"&&(v+=1);let w=typeof M.role=="string"?M.role:"agent",S=typeof M.requestedTier=="string"?M.requestedTier:"inherited",I=`${w}/${S}`;T[I]=(T[I]??0)+1;continue}if(C.type==="agent_completed"||C.type==="agent_unverified"||C.type==="agent_failed"){let u=typeof M.taskId=="string"?M.taskId:void 0;if(!u||n.has(u))continue;n.add(u);let w=de(M.usage);!w||typeof w.totalTokens!="number"?typeof t.get(u)?.externalTarget=="string"?a.push(u):r.push(u):(g+=F(w.totalTokens),h+=F(w.inputTokens),y+=F(w.cacheReadTokens??w.cachedReadTokens),p+=F(w.outputTokens));let S=de(M.digestUsage);b+=F(S?.totalTokens),h+=F(S?.inputTokens),p+=F(S?.outputTokens),y+=F(S?.cacheReadTokens??S?.cachedReadTokens),W+=F(M.iterations);continue}if(C.type==="agent_summary_updated"){let u=de(M.usage),w=M.summaryKind;if((w==="digest"||w==="digest-failed")&&u){let S=F(u.totalTokens);g+=S,b+=S,h+=F(u.inputTokens),p+=F(u.outputTokens),y+=F(u.cacheReadTokens??u.cachedReadTokens)}continue}if(C.type!=="workflow_log")continue;let f=de(M.data);if(f?.kind==="review_quality_gate"&&typeof f.contentHash=="string"){$.push({contentHash:f.contentHash,actionableFindings:F(f.actionableFindings),unresolvedFindings:F(f.unresolvedFindings),unqualifiedApprovalAllowed:f.unqualifiedApprovalAllowed===!0});continue}if(f?.kind!=="review_packet_read"||typeof f.contentHash!="string")continue;let l={contentHash:f.contentHash,...typeof f.reason=="string"?{reason:f.reason}:{}};f.role==="primary"?(o.has(f.contentHash)&&(m+=1),o.add(f.contentHash)):f.role==="verification"?s.push(l):f.role==="synthesis"&&d.push(l)}for(let C of t.keys())n.has(C)||r.push(C);let G=[...new Set(r)].sort();return{totalModelTokens:g,inputTokens:h,cacheReadTokens:y,outputTokens:p,digestTokens:b,agentStarts:t.size,childTurns:W,agentStartsByRoleTier:T,primaryReviewStarts:v,duplicatePrimaryPacketReads:m,verificationPacketReads:s,synthesisPacketReads:d,reviewWaves:v>0?1:0,fixWaves:0,rereviewWaves:0,qualityGateOutcomes:$,tokenCoverage:{ok:G.length===0,missingTaskIds:G},excludedExternalTaskIds:[...new Set(a)].sort()}}i(_t,"buildWorkflowCostReport");function dr(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,120);return t.length>0?t:"artifact"}i(dr,"safeWorkflowArtifactName");function Nt(e,t={}){let n=t.now??(()=>Date.now()),r=J(e,"artifacts");sr(r,{recursive:!0});let a=J(e,"events.jsonl");return{runDir:e,onEvent:i(o=>{cr(a,`${JSON.stringify({...o,ts:n()})}