@kodax-ai/kodax 0.7.80 → 0.7.82

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 (64) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +26 -3
  3. package/README_CN.md +21 -3
  4. package/dist/chunks/{agent-5PHGNFW3.js → agent-4UTCCMD5.js} +1 -1
  5. package/dist/chunks/argument-completer-N7ORRJBS.js +2 -0
  6. package/dist/chunks/{chunk-PMKAG4SZ.js → chunk-7ZN2MLVM.js} +1 -1
  7. package/dist/chunks/{chunk-GC4JBMBS.js → chunk-GIVYTXQW.js} +7 -7
  8. package/dist/chunks/{chunk-IHPH3444.js → chunk-JDZFNWMZ.js} +2 -2
  9. package/dist/chunks/{chunk-BWX4YZX3.js → chunk-KH2HED37.js} +2 -2
  10. package/dist/chunks/{chunk-RXXKDR6Y.js → chunk-NINELPXH.js} +1 -1
  11. package/dist/chunks/chunk-PGTU7JQX.js +30 -0
  12. package/dist/chunks/{chunk-T5U4OP2N.js → chunk-S6JTWDN6.js} +1 -1
  13. package/dist/chunks/{chunk-CDCCTM5I.js → chunk-VQBJMNFD.js} +2 -2
  14. package/dist/chunks/{chunk-CEB5FDND.js → chunk-WMYCNECP.js} +57 -57
  15. package/dist/chunks/{chunk-FQ7NVMSU.js → chunk-XTCDCU2Q.js} +136 -136
  16. package/dist/chunks/{chunk-RPF5RGWZ.js → chunk-ZOBNDWOA.js} +151 -151
  17. package/dist/chunks/chunk-ZZUIO5KL.js +348 -0
  18. package/dist/chunks/{compaction-config-6J6XCBJS.js → compaction-config-IDL5JQVI.js} +1 -1
  19. package/dist/chunks/{construction-bootstrap-KPCAE3VN.js → construction-bootstrap-STYUR6XA.js} +1 -1
  20. package/dist/chunks/{dist-RWEVZOFK.js → dist-RKBHBUHV.js} +1 -1
  21. package/dist/chunks/{host-OGS2R5J4.js → host-RF2IX3N6.js} +1 -1
  22. package/dist/chunks/{run-manager-2YMM3BOT.js → run-manager-WE2KPAKZ.js} +1 -1
  23. package/dist/chunks/{utils-2YHRUZYC.js → utils-Z2RSAENX.js} +1 -1
  24. package/dist/index.d.ts +12 -12
  25. package/dist/index.js +1 -1
  26. package/dist/kodax_bootstrap.js +1 -1
  27. package/dist/kodax_cli.js +1292 -1292
  28. package/dist/kodax_resume.js +4 -4
  29. package/dist/runtime-worker.js +1148 -1148
  30. package/dist/sandbox-workspace-session.js +4 -4
  31. package/dist/sdk-a2a.d.ts +8 -8
  32. package/dist/sdk-a2a.js +1 -1
  33. package/dist/sdk-agent.d.ts +10 -10
  34. package/dist/sdk-agent.js +1 -1
  35. package/dist/sdk-coding.d.ts +13 -13
  36. package/dist/sdk-coding.js +1 -1
  37. package/dist/sdk-mcp.js +1 -1
  38. package/dist/sdk-repl.d.ts +11 -11
  39. package/dist/sdk-repl.js +1 -1
  40. package/dist/sdk-runtime.d.ts +15 -8
  41. package/dist/sdk-runtime.js +1 -1
  42. package/dist/sdk-sandbox.js +1 -1
  43. package/dist/sdk-session.d.ts +4 -4
  44. package/dist/sdk-session.js +1 -1
  45. package/dist/sdk-skills.js +1 -1
  46. package/dist/semantic-worker.js +2 -2
  47. package/dist/types-chunks/{bash-prefix-extractor.d-DStqKIlu.d.ts → bash-prefix-extractor.d-CJM7OY-L.d.ts} +4 -2
  48. package/dist/types-chunks/{capsule.d-BuFJaYxA.d.ts → capsule.d-B7yoH4dM.d.ts} +4 -2
  49. package/dist/types-chunks/{controller.d-C2aHqzHj.d.ts → controller.d-CYNuR2n9.d.ts} +2 -2
  50. package/dist/types-chunks/{guardrail.d-DM-OK0m3.d.ts → guardrail.d-fM3mn4Op.d.ts} +2 -2
  51. package/dist/types-chunks/{history-retrieval.d-DImTKgO6.d.ts → history-retrieval.d-BDI-ZMvY.d.ts} +1 -1
  52. package/dist/types-chunks/{public-api.d-CewTvUKV.d.ts → public-api.d-i10kvYFs.d.ts} +2 -2
  53. package/dist/types-chunks/{repl.d-DvXQtgr7.d.ts → repl.d-Cs3eqGVT.d.ts} +5 -5
  54. package/dist/types-chunks/{run-manager.d-C6ahvZqK.d.ts → run-manager.d-CodHf6rw.d.ts} +1 -1
  55. package/dist/types-chunks/{sdk-session-C59RUrri.d.ts → sdk-session-CRXu5xNs.d.ts} +2 -2
  56. package/dist/types-chunks/{shell-command-sets.d-Dp4UvPLL.d.ts → shell-command-sets.d-DfeSUjjM.d.ts} +1 -1
  57. package/dist/types-chunks/{types.d-BzpPDBPV.d.ts → types.d-DIXZFauU.d.ts} +1 -1
  58. package/dist/types-chunks/{types.d-yuJzE82x.d.ts → types.d-DKs4tfSd.d.ts} +2 -2
  59. package/dist/types-chunks/{utils.d-BpACJmzt.d.ts → utils.d-CgITiLyc.d.ts} +4 -4
  60. package/docs/SDK_EMBEDDER_GUIDE.md +38 -10
  61. package/package.json +1 -1
  62. package/dist/chunks/argument-completer-FXRZFMTC.js +0 -2
  63. package/dist/chunks/chunk-UZSHBQER.js +0 -30
  64. package/dist/chunks/chunk-VECRQTSD.js +0 -348
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{a as od,b as id,c as sd,d as ad,e as cd,f as ld,g as Ai}from"./chunk-KHEFUT6O.js";import{C as on,Ja as ki,Pa as _i,S as Ir,Sa as Dl,e as wi,f as bi,g as vi,ka as Or,ma as xi}from"./chunk-TRNAWSXP.js";import{Eb as je,Fb as Ql,L as Fl,La as ql,Ma as Si,Qa as Pr,V as Ul,Va as Bl,X as Rt,Ya as Ie,Za as qn,_a as It,ab as Wl,b as Ei,bb as Hl,bd as Zl,c as Fn,cb as Kl,ed,je as nd,le as rd,ob as zl,p as $r,pd as td,q as jl,va as ce}from"./chunk-CEB5FDND.js";import{$a as Mr,D as Vl,J as Yl,ab as Lr,b as V,d as P,fb as Jl,g as sn,h as Un,kb as Ti,o as Gl,v as Xl}from"./chunk-EVXIJPZ6.js";import{b as st,d as ke}from"./chunk-E7C4DRD2.js";import{a as i}from"./chunk-ONUPGMER.js";import{createHash as Ly}from"node:crypto";import dd from"node:path";var ud=32,Ny=4096,fd=128,Dy=65536,jy=262144,Fy=65536,pd=64,Uy=6e5,qy=6e4,By=new Set(["pwsh","powershell","cmd","bash","zsh"]),Wy=new Set(["default","none","login","interactive","login-interactive"]),md=3e4,Ri=1e4;function Ii(e){let t=Bn(e,"shellExecution");if(Nr(t,["version","shell","environment","cache","probeTimeoutMs"],"shellExecution"),t.version!==1)throw new Error("shellExecution.version must be 1");let n=Bn(t.shell,"shellExecution.shell");if(Nr(n,["kind","executable","args","profile"],"shellExecution.shell"),!By.has(n.kind))throw new Error("shellExecution.shell.kind is not supported");let r=n.kind,o=yd(n.executable,"shellExecution.shell.executable",4096);if(o!==void 0&&!dd.isAbsolute(o)&&!dd.win32.isAbsolute(o)&&/[\\/]/.test(o))throw new Error("shellExecution.shell.executable must be absolute or a bare executable name");let s=Hy(n.args,r),a=Gy(n.profile,r),c=Xy(t.environment),l=Jy(t.cache),d=gd(t.probeTimeoutMs,"shellExecution.probeTimeoutMs",100,qy);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(Ii,"normalizeShellExecutionContract");function hd(e){return Ly("sha256").update(Ci(Ii(e))).digest("hex")}i(hd,"shellExecutionContractFingerprint");function Dr(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(Dr,"isSensitiveShellEnvironmentName");function Hy(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length>ud)throw new Error(`shellExecution.shell.args must contain at most ${ud} strings`);let n=e.map((o,s)=>Oi(o,`shellExecution.shell.args[${s}]`,Ny)),r=zy(t);if(n.some(o=>Ky(t,o,r)))throw new Error("shellExecution.shell.args cannot override KodaX command or persistence flags");return n}i(Hy,"normalizeShellArgs");function Ky(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(Ky,"isShellControlArgument");function zy(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(zy,"commandControlArgs");function Gy(e,t){if(e===void 0)return;if(!Wy.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(Gy,"normalizeProfileMode");function Xy(e){if(e===void 0)return;let t=Bn(e,"shellExecution.environment");Nr(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=Vy(t.set),o=Yy(t.denyPatterns),s=yd(t.setup,"shellExecution.environment.setup",Fy),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(Xy,"normalizeEnvironment");function Vy(e){if(e===void 0)return;let t=Object.entries(Bn(e,"shellExecution.environment.set"));if(t.length>fd)throw new Error(`shellExecution.environment.set must contain at most ${fd} 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(Dr(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=Qy(s,`shellExecution.environment.set.${o}`,Dy);if(n+=o.length+a.length,n>jy)throw new Error("shellExecution.environment.set exceeds the size limit");r[o]=a}return r}i(Vy,"normalizeEnvironmentSet");function Yy(e){if(e!==void 0){if(!Array.isArray(e)||e.length>pd)throw new Error(`shellExecution.environment.denyPatterns must contain at most ${pd} strings`);return e.map((t,n)=>{let r=Oi(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(Yy,"normalizeDenyPatterns");function Jy(e){if(e===void 0)return;let t=Bn(e,"shellExecution.cache");Nr(t,["ttlMs","refreshToken"],"shellExecution.cache");let n=gd(t.ttlMs,"shellExecution.cache.ttlMs",0,Uy),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(Jy,"normalizeCache");function gd(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(gd,"optionalInteger");function yd(e,t,n){return e===void 0?void 0:Oi(e,t,n)}i(yd,"optionalBoundedString");function Oi(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(Oi,"boundedString");function Qy(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(Qy,"boundedStringAllowEmpty");function Bn(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}i(Bn,"requireRecord");function Nr(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(Nr,"assertOnlyKeys");function Ci(e){if(e===null||typeof e!="object")return JSON.stringify(e)??"undefined";if(Array.isArray(e))return`[${e.map(Ci).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Ci(t[n])}`).join(",")}}`}i(Ci,"stableSerialize");import wd from"node:path";var Zy=new Set(["COMSPEC","HOMEDRIVE","HOMEPATH","HOME","LOCALAPPDATA","OS","PATH","PATHEXT","PROGRAMDATA","PROGRAMFILES","PROGRAMFILES(X86)","SYSTEMDRIVE","SYSTEMROOT","TEMP","TMP","USERPROFILE","WINDIR"]),ew=new Set(["HOME","LANG","LC_ALL","LOGNAME","PATH","SHELL","TERM","TMPDIR","USER"]),tw=new Set(["BASH_ENV","NODE_OPTIONS","RIPGREP_CONFIG_PATH"]),nw=4096,rw=2*1024*1024;function Fr(e,t,n=process.platform,r=[],o,s=[]){let a={...e};for(let c of Object.keys(a)){let l=ow(c,s,n);(Ni(c)||!l&&(Dr(c)||r.some(d=>d.toUpperCase()===c.toUpperCase())))&&iw(a,c,n)}return Mi(a,n,o),n!=="win32"||t!=="cmd"||_e(a,"NoDefaultCurrentDirectoryInExePath","1",n),a}i(Fr,"hardenShellCommandEnvironment");function Ur(e){return e?Wn(e.split(",")):[]}i(Ur,"parseSandboxEnvironmentPass");function Wn(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(Wn,"normalizeSandboxEnvironmentPass");function vd(e,t,n,r=process.platform){let o={...t};for(let s of n){if(Ni(s))continue;let a=Object.keys(e).find(c=>xd(c,s,r));a===void 0||e[a]===void 0||_e(o,a,e[a],r)}return o}i(vd,"applyShellEnvironmentPass");function ow(e,t,n){return t.some(r=>xd(e,r,n))}i(ow,"environmentNameIsListed");function xd(e,t,n){return n==="win32"?e.toUpperCase()===t.toUpperCase():e===t}i(xd,"environmentNamesEqual");function Mi(e,t,n){let r=Object.keys(e).find(l=>l.toUpperCase()==="PATH");if(!r||e[r]===void 0)return;let o=t==="win32"?wd.win32:wd.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(Mi,"sanitizeCommandPath");function iw(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(iw,"deleteEnvironmentValue");function Li(e,t,n,r=process.platform,o=[],s){let a=t.environment?.inherit??"filtered",c=r==="win32"?Zy:ew,l={};for(let[d,u]of Object.entries(e))u===void 0||jr(d,t,o)||a==="none"&&!c.has(d.toUpperCase())||_e(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(jr(d,t,o))throw new Error(`shellExecution.environment.set cannot contain denied variable ${d}`);_e(l,d,u,r)}return n!==void 0&&!jr("KODAX_SESSION_TMP",t,o)&&_e(l,"KODAX_SESSION_TMP",n,r),Mi(l,r,s),Sd(l),l}i(Li,"buildShellProbeEnvironment");function kd(e,t,n=process.platform,r=[],o){let s={};for(let[a,c]of Object.entries(e))jr(a,t,r)||_e(s,a,c,n);return Mi(s,n,o),Sd(s),s}i(kd,"sanitizeResolvedShellEnvironment");function jr(e,t,n=[]){return Dr(e)||Ni(e)||n.some(r=>r.toUpperCase()===e.toUpperCase())?!0:(t.environment?.denyPatterns??[]).some(r=>sw(e,r))}i(jr,"isDeniedEnvironmentName");function Ni(e){return tw.has(e.toUpperCase())||/^BASH_FUNC_.+(?:%%|\(\))$/i.test(e)}i(Ni,"isExecutionControlEnvironmentName");function sw(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(sw,"environmentNameMatchesPattern");function _d(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(_d,"parseWindowsRegistryEnvironment");function Ed(e,t,n){let r=bd(t,"PATH"),o=bd(n,"PATH");if(r===void 0&&o===void 0)return{...e};let s={...e};Pi(s,t),Pi(s,n);let a={...e};Pi(a,t),_e(a,"PATH","","win32");let c=r===void 0?"":$i(r,a),l={...s};_e(l,"PATH",c,"win32");for(let[m,h]of[...Object.entries(t),...Object.entries(n)])m.toUpperCase()!=="PATH"&&_e(s,m,$i(h,l),"win32");let d={...s};_e(d,"PATH",c,"win32");let u=o===void 0?"":$i(o,d),p=/%PATH%/i.test(o??"")?u:[c,u].filter(m=>m.length>0).join(";");return _e(s,"PATH",p,"win32"),s}i(Ed,"mergeWindowsRegistryEnvironment");function $i(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($i,"expandWindowsEnvironmentReferences");function Pi(e,t){for(let[n,r]of Object.entries(t))n.toUpperCase()!=="PATH"&&_e(e,n,r,"win32")}i(Pi,"overlayWindowsRegistryValues");function bd(e,t){return Object.entries(e).find(([n])=>n.toUpperCase()===t.toUpperCase())?.[1]}i(bd,"recordEnvironmentValue");function _e(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(_e,"setEnvironmentValue");function Sd(e){let t=Object.entries(e);if(t.length>nw)throw new Error("resolved shell environment contains too many variables");if(t.reduce((r,[o,s])=>r+Buffer.byteLength(o)+Buffer.byteLength(s??""),0)>rw)throw new Error("resolved shell environment exceeds the size limit")}i(Sd,"validateEnvironmentSize");import{spawn as aw}from"node:child_process";import{randomBytes as cw}from"node:crypto";import{accessSync as lw,constants as Td,realpathSync as dw,statSync as uw}from"node:fs";import{delimiter as fw,isAbsolute as Ad,join as Br,resolve as Md,win32 as Di}from"node:path";import ji from"iconv-lite";var pw=3*1024*1024,mw=64,hw=[`delete process.env.${Si};`,"const s=process.argv[1];","process.stdout.write(s+Buffer.from(JSON.stringify(process.env)).toString('base64')+s);"].join(""),gw=`eval(Buffer.from('${Buffer.from(hw).toString("base64")}','base64').toString())`,at=new Map,Ge=new Map,Ld=0;function BI(){Ld+=1,at.clear();for(let e of Ge.values())e.controller.abort();Ge.clear()}i(BI,"clearShellExecutionEnvironmentCache");async function Nd(e,t,n,r=[],o){if(o?.aborted)throw Fe();let s=Ii(e),a=Md(t),c=Id(a),l=hd(s),d=n===void 0?"":Id(n),u=[...r].map(y=>y.toUpperCase()).sort().join("\0"),f=[Ld,l,c,d,u].join("\0"),p=at.get(f);if(p!==void 0&&p.expiresAt>Date.now())return p.value;p!==void 0&&at.delete(f);let m=Ge.get(f);if(m?.controller.signal.aborted&&(Ge.get(f)===m&&Ge.delete(f),m=void 0),m!==void 0)return Cd(m,o);let h=new AbortController,g,w=yw(s,l,a,n,r,h.signal).then(y=>{if(h.signal.aborted||Ge.get(f)!==g)throw Fe();let b=s.cache?.ttlMs??md;return b>0&&Ow(f,y,b),y}).finally(()=>{g.settled=!0,Ge.get(f)===g&&Ge.delete(f)});return g={controller:h,promise:w,waiters:0,settled:!1},Ge.set(f,g),Cd(g,o)}i(Nd,"resolveShellExecution");function Cd(e,t){return t?.aborted?(e.waiters===0&&!e.settled&&e.controller.abort(),Promise.reject(Fe())):(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(Fe());return}e.controller.abort(),e.promise.then(()=>r(Fe()),()=>r(Fe()))},"onAbort");t?.addEventListener("abort",c,{once:!0}),e.promise.then(l=>a({value:l}),l=>a({error:l})),t?.aborted&&c()}))}i(Cd,"waitForInFlightResolution");function Fe(){return Object.assign(new Error("shell environment resolution cancelled"),{name:"AbortError"})}i(Fe,"shellResolutionAbortError");function Dd(e,t,n){let r=n===void 0?Ur(process.env.KODAX_SANDBOX_ENV_PASS):Wn(n),o=Fr(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:vd(process.env,o,r,process.platform),...e.contract.shell.kind==="cmd"?{windowsVerbatimArguments:!0}:{}}}i(Dd,"createShellCommandInvocation");async function yw(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=Li(process.env,e,r,process.platform,o,n);e.shell.kind==="bash"&&a==="none"&&(c=$w(c,"BASH_ENV")),process.platform==="win32"&&e.environment?.windowsPath==="registry"&&(c=await Rw(c,n,e,s),c=Li(c,e,r,process.platform,o,n));let l=Sw(e,c),d=await ww(l,e,n,c,s);return{executable:l,commandArgs:_w(e.shell.kind,e.shell.args),env:kd(d,e,process.platform,o),contract:e,contractFingerprint:t}}i(yw,"resolveFreshShellExecution");async function ww(e,t,n,r,o){let s=`__KODAX_ENV_${cw(16).toString("hex")}__`,a=vw(t.shell.kind,s),c=t.environment?.setup,l=xw(t.shell.kind,c,a),d=kw(t.shell.kind,t.shell.args,t.shell.profile??"default",l),u=await Ui({executable:e,args:d,cwd:n,env:r,timeoutMs:t.probeTimeoutMs??Ri,kind:"shell-environment-probe",windowsVerbatimArguments:t.shell.kind==="cmd",signal:o});return bw(u.stdout,s)}i(ww,"probeShellEnvironment");function bw(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(bw,"parseEnvironmentProbeOutput");function vw(e,t,n=process.execPath,r=process.versions.electron!==void 0,o=process.env.KODAX_BUNDLED==="true"){let s=Pr({args:["-e",gw,t],env:{},executable:n,isBundled:o,isElectron:r}),a;e==="pwsh"||e==="powershell"?a=`& ${$d(s.command)} ${s.args.map($d).join(" ")}`:e==="cmd"?a=[Pd(s.command),...s.args.map(Pd)].join(" "):a=[Od(s.command),...s.args.map(Od)].join(" ");let c=[Si,ql].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(vw,"buildNodeEnvironmentHelper");function xw(e,t,n){return t===void 0?e==="cmd"?`"${n}"`:n:e==="pwsh"||e==="powershell"?`$ErrorActionPreference='Stop'; ${t}
2
+ import{a as od,b as id,c as sd,d as ad,e as cd,f as ld,g as Ai}from"./chunk-KHEFUT6O.js";import{C as on,Ja as ki,Pa as _i,S as Ir,Sa as Dl,e as wi,f as bi,g as vi,ka as Or,ma as xi}from"./chunk-TRNAWSXP.js";import{Eb as je,Fb as Ql,L as Fl,La as ql,Ma as Si,Qa as Pr,V as Ul,Va as Bl,X as Rt,Ya as Ie,Za as qn,_a as It,ab as Wl,b as Ei,bb as Hl,c as Fn,cb as Kl,cd as Zl,fd as ed,ke as nd,me as rd,ob as zl,p as $r,q as jl,qd as td,va as ce}from"./chunk-WMYCNECP.js";import{$a as Mr,D as Vl,J as Yl,ab as Lr,b as V,d as P,fb as Jl,g as sn,h as Un,kb as Ti,o as Gl,v as Xl}from"./chunk-EVXIJPZ6.js";import{b as st,d as ke}from"./chunk-E7C4DRD2.js";import{a as i}from"./chunk-ONUPGMER.js";import{createHash as Ly}from"node:crypto";import dd from"node:path";var ud=32,Ny=4096,fd=128,Dy=65536,jy=262144,Fy=65536,pd=64,Uy=6e5,qy=6e4,By=new Set(["pwsh","powershell","cmd","bash","zsh"]),Wy=new Set(["default","none","login","interactive","login-interactive"]),md=3e4,Ri=1e4;function Ii(e){let t=Bn(e,"shellExecution");if(Nr(t,["version","shell","environment","cache","probeTimeoutMs"],"shellExecution"),t.version!==1)throw new Error("shellExecution.version must be 1");let n=Bn(t.shell,"shellExecution.shell");if(Nr(n,["kind","executable","args","profile"],"shellExecution.shell"),!By.has(n.kind))throw new Error("shellExecution.shell.kind is not supported");let r=n.kind,o=yd(n.executable,"shellExecution.shell.executable",4096);if(o!==void 0&&!dd.isAbsolute(o)&&!dd.win32.isAbsolute(o)&&/[\\/]/.test(o))throw new Error("shellExecution.shell.executable must be absolute or a bare executable name");let s=Hy(n.args,r),a=Gy(n.profile,r),c=Xy(t.environment),l=Jy(t.cache),d=gd(t.probeTimeoutMs,"shellExecution.probeTimeoutMs",100,qy);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(Ii,"normalizeShellExecutionContract");function hd(e){return Ly("sha256").update(Ci(Ii(e))).digest("hex")}i(hd,"shellExecutionContractFingerprint");function Dr(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(Dr,"isSensitiveShellEnvironmentName");function Hy(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length>ud)throw new Error(`shellExecution.shell.args must contain at most ${ud} strings`);let n=e.map((o,s)=>Oi(o,`shellExecution.shell.args[${s}]`,Ny)),r=zy(t);if(n.some(o=>Ky(t,o,r)))throw new Error("shellExecution.shell.args cannot override KodaX command or persistence flags");return n}i(Hy,"normalizeShellArgs");function Ky(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(Ky,"isShellControlArgument");function zy(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(zy,"commandControlArgs");function Gy(e,t){if(e===void 0)return;if(!Wy.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(Gy,"normalizeProfileMode");function Xy(e){if(e===void 0)return;let t=Bn(e,"shellExecution.environment");Nr(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=Vy(t.set),o=Yy(t.denyPatterns),s=yd(t.setup,"shellExecution.environment.setup",Fy),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(Xy,"normalizeEnvironment");function Vy(e){if(e===void 0)return;let t=Object.entries(Bn(e,"shellExecution.environment.set"));if(t.length>fd)throw new Error(`shellExecution.environment.set must contain at most ${fd} 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(Dr(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=Qy(s,`shellExecution.environment.set.${o}`,Dy);if(n+=o.length+a.length,n>jy)throw new Error("shellExecution.environment.set exceeds the size limit");r[o]=a}return r}i(Vy,"normalizeEnvironmentSet");function Yy(e){if(e!==void 0){if(!Array.isArray(e)||e.length>pd)throw new Error(`shellExecution.environment.denyPatterns must contain at most ${pd} strings`);return e.map((t,n)=>{let r=Oi(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(Yy,"normalizeDenyPatterns");function Jy(e){if(e===void 0)return;let t=Bn(e,"shellExecution.cache");Nr(t,["ttlMs","refreshToken"],"shellExecution.cache");let n=gd(t.ttlMs,"shellExecution.cache.ttlMs",0,Uy),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(Jy,"normalizeCache");function gd(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(gd,"optionalInteger");function yd(e,t,n){return e===void 0?void 0:Oi(e,t,n)}i(yd,"optionalBoundedString");function Oi(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(Oi,"boundedString");function Qy(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(Qy,"boundedStringAllowEmpty");function Bn(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}i(Bn,"requireRecord");function Nr(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(Nr,"assertOnlyKeys");function Ci(e){if(e===null||typeof e!="object")return JSON.stringify(e)??"undefined";if(Array.isArray(e))return`[${e.map(Ci).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Ci(t[n])}`).join(",")}}`}i(Ci,"stableSerialize");import wd from"node:path";var Zy=new Set(["COMSPEC","HOMEDRIVE","HOMEPATH","HOME","LOCALAPPDATA","OS","PATH","PATHEXT","PROGRAMDATA","PROGRAMFILES","PROGRAMFILES(X86)","SYSTEMDRIVE","SYSTEMROOT","TEMP","TMP","USERPROFILE","WINDIR"]),ew=new Set(["HOME","LANG","LC_ALL","LOGNAME","PATH","SHELL","TERM","TMPDIR","USER"]),tw=new Set(["BASH_ENV","NODE_OPTIONS","RIPGREP_CONFIG_PATH"]),nw=4096,rw=2*1024*1024;function Fr(e,t,n=process.platform,r=[],o,s=[]){let a={...e};for(let c of Object.keys(a)){let l=ow(c,s,n);(Ni(c)||!l&&(Dr(c)||r.some(d=>d.toUpperCase()===c.toUpperCase())))&&iw(a,c,n)}return Mi(a,n,o),n!=="win32"||t!=="cmd"||_e(a,"NoDefaultCurrentDirectoryInExePath","1",n),a}i(Fr,"hardenShellCommandEnvironment");function Ur(e){return e?Wn(e.split(",")):[]}i(Ur,"parseSandboxEnvironmentPass");function Wn(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(Wn,"normalizeSandboxEnvironmentPass");function vd(e,t,n,r=process.platform){let o={...t};for(let s of n){if(Ni(s))continue;let a=Object.keys(e).find(c=>xd(c,s,r));a===void 0||e[a]===void 0||_e(o,a,e[a],r)}return o}i(vd,"applyShellEnvironmentPass");function ow(e,t,n){return t.some(r=>xd(e,r,n))}i(ow,"environmentNameIsListed");function xd(e,t,n){return n==="win32"?e.toUpperCase()===t.toUpperCase():e===t}i(xd,"environmentNamesEqual");function Mi(e,t,n){let r=Object.keys(e).find(l=>l.toUpperCase()==="PATH");if(!r||e[r]===void 0)return;let o=t==="win32"?wd.win32:wd.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(Mi,"sanitizeCommandPath");function iw(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(iw,"deleteEnvironmentValue");function Li(e,t,n,r=process.platform,o=[],s){let a=t.environment?.inherit??"filtered",c=r==="win32"?Zy:ew,l={};for(let[d,u]of Object.entries(e))u===void 0||jr(d,t,o)||a==="none"&&!c.has(d.toUpperCase())||_e(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(jr(d,t,o))throw new Error(`shellExecution.environment.set cannot contain denied variable ${d}`);_e(l,d,u,r)}return n!==void 0&&!jr("KODAX_SESSION_TMP",t,o)&&_e(l,"KODAX_SESSION_TMP",n,r),Mi(l,r,s),Sd(l),l}i(Li,"buildShellProbeEnvironment");function kd(e,t,n=process.platform,r=[],o){let s={};for(let[a,c]of Object.entries(e))jr(a,t,r)||_e(s,a,c,n);return Mi(s,n,o),Sd(s),s}i(kd,"sanitizeResolvedShellEnvironment");function jr(e,t,n=[]){return Dr(e)||Ni(e)||n.some(r=>r.toUpperCase()===e.toUpperCase())?!0:(t.environment?.denyPatterns??[]).some(r=>sw(e,r))}i(jr,"isDeniedEnvironmentName");function Ni(e){return tw.has(e.toUpperCase())||/^BASH_FUNC_.+(?:%%|\(\))$/i.test(e)}i(Ni,"isExecutionControlEnvironmentName");function sw(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(sw,"environmentNameMatchesPattern");function _d(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(_d,"parseWindowsRegistryEnvironment");function Ed(e,t,n){let r=bd(t,"PATH"),o=bd(n,"PATH");if(r===void 0&&o===void 0)return{...e};let s={...e};Pi(s,t),Pi(s,n);let a={...e};Pi(a,t),_e(a,"PATH","","win32");let c=r===void 0?"":$i(r,a),l={...s};_e(l,"PATH",c,"win32");for(let[m,h]of[...Object.entries(t),...Object.entries(n)])m.toUpperCase()!=="PATH"&&_e(s,m,$i(h,l),"win32");let d={...s};_e(d,"PATH",c,"win32");let u=o===void 0?"":$i(o,d),p=/%PATH%/i.test(o??"")?u:[c,u].filter(m=>m.length>0).join(";");return _e(s,"PATH",p,"win32"),s}i(Ed,"mergeWindowsRegistryEnvironment");function $i(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($i,"expandWindowsEnvironmentReferences");function Pi(e,t){for(let[n,r]of Object.entries(t))n.toUpperCase()!=="PATH"&&_e(e,n,r,"win32")}i(Pi,"overlayWindowsRegistryValues");function bd(e,t){return Object.entries(e).find(([n])=>n.toUpperCase()===t.toUpperCase())?.[1]}i(bd,"recordEnvironmentValue");function _e(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(_e,"setEnvironmentValue");function Sd(e){let t=Object.entries(e);if(t.length>nw)throw new Error("resolved shell environment contains too many variables");if(t.reduce((r,[o,s])=>r+Buffer.byteLength(o)+Buffer.byteLength(s??""),0)>rw)throw new Error("resolved shell environment exceeds the size limit")}i(Sd,"validateEnvironmentSize");import{spawn as aw}from"node:child_process";import{randomBytes as cw}from"node:crypto";import{accessSync as lw,constants as Td,realpathSync as dw,statSync as uw}from"node:fs";import{delimiter as fw,isAbsolute as Ad,join as Br,resolve as Md,win32 as Di}from"node:path";import ji from"iconv-lite";var pw=3*1024*1024,mw=64,hw=[`delete process.env.${Si};`,"const s=process.argv[1];","process.stdout.write(s+Buffer.from(JSON.stringify(process.env)).toString('base64')+s);"].join(""),gw=`eval(Buffer.from('${Buffer.from(hw).toString("base64")}','base64').toString())`,at=new Map,Ge=new Map,Ld=0;function BI(){Ld+=1,at.clear();for(let e of Ge.values())e.controller.abort();Ge.clear()}i(BI,"clearShellExecutionEnvironmentCache");async function Nd(e,t,n,r=[],o){if(o?.aborted)throw Fe();let s=Ii(e),a=Md(t),c=Id(a),l=hd(s),d=n===void 0?"":Id(n),u=[...r].map(y=>y.toUpperCase()).sort().join("\0"),f=[Ld,l,c,d,u].join("\0"),p=at.get(f);if(p!==void 0&&p.expiresAt>Date.now())return p.value;p!==void 0&&at.delete(f);let m=Ge.get(f);if(m?.controller.signal.aborted&&(Ge.get(f)===m&&Ge.delete(f),m=void 0),m!==void 0)return Cd(m,o);let h=new AbortController,g,w=yw(s,l,a,n,r,h.signal).then(y=>{if(h.signal.aborted||Ge.get(f)!==g)throw Fe();let b=s.cache?.ttlMs??md;return b>0&&Ow(f,y,b),y}).finally(()=>{g.settled=!0,Ge.get(f)===g&&Ge.delete(f)});return g={controller:h,promise:w,waiters:0,settled:!1},Ge.set(f,g),Cd(g,o)}i(Nd,"resolveShellExecution");function Cd(e,t){return t?.aborted?(e.waiters===0&&!e.settled&&e.controller.abort(),Promise.reject(Fe())):(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(Fe());return}e.controller.abort(),e.promise.then(()=>r(Fe()),()=>r(Fe()))},"onAbort");t?.addEventListener("abort",c,{once:!0}),e.promise.then(l=>a({value:l}),l=>a({error:l})),t?.aborted&&c()}))}i(Cd,"waitForInFlightResolution");function Fe(){return Object.assign(new Error("shell environment resolution cancelled"),{name:"AbortError"})}i(Fe,"shellResolutionAbortError");function Dd(e,t,n){let r=n===void 0?Ur(process.env.KODAX_SANDBOX_ENV_PASS):Wn(n),o=Fr(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:vd(process.env,o,r,process.platform),...e.contract.shell.kind==="cmd"?{windowsVerbatimArguments:!0}:{}}}i(Dd,"createShellCommandInvocation");async function yw(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=Li(process.env,e,r,process.platform,o,n);e.shell.kind==="bash"&&a==="none"&&(c=$w(c,"BASH_ENV")),process.platform==="win32"&&e.environment?.windowsPath==="registry"&&(c=await Rw(c,n,e,s),c=Li(c,e,r,process.platform,o,n));let l=Sw(e,c),d=await ww(l,e,n,c,s);return{executable:l,commandArgs:_w(e.shell.kind,e.shell.args),env:kd(d,e,process.platform,o),contract:e,contractFingerprint:t}}i(yw,"resolveFreshShellExecution");async function ww(e,t,n,r,o){let s=`__KODAX_ENV_${cw(16).toString("hex")}__`,a=vw(t.shell.kind,s),c=t.environment?.setup,l=xw(t.shell.kind,c,a),d=kw(t.shell.kind,t.shell.args,t.shell.profile??"default",l),u=await Ui({executable:e,args:d,cwd:n,env:r,timeoutMs:t.probeTimeoutMs??Ri,kind:"shell-environment-probe",windowsVerbatimArguments:t.shell.kind==="cmd",signal:o});return bw(u.stdout,s)}i(ww,"probeShellEnvironment");function bw(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(bw,"parseEnvironmentProbeOutput");function vw(e,t,n=process.execPath,r=process.versions.electron!==void 0,o=process.env.KODAX_BUNDLED==="true"){let s=Pr({args:["-e",gw,t],env:{},executable:n,isBundled:o,isElectron:r}),a;e==="pwsh"||e==="powershell"?a=`& ${$d(s.command)} ${s.args.map($d).join(" ")}`:e==="cmd"?a=[Pd(s.command),...s.args.map(Pd)].join(" "):a=[Od(s.command),...s.args.map(Od)].join(" ");let c=[Si,ql].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(vw,"buildNodeEnvironmentHelper");function xw(e,t,n){return t===void 0?e==="cmd"?`"${n}"`:n:e==="pwsh"||e==="powershell"?`$ErrorActionPreference='Stop'; ${t}
3
3
  ${n}`:e==="cmd"?`(${t}) && ${n}`:`set -e
4
4
  ${t}
5
5
  ${n}`}i(xw,"combineProbeSetup");function kw(e,t,n,r){let o=[...t??[]];if(e==="cmd")return[...o,"/d","/v:off","/s","/c",r];if(e==="pwsh"||e==="powershell"){let a=n==="interactive"||n==="login-interactive";return[...e==="pwsh"&&(n==="login"||n==="login-interactive")?["-Login"]:[],...o,"-NoLogo",...a?["-Interactive"]:["-NonInteractive"],...n==="none"?["-NoProfile"]:[],"-Command",r]}let s=Ew(e,n);return[...o,...s,"-c",r]}i(kw,"buildShellProbeArgs");function _w(e,t){let n=[...t??[]];return e==="cmd"?[...n,"/d","/v:off","/s","/c"]:e==="pwsh"||e==="powershell"?[...n,"-NoLogo","-NonInteractive","-NoProfile","-Command"]:e==="bash"?[...n,"--noprofile","--norc","-c"]:[...n,"-f","-c"]}i(_w,"buildCommandArgs");function Ew(e,t){return t==="default"?[]:t==="none"?e==="bash"?["--noprofile","--norc"]:["-f"]:t==="login"?e==="bash"?["--login"]:["-l"]:t==="interactive"?["-i"]:e==="bash"?["--login","-i"]:["-l","-i"]}i(Ew,"posixProfileArgs");function Sw(e,t){let n=e.shell.executable??Tw(e.shell.kind,t),r=Aw(n,t);if(r===void 0)throw new Error(`configured shell is unavailable: ${n}`);return r}i(Sw,"resolveShellExecutable");function Tw(e,t){if(e==="cmd")return t.ComSpec??t.COMSPEC??"cmd.exe";if(e==="powershell"){let n=t.SystemRoot??t.SYSTEMROOT;return n===void 0?"powershell.exe":Br(n,"System32","WindowsPowerShell","v1.0","powershell.exe")}return e==="pwsh"?process.platform==="win32"?"pwsh.exe":"pwsh":e==="bash"?process.platform==="win32"?"bash.exe":"bash":process.platform==="win32"?"zsh.exe":"zsh"}i(Tw,"defaultShellExecutable");function Aw(e,t){if(Ad(e)||Di.isAbsolute(e))return qr(e)?e:void 0;let n=Fi(t,"PATH")??"",r=process.platform==="win32"?Cw(e,Fi(t,"PATHEXT")):[""];for(let o of n.split(fw)){let s=o.replace(/^"|"$/g,"");if(!(!Ad(s)&&!Di.isAbsolute(s)))for(let a of r){let c=Br(s,`${e}${a}`);if(qr(c))return c}}}i(Aw,"resolveExecutableFromEnvironment");function Cw(e,t){return Di.extname(e).length>0?[""]:(t??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(n=>n.toLowerCase())}i(Cw,"executableExtensions");function qr(e){try{return uw(e).isFile()?(lw(e,process.platform==="win32"?Td.F_OK:Td.X_OK),!0):!1}catch{return!1}}i(qr,"isExecutableFile");async function Rw(e,t,n,r){let o=Fi(e,"SystemRoot");if(o===void 0)throw new Error("Windows registry PATH resolution requires SystemRoot");let s=Br(o,"System32","reg.exe");if(!qr(s))throw new Error("Windows registry PATH resolution requires reg.exe");let a=n.probeTimeoutMs??Ri,c=await Iw(o,t,e,a,r),[l,d]=await Promise.all([Rd(s,"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",t,e,a,c,r),Rd(s,"HKCU\\Environment",t,e,a,c,r)]);if(l===void 0&&d===void 0)throw new Error("Windows registry PATH could not be resolved");return Ed(e,l??{},d??{})}i(Rw,"withCurrentWindowsRegistryPath");async function Rd(e,t,n,r,o,s,a){try{let c=await Ui({executable:e,args:["query",t],cwd:n,env:r,timeoutMs:o,kind:"shell-registry-path-probe",acceptNonZeroExit:!0,signal:a});if(c.exitCode!==0)return;let l=c.stdout.toString("utf8"),d=l;s!==void 0?d=ji.decode(c.stdout,s):l.includes("\uFFFD")&&(d=ji.decode(c.stdout,"cp936"));let u=_d(d);return Object.keys(u).length>0?u:void 0}catch{return}}i(Rd,"queryWindowsRegistryEnvironment");async function Iw(e,t,n,r,o){let s=Br(e,"System32","cmd.exe");if(qr(s))try{let a=await Ui({executable:s,args:["/d","/s","/c","chcp"],cwd:t,env:n,timeoutMs:r,kind:"shell-windows-codepage-probe",acceptNonZeroExit:!0,signal:o});if(a.exitCode!==0)return;let c=/(\d{3,5})/.exec(a.stdout.toString("ascii"));if(c?.[1]===void 0||c[1]==="65001")return;let l=`cp${c[1]}`;return ji.encodingExists(l)?l:void 0}catch{return}}i(Iw,"resolveWindowsCommandEncoding");function Ui(e){return new Promise((t,n)=>{if(e.signal?.aborted){n(Fe());return}let r=aw(e.executable,e.args,{cwd:e.cwd,env:e.env,shell:!1,windowsHide:!0,detached:process.platform!=="win32",...e.windowsVerbatimArguments===!0?{windowsVerbatimArguments:!0}:{}}),o=It(r,{kind:e.kind,command:e.executable,cwd:e.cwd}),s=[],a=0,c=!1,l,d,u=i((h,g=null)=>{c||(c=!0,clearTimeout(p),e.signal?.removeEventListener("abort",m),o(),h!==void 0?n(h):t({stdout:Buffer.concat(s),exitCode:g}))},"finish"),f=i(h=>{d??=h;let g=l??Ie(r).then(()=>{});l=g,g.then(()=>u(d),()=>u(d))},"finishAfterTermination"),p=setTimeout(()=>{f(new Error("shell environment probe timed out"))},e.timeoutMs),m=i(()=>{f(Fe())},"onAbort");e.signal?.addEventListener("abort",m,{once:!0}),e.signal?.aborted&&m(),r.stdout?.on("data",h=>{if(a+=h.length,a>pw){f(new Error("shell environment probe output exceeds the size limit"));return}s.push(h)}),r.stderr?.resume(),r.on("error",()=>{if(e.signal?.aborted||l!==void 0){f(d??Fe());return}u(new Error("configured shell could not be started"))}),r.on("close",h=>{if(l!==void 0){f(d??Fe());return}if(h!==0&&e.acceptNonZeroExit!==!0){u(new Error("shell environment probe failed"),h);return}u(void 0,h)})})}i(Ui,"captureProcess");function Ow(e,t,n){for(at.delete(e),at.set(e,{expiresAt:Date.now()+n,value:t});at.size>mw;){let r=at.keys().next().value;if(r===void 0)break;at.delete(r)}}i(Ow,"cacheResolvedEnvironment");function Id(e){let t=Md(e),n=t;try{n=dw.native(t)}catch{}return process.platform==="win32"?n.toLowerCase():n}i(Id,"normalizeCacheCwd");function Fi(e,t){return Object.entries(e).find(([r])=>r.toUpperCase()===t.toUpperCase())?.[1]}i(Fi,"environmentValue");function $w(e,t){return Object.fromEntries(Object.entries(e).filter(([n])=>n.toUpperCase()!==t.toUpperCase()))}i($w,"withoutEnvironmentVariable");function Od(e){return`'${e.replaceAll("'",`'"'"'`)}'`}i(Od,"quotePosix");function $d(e){return`'${e.replaceAll("'","''")}'`}i($d,"quotePowerShell");function Pd(e){return`"${e.replaceAll('"','\\"')}"`}i(Pd,"quoteCmd");var ZI=2,eO=500,tO=500,nO=Number.POSITIVE_INFINITY,qi="[Cancelled]",Bi=`${qi} Operation cancelled by user`;import jd from"fs/promises";import Fd from"path";var qd=2e3,an=50*1024,Pw=500,Wr=2e3,Wi=256*1024,Hi=2e3,Mw="KODAX_TOOL_OUTPUT_DIR";function Bd(e){return{maxLines:e.maxLines??qd,maxBytes:e.maxBytes??an}}i(Bd,"getLimits");function Ue(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}i(Ue,"formatSize");function Hn(e,t={}){let{maxLines:n,maxBytes:r}=Bd(t),o=Buffer.byteLength(e,"utf-8"),s=e.split(`
@@ -26,14 +26,14 @@ ${t.join(`
26
26
  `),sources:[{label:"tools",path:"packages/coding/src/tools/"}],nextTopics:["agents","repo-intelligence","permissions"]},{id:"agents",title:"Agents & coordination",aliases:["agent","subagent","specialist","\u81EA\u5B9A\u4E49agent","\u667A\u80FD\u4F53","\u5B50\u4EE3\u7406"],summary:"Author specialist agents and coordinate Actor turns through mailbox-driven control.",body:["Write a specialist agent as a markdown file with frontmatter (name, description,","tools, model) + a body prompt. KodaX loads:"," - user agents: ~/.kodax/agents/*.md"," - project agents: <repo>/.kodax/agents/*.md (override user agents of the same name)",'The main Agent starts one through spawn_agent(agent_id="<name>").',"Difference from skills: an agent is a full sub-agent (own prompt/tools); a skill is","reference knowledge injected into the current agent.","","All native, constructed, Workflow-owned, recursive, and external children use one","Runtime-owned Actor/Turn tree. Use `spawn_agent`, `send_message`, and `followup_task`","to start or steer work; `list_agents` reads current tree state; `agent_output` reads","the bounded output of a known Actor/Turn.","","AMA uses parallel-first collaboration: when two or more substantive lanes are independent","and child start slots are available, fan them out through ordinary Actor operations.","Solo work is reserved for genuinely indivisible or strongly serial tasks. Optional","`quality_strategy` metadata records provenance without admitting or blocking a turn. Runtime derives","a bounded, fact-only `PatternTrace`; it distinguishes coverage, replication, and","opposition but never proves correctness. The existing Sidecar remains the sole","terminal-answer quality adjudicator, and pattern/trace presence never forces a verifier","call, child launch, fixed topology, or hidden Workflow. The pattern catalog remains available","to explicit Workflow composition and observability; it is not a Worker dispatch gate.","","One uninterrupted managed Runner invocation is mechanically capped at 500 tool-loop","iterations. Every idle-yield resume starts a fresh invocation and resets that fuse, so","the managed-task lifecycle remains unbounded. If the fuse trips, callers receive the","structured `RunnerIterationLimitError` (`code: 'RUNNER_ITERATION_LIMIT'`) with the","last legal recovery transcript; use `isRunnerIterationLimitError` and","`readRunnerRecoveryTranscript` to distinguish a runaway loop from an ordinary failure.","","`wait_agent` is a model-facing mailbox yield, not an Actor event reader. Its current","schema contains only `timeout_ms` (10,000..3,600,000 ms; default 120,000). It wakes","for scoped Agent messages/completions, root user input, interruption, or timeout and","returns only `mailbox`, `user_input_pending`, `interrupted`, or `wait_expired` as a","small acknowledgement. Actor progress and system reminders do not wake the model.","Progress remains available to UI and SDK consumers through event snapshots, replay,","and long-poll. Do not poll `agent_output` to imitate waiting.","","A Managed Workflow `runAgent` wait with an omitted workflow timeout is unbounded at","the Workflow layer. The Actor API's internal wait is only a polling window; an empty","poll cannot stop or fail the task. Only an explicit workflow deadline produces a","timeout, while terminal Actor output closes an event-delivery race.","","Authenticated Agent messages and structured completion metadata enter the next safe","model boundary as synthetic evidence; a queued root prompt remains a real user turn.","A completion is acknowledged only after the parent transcript commits. If the process","stops earlier, an explicit pending-delivery record restores that completion once;","same-process reconstruction deduplicates by child turn ID, and acknowledged or legacy","historical completions are not replayed."].join(`
27
27
  `),sources:[{label:"markdown loader",path:"packages/coding/src/construction/markdown-loader.ts"},{label:"coordination tools",path:"packages/coding/src/tools/agent-collaboration.ts"},{label:"Actor controller",path:"packages/agent/src/actors/controller.ts"}],nextTopics:["skills","tools","sdk"]},{id:"skills",title:"Skills",aliases:["skill","agent skills","\u6280\u80FD"],summary:"What skills are, where they live, how they trigger, vs AGENTS.md.",body:["Skills are reusable, zero-dependency knowledge/instruction bundles the agent can pull","in on demand. Built-in skills ship inside the agent package","(packages/agent/src/capabilities/skills/); user skills are discovered from disk.","Trigger: the agent selects a relevant skill for the task. Versus AGENTS.md \u2014 AGENTS.md","sets repo-wide rules always in context; a skill is task-specific and loaded when needed.","Background learning is Memory first: one correction or recovery is evidence, not permission","to create a Skill. Repeated independently verified evidence, or an explicit preserve-as-Skill","request with verified terminal evidence, may create a low-risk declarative Skill as an","immutable project-scoped testing revision backed by the canonical Learning Center record.","Testing is a bounded canary: at most one concurrent root binding and three exact-revision invocations.","Automatic canary activation waits until all three outcomes settle and requires independently verified success","in at least one. A credible negative quarantines immediately; an exhausted canary without success returns","the revision to Ready/attention. Inspect, disable, rollback, trust, or reject it with /learn.","Use `/learn promote <name|slug|capability-id> --scope user` for a reviewed ready or active_learned","revision. KodaX verifies the exact fingerprint and publishes `SKILL.md` atomically to","the formal user catalog without overwriting a different existing Skill; repeating the","same promotion is idempotent.","Protected/formal Skills, global promotion, and Extension authoring remain manual; background","learning cannot shadow formal Skills, broaden authority, or auto-create an Extension."].join(`
28
28
  `),sources:[{label:"skills",path:"packages/agent/src/capabilities/skills/"},{label:"learning",path:"packages/agent/src/learning/"},{label:"reviewer",path:"packages/coding/src/learning-reviewer.ts"},{label:"Learning Center command",path:"packages/repl/src/commands/learn-command.ts"}],nextTopics:["agents","extensions","mcp"]},{id:"extensions",title:"Extensions",aliases:["extension","extensions","plugin","plugins","runtime extension","extension api","write extension","author extension","extension.mjs","kodax extension"],summary:"How to write, install, load, reload, and debug KodaX runtime extensions.",body:["Extensions are trusted local code that extend the active KodaX runtime.","Entry formats:"," - package directory in ~/.kodax/extensions/<name>/ with extension.mjs/js/cjs/mts/ts/cts or index.*"," - standalone module file (.js/.mjs/.cjs/.ts/.mts/.cts)","","Managed declarations live in ~/.kodax/integrations/extensions.json. Use `kodax","extensions list|add|remove|reload`; repeated `--extension <path>` remains a launch-only","override. Default discovery still scans ~/.kodax/extensions. Equivalent directory and","entrypoint paths are deduped by resolved entrypoint.","Until migration, config.json#extensions remains readable; the first managed mutation","stages those legacy paths into the split file before changing it.","","Minimal extension:"," export default function activate(api) {"," api.registerTool({",' name: "hello",',' description: "Say hello",',' input_schema: { type: "object", properties: {} },',' sideEffect: "readonly",',' handler: async () => "hello"'," });"," }","","Authoring surface: api.registerTool, registerCommand, registerSkillPath, registerAgent, registerCapabilityProvider, registerModelProvider, api.on(event), api.hook(hook), api.persistence, api.exec, and api.webhook. For TypeScript authors, import public types from @kodax-ai/coding/extensions.","","Operational commands: /extensions prints loaded modules, tools, commands, hooks,","capabilities, defaults, and failures. /reload hot-reloads active modules. User-file","reload is entry-transactional: an activation failure retains that entry's prior instance","while independent additions/removals proceed. Extension slash commands appear in /help.","","Security boundary: extensions run as local trusted code in the KodaX process. Do not install untrusted extension modules; prefer MCP or a sidecar service for untrusted or heavyweight external integrations."].join(`
29
- `),sources:[{label:"extension api",path:"packages/coding/src/extensions/types.ts"},{label:"extension discovery",path:"packages/coding/src/extensions/discovery.ts"},{label:"extension runtime",path:"packages/coding/src/extensions/runtime.ts"},{label:"integration config",path:"packages/repl/src/common/integration-config.ts"},{label:"CLI extension loading",path:"src/kodax_cli.ts"},{label:"REPL extension commands",path:"packages/repl/src/interactive/commands.ts"}],nextTopics:["config","skills","mcp"]},{id:"mcp",title:"MCP servers",aliases:["mcp server","model context protocol","mcp\u914D\u7F6E"],summary:"Configure, hot-reload, inspect, and troubleshoot MCP servers.",body:["MCP declarations live in ~/.kodax/integrations/mcp.json (version 1; stdio or remote).","Use `kodax mcp list|add|remove` to manage them and /mcp in the REPL to inspect live","connection status. Legacy `mcpServers` in core config remains readable until explicitly","migrated with `kodax integrations migrate --apply`.","","Long-lived owners hot-reload a valid candidate as one provider replacement and drain","in-flight calls. Invalid edits keep the last-known-good provider. Credentials stay in","${env:NAME} references. Common issues: wrong command/args, missing binary on PATH,","missing credential env, or a server that needs interactive auth in a headless run.","","`mcp_search` returns exact capability ids from an untrusted catalog snapshot. Complete","inventory/search pages are bounded by the physical result capacity and use revisioned","cursors instead of silent truncation. A zero lexical match may return a lossless grouped","exact-id inventory only when the entire filtered snapshot is cheaper than a normal page","and fits capacity; otherwise it returns one concise catalog-language retry with no biased","partial list. Stale/mixed snapshots and partial provider failure remain explicit."].join(`
29
+ `),sources:[{label:"extension api",path:"packages/coding/src/extensions/types.ts"},{label:"extension discovery",path:"packages/coding/src/extensions/discovery.ts"},{label:"extension runtime",path:"packages/coding/src/extensions/runtime.ts"},{label:"integration config",path:"packages/repl/src/common/integration-config.ts"},{label:"CLI extension loading",path:"src/kodax_cli.ts"},{label:"REPL extension commands",path:"packages/repl/src/interactive/commands.ts"}],nextTopics:["config","skills","mcp"]},{id:"mcp",title:"MCP servers",aliases:["mcp server","model context protocol","mcp\u914D\u7F6E"],summary:"Configure, hot-reload, inspect, and troubleshoot MCP servers.",body:["MCP declarations live in ~/.kodax/integrations/mcp.json (version 1; stdio or remote).","Use `kodax mcp list|add|remove` to manage them and /mcp in the REPL to inspect live","connection status. Legacy `mcpServers` in core config remains readable until explicitly","migrated with `kodax integrations migrate --apply`.","","Long-lived owners hot-reload a valid candidate as one provider replacement and drain","in-flight calls. Invalid edits keep the last-known-good provider. Credentials stay in","${env:NAME} references. Common issues: wrong command/args, missing binary on PATH,","missing credential env, or a server that needs interactive auth in a headless run.","","`mcp_search` returns exact capability ids from an untrusted catalog snapshot. Complete","inventory/search pages are bounded by the physical result capacity and use revisioned","cursors instead of silent truncation. A zero lexical match may return a lossless grouped","exact-id inventory only when the entire filtered snapshot is cheaper than a normal page","and fits capacity; otherwise it returns one concise catalog-language retry with no biased","partial list. Stale/mixed snapshots and partial provider failure remain explicit.","Daemon-owned Host Tools publish a lease-scoped live, complete snapshot. An unfiltered","search composes active MCP and Host Tool snapshots; `mcp_search({server})` selects only","that source. A legacy provider without a snapshot is queried uncapped and remains","incomplete/unknown rather than silently truncated."].join(`
30
30
  `),sources:[{label:"mcp",path:"packages/agent/src/capabilities/mcp/"},{label:"integration config",path:"packages/repl/src/common/integration-config.ts"},{label:"MCP runtime adapter",path:"packages/repl/src/common/mcp-servers.ts"}],nextTopics:["config","a2a","tools"]},{id:"a2a",title:"A2A 1.0 integration",aliases:["agent2agent","agent card","external agent","a2a server","a2a client","a2a\u914D\u7F6E","\u5916\u90E8agent"],summary:"Configure, authenticate, activate, call, and serve A2A 1.0 Agents safely.",body:["A2A declarations live in ~/.kodax/integrations/a2a.json (version 2). Legacy non-empty","version 1 files stay readable but require `kodax a2a migrate` after every daemon using","that config home is stopped. Use `kodax a2a add|list|test|call|enable|disable|remove`","for outbound Agents, `kodax a2a expose` to configure an inbound profile, and","`kodax a2a serve` to run the built-in server. `enabled` is desired state: disabling","blocks new dispatch after owner reconciliation but does not cancel an admitted task.","Configured outbound Agents register as `external:<name>` in embedded and user-daemon","Runtimes. Worker-hosted embedded Runtimes can opt into the same configured plane with","`worker.configuredA2A`, installing the full list/describe/preflight and external Actor","dispatch surface inside the Worker. The CLI honors the same opt-in from",'`~/.kodax/config.json` (`"worker": { "configuredA2A": true }`), creating a',"Worker-hosted embedded Runtime that loads the configured A2A plane. This mode rejects","configured MCP servers or Extensions; use the default inline Runtime to retain those","capabilities while loading configured A2A. `serve` uses CLI/env/core-config/built-in provider","precedence; an admitted","Markdown Agent may pin its own provider/model, but remote input cannot override them.","","Private-address and non-loopback plaintext access are independent and default deny.","`kodax a2a add` persists them as `network.allowPrivateAddresses` and","`network.allowInsecureHttp` through `--allow-private` and `--allow-insecure-http`.","Private HTTP requires both flags, private HTTPS only `--allow-private`, and public HTTP","only `--allow-insecure-http`; exact loopback HTTP remains available without either.","`a2a test` and `a2a call` also accept the flags as one-shot authorization. Runtime","reconciliation, registration fingerprints, discovery, and execution preserve the same","configured authority, so revocation takes effect on the next reconciliation.","","Outbound discovery accepts A2A 1.0 JSON-RPC only. The selected interface must stay on","the same trusted origin as its Agent Card. One complete advertised security alternative","must be satisfiable. Built-in outbound profiles support HTTP Bearer compatibility or","OAuth 2.0 Client Credentials from an external Authorization Server; Card/RPC/token","origins remain separate. `a2a test` plans security without obtaining an access token.","Safe fetch also enforces TLS, DNS/private-address, redirect, credential, timeout,","content-type, and size policy.","","Inbound fixed Bearer remains available. For dynamic production access tokens KodaX is","an OAuth Resource Server: it validates external-issuer RFC 9068 JWTs and JWKS, but does","not issue or sign tokens. Every authentication adapter supplies a stable `securityRealm`;","task ownership hashes realm, subject, and tenant so authority changes fail closed.","Pre-realm durable tasks stay inaccessible during normal serving. Stop the server, run","`kodax a2a migrate-tasks` for a dry-run, then apply with --confirm-server-stopped;","custom hosts use `migrateA2ALegacyTaskOwners()` with exact mappings. KodaX never","guesses an owner or uses heuristic dual-read fallback.","","The built-in listener is loopback-only; public deployment wraps `handle()` in host-owned","TLS and authorization. INPUT_REQUIRED resumes the original Runtime run. Task history and","listing are bounded, terminal retention prunes oldest records, and pagination uses a","stable opaque cursor. Only explicitly admitted artifacts are published: staged outputs,","successful admitted Skill-script outputs, negotiated remote file Parts, or authorized URI","references. Ordinary workspace writes, local paths, prompts, credentials, and raw tool","traffic are never exposed implicitly."].join(`
31
31
  `),sources:[{label:"A2A SDK guide",path:"docs/SDK_EMBEDDER_GUIDE.md"},{label:"A2A client",path:"src/a2a/client-executor.ts"},{label:"A2A server",path:"src/a2a/server.ts"},{label:"A2A CLI",path:"src/integration-cli.ts"}],nextTopics:["config","sdk","agents"]},{id:"repo-intelligence",title:"Repo intelligence",aliases:["repointel","repo intel","code intelligence","\u4ED3\u5E93\u667A\u80FD","\u4EE3\u7801\u5E93\u7406\u89E3"],summary:"What the repo-intelligence tools do and their limits.",body:["Repo intelligence gives the agent a repo-scope map (overview, symbols, module/flow","capsules, change-impact) to narrow scope before large reviews/refactors \u2014 cached under","<repo>/.agent/repo-intelligence/. Modes via repoIntelligenceMode / KODAX_REPO_INTELLIGENCE","(auto/off/light/full). It is batch, pre-task context \u2014 not a realtime type checker."].join(`
32
32
  `),sources:[{label:"repo-intelligence",path:"packages/coding/src/repo-intelligence/"}],nextTopics:["tools","config","sessions"]},{id:"sessions",title:"Sessions & goals",aliases:["session","resume","goal","\u4F1A\u8BDD","\u6062\u590D","\u76EE\u6807"],summary:"resume / -c / -r, per-project storage, and /goal.",body:["Continue work: `kodax -c` selects the most recent non-empty session in the project,","skipping newer zero-message ACP/bootstrap placeholders; `kodax -r` lets you pick one.","The same non-empty selection rule applies to classic and Ink REPL startup plus one-shot","and SDK auto-resume. An explicit session id always wins. Interactive resume restores the","saved workspace runtime, messages, UI history, lineage, artifacts, extensions, title,","tag, and session id before the next turn. Long sessions compact automatically to stay","within context. Sessions are stored per project. Set a","persistent objective with the /goal","command; the agent tracks it and a verifier checks completion.","If a provider starts rejecting the current history (oversized or locked session), /recover","forks a fresh session seeded from a compact local summary instead of replaying raw history.","Clean duplicate ghost sessions with `kodax sessions dedupe` (dry-run first; reversible archive).","SDK readers should prefer readSessionCapture() when active context and full transcript must","come from one immutable storage boundary. readFullTranscript() and readSessionCapture() are","deadline/cancellation-aware, read-only, and fail closed on corruption or version drift; they","never resume, migrate, repair, or recover a Session. exportSessionBundle() returns the exact","main and sidecar bytes plus hashes and compatibility diagnostics for support or recovery.","Use readConversationHistory() for an ordinary chat view. It folds only compaction copies","proven equivalent by persisted provenance or unambiguous lineage, reports resolved / partial /","ambiguous status, and preserves unresolved candidates. loadSession() remains active model","context; readFullTranscript() remains raw append-order audit. Do not fold by role, content,","timestamp, turnId, or logicalId alone."].join(`
33
33
  `),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(`
34
34
  `),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.","","When the current user semantically asks KodaX to remember a durable claim or correct","prior Memory, the root Action LLM may call memory_intent with an exact quote from that","user turn. This records authoritative intent for the post-episode governed reviewer; it",'does not write Memory directly. Ordinary narration such as "I remember yesterday", quoted',"examples, and temporary task instructions are not durable intent. The structured episode","review remains the fallback when the model omits the tool. Only an applied host receipt and","client notice justify saying that Memory was updated; a tool success means captured only,","before any durable review job exists.","If the root task is later cancelled, only that exact host-bound intent may still enter","durable review; observations, checks, and lessons from the cancelled task are discarded.","Foreground completion waits for durable enqueue, not semantic review. Same-process drains","are best effort and a later run recovers any persisted remainder.","","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|pending|show|approve|reject|curate|rebuild|open to inspect and govern the","project memory plane. Durable changes still require proposal/preview/fingerprint/apply;","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(`
35
35
  `),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(`
36
- `),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.","","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.","","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(`
36
+ `),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.","","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.","","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(`
37
37
  `),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:"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(`
38
38
  `),sources:[{label:"doctor CLI",path:"src/kodax_doctor.ts"}],nextTopics:["doctor","providers","config"]}],Gd=Object.freeze(Object.fromEntries(Jw.map(e=>[e.id,e])));var Qw="KodaX";function Zw(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(Zw,"normalizeInjected");function eb(e,t){let n=new Map,r=[],o=t??zd;for(let s of o){if(n.has(s))continue;let a=Gd[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,Zw(s));return{ids:r,byId:n}}i(eb,"buildEntries");function tb(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(tb,"scopeAnchor");function Yd(e){return e.toLowerCase().split(/[^a-z0-9一-鿿]+/u).filter(t=>t.length>0)}i(Yd,"tokenize");function nb(e,t,n){return e.includes(n)?t.get(n):void 0}i(nb,"findByExactId");function rb(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(rb,"findByAlias");function ob(e,t,n){if(t.length===0)return 0;let r=new Set(Yd([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(ob,"scoreTopic");function Xd(e,t,n){let r=Yd(n),o=n.toLowerCase();return e.map(s=>t.get(s)).map(s=>({topic:s,score:ob(s,r,o)})).filter(s=>s.score>0).sort((s,a)=>a.score-s.score).map(s=>s.topic)}i(Xd,"rankByQuery");function Vd(e,t){return{matchedTopic:e.id,title:e.title,content:`${tb(e.id,t)}
39
39
 
@@ -303,7 +303,7 @@ TODO: replace with the agent's full operating instructions.`,tools:[],reasoning:
303
303
  `)}catch(n){return`[Tool Error] stage_agent_construction: ${n.message}`}}i(xh,"toolStageAgentConstruction");async function kh(e,t){try{let n=Zt(e,"name"),r=Zt(e,"version"),o=await Yt(n,r);if(!o)return`[Tool Error] test_agent: no staged artifact found for ${n}@${r}.`;if(o.kind!=="agent")return`[Tool Error] test_agent: ${n}@${r} has kind='${o.kind}', expected 'agent'. Use test_tool for tool artifacts.`;if(o.status==="revoked")return`[Tool Error] test_agent: ${n}@${r} is revoked. Bump the version and re-stage.`;let s={artifact:o,stagedAt:Date.now()},a=await br(s);return wh(a)}catch(n){return`[Tool Error] test_agent: ${n.message}`}}i(kh,"toolTestAgent");async function _h(e,t){try{let n=Zt(e,"name"),r=Zt(e,"version"),o=await Yt(n,r);if(!o)return`[Tool Error] activate_agent: no artifact found for ${n}@${r}. Stage and test it first.`;if(o.kind!=="agent")return`[Tool Error] activate_agent: ${n}@${r} has kind='${o.kind}', expected 'agent'. Use activate_tool for tool artifacts.`;if(o.status==="revoked")return`[Tool Error] activate_agent: ${n}@${r} is revoked. Bump the version and re-stage.`;let s={artifact:o,stagedAt:Date.now()};return await vr(s),[`activated: ${n}@${r} (kind=agent)`,"Resolver now exposes the agent at this name; subsequent Runner.run calls can resolve it."].join(`
304
304
  `)}catch(n){return`[Tool Error] activate_agent: ${n.message}`}}i(_h,"toolActivateAgent");import $n from"fs/promises";import Gc from"path";var Go=336*60*60*1e3,Sh=3600*1e3;async function Th(e,t=Go,n=Date.now()){let r;try{r=await $n.readdir(e)}catch{return{scanned:0,removed:0,failed:0,bytesRemoved:0}}let o=0,s=0,a=0,c=0;for(let l of r){let d=Gc.join(e,l),u;try{u=await $n.stat(d)}catch{a+=1;continue}if(!(!u.isFile()||(o+=1,n-u.mtimeMs<=t)))try{await $n.unlink(d),s+=1,c+=u.size}catch{a+=1}}return{scanned:o,removed:s,failed:a,bytesRemoved:c}}i(Th,"cleanupExpiredToolOutputs");function Eh(e){let t=Gc.resolve(e);return process.platform==="win32"?t.toLowerCase():t}i(Eh,"normalizeArtifactPath");async function Ah(e,t,n=Go,r=Date.now()){let o;try{o=await $n.readdir(e)}catch{return{scanned:0,removed:0,failed:0,bytesRemoved:0}}let s=new Set([...t].map(Eh)),a=0,c=0,l=0,d=0;for(let u of o){let f=Gc.join(e,u);try{let p=await $n.stat(f);if(!p.isFile()||(a+=1,s.has(Eh(f))||r-p.mtimeMs<=n))continue;await $n.unlink(f),c+=1,d+=p.size}catch{l+=1}}return{scanned:a,removed:c,failed:l,bytesRemoved:d}}i(Ah,"cleanupUnreferencedToolOutputs");var zo=0,Te=null;function xT(e,t=Go,n=Date.now()){return Te||(n-zo<Sh?Promise.resolve(null):(zo=n,Te=Th(e,t,n).then(r=>(Te=null,r)).catch(()=>(Te=null,null)),Te))}i(xT,"maybeRunToolOutputGc");function kT(e,t,n=Go,r=Date.now()){return Te||(r-zo<Sh?Promise.resolve(null):(zo=r,Te=t().then(o=>Ah(e,o,n,r)).then(o=>(Te=null,o)).catch(()=>(Te=null,null)),Te))}i(kT,"maybeRunReferenceAwareToolOutputGc");var Ch=4,Rh=12*1024,Ih=4*1024,_T=192*1024,ET=64*1024;function ST(e){return{aggregateInlineTokens:Math.max(0,Math.floor(e.availableTokens)),...Oh({availableTokens:e.availableTokens,contextWindow:e.contextWindow,pressure:e.pressure,smallWindow:e.smallWindow})}}i(ST,"buildToolResultBudget");function TT(e){let t=Math.max(0,Math.floor(e.contextWindow)),n=Math.max(0,Math.floor(e.currentTokens)),r=Math.max(0,Math.floor(e.reservedResponseTokens??0)),o=$r(t,r),s=Math.max(0,o-n),a=t>0?n/t:1,c=t>0&&t<=32e3,l=RT(t,s,a,c);return{aggregateInlineTokens:s,...Oh({availableTokens:s,contextWindow:t,pressure:l,smallWindow:c})}}i(TT,"buildToolResultBudgetFromUsage");function AT(e,t){if(!t)return e;let n=Math.min(e.maxBytes,t.perResultInlineBytes);return{...e,maxBytes:n,maxLines:Math.min(e.maxLines,CT(e,n))}}i(AT,"clampToolResultPolicyToBudget");function Oh(e){if(e.pressure==="critical")return{pressure:e.pressure,contextWindow:e.contextWindow,aggregateInlineBytes:Math.max(Rh,Math.floor(e.availableTokens*Ch*.2)),perResultInlineBytes:Ih,reason:"critical_pressure"};if(e.smallWindow||e.pressure==="high"){let t=Math.max(Rh,Math.floor(e.availableTokens*Ch*.35));return{pressure:e.pressure,contextWindow:e.contextWindow,aggregateInlineBytes:t,perResultInlineBytes:Math.min(16*1024,Math.max(Ih,Math.floor(t/3))),reason:"small_window_pressure"}}return e.pressure==="medium"?{pressure:e.pressure,contextWindow:e.contextWindow,aggregateInlineBytes:96*1024,perResultInlineBytes:32*1024,reason:"normal_pressure"}:{pressure:e.pressure,contextWindow:e.contextWindow,aggregateInlineBytes:_T,perResultInlineBytes:ET,reason:"large_window"}}i(Oh,"buildCompatibilityMetadata");function CT(e,t){return Math.max(20,Math.floor(e.maxLines*(t/Math.max(1,e.maxBytes))))}i(CT,"estimateLineCap");function RT(e,t,n,r){return e<=0||t<=0||n>=.9?"critical":n>=.75?"high":n>=.55||r&&n>=.4?"medium":"low"}i(RT,"classifyPressure");var en=Object.freeze({web_search:'Discover web content when no specific URL is known \u2014 call `tool_search("web_search")` for full schema.',web_fetch:'Fetch a specific remote URL (HTML\u2192markdown, cached) \u2014 call `tool_search("web_fetch")` for full schema (includes GitHub-URL gh-CLI guidance).',code_search:'Ranked text search across the repo with noise filtering \u2014 call `tool_search("code_search")` for selection heuristics vs grep / symbol_context.',semantic_lookup:'Symbol-/module-/process-aware semantic queries against repo intelligence \u2014 call `tool_search("semantic_lookup")` for full schema and selection rules.',repo_overview:'Workspace structure snapshot \u2014 call ONCE at session start; `tool_search("repo_overview")` for full schema.',changed_scope:'List files / areas changed in current git diff \u2014 for worktree, range, and other change-set reviews. After scope, fan out independent review lanes before reading every diff. `tool_search("changed_scope")` for full schema.',module_context:'Compact module capsule (deps, entries, symbols, tests) \u2014 call `tool_search("module_context")` for full schema and selection rules vs symbol_context.',symbol_context:'Definition + callers/callees for one symbol \u2014 call `tool_search("symbol_context")` for full schema and selection rules.',process_context:'Static execution/process trace from an entry \u2014 call `tool_search("process_context")` for full schema.',impact_estimate:'Blast radius estimate BEFORE a rename or refactor \u2014 call `tool_search("impact_estimate")` for full schema (replaces guessing impact from grep).',run_workflow:'Explicitly requested Workflow execution: runs manifest + source with structured output/resume and returns a canonical Workflow actor path. `tool_search("run_workflow")` for contract.'});function Xo(e){return e in en}i(Xo,"isDeferredTool");var Qc=new WeakMap;function Lh(e,t){let n=Qc.get(e);n||(n=new Set,Qc.set(e,n)),n.add(t)}i(Lh,"unlockDeferredToolForContext");function qq(e){let t=Qc.get(e);return t?new Set(t):new Set}i(qq,"getUnlockedDeferredTools");function jh(e,t={}){let n=e.map(o=>qT(o,t.hints?.[o.name])),r=new Map;for(let o of n)for(let s of o.terms.keys())r.set(s,(r.get(s)??0)+1);return{entries:n,documentFrequency:r}}i(jh,"buildToolSearchIndex");function Fh(e,t,n){let r=typeof t=="string"?UT(t):Uh(t),o=Math.max(0,Math.floor(n));if(o===0||r.required.length===0&&r.loose.length===0)return[];let s=[];for(let a of e.entries){if(!r.required.every(u=>Nh(a,u)))continue;let l=r.loose.filter(u=>Nh(a,u));if(r.loose.length>0&&l.length===0)continue;let d=[...r.required,...l];s.push({name:a.name,score:BT(e,a,d,r.loose),matchedTerms:d})}return s.sort((a,c)=>c.score!==a.score?c.score-a.score:a.name.localeCompare(c.name)),s.slice(0,o)}i(Fh,"searchToolIndex");function UT(e){let t=[],n=[];for(let r of qh(e))r.startsWith("+")&&r.length>1?t.push(Mn(r.slice(1))):n.push(Mn(r));return Uh({required:t,loose:n})}i(UT,"parseToolSearchQuery");function qT(e,t){let n=HT(e.input_schema),r=Bh(e.name).join(" "),o=[e.name,r,t,e.description,n].filter(a=>typeof a=="string"&&a.length>0).join(" "),s=new Map;for(let a of qh(o)){let c=Mn(a);c.length!==0&&s.set(c,(s.get(c)??0)+1)}return{name:e.name,text:o.toLowerCase(),terms:s,tokenCount:Array.from(s.values()).reduce((a,c)=>a+c,0)}}i(qT,"buildEntry");function BT(e,t,n,r){let o=0,s=WT(e);for(let c of n){let l=t.terms.get(c)??(t.text.includes(c)?1:0),d=e.documentFrequency.get(c)??1,u=Math.log(1+(e.entries.length-d+.5)/(d+.5)),f=t.tokenCount>0&&s>0?1.2*(1-.75+.75*(t.tokenCount/s)):1.2;o+=u*(l*2.2/(l+f))}let a=Mn(t.name);for(let c of[...n,...r])a===c?o+=5:Bh(t.name).includes(c)?o+=2:a.includes(c)&&(o+=1);return o}i(BT,"scoreEntry");function WT(e){return e.entries.length===0?0:e.entries.reduce((t,n)=>t+n.tokenCount,0)/e.entries.length}i(WT,"averageDocumentLength");function Nh(e,t){return e.terms.has(t)||e.text.includes(t)}i(Nh,"entryMatchesTerm");function Uh(e){return{required:Dh(e.required),loose:Dh(e.loose)}}i(Uh,"normalizeQueryParts");function Dh(e){let t=[],n=new Set;for(let r of e){let o=Mn(r);o.length===0||n.has(o)||(n.add(o),t.push(o))}return t}i(Dh,"uniqueNormalized");function qh(e){return e.match(/\+?[\p{L}\p{N}_-]+/gu)??[]}i(qh,"tokenize");function Mn(e){return e.toLowerCase().replace(/[^a-z0-9\p{L}\p{N}]+/gu,"")}i(Mn,"normalizeTerm");function Bh(e){return e.split(/[_-]+/g).map(t=>Mn(t)).filter(t=>t.length>0)}i(Bh,"splitToolName");function HT(e){let t=[];return Zc(e,t,0),t.join(" ")}i(HT,"collectSchemaText");function Zc(e,t,n){if(!(n>8||e===null||e===void 0)){if(typeof e=="string"){t.push(e);return}if(typeof e=="number"||typeof e=="boolean"){t.push(String(e));return}if(Array.isArray(e)){for(let r of e)Zc(r,t,n+1);return}if(typeof e=="object")for(let[r,o]of Object.entries(e))t.push(r),Zc(o,t,n+1)}}i(Zc,"collectSchemaTextInto");var KT=5,zT=15;function GT(e){let t=e.trim();if(t.startsWith("select:"))return{mode:"select",names:t.slice(7).split(/[,\s]+/).map(c=>c.trim()).filter(c=>c.length>0),required:[],loose:[]};let n=t.split(/\s+/).filter(s=>s.length>0),r=[],o=[];for(let s of n)s.startsWith("+")&&s.length>1?r.push(s.slice(1).toLowerCase()):o.push(s.toLowerCase());return{mode:"keyword",names:[],required:r,loose:o}}i(GT,"parseQuery");function XT(e){let t=[],n=new Set;for(let r of e)n.has(r)||(n.add(r),(Xo(r)||Pn(r))&&t.push(r));return t}i(XT,"resolveSelectNames");function VT(e,t,n){let r=Object.keys(en).map(s=>Pn(s)).filter(s=>s!==void 0),o=jh(r,{hints:en});return Fh(o,{required:e,loose:t},n).map(s=>s.name)}i(VT,"searchKeywords");function YT(e){let t={description:e.description,name:e.name,parameters:e.input_schema};return`<function>${JSON.stringify(t)}</function>`}i(YT,"formatToolAsFunctionBlock");function Wh(e,t,n){if(e.length===0)return"No tools matched the query. Available deferred tools: "+Object.keys(en).join(", ")+". Use query form `select:NAME` to fetch a specific schema.";let r=[];for(let o of e){let s=Pn(o);if(!s){r.push(`<!-- ${o}: not registered (skipped) -->`);continue}Lh(t,o),r.push(YT(Gr(s,n)))}return r.join(`
305
305
  `)}i(Wh,"buildResult");function JT(e,t,n){return n?`${e}
306
- [RESULT_LIMIT_REACHED: max_results=${t}; additional tools matched. Narrow the keyword query or use \`select:NAME\` for an exact schema.]`:e}i(JT,"appendLimitMarker");var QT=i(async(e,t)=>{let n=e,r=typeof n.query=="string"?n.query:"";if(r.length===0)return"tool_search: `query` is required. Forms: `select:NAME[,NAME...]` for exact lookup, or keyword search (`+required loose terms`).";let o=typeof n.max_results=="number"&&n.max_results>0?Math.min(Math.floor(n.max_results),zT):KT,s=GT(r);if(s.mode==="select")return Wh(XT(s.names),t,t.selfManual?.productName);let a=VT(s.required,s.loose,o+1),c=a.slice(0,o),l=Wh(c,t,t.selfManual?.productName);return JT(l,o,a.length>o)},"toolSearchHandler"),Hh={name:"tool_search",description:["Fetch full schema definitions for tools whose rich descriptions are deferred behind compact search hints.","The deferred catalog includes web discovery, repo intelligence (module_context / symbol_context / impact_estimate / process_context / changed_scope / repo_overview / semantic_lookup / code_search), and run_workflow.","Use `tool_search` when a hint suggests a tool fits the task and you need the full schema (parameter shape, when-to-prefer-X, behavioral contracts) before invoking.",'Query forms: `select:ToolName` (exact, recommended) or keyword search like `"+module exploration"` (require keyword) / `"refactor impact"` (loose match, ranked).',"On the SA path, resolving a deferred tool unlocks its full description for later tool lists in the same context. On the AMA managed path, the tool list is static, so the `tool_search` result itself is the durable teaching surface."].join(" "),input_schema:{type:"object",properties:{query:{type:"string",description:"Either `select:ToolName[,ToolName...]` for exact lookup, or keyword search (`+keyword required loose terms`)."},max_results:{type:"number",description:"Maximum number of results to return (default 5, capped at 15). Ignored in `select:` mode."}},required:["query"]},handler:QT,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")};import Ae from"path";import{pathToFileURL as Yh}from"url";import{createHash as pA}from"node:crypto";import{execFile as ZT}from"child_process";import{promisify as eA}from"util";var tA=eA(ZT),nA=3e4,rA=1e4;async function Kh(e,t={}){let n=t.timeout??nA,r=t.shell??(process.platform==="win32"?"powershell":"bash"),o=r==="powershell"?["-Command",e]:["-c",e],s={PATH:process.env.PATH??"",HOME:process.env.HOME??process.env.USERPROFILE??"",LANG:process.env.LANG??"",TERM:process.env.TERM??"",...process.platform==="win32"?{SYSTEMROOT:process.env.SYSTEMROOT??"",COMSPEC:process.env.COMSPEC??"",PATHEXT:process.env.PATHEXT??""}:{},...t.env};try{let{stdout:a,stderr:c}=await tA(r,o,{timeout:n,cwd:t.cwd,env:s,windowsHide:!0});return{exitCode:0,stdout:a.trim(),stderr:c.trim()}}catch(a){let c=a&&typeof a=="object"&&"code"in a&&typeof a.code=="number"?a.code:1,l=a&&typeof a=="object"&&"stdout"in a?String(a.stdout??"").trim():"",d=a&&typeof a=="object"&&"stderr"in a?String(a.stderr??"").trim():a instanceof Error?a.message:String(a);return{exitCode:c,stdout:l,stderr:d}}}i(Kh,"exec");async function zh(e,t,n={}){let r=n.timeout??rA,o=new AbortController,s=setTimeout(()=>o.abort(),r);try{let a=await fetch(e,{method:n.method??"POST",headers:{"Content-Type":"application/json",...n.headers},body:JSON.stringify(t),signal:o.signal});clearTimeout(s);let c=await a.text().catch(()=>{});return{ok:a.ok,status:a.status,body:c}}catch(a){return clearTimeout(s),{ok:!1,status:0,body:a instanceof Error?a.message:String(a)}}}i(zh,"webhook");import We from"path";import{access as oA,readdir as iA,realpath as sA,stat as nl}from"fs/promises";import{constants as aA}from"fs";var Gh=new Set([".js",".mjs",".cjs",".ts",".mts",".cts"]),Vo=["extension.mjs","extension.js","extension.cjs","extension.mts","extension.ts","extension.cts","index.mjs","index.js","index.cjs","index.mts","index.ts","index.cts"];function rl(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}i(rl,"isMissingPathError");async function Xh(e){try{return(await nl(e)).isFile()?(await oA(e,aA.R_OK),!0):!1}catch(t){if(rl(t))return!1;throw t}}i(Xh,"isReadableFile");function kr(e){return Gh.has(We.extname(e).toLowerCase())}i(kr,"isSupportedExtensionModulePath");function cA(e=sn()){return We.join(e,"extensions")}i(cA,"getDefaultExtensionDirectory");async function ol(e){let t=We.resolve(e),n=await nl(t);if(n.isFile()){if(!kr(t))throw new Error(`Unsupported extension module "${t}". Expected one of: ${[...Gh].join(", ")}.`);return t}if(!n.isDirectory())throw new Error(`Extension path "${t}" must be a file or directory.`);for(let r of Vo){let o=We.join(t,r);if(await Xh(o))return o}throw new Error(`Extension directory "${t}" must contain one of: ${Vo.join(", ")}.`)}i(ol,"resolveExtensionEntrypoint");async function Vh(e){for(let t of Vo){let n=We.join(e,t);if(await Xh(n))return n}}i(Vh,"tryResolveDirectoryEntrypoint");async function lA(e){try{let t=await nl(e);return t.isFile()?kr(e)?We.resolve(e):void 0:t.isDirectory()?Vh(e):void 0}catch(t){if(rl(t))return;throw t}}i(lA,"tryResolveDiscoveredEntrypoint");async function dA(e){try{return await sA(e)}catch(t){return We.resolve(e)}}i(dA,"canonicalEntrypointIdentity");async function tl(e){let t=e.trim();try{return await dA(await ol(t))}catch(n){return We.resolve(t)}}i(tl,"getExtensionEntrypointIdentity");async function il(e){let t=[],n=new Set;for(let r of e){let o=r.trim();if(!o)continue;let s=await tl(o);n.has(s)||(n.add(s),t.push(o))}return t}i(il,"dedupeExtensionPathsByEntrypoint");async function s1(e,t){let n=new Set;for(let s of t){let a=s.trim();a&&n.add(await tl(a))}let r=[],o=new Set;for(let s of e){let a=s.trim();if(!a)continue;let c=await tl(a);n.has(c)||o.has(c)||(o.add(c),r.push(a))}return r}i(s1,"excludeExtensionPathsByEntrypoint");function el(e,t,n){return{path:e,reason:t,message:n}}i(el,"skippedEntry");async function uA(e){let t=We.resolve(e),n;try{n=await iA(t,{withFileTypes:!0})}catch(s){if(rl(s))return{paths:[],skipped:[]};throw s}let r=[],o=[];for(let s of n.sort((a,c)=>a.name.localeCompare(c.name))){let a=We.join(t,s.name);if(s.isFile()){kr(a)?r.push(a):o.push(el(a,"unsupported_module","File extension is not supported for KodaX runtime extensions."));continue}if(s.isDirectory()){let c=await Vh(a);c?r.push(c):o.push(el(a,"missing_entrypoint",`Directory does not contain one of: ${Vo.join(", ")}.`));continue}if(s.isSymbolicLink()){let c=await lA(a);c?r.push(c):o.push(el(a,"unsupported_target","Symlink target is not a supported extension file or package directory."))}}return{paths:r,skipped:o}}i(uA,"discoverExtensionsInDirectoryDetailed");async function fA(e){return(await uA(e)).paths}i(fA,"discoverExtensionsInDirectory");async function a1(){return fA(cA())}i(a1,"discoverDefaultExtensions");import{tsImport as mA}from"tsx/esm/api";function hA(e){return e.length===0?"unknown":e.every(t=>t===e[0])?e[0]??"unknown":"mixed"}i(hA,"combineSearchFreshness");function gA(e){let t=e.map(n=>n.revision??JSON.stringify(n.items));return pA("sha256").update(JSON.stringify(t)).digest("hex").slice(0,16)}i(gA,"combineSearchRevision");function yA(e){return e.map(t=>{if(typeof t=="string")return t;if(t instanceof Error)return t.stack??t.message;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ")}i(yA,"formatExtensionLogArgs");function Ct(e,t,n){P({source:e,level:t,message:yA(n)})}i(Ct,"emitExtensionDiagnostic");function wA(e){let t=Ae.basename(e),n=Ae.parse(t).name;return n==="extension"||n==="index"?Ae.basename(Ae.dirname(e)):t}i(wA,"getExtensionLabel");var tn=null,nn=null;function bA(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.emit=="function"&&typeof t.runHook=="function"}i(bA,"isActiveExtensionExecutionRuntime");function vA(e){let t=[];for(let n of e){let r=n.trim();!r||t.includes(r)||t.push(r)}return t}i(vA,"dedupeStrings");function Jh(e){return typeof e=="string"?{role:"user",content:e}:e}i(Jh,"normalizeQueuedMessage");function xA(e){let t={};return e.provider?.trim()&&(t.provider=e.provider.trim()),e.model?.trim()&&(t.model=e.model.trim()),t}i(xA,"normalizeModelSelection");function Ln(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return!0;if(Array.isArray(e))return e.every(Ln);if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(Ln)}i(Ln,"isJsonValue");var sl=class{static{i(this,"KodaXExtensionRuntime")}capabilityProviders=new Map;commands=new Map;eventHandlers=new Map;hookHandlers=new Map;loadedExtensions=new Map;failures=[];runtimeDisposables=[];disposedCapabilityProviders=new WeakSet;capabilityProviderUses=new WeakMap;capabilityProviderWaiters=new WeakMap;capabilityProviderDisposals=new WeakMap;runtimeLogger;config;runtimeController;nextRecordId=0;boundController=null;defaultActiveTools;defaultModelSelection={};defaultThinkingLevel;constructor(t={}){this.config=t.config??{},this.runtimeLogger={debug:i((...n)=>Ct("coding:extension","debug",n),"debug"),info:i((...n)=>Ct("coding:extension","info",n),"info"),warn:i((...n)=>Ct("coding:extension","warn",n),"warn"),error:i((...n)=>Ct("coding:extension","error",n),"error")},this.runtimeController=this.createRuntimeControllerProxy()}activate(){return tn=this,this}getDefaults(){return{activeTools:this.defaultActiveTools===void 0?void 0:[...this.defaultActiveTools],modelSelection:{...this.defaultModelSelection},thinkingLevel:this.defaultThinkingLevel}}bindController(t){let n=this.boundController;return this.boundController=t,()=>{this.boundController=n}}async dispose(){for(let t of Array.from(this.loadedExtensions.values()).reverse())await t.disposeAll();this.loadedExtensions.clear();for(let t of this.runtimeDisposables.reverse())await t();this.runtimeDisposables.length=0,this.failures.length=0,this.boundController=null,tn===this&&(tn=null),nn===this&&(nn=null)}async loadExtensions(t,n={}){let r=await il(t);for(let o of r)try{await this.loadExtension(o,{loadSource:n.loadSource,stage:n.stage??"load"})}catch(s){if(!n.continueOnError)throw s;this.runtimeLogger.warn(`Failed to load extension "${o}" during ${n.stage??"load"}:`,s instanceof Error?s.message:String(s))}}async loadExtension(t,n={}){let r=Ae.resolve(t);try{r=await ol(r);let o=this.loadedExtensions.get(r),s=n.loadSource??o?.loadSource??"api",a=await this.importExtensionModule(r),c=a.default,l=c&&typeof c=="object"&&"default"in c?c.default:void 0,d=c&&typeof c=="object"&&"activate"in c?c.activate:void 0,u=typeof c=="function"?c:typeof l=="function"?l:typeof a.activate=="function"?a.activate:typeof d=="function"?d:void 0;if(!u)throw new Error(`Extension "${r}" must export a default function or named activate() function.`);try{let f=[],p=this.createExtensionApi(r,f,s),m={path:r,label:wA(r),loadSource:s,disposeAll:i(async()=>{for(let h of f.reverse())await h()},"disposeAll")};try{let h=await u(p);typeof h=="function"&&f.push(h)}catch(h){throw await m.disposeAll(),h}if(o)try{await o.disposeAll()}catch(h){throw await m.disposeAll(),h}this.loadedExtensions.set(r,m)}catch(f){throw f}}catch(o){throw this.recordFailure(n.stage??(this.loadedExtensions.has(r)?"reload":"load"),r,this.createExtensionSource(r,n.loadSource??this.loadedExtensions.get(r)?.loadSource??"api"),o),o}}async reloadExtensions(t={continueOnError:!0}){let n=Array.from(this.loadedExtensions.keys());for(let r of n)try{await this.loadExtension(r,{loadSource:this.loadedExtensions.get(r)?.loadSource,stage:"reload"})}catch(o){if(!t.continueOnError)throw o;this.runtimeLogger.warn(`Failed to reload extension "${r}":`,o instanceof Error?o.message:String(o))}}listCapabilityProviders(){return Array.from(this.capabilityProviders.values()).map(t=>t[t.length-1]?.value).filter(t=>t!==void 0)}registerCapabilityProvider(t,n={}){let r=n.source??this.createRuntimeSource(`runtime:capability:${t.id}`,t.id),o=this.registerRecord(this.capabilityProviders,t.id,t,r,this.runtimeDisposables);return t.dispose&&this.runtimeDisposables.push(()=>this.disposeCapabilityProvider(t)),o}hasCapabilityProvider(t){return this.getCapabilityProvider(t)!==void 0}async replaceCapabilityProvider(t,n,r={}){if(n&&n.id!==t)throw new Error("Capability provider id mismatch.");let o=this.capabilityProviders.get(t)??[];if(n){let s=`runtime:${++this.nextRecordId}`,a=r.source??this.createRuntimeSource(`runtime:capability:${t}`,t);this.capabilityProviders.set(t,[{id:s,value:n,source:a}]),this.runtimeDisposables.push(()=>{this.capabilityProviders.get(t)?.[0]?.id===s&&this.capabilityProviders.delete(t)}),this.runtimeDisposables.push(()=>this.disposeCapabilityProvider(n))}else this.capabilityProviders.delete(t);for(let s of o)try{await this.disposeCapabilityProvider(s.value)}catch{let a=new Error("Previous capability provider cleanup failed after replacement.");this.recordFailure("dispose",`capability-provider:${t}`,s.source,a),this.runtimeLogger.warn(a.message)}}async reconcileExtensions(t,n){let r=await il([...t]),o=0,s=0;for(let l of r)try{await this.loadExtension(l,{loadSource:n.loadSource,stage:"reload"}),o+=1}catch{s+=1}let a=new Set(r.map(l=>Ae.resolve(l))),c=[...this.loadedExtensions.values()].filter(l=>l.loadSource===n.loadSource&&!a.has(l.path));for(let l of c)await this.unloadExtension(l.path);return{applied:o,retained:s,removed:c.length}}registerTool(t,n={}){let r=n.source??{kind:"extension",id:`runtime:tool:${t.name}`,label:t.name},o=On(t,{source:r});return this.runtimeDisposables.push(o),o}registerHook(t,n,r={}){let o=r.source??this.createRuntimeSource(`runtime:hook:${String(t)}`,String(t)),s=this.registerHookHandler(t,n,o);return this.runtimeDisposables.push(s),s}on(t,n,r={}){let o=r.source??this.createRuntimeSource(`runtime:event:${String(t)}`,String(t)),s=this.registerEventHandler(t,n,o);return this.runtimeDisposables.push(s),s}listCommands(){return Array.from(this.commands.values()).map(t=>t[t.length-1]?.value).filter(t=>t!==void 0)}getCommand(t){let n=t.trim().toLowerCase();if(n)return this.listCommands().find(r=>r.name.trim().toLowerCase()===n||(r.aliases??[]).some(o=>o.trim().toLowerCase()===n))}getDiagnostics(){let t=Array.from(this.capabilityProviders.entries()).map(([a,c])=>{let l=c[c.length-1];if(l)return{id:a,kinds:[...l.value.kinds],source:{...l.source},metadata:l.value.getDiagnostics?.()}}).filter(a=>a!==void 0).sort((a,c)=>a.id.localeCompare(c.id)),n=Array.from(this.commands.entries()).map(([a,c])=>{let l=c[c.length-1];if(l)return{name:a,aliases:l.value.aliases,description:l.value.description,usage:l.value.usage,metadata:l.value.metadata,source:{...l.source}}}).filter(a=>a!==void 0).sort((a,c)=>a.name.localeCompare(c.name)),r=et().map(a=>{let c=Jt(a),l=c[c.length-1];if(l)return{name:l.name,description:l.description,requiredParams:[...l.requiredParams],source:{...l.source},shadowedSources:c.slice(0,-1).map(d=>({...d.source}))}}).filter(a=>a!==void 0).sort((a,c)=>a.name.localeCompare(c.name)),o=Array.from(this.loadedExtensions.values()).map(a=>{let c=this.boundController?Object.keys(this.boundController.getSessionStateSnapshot(this.createExtensionSource(a.path,a.loadSource).id)).sort((d,u)=>d.localeCompare(u)):void 0,l=this.boundController?this.boundController.listSessionRecords(this.createExtensionSource(a.path,a.loadSource).id).reduce((d,u)=>(d[u.type]=(d[u.type]??0)+1,d),{}):void 0;return{path:a.path,label:a.label,loadSource:a.loadSource,sessionStateKeys:c&&c.length>0?c:void 0,sessionRecordCounts:l&&Object.keys(l).length>0?l:void 0}}).sort((a,c)=>a.path.localeCompare(c.path)),s=Array.from(this.hookHandlers.entries()).flatMap(([a,c])=>c.map((l,d)=>({hook:a,order:d+1,source:{...l.source}}))).sort((a,c)=>{let l=a.hook.localeCompare(c.hook);return l!==0?l:a.order-c.order});return{loadedExtensions:o,capabilityProviders:t,commands:n,tools:r,hooks:s,failures:this.failures.map(a=>({...a,source:{...a.source}})),defaults:this.getDefaults()}}getCapabilityProvider(t){let n=this.capabilityProviders.get(t);if(!(!n||n.length===0))return n[n.length-1]?.value}async searchCapabilities(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o)throw new Error(`Unknown capability provider: ${t}`);return o.search?(await this.emit("capability:search",{providerId:t,query:n,kind:r.kind,limit:r.limit}),this.withCapabilityProvider(o,()=>o.search(n,r))):[]}async searchCapabilitySnapshot(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o)throw new Error(`Unknown capability provider: ${t}`);return await this.emit("capability:search",{providerId:t,query:n,kind:r.kind}),o.searchSnapshot?this.withCapabilityProvider(o,()=>o.searchSnapshot(n,r)):{items:o.search?await this.withCapabilityProvider(o,()=>o.search(n,r)):[],complete:!1,freshness:"unknown"}}async describeCapability(t,n){let r=this.getCapabilityProvider(t);if(!r)throw new Error(`Unknown capability provider: ${t}`);return await this.emit("capability:describe",{providerId:t,capabilityId:n}),this.withCapabilityProvider(r,()=>r.describe?.(n))}async executeCapability(t,n,r){let o=this.getCapabilityProvider(t);if(!o?.execute)throw new Error(`Capability provider "${t}" does not implement execute().`);return await this.emit("capability:invoke",{providerId:t,capabilityId:n,kind:"tool"}),this.withCapabilityProvider(o,()=>o.execute(n,r))}async readCapability(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o?.read)throw new Error(`Capability provider "${t}" does not implement read().`);return await this.emit("capability:invoke",{providerId:t,capabilityId:n,kind:"resource"}),this.withCapabilityProvider(o,()=>o.read(n,r))}async getCapabilityPrompt(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o?.getPrompt)throw new Error(`Capability provider "${t}" does not implement getPrompt().`);return await this.emit("capability:invoke",{providerId:t,capabilityId:n,kind:"prompt"}),this.withCapabilityProvider(o,()=>o.getPrompt(n,r))}async getCapabilityPromptContext(t){let n=this.getCapabilityProvider(t);if(n?.getPromptContext)return this.withCapabilityProvider(n,()=>n.getPromptContext())}async refreshCapabilityProviders(t){if(t){let n=this.getCapabilityProvider(t);if(!n)throw new Error(`Unknown capability provider: ${t}`);await this.emit("capability:refresh",{providerId:t}),await n.refresh?.();return}for(let n of this.listCapabilityProviders())await this.emit("capability:refresh",{providerId:n.id}),await n.refresh?.()}async hydrateSession(t){let n=this.hookHandlers.get("session:hydrate");if(!n||n.length===0)return;let r=this.boundController;if(!r)throw new Error("Session hydration requires an active KodaX session binding.");for(let o of n)try{let s=o.source,a=i((c,l)=>{let d=new Error(l);this.recordFailure("persistence",c,s,d),this.runtimeLogger.warn(l)},"warnPersistence");await o.value({sessionId:t,getState:i(c=>r.getSessionState(s.id,c),"getState"),setState:i((c,l)=>{if(l!==void 0&&!Ln(l)){a(`sessionState:${c}`,`Ignoring non-JSON session state for "${s.label}" key "${c}".`);return}r.setSessionState(s.id,c,l)},"setState"),listRecords:i(c=>r.listSessionRecords(s.id,c),"listRecords"),appendRecord:i((c,l,d)=>{let u=c.trim();if(!u){a("sessionRecord",`Ignoring session record with an empty type for "${s.label}".`);return}if(l!==void 0&&!Ln(l)){a(`sessionRecord:${u}`,`Ignoring non-JSON session record "${u}" for "${s.label}".`);return}return r.appendSessionRecord(s.id,u,l,d)},"appendRecord"),clearRecords:i(c=>r.clearSessionRecords(s.id,c),"clearRecords")})}catch(s){this.recordFailure("hook","session:hydrate",o.source,s),this.runtimeLogger.warn('Extension hook failed for "session:hydrate":',s instanceof Error?s.message:String(s))}}async emit(t,n){let r=this.eventHandlers.get(t);if(!(!r||r.length===0))for(let o of r)try{await o.value(n)}catch(s){this.recordFailure("event",t,o.source,s),this.runtimeLogger.warn(`Extension event handler failed for "${t}":`,s instanceof Error?s.message:String(s))}}async runHook(t,n){let r=this.hookHandlers.get(t);if(!(!r||r.length===0))for(let o of r)try{let s=await o.value(n);if(s!==void 0)return s}catch(s){this.recordFailure("hook",t,o.source,s),this.runtimeLogger.warn(`Extension hook failed for "${t}":`,s instanceof Error?s.message:String(s))}}createExtensionSource(t,n="api"){return{kind:"extension",id:`${n}:extension:${t}`,label:Ae.basename(t),path:t}}createRuntimeSource(t,n){return{kind:"runtime",id:t,label:n}}recordFailure(t,n,r,o){this.failures.push({stage:t,target:n,message:o instanceof Error?o.message:String(o),occurredAt:new Date().toISOString(),source:{...r}}),this.failures.length>50&&this.failures.shift()}createExtensionApi(t,n,r="api"){let o=this.createLogger(t),s=this.createExtensionSource(t,r);return{registerTool:i(a=>{let c=On(a,{source:s});return n.push(c),c},"registerTool"),getTool:i(a=>Se(a),"getTool"),getBuiltinTool:i(a=>Xc(a),"getBuiltinTool"),registerModelProvider:i(a=>{let c=ki(a.name,a.factory);return n.push(c),c},"registerModelProvider"),registerCapabilityProvider:i(a=>{let c=this.registerRecord(this.capabilityProviders,a.id,a,s,n);return a.dispose&&n.push(()=>a.dispose?.()),c},"registerCapabilityProvider"),registerCommand:i(a=>this.registerRecord(this.commands,a.name,a,s,n),"registerCommand"),registerSkillPath:i(a=>{let c=Ae.isAbsolute(a)?a:Ae.resolve(Ae.dirname(t),a),l=Vl(c);return n.push(l),l},"registerSkillPath"),registerAgent:i(async(a,c)=>{let l=pe({name:a,content:c}),d=new Map(Pe().map(m=>[m.name,m])),u=await ce.admit(l,{activatedAgents:d});if(!u.ok)throw new Error(`[extension:${s.id}] registerAgent("${a}") rejected by admission: ${u.reason}`);let f={kind:"agent",name:a,version:"0.0.0-extension",content:c,status:"active",createdAt:Date.now(),testedAt:Date.now(),activatedAt:Date.now()},p=Me(f,{bindings:u.handle.invariantBindings,manifest:u.handle.manifest,source:"extension"});return n.push(p),p},"registerAgent"),on:i((a,c)=>{let l=this.registerEventHandler(a,c,s);return n.push(l),l},"on"),hook:i((a,c)=>{let l=this.registerHookHandler(a,c,s);return n.push(l),l},"hook"),logger:o,config:this.config,runtime:this.createExtensionApiRuntimeController(s,o,n),persistence:td(s.id),exec:Kh,webhook:zh}}createLogger(t){let r=`coding:extension:${Ae.basename(t)}`;return{debug:i((...o)=>Ct(r,"debug",o),"debug"),info:i((...o)=>Ct(r,"info",o),"info"),warn:i((...o)=>Ct(r,"warn",o),"warn"),error:i((...o)=>Ct(r,"error",o),"error")}}createRuntimeControllerProxy(){return{queueUserMessage:i(t=>{let n=this.boundController;if(!n)throw new Error("No active KodaX session is bound to the extension runtime.");n.queueUserMessage(Jh(t))},"queueUserMessage"),getSessionState:i((t,n)=>this.boundController?.getSessionState(t,n),"getSessionState"),setSessionState:i((t,n,r)=>{let o=this.boundController;if(!o)throw new Error("Session state is only available while a KodaX session is active.");o.setSessionState(t,n,r)},"setSessionState"),getSessionStateSnapshot:i(t=>this.boundController?this.boundController.getSessionStateSnapshot(t):{},"getSessionStateSnapshot"),appendSessionRecord:i((t,n,r,o)=>{let s=this.boundController;if(!s)throw new Error("Session records are only available while a KodaX session is active.");return s.appendSessionRecord(t,n,r,o)},"appendSessionRecord"),listSessionRecords:i((t,n)=>this.boundController?this.boundController.listSessionRecords(t,n):[],"listSessionRecords"),clearSessionRecords:i((t,n)=>{let r=this.boundController;if(!r)throw new Error("Session records are only available while a KodaX session is active.");return r.clearSessionRecords(t,n)},"clearSessionRecords"),getActiveTools:i(()=>this.boundController?this.boundController.getActiveTools():this.defaultActiveTools===void 0?et():[...this.defaultActiveTools],"getActiveTools"),setActiveTools:i(t=>{let n=vA(t);if(this.boundController){this.boundController.setActiveTools(n);return}this.defaultActiveTools=n},"setActiveTools"),getModelSelection:i(()=>this.boundController?this.boundController.getModelSelection():{...this.defaultModelSelection},"getModelSelection"),setModelSelection:i(t=>{let n=xA(t);if(this.boundController){this.boundController.setModelSelection(n);return}this.defaultModelSelection=n},"setModelSelection"),getThinkingLevel:i(()=>this.boundController?.getThinkingLevel()??this.defaultThinkingLevel,"getThinkingLevel"),setThinkingLevel:i(t=>{if(this.boundController){this.boundController.setThinkingLevel(t);return}this.defaultThinkingLevel=t},"setThinkingLevel")}}createExtensionApiRuntimeController(t,n,r){let o=!1,s,a=!1,c={},l=!1,d,u=i(()=>{o||this.boundController||(o=!0,s=this.defaultActiveTools===void 0?void 0:[...this.defaultActiveTools],r.push(()=>{this.defaultActiveTools=s===void 0?void 0:[...s]}))},"captureActiveToolsRestore"),f=i(()=>{a||this.boundController||(a=!0,c={...this.defaultModelSelection},r.push(()=>{this.defaultModelSelection={...c}}))},"captureModelSelectionRestore"),p=i(()=>{l||this.boundController||(l=!0,d=this.defaultThinkingLevel,r.push(()=>{this.defaultThinkingLevel=d}))},"captureThinkingLevelRestore"),m=i((h,g)=>{let w=new Error(g);this.recordFailure("persistence",h,t,w),n.warn(g)},"recordPersistenceFailure");return{queueUserMessage:i(h=>this.runtimeController.queueUserMessage(Jh(h)),"queueUserMessage"),getSessionState:i(h=>this.runtimeController.getSessionState(t.id,h),"getSessionState"),setSessionState:i((h,g)=>{if(g!==void 0&&!Ln(g)){m(`sessionState:${h}`,`Ignoring non-JSON session state for "${t.label}" key "${h}".`);return}this.runtimeController.setSessionState(t.id,h,g)},"setSessionState"),appendSessionRecord:i((h,g,w)=>{let y=h.trim();if(!y){m("sessionRecord",`Ignoring session record with an empty type for "${t.label}".`);return}if(g!==void 0&&!Ln(g)){m(`sessionRecord:${y}`,`Ignoring non-JSON session record "${y}" for "${t.label}".`);return}return this.runtimeController.appendSessionRecord(t.id,y,g,w)},"appendSessionRecord"),listSessionRecords:i(h=>this.runtimeController.listSessionRecords(t.id,h),"listSessionRecords"),clearSessionRecords:i(h=>this.runtimeController.clearSessionRecords(t.id,h),"clearSessionRecords"),getActiveTools:i(()=>this.runtimeController.getActiveTools(),"getActiveTools"),setActiveTools:i(h=>{u(),this.runtimeController.setActiveTools(h)},"setActiveTools"),getModelSelection:i(()=>this.runtimeController.getModelSelection(),"getModelSelection"),setModelSelection:i(h=>{f(),this.runtimeController.setModelSelection(h)},"setModelSelection"),getThinkingLevel:i(()=>this.runtimeController.getThinkingLevel(),"getThinkingLevel"),setThinkingLevel:i(h=>{p(),this.runtimeController.setThinkingLevel(h)},"setThinkingLevel")}}registerRecord(t,n,r,o,s){let a=`runtime:${++this.nextRecordId}`,c=t.get(n)??[];t.set(n,[...c,{id:a,value:r,source:o}]);let l=i(()=>{let u=(t.get(n)??[]).filter(f=>f.id!==a);u.length===0?t.delete(n):t.set(n,u)},"dispose");return s.push(l),l}async disposeCapabilityProvider(t){let n=this.capabilityProviderDisposals.get(t);if(n)return n;let r=(async()=>{(this.capabilityProviderUses.get(t)??0)>0&&await new Promise(o=>{let s=this.capabilityProviderWaiters.get(t)??new Set;s.add(o),this.capabilityProviderWaiters.set(t,s)}),!this.disposedCapabilityProviders.has(t)&&(this.disposedCapabilityProviders.add(t),await t.dispose?.())})();this.capabilityProviderDisposals.set(t,r);try{await r}catch(o){throw this.capabilityProviderDisposals.delete(t),o}}async withCapabilityProvider(t,n){this.capabilityProviderUses.set(t,(this.capabilityProviderUses.get(t)??0)+1);try{return await n()}finally{let r=(this.capabilityProviderUses.get(t)??1)-1;if(r>0)this.capabilityProviderUses.set(t,r);else{this.capabilityProviderUses.delete(t);let o=this.capabilityProviderWaiters.get(t);this.capabilityProviderWaiters.delete(t);for(let s of o??[])s()}}}registerEventHandler(t,n,r){let o=`runtime:${++this.nextRecordId}`,s=this.eventHandlers.get(t)??[];return s.push({id:o,value:n,source:r}),this.eventHandlers.set(t,s),()=>{let a=this.eventHandlers.get(t);if(!a)return;let c=a.filter(l=>l.id!==o);if(c.length===0){this.eventHandlers.delete(t);return}this.eventHandlers.set(t,c)}}registerHookHandler(t,n,r){let o=`runtime:${++this.nextRecordId}`,s=this.hookHandlers.get(t)??[];return s.push({id:o,value:n,source:r}),this.hookHandlers.set(t,s),()=>{let a=this.hookHandlers.get(t);if(!a)return;let c=a.filter(l=>l.id!==o);if(c.length===0){this.hookHandlers.delete(t);return}this.hookHandlers.set(t,c)}}async unloadExtension(t){let n=this.loadedExtensions.get(t);n&&(await n.disposeAll(),this.loadedExtensions.delete(t))}async importExtensionModule(t){let n=Ae.extname(t).toLowerCase();if(!kr(t))throw new Error(`Unsupported extension module "${t}". FEATURE_034 currently loads .js/.mjs/.cjs/.ts/.mts/.cts files.`);if([".js",".mjs",".cjs"].includes(n)){let r=new URL(Yh(t).href);return r.searchParams.set("kodax_ext_reload",`${Date.now()}:${Math.random()}`),import(r.href)}if([".ts",".mts",".cts"].includes(n))return mA(Yh(t).href,{parentURL:import.meta.url});throw new Error(`Unsupported extension module "${t}". FEATURE_034 currently loads .js/.mjs/.cjs/.ts/.mts/.cts files.`)}},al=class{static{i(this,"CombinedExtensionRuntime")}primary;secondary;constructor(t,n){this.primary=t,this.secondary=n}getDefaults(){let t=this.primary.getDefaults(),n=this.secondary.getDefaults();return{activeTools:t.activeTools??n.activeTools,modelSelection:{...n.modelSelection,...t.modelSelection},thinkingLevel:t.thinkingLevel??n.thinkingLevel}}hasCapabilityProvider(t){return this.primary.hasCapabilityProvider(t)||this.secondary.hasCapabilityProvider(t)}bindController(t){let n=[this.secondary.bindController(t),this.primary.bindController(t)];return()=>{for(let r of n.reverse())r()}}async hydrateSession(t){await this.secondary.hydrateSession(t),await this.primary.hydrateSession(t)}async runHook(t,n){let r=await this.secondary.runHook(t,n);return r!==void 0?r:this.primary.runHook(t,n)}async emit(t,n){await this.secondary.emit(t,n),await this.primary.emit(t,n)}async searchCapabilities(t,n,r={}){let o=[],s;for(let a of[this.primary,this.secondary])try{o.push(...await a.searchCapabilities(t,n,r))}catch(c){if(!this.shouldTryNextCapabilityRuntime(c,t))throw c;s??=c}if(o.length===0&&s)throw s;return typeof r.limit=="number"?o.slice(0,r.limit):o}async searchCapabilitySnapshot(t,n,r={}){let o=[],s;for(let l of[this.primary,this.secondary])try{o.push(await l.searchCapabilitySnapshot(t,n,r))}catch(d){if(!this.shouldTryNextCapabilityRuntime(d,t))throw d;s??=d}if(o.length===0&&s)throw s;let a=new Set;return{items:o.flatMap(l=>l.items).filter(l=>{let d=l&&typeof l=="object"&&!Array.isArray(l)?l.id:void 0;return typeof d!="string"?!0:a.has(d)?!1:(a.add(d),!0)}),revision:gA(o),complete:o.every(l=>l.complete),freshness:hA(o.map(l=>l.freshness)),failures:o.flatMap(l=>l.failures??[])}}describeCapability(t,n){return this.firstCapabilityResult(t,[()=>this.primary.describeCapability(t,n),()=>this.secondary.describeCapability(t,n)])}executeCapability(t,n,r){return this.firstCapabilityResult(t,[()=>this.primary.executeCapability(t,n,r),()=>this.secondary.executeCapability(t,n,r)])}readCapability(t,n,r={}){return this.firstCapabilityResult(t,[()=>this.primary.readCapability(t,n,r),()=>this.secondary.readCapability(t,n,r)])}getCapabilityPrompt(t,n,r={}){return this.firstCapabilityResult(t,[()=>this.primary.getCapabilityPrompt(t,n,r),()=>this.secondary.getCapabilityPrompt(t,n,r)])}async getCapabilityPromptContext(t){return(await Promise.all([this.secondary.getCapabilityPromptContext(t),this.primary.getCapabilityPromptContext(t)])).filter(o=>typeof o=="string"&&o.trim().length>0).join(`
306
+ [RESULT_LIMIT_REACHED: max_results=${t}; additional tools matched. Narrow the keyword query or use \`select:NAME\` for an exact schema.]`:e}i(JT,"appendLimitMarker");var QT=i(async(e,t)=>{let n=e,r=typeof n.query=="string"?n.query:"";if(r.length===0)return"tool_search: `query` is required. Forms: `select:NAME[,NAME...]` for exact lookup, or keyword search (`+required loose terms`).";let o=typeof n.max_results=="number"&&n.max_results>0?Math.min(Math.floor(n.max_results),zT):KT,s=GT(r);if(s.mode==="select")return Wh(XT(s.names),t,t.selfManual?.productName);let a=VT(s.required,s.loose,o+1),c=a.slice(0,o),l=Wh(c,t,t.selfManual?.productName);return JT(l,o,a.length>o)},"toolSearchHandler"),Hh={name:"tool_search",description:["Fetch full schema definitions for tools whose rich descriptions are deferred behind compact search hints.","The deferred catalog includes web discovery, repo intelligence (module_context / symbol_context / impact_estimate / process_context / changed_scope / repo_overview / semantic_lookup / code_search), and run_workflow.","Use `tool_search` when a hint suggests a tool fits the task and you need the full schema (parameter shape, when-to-prefer-X, behavioral contracts) before invoking.",'Query forms: `select:ToolName` (exact, recommended) or keyword search like `"+module exploration"` (require keyword) / `"refactor impact"` (loose match, ranked).',"On the SA path, resolving a deferred tool unlocks its full description for later tool lists in the same context. On the AMA managed path, the tool list is static, so the `tool_search` result itself is the durable teaching surface."].join(" "),input_schema:{type:"object",properties:{query:{type:"string",description:"Either `select:ToolName[,ToolName...]` for exact lookup, or keyword search (`+keyword required loose terms`)."},max_results:{type:"number",description:"Maximum number of results to return (default 5, capped at 15). Ignored in `select:` mode."}},required:["query"]},handler:QT,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")};import Ae from"path";import{pathToFileURL as Yh}from"url";import{createHash as pA}from"node:crypto";import{execFile as ZT}from"child_process";import{promisify as eA}from"util";var tA=eA(ZT),nA=3e4,rA=1e4;async function Kh(e,t={}){let n=t.timeout??nA,r=t.shell??(process.platform==="win32"?"powershell":"bash"),o=r==="powershell"?["-Command",e]:["-c",e],s={PATH:process.env.PATH??"",HOME:process.env.HOME??process.env.USERPROFILE??"",LANG:process.env.LANG??"",TERM:process.env.TERM??"",...process.platform==="win32"?{SYSTEMROOT:process.env.SYSTEMROOT??"",COMSPEC:process.env.COMSPEC??"",PATHEXT:process.env.PATHEXT??""}:{},...t.env};try{let{stdout:a,stderr:c}=await tA(r,o,{timeout:n,cwd:t.cwd,env:s,windowsHide:!0});return{exitCode:0,stdout:a.trim(),stderr:c.trim()}}catch(a){let c=a&&typeof a=="object"&&"code"in a&&typeof a.code=="number"?a.code:1,l=a&&typeof a=="object"&&"stdout"in a?String(a.stdout??"").trim():"",d=a&&typeof a=="object"&&"stderr"in a?String(a.stderr??"").trim():a instanceof Error?a.message:String(a);return{exitCode:c,stdout:l,stderr:d}}}i(Kh,"exec");async function zh(e,t,n={}){let r=n.timeout??rA,o=new AbortController,s=setTimeout(()=>o.abort(),r);try{let a=await fetch(e,{method:n.method??"POST",headers:{"Content-Type":"application/json",...n.headers},body:JSON.stringify(t),signal:o.signal});clearTimeout(s);let c=await a.text().catch(()=>{});return{ok:a.ok,status:a.status,body:c}}catch(a){return clearTimeout(s),{ok:!1,status:0,body:a instanceof Error?a.message:String(a)}}}i(zh,"webhook");import We from"path";import{access as oA,readdir as iA,realpath as sA,stat as nl}from"fs/promises";import{constants as aA}from"fs";var Gh=new Set([".js",".mjs",".cjs",".ts",".mts",".cts"]),Vo=["extension.mjs","extension.js","extension.cjs","extension.mts","extension.ts","extension.cts","index.mjs","index.js","index.cjs","index.mts","index.ts","index.cts"];function rl(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}i(rl,"isMissingPathError");async function Xh(e){try{return(await nl(e)).isFile()?(await oA(e,aA.R_OK),!0):!1}catch(t){if(rl(t))return!1;throw t}}i(Xh,"isReadableFile");function kr(e){return Gh.has(We.extname(e).toLowerCase())}i(kr,"isSupportedExtensionModulePath");function cA(e=sn()){return We.join(e,"extensions")}i(cA,"getDefaultExtensionDirectory");async function ol(e){let t=We.resolve(e),n=await nl(t);if(n.isFile()){if(!kr(t))throw new Error(`Unsupported extension module "${t}". Expected one of: ${[...Gh].join(", ")}.`);return t}if(!n.isDirectory())throw new Error(`Extension path "${t}" must be a file or directory.`);for(let r of Vo){let o=We.join(t,r);if(await Xh(o))return o}throw new Error(`Extension directory "${t}" must contain one of: ${Vo.join(", ")}.`)}i(ol,"resolveExtensionEntrypoint");async function Vh(e){for(let t of Vo){let n=We.join(e,t);if(await Xh(n))return n}}i(Vh,"tryResolveDirectoryEntrypoint");async function lA(e){try{let t=await nl(e);return t.isFile()?kr(e)?We.resolve(e):void 0:t.isDirectory()?Vh(e):void 0}catch(t){if(rl(t))return;throw t}}i(lA,"tryResolveDiscoveredEntrypoint");async function dA(e){try{return await sA(e)}catch(t){return We.resolve(e)}}i(dA,"canonicalEntrypointIdentity");async function tl(e){let t=e.trim();try{return await dA(await ol(t))}catch(n){return We.resolve(t)}}i(tl,"getExtensionEntrypointIdentity");async function il(e){let t=[],n=new Set;for(let r of e){let o=r.trim();if(!o)continue;let s=await tl(o);n.has(s)||(n.add(s),t.push(o))}return t}i(il,"dedupeExtensionPathsByEntrypoint");async function s1(e,t){let n=new Set;for(let s of t){let a=s.trim();a&&n.add(await tl(a))}let r=[],o=new Set;for(let s of e){let a=s.trim();if(!a)continue;let c=await tl(a);n.has(c)||o.has(c)||(o.add(c),r.push(a))}return r}i(s1,"excludeExtensionPathsByEntrypoint");function el(e,t,n){return{path:e,reason:t,message:n}}i(el,"skippedEntry");async function uA(e){let t=We.resolve(e),n;try{n=await iA(t,{withFileTypes:!0})}catch(s){if(rl(s))return{paths:[],skipped:[]};throw s}let r=[],o=[];for(let s of n.sort((a,c)=>a.name.localeCompare(c.name))){let a=We.join(t,s.name);if(s.isFile()){kr(a)?r.push(a):o.push(el(a,"unsupported_module","File extension is not supported for KodaX runtime extensions."));continue}if(s.isDirectory()){let c=await Vh(a);c?r.push(c):o.push(el(a,"missing_entrypoint",`Directory does not contain one of: ${Vo.join(", ")}.`));continue}if(s.isSymbolicLink()){let c=await lA(a);c?r.push(c):o.push(el(a,"unsupported_target","Symlink target is not a supported extension file or package directory."))}}return{paths:r,skipped:o}}i(uA,"discoverExtensionsInDirectoryDetailed");async function fA(e){return(await uA(e)).paths}i(fA,"discoverExtensionsInDirectory");async function a1(){return fA(cA())}i(a1,"discoverDefaultExtensions");import{tsImport as mA}from"tsx/esm/api";function hA(e){return e.length===0?"unknown":e.every(t=>t===e[0])?e[0]??"unknown":"mixed"}i(hA,"combineSearchFreshness");function gA(e){let t=e.map(n=>n.revision??JSON.stringify(n.items));return pA("sha256").update(JSON.stringify(t)).digest("hex").slice(0,16)}i(gA,"combineSearchRevision");function yA(e){return e.map(t=>{if(typeof t=="string")return t;if(t instanceof Error)return t.stack??t.message;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ")}i(yA,"formatExtensionLogArgs");function Ct(e,t,n){P({source:e,level:t,message:yA(n)})}i(Ct,"emitExtensionDiagnostic");function wA(e){let t=Ae.basename(e),n=Ae.parse(t).name;return n==="extension"||n==="index"?Ae.basename(Ae.dirname(e)):t}i(wA,"getExtensionLabel");var tn=null,nn=null;function bA(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.emit=="function"&&typeof t.runHook=="function"}i(bA,"isActiveExtensionExecutionRuntime");function vA(e){let t=[];for(let n of e){let r=n.trim();!r||t.includes(r)||t.push(r)}return t}i(vA,"dedupeStrings");function Jh(e){return typeof e=="string"?{role:"user",content:e}:e}i(Jh,"normalizeQueuedMessage");function xA(e){let t={};return e.provider?.trim()&&(t.provider=e.provider.trim()),e.model?.trim()&&(t.model=e.model.trim()),t}i(xA,"normalizeModelSelection");function Ln(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return!0;if(Array.isArray(e))return e.every(Ln);if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(Ln)}i(Ln,"isJsonValue");var sl=class{static{i(this,"KodaXExtensionRuntime")}capabilityProviders=new Map;commands=new Map;eventHandlers=new Map;hookHandlers=new Map;loadedExtensions=new Map;failures=[];runtimeDisposables=[];disposedCapabilityProviders=new WeakSet;capabilityProviderUses=new WeakMap;capabilityProviderWaiters=new WeakMap;capabilityProviderDisposals=new WeakMap;runtimeLogger;config;runtimeController;nextRecordId=0;boundController=null;defaultActiveTools;defaultModelSelection={};defaultThinkingLevel;constructor(t={}){this.config=t.config??{},this.runtimeLogger={debug:i((...n)=>Ct("coding:extension","debug",n),"debug"),info:i((...n)=>Ct("coding:extension","info",n),"info"),warn:i((...n)=>Ct("coding:extension","warn",n),"warn"),error:i((...n)=>Ct("coding:extension","error",n),"error")},this.runtimeController=this.createRuntimeControllerProxy()}activate(){return tn=this,this}getDefaults(){return{activeTools:this.defaultActiveTools===void 0?void 0:[...this.defaultActiveTools],modelSelection:{...this.defaultModelSelection},thinkingLevel:this.defaultThinkingLevel}}bindController(t){let n=this.boundController;return this.boundController=t,()=>{this.boundController=n}}async dispose(){for(let t of Array.from(this.loadedExtensions.values()).reverse())await t.disposeAll();this.loadedExtensions.clear();for(let t of this.runtimeDisposables.reverse())await t();this.runtimeDisposables.length=0,this.failures.length=0,this.boundController=null,tn===this&&(tn=null),nn===this&&(nn=null)}async loadExtensions(t,n={}){let r=await il(t);for(let o of r)try{await this.loadExtension(o,{loadSource:n.loadSource,stage:n.stage??"load"})}catch(s){if(!n.continueOnError)throw s;this.runtimeLogger.warn(`Failed to load extension "${o}" during ${n.stage??"load"}:`,s instanceof Error?s.message:String(s))}}async loadExtension(t,n={}){let r=Ae.resolve(t);try{r=await ol(r);let o=this.loadedExtensions.get(r),s=n.loadSource??o?.loadSource??"api",a=await this.importExtensionModule(r),c=a.default,l=c&&typeof c=="object"&&"default"in c?c.default:void 0,d=c&&typeof c=="object"&&"activate"in c?c.activate:void 0,u=typeof c=="function"?c:typeof l=="function"?l:typeof a.activate=="function"?a.activate:typeof d=="function"?d:void 0;if(!u)throw new Error(`Extension "${r}" must export a default function or named activate() function.`);try{let f=[],p=this.createExtensionApi(r,f,s),m={path:r,label:wA(r),loadSource:s,disposeAll:i(async()=>{for(let h of f.reverse())await h()},"disposeAll")};try{let h=await u(p);typeof h=="function"&&f.push(h)}catch(h){throw await m.disposeAll(),h}if(o)try{await o.disposeAll()}catch(h){throw await m.disposeAll(),h}this.loadedExtensions.set(r,m)}catch(f){throw f}}catch(o){throw this.recordFailure(n.stage??(this.loadedExtensions.has(r)?"reload":"load"),r,this.createExtensionSource(r,n.loadSource??this.loadedExtensions.get(r)?.loadSource??"api"),o),o}}async reloadExtensions(t={continueOnError:!0}){let n=Array.from(this.loadedExtensions.keys());for(let r of n)try{await this.loadExtension(r,{loadSource:this.loadedExtensions.get(r)?.loadSource,stage:"reload"})}catch(o){if(!t.continueOnError)throw o;this.runtimeLogger.warn(`Failed to reload extension "${r}":`,o instanceof Error?o.message:String(o))}}listCapabilityProviders(){return Array.from(this.capabilityProviders.values()).map(t=>t[t.length-1]?.value).filter(t=>t!==void 0)}registerCapabilityProvider(t,n={}){let r=n.source??this.createRuntimeSource(`runtime:capability:${t.id}`,t.id),o=this.registerRecord(this.capabilityProviders,t.id,t,r,this.runtimeDisposables);return t.dispose&&this.runtimeDisposables.push(()=>this.disposeCapabilityProvider(t)),o}hasCapabilityProvider(t){return this.getCapabilityProvider(t)!==void 0}async replaceCapabilityProvider(t,n,r={}){if(n&&n.id!==t)throw new Error("Capability provider id mismatch.");let o=this.capabilityProviders.get(t)??[];if(n){let s=`runtime:${++this.nextRecordId}`,a=r.source??this.createRuntimeSource(`runtime:capability:${t}`,t);this.capabilityProviders.set(t,[{id:s,value:n,source:a}]),this.runtimeDisposables.push(()=>{this.capabilityProviders.get(t)?.[0]?.id===s&&this.capabilityProviders.delete(t)}),this.runtimeDisposables.push(()=>this.disposeCapabilityProvider(n))}else this.capabilityProviders.delete(t);for(let s of o)try{await this.disposeCapabilityProvider(s.value)}catch{let a=new Error("Previous capability provider cleanup failed after replacement.");this.recordFailure("dispose",`capability-provider:${t}`,s.source,a),this.runtimeLogger.warn(a.message)}}async reconcileExtensions(t,n){let r=await il([...t]),o=0,s=0;for(let l of r)try{await this.loadExtension(l,{loadSource:n.loadSource,stage:"reload"}),o+=1}catch{s+=1}let a=new Set(r.map(l=>Ae.resolve(l))),c=[...this.loadedExtensions.values()].filter(l=>l.loadSource===n.loadSource&&!a.has(l.path));for(let l of c)await this.unloadExtension(l.path);return{applied:o,retained:s,removed:c.length}}registerTool(t,n={}){let r=n.source??{kind:"extension",id:`runtime:tool:${t.name}`,label:t.name},o=On(t,{source:r});return this.runtimeDisposables.push(o),o}registerHook(t,n,r={}){let o=r.source??this.createRuntimeSource(`runtime:hook:${String(t)}`,String(t)),s=this.registerHookHandler(t,n,o);return this.runtimeDisposables.push(s),s}on(t,n,r={}){let o=r.source??this.createRuntimeSource(`runtime:event:${String(t)}`,String(t)),s=this.registerEventHandler(t,n,o);return this.runtimeDisposables.push(s),s}listCommands(){return Array.from(this.commands.values()).map(t=>t[t.length-1]?.value).filter(t=>t!==void 0)}getCommand(t){let n=t.trim().toLowerCase();if(n)return this.listCommands().find(r=>r.name.trim().toLowerCase()===n||(r.aliases??[]).some(o=>o.trim().toLowerCase()===n))}getDiagnostics(){let t=Array.from(this.capabilityProviders.entries()).map(([a,c])=>{let l=c[c.length-1];if(l)return{id:a,kinds:[...l.value.kinds],source:{...l.source},metadata:l.value.getDiagnostics?.()}}).filter(a=>a!==void 0).sort((a,c)=>a.id.localeCompare(c.id)),n=Array.from(this.commands.entries()).map(([a,c])=>{let l=c[c.length-1];if(l)return{name:a,aliases:l.value.aliases,description:l.value.description,usage:l.value.usage,metadata:l.value.metadata,source:{...l.source}}}).filter(a=>a!==void 0).sort((a,c)=>a.name.localeCompare(c.name)),r=et().map(a=>{let c=Jt(a),l=c[c.length-1];if(l)return{name:l.name,description:l.description,requiredParams:[...l.requiredParams],source:{...l.source},shadowedSources:c.slice(0,-1).map(d=>({...d.source}))}}).filter(a=>a!==void 0).sort((a,c)=>a.name.localeCompare(c.name)),o=Array.from(this.loadedExtensions.values()).map(a=>{let c=this.boundController?Object.keys(this.boundController.getSessionStateSnapshot(this.createExtensionSource(a.path,a.loadSource).id)).sort((d,u)=>d.localeCompare(u)):void 0,l=this.boundController?this.boundController.listSessionRecords(this.createExtensionSource(a.path,a.loadSource).id).reduce((d,u)=>(d[u.type]=(d[u.type]??0)+1,d),{}):void 0;return{path:a.path,label:a.label,loadSource:a.loadSource,sessionStateKeys:c&&c.length>0?c:void 0,sessionRecordCounts:l&&Object.keys(l).length>0?l:void 0}}).sort((a,c)=>a.path.localeCompare(c.path)),s=Array.from(this.hookHandlers.entries()).flatMap(([a,c])=>c.map((l,d)=>({hook:a,order:d+1,source:{...l.source}}))).sort((a,c)=>{let l=a.hook.localeCompare(c.hook);return l!==0?l:a.order-c.order});return{loadedExtensions:o,capabilityProviders:t,commands:n,tools:r,hooks:s,failures:this.failures.map(a=>({...a,source:{...a.source}})),defaults:this.getDefaults()}}getCapabilityProvider(t){let n=this.capabilityProviders.get(t);if(!(!n||n.length===0))return n[n.length-1]?.value}async searchCapabilities(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o)throw new Error(`Unknown capability provider: ${t}`);return o.search?(await this.emit("capability:search",{providerId:t,query:n,kind:r.kind,limit:r.limit}),this.withCapabilityProvider(o,()=>o.search(n,r))):[]}async searchCapabilitySnapshot(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o)throw new Error(`Unknown capability provider: ${t}`);return await this.emit("capability:search",{providerId:t,query:n,kind:r.kind}),o.searchSnapshot?this.withCapabilityProvider(o,()=>o.searchSnapshot(n,r)):{items:o.search?await this.withCapabilityProvider(o,()=>o.search(n,{...r,limit:Number.MAX_SAFE_INTEGER})):[],complete:!1,freshness:"unknown"}}async describeCapability(t,n){let r=this.getCapabilityProvider(t);if(!r)throw new Error(`Unknown capability provider: ${t}`);return await this.emit("capability:describe",{providerId:t,capabilityId:n}),this.withCapabilityProvider(r,()=>r.describe?.(n))}async executeCapability(t,n,r){let o=this.getCapabilityProvider(t);if(!o?.execute)throw new Error(`Capability provider "${t}" does not implement execute().`);return await this.emit("capability:invoke",{providerId:t,capabilityId:n,kind:"tool"}),this.withCapabilityProvider(o,()=>o.execute(n,r))}async readCapability(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o?.read)throw new Error(`Capability provider "${t}" does not implement read().`);return await this.emit("capability:invoke",{providerId:t,capabilityId:n,kind:"resource"}),this.withCapabilityProvider(o,()=>o.read(n,r))}async getCapabilityPrompt(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o?.getPrompt)throw new Error(`Capability provider "${t}" does not implement getPrompt().`);return await this.emit("capability:invoke",{providerId:t,capabilityId:n,kind:"prompt"}),this.withCapabilityProvider(o,()=>o.getPrompt(n,r))}async getCapabilityPromptContext(t){let n=this.getCapabilityProvider(t);if(n?.getPromptContext)return this.withCapabilityProvider(n,()=>n.getPromptContext())}async refreshCapabilityProviders(t){if(t){let n=this.getCapabilityProvider(t);if(!n)throw new Error(`Unknown capability provider: ${t}`);await this.emit("capability:refresh",{providerId:t}),await n.refresh?.();return}for(let n of this.listCapabilityProviders())await this.emit("capability:refresh",{providerId:n.id}),await n.refresh?.()}async hydrateSession(t){let n=this.hookHandlers.get("session:hydrate");if(!n||n.length===0)return;let r=this.boundController;if(!r)throw new Error("Session hydration requires an active KodaX session binding.");for(let o of n)try{let s=o.source,a=i((c,l)=>{let d=new Error(l);this.recordFailure("persistence",c,s,d),this.runtimeLogger.warn(l)},"warnPersistence");await o.value({sessionId:t,getState:i(c=>r.getSessionState(s.id,c),"getState"),setState:i((c,l)=>{if(l!==void 0&&!Ln(l)){a(`sessionState:${c}`,`Ignoring non-JSON session state for "${s.label}" key "${c}".`);return}r.setSessionState(s.id,c,l)},"setState"),listRecords:i(c=>r.listSessionRecords(s.id,c),"listRecords"),appendRecord:i((c,l,d)=>{let u=c.trim();if(!u){a("sessionRecord",`Ignoring session record with an empty type for "${s.label}".`);return}if(l!==void 0&&!Ln(l)){a(`sessionRecord:${u}`,`Ignoring non-JSON session record "${u}" for "${s.label}".`);return}return r.appendSessionRecord(s.id,u,l,d)},"appendRecord"),clearRecords:i(c=>r.clearSessionRecords(s.id,c),"clearRecords")})}catch(s){this.recordFailure("hook","session:hydrate",o.source,s),this.runtimeLogger.warn('Extension hook failed for "session:hydrate":',s instanceof Error?s.message:String(s))}}async emit(t,n){let r=this.eventHandlers.get(t);if(!(!r||r.length===0))for(let o of r)try{await o.value(n)}catch(s){this.recordFailure("event",t,o.source,s),this.runtimeLogger.warn(`Extension event handler failed for "${t}":`,s instanceof Error?s.message:String(s))}}async runHook(t,n){let r=this.hookHandlers.get(t);if(!(!r||r.length===0))for(let o of r)try{let s=await o.value(n);if(s!==void 0)return s}catch(s){this.recordFailure("hook",t,o.source,s),this.runtimeLogger.warn(`Extension hook failed for "${t}":`,s instanceof Error?s.message:String(s))}}createExtensionSource(t,n="api"){return{kind:"extension",id:`${n}:extension:${t}`,label:Ae.basename(t),path:t}}createRuntimeSource(t,n){return{kind:"runtime",id:t,label:n}}recordFailure(t,n,r,o){this.failures.push({stage:t,target:n,message:o instanceof Error?o.message:String(o),occurredAt:new Date().toISOString(),source:{...r}}),this.failures.length>50&&this.failures.shift()}createExtensionApi(t,n,r="api"){let o=this.createLogger(t),s=this.createExtensionSource(t,r);return{registerTool:i(a=>{let c=On(a,{source:s});return n.push(c),c},"registerTool"),getTool:i(a=>Se(a),"getTool"),getBuiltinTool:i(a=>Xc(a),"getBuiltinTool"),registerModelProvider:i(a=>{let c=ki(a.name,a.factory);return n.push(c),c},"registerModelProvider"),registerCapabilityProvider:i(a=>{let c=this.registerRecord(this.capabilityProviders,a.id,a,s,n);return a.dispose&&n.push(()=>a.dispose?.()),c},"registerCapabilityProvider"),registerCommand:i(a=>this.registerRecord(this.commands,a.name,a,s,n),"registerCommand"),registerSkillPath:i(a=>{let c=Ae.isAbsolute(a)?a:Ae.resolve(Ae.dirname(t),a),l=Vl(c);return n.push(l),l},"registerSkillPath"),registerAgent:i(async(a,c)=>{let l=pe({name:a,content:c}),d=new Map(Pe().map(m=>[m.name,m])),u=await ce.admit(l,{activatedAgents:d});if(!u.ok)throw new Error(`[extension:${s.id}] registerAgent("${a}") rejected by admission: ${u.reason}`);let f={kind:"agent",name:a,version:"0.0.0-extension",content:c,status:"active",createdAt:Date.now(),testedAt:Date.now(),activatedAt:Date.now()},p=Me(f,{bindings:u.handle.invariantBindings,manifest:u.handle.manifest,source:"extension"});return n.push(p),p},"registerAgent"),on:i((a,c)=>{let l=this.registerEventHandler(a,c,s);return n.push(l),l},"on"),hook:i((a,c)=>{let l=this.registerHookHandler(a,c,s);return n.push(l),l},"hook"),logger:o,config:this.config,runtime:this.createExtensionApiRuntimeController(s,o,n),persistence:td(s.id),exec:Kh,webhook:zh}}createLogger(t){let r=`coding:extension:${Ae.basename(t)}`;return{debug:i((...o)=>Ct(r,"debug",o),"debug"),info:i((...o)=>Ct(r,"info",o),"info"),warn:i((...o)=>Ct(r,"warn",o),"warn"),error:i((...o)=>Ct(r,"error",o),"error")}}createRuntimeControllerProxy(){return{queueUserMessage:i(t=>{let n=this.boundController;if(!n)throw new Error("No active KodaX session is bound to the extension runtime.");n.queueUserMessage(Jh(t))},"queueUserMessage"),getSessionState:i((t,n)=>this.boundController?.getSessionState(t,n),"getSessionState"),setSessionState:i((t,n,r)=>{let o=this.boundController;if(!o)throw new Error("Session state is only available while a KodaX session is active.");o.setSessionState(t,n,r)},"setSessionState"),getSessionStateSnapshot:i(t=>this.boundController?this.boundController.getSessionStateSnapshot(t):{},"getSessionStateSnapshot"),appendSessionRecord:i((t,n,r,o)=>{let s=this.boundController;if(!s)throw new Error("Session records are only available while a KodaX session is active.");return s.appendSessionRecord(t,n,r,o)},"appendSessionRecord"),listSessionRecords:i((t,n)=>this.boundController?this.boundController.listSessionRecords(t,n):[],"listSessionRecords"),clearSessionRecords:i((t,n)=>{let r=this.boundController;if(!r)throw new Error("Session records are only available while a KodaX session is active.");return r.clearSessionRecords(t,n)},"clearSessionRecords"),getActiveTools:i(()=>this.boundController?this.boundController.getActiveTools():this.defaultActiveTools===void 0?et():[...this.defaultActiveTools],"getActiveTools"),setActiveTools:i(t=>{let n=vA(t);if(this.boundController){this.boundController.setActiveTools(n);return}this.defaultActiveTools=n},"setActiveTools"),getModelSelection:i(()=>this.boundController?this.boundController.getModelSelection():{...this.defaultModelSelection},"getModelSelection"),setModelSelection:i(t=>{let n=xA(t);if(this.boundController){this.boundController.setModelSelection(n);return}this.defaultModelSelection=n},"setModelSelection"),getThinkingLevel:i(()=>this.boundController?.getThinkingLevel()??this.defaultThinkingLevel,"getThinkingLevel"),setThinkingLevel:i(t=>{if(this.boundController){this.boundController.setThinkingLevel(t);return}this.defaultThinkingLevel=t},"setThinkingLevel")}}createExtensionApiRuntimeController(t,n,r){let o=!1,s,a=!1,c={},l=!1,d,u=i(()=>{o||this.boundController||(o=!0,s=this.defaultActiveTools===void 0?void 0:[...this.defaultActiveTools],r.push(()=>{this.defaultActiveTools=s===void 0?void 0:[...s]}))},"captureActiveToolsRestore"),f=i(()=>{a||this.boundController||(a=!0,c={...this.defaultModelSelection},r.push(()=>{this.defaultModelSelection={...c}}))},"captureModelSelectionRestore"),p=i(()=>{l||this.boundController||(l=!0,d=this.defaultThinkingLevel,r.push(()=>{this.defaultThinkingLevel=d}))},"captureThinkingLevelRestore"),m=i((h,g)=>{let w=new Error(g);this.recordFailure("persistence",h,t,w),n.warn(g)},"recordPersistenceFailure");return{queueUserMessage:i(h=>this.runtimeController.queueUserMessage(Jh(h)),"queueUserMessage"),getSessionState:i(h=>this.runtimeController.getSessionState(t.id,h),"getSessionState"),setSessionState:i((h,g)=>{if(g!==void 0&&!Ln(g)){m(`sessionState:${h}`,`Ignoring non-JSON session state for "${t.label}" key "${h}".`);return}this.runtimeController.setSessionState(t.id,h,g)},"setSessionState"),appendSessionRecord:i((h,g,w)=>{let y=h.trim();if(!y){m("sessionRecord",`Ignoring session record with an empty type for "${t.label}".`);return}if(g!==void 0&&!Ln(g)){m(`sessionRecord:${y}`,`Ignoring non-JSON session record "${y}" for "${t.label}".`);return}return this.runtimeController.appendSessionRecord(t.id,y,g,w)},"appendSessionRecord"),listSessionRecords:i(h=>this.runtimeController.listSessionRecords(t.id,h),"listSessionRecords"),clearSessionRecords:i(h=>this.runtimeController.clearSessionRecords(t.id,h),"clearSessionRecords"),getActiveTools:i(()=>this.runtimeController.getActiveTools(),"getActiveTools"),setActiveTools:i(h=>{u(),this.runtimeController.setActiveTools(h)},"setActiveTools"),getModelSelection:i(()=>this.runtimeController.getModelSelection(),"getModelSelection"),setModelSelection:i(h=>{f(),this.runtimeController.setModelSelection(h)},"setModelSelection"),getThinkingLevel:i(()=>this.runtimeController.getThinkingLevel(),"getThinkingLevel"),setThinkingLevel:i(h=>{p(),this.runtimeController.setThinkingLevel(h)},"setThinkingLevel")}}registerRecord(t,n,r,o,s){let a=`runtime:${++this.nextRecordId}`,c=t.get(n)??[];t.set(n,[...c,{id:a,value:r,source:o}]);let l=i(()=>{let u=(t.get(n)??[]).filter(f=>f.id!==a);u.length===0?t.delete(n):t.set(n,u)},"dispose");return s.push(l),l}async disposeCapabilityProvider(t){let n=this.capabilityProviderDisposals.get(t);if(n)return n;let r=(async()=>{(this.capabilityProviderUses.get(t)??0)>0&&await new Promise(o=>{let s=this.capabilityProviderWaiters.get(t)??new Set;s.add(o),this.capabilityProviderWaiters.set(t,s)}),!this.disposedCapabilityProviders.has(t)&&(this.disposedCapabilityProviders.add(t),await t.dispose?.())})();this.capabilityProviderDisposals.set(t,r);try{await r}catch(o){throw this.capabilityProviderDisposals.delete(t),o}}async withCapabilityProvider(t,n){this.capabilityProviderUses.set(t,(this.capabilityProviderUses.get(t)??0)+1);try{return await n()}finally{let r=(this.capabilityProviderUses.get(t)??1)-1;if(r>0)this.capabilityProviderUses.set(t,r);else{this.capabilityProviderUses.delete(t);let o=this.capabilityProviderWaiters.get(t);this.capabilityProviderWaiters.delete(t);for(let s of o??[])s()}}}registerEventHandler(t,n,r){let o=`runtime:${++this.nextRecordId}`,s=this.eventHandlers.get(t)??[];return s.push({id:o,value:n,source:r}),this.eventHandlers.set(t,s),()=>{let a=this.eventHandlers.get(t);if(!a)return;let c=a.filter(l=>l.id!==o);if(c.length===0){this.eventHandlers.delete(t);return}this.eventHandlers.set(t,c)}}registerHookHandler(t,n,r){let o=`runtime:${++this.nextRecordId}`,s=this.hookHandlers.get(t)??[];return s.push({id:o,value:n,source:r}),this.hookHandlers.set(t,s),()=>{let a=this.hookHandlers.get(t);if(!a)return;let c=a.filter(l=>l.id!==o);if(c.length===0){this.hookHandlers.delete(t);return}this.hookHandlers.set(t,c)}}async unloadExtension(t){let n=this.loadedExtensions.get(t);n&&(await n.disposeAll(),this.loadedExtensions.delete(t))}async importExtensionModule(t){let n=Ae.extname(t).toLowerCase();if(!kr(t))throw new Error(`Unsupported extension module "${t}". FEATURE_034 currently loads .js/.mjs/.cjs/.ts/.mts/.cts files.`);if([".js",".mjs",".cjs"].includes(n)){let r=new URL(Yh(t).href);return r.searchParams.set("kodax_ext_reload",`${Date.now()}:${Math.random()}`),import(r.href)}if([".ts",".mts",".cts"].includes(n))return mA(Yh(t).href,{parentURL:import.meta.url});throw new Error(`Unsupported extension module "${t}". FEATURE_034 currently loads .js/.mjs/.cjs/.ts/.mts/.cts files.`)}},al=class{static{i(this,"CombinedExtensionRuntime")}primary;secondary;constructor(t,n){this.primary=t,this.secondary=n}getDefaults(){let t=this.primary.getDefaults(),n=this.secondary.getDefaults();return{activeTools:t.activeTools??n.activeTools,modelSelection:{...n.modelSelection,...t.modelSelection},thinkingLevel:t.thinkingLevel??n.thinkingLevel}}hasCapabilityProvider(t){return this.primary.hasCapabilityProvider(t)||this.secondary.hasCapabilityProvider(t)}bindController(t){let n=[this.secondary.bindController(t),this.primary.bindController(t)];return()=>{for(let r of n.reverse())r()}}async hydrateSession(t){await this.secondary.hydrateSession(t),await this.primary.hydrateSession(t)}async runHook(t,n){let r=await this.secondary.runHook(t,n);return r!==void 0?r:this.primary.runHook(t,n)}async emit(t,n){await this.secondary.emit(t,n),await this.primary.emit(t,n)}async searchCapabilities(t,n,r={}){let o=[],s;for(let a of[this.primary,this.secondary])try{o.push(...await a.searchCapabilities(t,n,r))}catch(c){if(!this.shouldTryNextCapabilityRuntime(c,t))throw c;s??=c}if(o.length===0&&s)throw s;return typeof r.limit=="number"?o.slice(0,r.limit):o}async searchCapabilitySnapshot(t,n,r={}){let o=[],s;for(let l of[this.primary,this.secondary])try{o.push(await l.searchCapabilitySnapshot(t,n,r))}catch(d){if(!this.shouldTryNextCapabilityRuntime(d,t))throw d;s??=d}if(o.length===0&&s)throw s;let a=new Set;return{items:o.flatMap(l=>l.items).filter(l=>{let d=l&&typeof l=="object"&&!Array.isArray(l)?l.id:void 0;return typeof d!="string"?!0:a.has(d)?!1:(a.add(d),!0)}),revision:gA(o),complete:o.every(l=>l.complete),freshness:hA(o.map(l=>l.freshness)),failures:o.flatMap(l=>l.failures??[])}}describeCapability(t,n){return this.firstCapabilityResult(t,[()=>this.primary.describeCapability(t,n),()=>this.secondary.describeCapability(t,n)])}executeCapability(t,n,r){return this.firstCapabilityResult(t,[()=>this.primary.executeCapability(t,n,r),()=>this.secondary.executeCapability(t,n,r)])}readCapability(t,n,r={}){return this.firstCapabilityResult(t,[()=>this.primary.readCapability(t,n,r),()=>this.secondary.readCapability(t,n,r)])}getCapabilityPrompt(t,n,r={}){return this.firstCapabilityResult(t,[()=>this.primary.getCapabilityPrompt(t,n,r),()=>this.secondary.getCapabilityPrompt(t,n,r)])}async getCapabilityPromptContext(t){return(await Promise.all([this.secondary.getCapabilityPromptContext(t),this.primary.getCapabilityPromptContext(t)])).filter(o=>typeof o=="string"&&o.trim().length>0).join(`
307
307
 
308
308
  `)||void 0}async refreshCapabilityProviders(t){let n=!1,r;for(let o of[this.primary,this.secondary])try{await o.refreshCapabilityProviders(t),n=!0}catch(s){if(r??=s,!t||!this.shouldTryNextCapabilityRuntime(s,t))throw s}if(!n&&r)throw r}getDiagnostics(){let t=this.primary.getDiagnostics(),n=this.secondary.getDiagnostics();return{loadedExtensions:[...n.loadedExtensions,...t.loadedExtensions].sort((r,o)=>r.path.localeCompare(o.path)),capabilityProviders:[...n.capabilityProviders,...t.capabilityProviders].sort((r,o)=>r.id.localeCompare(o.id)),commands:[...n.commands,...t.commands].sort((r,o)=>r.name.localeCompare(o.name)),tools:this.dedupeToolDiagnostics([...n.tools,...t.tools]),hooks:[...n.hooks,...t.hooks].sort((r,o)=>r.hook.localeCompare(o.hook)||r.order-o.order),failures:[...n.failures,...t.failures],defaults:this.getDefaults()}}async firstCapabilityResult(t,n){let r;for(let o of n)try{return await o()}catch(s){if(r??=s,!this.shouldTryNextCapabilityRuntime(s,t))throw s}throw r}shouldTryNextCapabilityRuntime(t,n){return t instanceof Error?t.message==="Unknown capability provider: "+n||t.message.startsWith('Capability provider "'+n+'" does not implement ')||n==="mcp"&&t.message.startsWith("Unknown MCP server:"):!1}dedupeToolDiagnostics(t){let n=new Set,r=[];for(let o of t){let s=`${o.name}\0${o.source.kind}\0${o.source.id}`;n.has(s)||(n.add(s),r.push(o))}return r.sort((o,s)=>o.name.localeCompare(s.name))}};function _1(e,t){return new al(e,t)}i(_1,"combineExtensionRuntimes");function E1(e={}){return new sl(e)}i(E1,"createExtensionRuntime");function S1(e){tn=e}i(S1,"setActiveExtensionRuntime");function T1(){return tn}i(T1,"getActiveExtensionRuntime");function A1(e){let t=nn;return nn=bA(e)?e:null,()=>{nn=t}}i(A1,"bindActiveExtensionExecutionRuntime");async function _r(e,t){await(nn??tn)?.emit(e,t)}i(_r,"emitActiveExtensionEvent");async function Yo(e,t){return(nn??tn)?.runHook(e,t)}i(Yo,"runActiveExtensionHook");var kA=new Set(["in_progress","completed","failed","skipped","cancelled","deleted"]),eg=new Set(["build","test","lint"]),_A=new Set(["init","update"]),Er=new Set(["completed","skipped","cancelled"]),Qh=3,Zh="All plan-list items are now in a terminal state (completed / skipped / cancelled). Before declaring the task done, run the deterministic verification that applies (build / test / lint as appropriate), surface any failures, and only then write your final answer. If you have already verified within this run, ignore this reminder. NEVER mention this reminder to the user.";function W(e){return JSON.stringify(e)}i(W,"jsonResult");function EA(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(EA,"isPlainObject");function SA(e,t){let n=[];return e.subject!==t.subject&&n.push("subject"),e.description!==t.description&&n.push("description"),e.status!==t.status&&n.push("status"),e.activeForm!==t.activeForm&&n.push("activeForm"),e.note!==t.note&&n.push("note"),e.evaluator!==t.evaluator&&n.push("evaluator"),e.metadata!==t.metadata&&n.push("metadata"),Object.freeze(n)}i(SA,"changedFieldsOf");function TA(e,t){if(!Array.isArray(e.items))return W({ok:!1,reason:"Invalid op:'init' payload: `items` must be an array of {id, content, activeForm?} objects (>= 1 entry)."});let n=e.items;if(n.length===0)return W({ok:!1,reason:"Invalid op:'init' payload: `items` array must contain >= 1 entry. Use op:'update' (or pass a non-empty list) instead of an empty init."});let r=new Set,o=[];for(let s=0;s<n.length;s++){let a=n[s];if(a==null||typeof a!="object")return W({ok:!1,reason:`Invalid op:'init' items[${s}]: must be an object {id, subject, description?, activeForm?}.`});let{id:c,subject:l,description:d,activeForm:u,evaluator:f}=a;if(typeof c!="string"||c.length===0)return W({ok:!1,reason:`Invalid op:'init' items[${s}].id: must be a non-empty string.`});if(r.has(c))return W({ok:!1,reason:`Invalid op:'init' items[${s}].id: duplicate id ${JSON.stringify(c)}. Each item id must be unique within the list.`});if(r.add(c),typeof l!="string"||l.length===0)return W({ok:!1,reason:`Invalid op:'init' items[${s}].subject: must be a non-empty string (brief imperative title shown in the plan-list row).`});if(d!==void 0&&typeof d!="string")return W({ok:!1,reason:`Invalid op:'init' items[${s}].description: when provided, must be a string (fuller context / work instructions; multi-line OK).`});if(u!==void 0&&typeof u!="string")return W({ok:!1,reason:`Invalid op:'init' items[${s}].activeForm: when provided, must be a string (present-continuous form, e.g. "Running tests").`});if(f!==void 0&&(typeof f!="string"||!eg.has(f)))return W({ok:!1,reason:`Invalid op:'init' items[${s}].evaluator: when provided, must be one of 'build' | 'test' | 'lint'. Got ${JSON.stringify(f)}.`});o.push({id:c,subject:l,...typeof d=="string"?{description:d}:{},...typeof u=="string"?{activeForm:u}:{},...typeof f=="string"?{evaluator:f}:{}})}return t.todoStore.init(o),W({ok:!0,count:o.length})}i(TA,"executeInitOp");async function tg(e,t){let{op:n,id:r,status:o,note:s,activeForm:a,subject:c,description:l,evaluator:d,metadata:u}=e;if(!t.todoStore)return W({ok:!1,reason:"todo_update is not active in this run (no plan list was seeded). You may continue working without calling todo_update."});let f=n===void 0?"update":n;if(typeof f!="string"||!_A.has(f))return W({ok:!1,reason:`Invalid op: ${JSON.stringify(n)}. Allowed: 'init' | 'update' (omit for default 'update').`});if(f==="init")return TA(e,t);if(typeof r!="string"||r.length===0)return W({ok:!1,reason:"Missing or invalid required parameter: id (non-empty string)."});if(o!==void 0&&(typeof o!="string"||!kA.has(o)))return W({ok:!1,reason:`Invalid status: ${JSON.stringify(o)}. Allowed: in_progress | completed | failed | skipped | cancelled | deleted.`});if(o===void 0&&c===void 0&&l===void 0&&a===void 0&&s===void 0&&d===void 0&&u===void 0)return W({ok:!1,reason:"Empty op:'update' payload. Supply at least one of: status, subject, description, activeForm, note, evaluator, metadata."});if(!t.todoStore.has(r)){let g=t.todoStore.allIds(),w=g.length===0?"no todos currently exist":g.join(", ");return W({ok:!1,reason:`Unknown todo id: ${JSON.stringify(r)}. Current valid ids: ${w}. Please retry with one of the valid ids, or skip this update.`})}if(o==="deleted"){let g=t.todoStore.getAll().find(b=>b.id===r);if(!t.todoStore.remove(r)||!g)return W({ok:!1,reason:`Failed to delete ${JSON.stringify(r)}.`});await _r("todo:deleted",{id:r,item:g,source:"tool"});let y=t.todoStore.getAll();return y.length>=Qh&&y.every(b=>Er.has(b.status))&&!Er.has(g.status)?W({ok:!0,reminder:Zh}):W({ok:!0})}if(s!==void 0&&typeof s!="string")return W({ok:!1,reason:"Invalid note: when provided, must be a string."});if(a!==void 0&&typeof a!="string")return W({ok:!1,reason:'Invalid activeForm: when provided, must be a string (present-continuous, e.g. "Running tests").'});if(c!==void 0&&(typeof c!="string"||c.length===0))return W({ok:!1,reason:"Invalid subject: when provided, must be a non-empty string (brief imperative title for the plan-list row)."});if(l!==void 0&&typeof l!="string")return W({ok:!1,reason:"Invalid description: when provided, must be a string (fuller context; pass empty string to clear)."});if(d!==void 0&&(typeof d!="string"||!eg.has(d)))return W({ok:!1,reason:`Invalid evaluator: when provided, must be one of 'build' | 'test' | 'lint'. Got ${JSON.stringify(d)}.`});if(u!=null&&!EA(u))return W({ok:!1,reason:"Invalid metadata: when provided, must be a plain object or null (to clear)."});let p=t.todoStore.getAll().find(g=>g.id===r);if(!p)return W({ok:!1,reason:`Failed to read ${JSON.stringify(r)} before patch.`});if(o==="completed"&&p.status!=="completed"){let g=await Yo("todo:before-complete",{id:r,item:p});if(typeof g=="string")return W({ok:!1,reason:g});if(g===!1)return W({ok:!1,reason:"blocked-by-hook"})}t.todoStore.patch(r,{...o!==void 0?{status:o}:{},...c!==void 0?{subject:c}:{},...l!==void 0?{description:l}:{},...a!==void 0?{activeForm:a}:{},...s!==void 0?{note:s}:{},...d!==void 0?{evaluator:d}:{},...u!==void 0?{metadata:u}:{}});let m=t.todoStore.getAll().find(g=>g.id===r);if(m){let g=SA(p,m);g.length>0&&await _r("todo:updated",{id:r,before:p,after:m,changedFields:g,source:"tool"})}let h=t.todoStore.getAll();return h.length>=Qh&&h.every(w=>Er.has(w.status))&&!(t.todoStore.getAll().filter(y=>y.id!==r).every(y=>Er.has(y.status))&&Er.has(p.status))?W({ok:!0,reminder:Zh}):W({ok:!0})}i(tg,"toolTodoUpdate");function AA(e){return{id:e.id,subject:e.subject,status:e.status,...e.description?{description:e.description}:{},...e.activeForm?{activeForm:e.activeForm}:{},...e.note?{note:e.note}:{}}}i(AA,"toDTO");function ng(e){return JSON.stringify(e)}i(ng,"jsonResult");async function rg(e,t){if(!t.todoStore)return ng({ok:!1,reason:"todo_list is not active in this run (no plan list infrastructure is wired). Either no managed task is active, or the runtime did not provide a todo store. You may continue working without querying the plan list."});let n=t.todoStore.getAll().map(AA);return ng({ok:!0,count:n.length,items:n})}i(rg,"toolTodoList");var CA=new Set(["build","test","lint"]);function nt(e){return JSON.stringify(e)}i(nt,"jsonResult");function RA(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(RA,"isPlainObject");async function og(e,t){let{subject:n,description:r,activeForm:o,evaluator:s,metadata:a}=e;if(!t.todoStore)return nt({ok:!1,reason:"todo_create is not active in this run (no plan list was seeded). You may continue working without calling todo_create."});if(typeof n!="string"||n.length===0)return nt({ok:!1,reason:'Missing or invalid required parameter: subject (non-empty string). Provide a brief imperative title for the plan-list row, e.g. "Audit handleAuth callers".'});if(r!==void 0&&typeof r!="string")return nt({ok:!1,reason:"Invalid description: when provided, must be a string (fuller context / work instructions; multi-line OK)."});if(o!==void 0&&typeof o!="string")return nt({ok:!1,reason:'Invalid activeForm: when provided, must be a string (present-continuous form, e.g. "Running tests").'});if(s!==void 0&&(typeof s!="string"||!CA.has(s)))return nt({ok:!1,reason:`Invalid evaluator: when provided, must be one of 'build' | 'test' | 'lint'. Got ${JSON.stringify(s)}.`});if(a!==void 0&&!RA(a))return nt({ok:!1,reason:"Invalid metadata: when provided, must be a plain object."});let c={subject:n,...typeof r=="string"?{description:r}:{},...typeof o=="string"?{activeForm:o}:{},...typeof s=="string"?{evaluator:s}:{},...a!==void 0?{metadata:a}:{}},l=await Yo("todo:before-create",{seed:c});if(typeof l=="string")return nt({ok:!1,reason:l});if(l===!1)return nt({ok:!1,reason:"blocked-by-hook"});let d=t.todoStore.add(c),f=t.todoStore.getAll().find(p=>p.id===d);return f&&await _r("todo:created",{id:d,item:f,source:"tool"}),nt({ok:!0,id:d})}i(og,"toolTodoCreate");function IA(e){return{id:e.id,subject:e.subject,status:e.status,...e.description?{description:e.description}:{},...e.activeForm?{activeForm:e.activeForm}:{},...e.note?{note:e.note}:{},...e.evaluator?{evaluator:e.evaluator}:{},...e.metadata?{metadata:e.metadata}:{}}}i(IA,"toDTO");function Jo(e){return JSON.stringify(e)}i(Jo,"jsonResult");async function ig(e,t){let{id:n}=e;if(!t.todoStore)return Jo({ok:!1,reason:"todo_get is not active in this run (no plan list infrastructure is wired). Either no managed task is active, or the runtime did not provide a todo store. You may continue working without querying the plan list."});if(typeof n!="string"||n.length===0)return Jo({ok:!1,reason:"Missing or invalid required parameter: id (non-empty string)."});let r=t.todoStore.getAll().find(o=>o.id===n);if(!r){let o=t.todoStore.allIds(),s=o.length===0?"no todos currently exist":o.join(", ");return Jo({ok:!1,reason:`Unknown todo id: ${JSON.stringify(n)}. Current valid ids: ${s}. Call todo_list to see the full plan, or retry with one of the valid ids.`})}return Jo({ok:!0,item:IA(r)})}i(ig,"toolTodoGet");function cl(e){if(typeof e!="string"||e.length===0)return"<no-artifact>";try{let t=JSON.parse(e),n=typeof t?.name=="string"?t.name:"<no-name>",r=typeof t?.version=="string"?t.version:"<no-version>";return`${n}@${r}`}catch{return"<unparseable>"}}i(cl,"stageArtifactPreview");function sg(e,t){if(!e)return So("<no-server>","<no-tool>",t);try{let{serverId:n,kind:r,name:o}=Ql(je(e));return So(n,`${r}:${o}`,t)}catch{return So(e,"<invalid-id>",t)}}i(sg,"mcpCapabilityPreview");function F(e,t=200,n="<missing>"){if(typeof e!="string"||e.length===0)return n;if(e.length<=t)return e;let r=Math.min(48,Math.floor((t-1)/3)),o=t-r-1;return`${e.slice(0,o)}\u2026${e.slice(-r)}`}i(F,"boundedText");function ll(e,t=8){return Array.isArray(e)?`[${e.slice(0,t).filter(r=>typeof r=="string").map(r=>F(r,120)).join(", ")}${e.length>t?", \u2026":""}]`:"[]"}i(ll,"stringArrayPreview");function ag(e,t,n){return Array.isArray(e)?`[${e.slice(0,8).map(o=>{if(o===null||typeof o!="object")return"<invalid>";let s=o,a=F(s[t],120),c=F(s[n],120,"");return c?`${a}->${c}`:a}).join(", ")}${e.length>8?", \u2026":""}]`:"[]"}i(ag,"mappedPathPreview");function OA(e){if(e===null||typeof e!="object"||Array.isArray(e))return"[]";let t=Object.keys(e);return`[${t.slice(0,16).join(", ")}${t.length>16?", \u2026":""}]`}i(OA,"objectKeysPreview");var $A=[Sp,"Author and start a bounded deterministic JavaScript protocol over the Runtime-owned Actor tree. The call returns a run_id and Workflow actor path immediately; inspect progress with list_agents, wait for critical mailbox evidence with wait_agent, read its structured WorkflowOutcome with agent_output, and stop it with interrupt_agent.","Make the Workflow acquire and inspect the real scope before analysis, then give child Agents concrete paths, constraints, evidence, and outputSchema values. Write child prompts in the same natural language as the user's request. Declared fields live on result.structured: read your declared fields off result.structured, never off the top-level result, where they are undefined and can produce an empty report.","The run(wf, args) body may use wf.runAgent, wf.parallel, wf.pipeline, wf.synthesize, wf.workflow, and wf.artifact. Use wf.pipeline for streaming stages and wf.parallel as a barrier only when a stage needs every prior result.","Do not call this tool for an ordinary review or merely because a task is parallel, partitionable, or needs synthesis. Unless the user explicitly requested a Workflow, use adaptive spawn_agent waves instead.",`Available single-phase shapes:
309
309
  ${Tp().slice(0,-1).join(`
@@ -347,7 +347,7 @@ LSP errors detected in this file, please fix:
347
347
  ${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(me.resolve(t),n).catch(()=>[]);return ti(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(me.resolve(t),n).catch(()=>null);return Eg(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(me.resolve(t),n).catch(()=>[]);return ti(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(me.resolve(t)).catch(()=>[]);return Sg(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 Tg(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(me.resolve(t),n).catch(()=>[]);return ti(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(me.resolve(t),n).catch(()=>[]);return Cg(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=me.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 Rg(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=me.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 Ig(c.flat(),"No outgoing calls found for that symbol.")}async navClient(t,n){let r=Sr(t);if(!r)return{kind:"message",message:`No language server is configured for ${me.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 ${me.basename(t)}.`};let s=me.resolve(t),a=n.gitRoot??me.dirname(s);for(let c of o){let l=ml(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(`
348
348
  `)}}async workspaceClients(t){let n=me.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=`${Ne(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??Pg)({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||!gl()))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}}},Ar,Mg=!1;function Lg(){let e=Ir()?.lsp;if(!(e===!1||e===void 0&&process.env.KODAX_LSP==="0"))return Ar||(Ar=new xl({moduleUrl:import.meta.url,debug:process.env.KODAX_DEBUG_LSP?t=>P({source:"coding:lsp",level:"debug",message:t}):void 0}),Mg||(Mg=!0,process.once("exit",()=>Ar?.killAllSync()))),Ar}i(Lg,"getDefaultLspService");async function QW(){await Ar?.shutdownAll()}i(QW,"shutdownDefaultLspService");import{createHash as VR}from"node:crypto";import{execFileSync as pR}from"child_process";import{randomUUID as mR}from"node:crypto";import hR from"fs/promises";import zg from"os";function Ng(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(Ng,"resolveTier");function kl(e,t){let n=Ir()?.modelTiers;if(e==="fast")return t?Ng(n?.fast,"KODAX_FAST_PROVIDER","KODAX_FAST_MODEL"):void 0;if(e==="deep")return Ng(n?.deep,"KODAX_DEEP_PROVIDER","KODAX_DEEP_MODEL")}i(kl,"resolveModelHintTier");function rR(){let e=process.env.KODAX_FALLBACK_PROVIDERS?.trim();return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}i(rR,"resolveFallbackChain");function Dg(e){return e instanceof bi||e instanceof vi||e instanceof wi}i(Dg,"isFallbackEligibleError");function oR(e){return e instanceof bi?"rate-limit exhausted":e instanceof vi?"network error":e instanceof wi?"provider error":e instanceof Error?e.message:String(e)}i(oR,"errorReason");async function _l(e,t,n,r){let o=e.provider??"anthropic";try{return await n(e,t)}catch(s){if(e.abortSignal?.aborted||!Dg(s))throw s;let a=rR().filter(l=>l!==o&&(r?.isProviderAllowed?.(l)??!0)),c=s;for(let l of a){r?.onFallback?.({fromProvider:o,toProvider:l,reason:oR(c)});try{return await n({...e,provider:l,model:void 0},t)}catch(d){if(e.abortSignal?.aborted||!Dg(d))throw d;c=d}}throw c}}i(_l,"invokeChildWithFallback");function iR(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(iR,"parseInlineSkillReferences");function sR(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(sR,"parseBareInlineSlashReferences");function jg(e){return Array.from(new Set(iR(e).map(t=>t.name)))}i(jg,"uniqueInlineSkillNames");function Fg(e){return Array.from(new Set(sR(e).map(t=>t.name)))}i(Fg,"uniqueBareInlineSlashNames");function ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ze,"isRecord");function aR(e){return e instanceof Error?e.message:String(e)}i(aR,"errorMessage");function ii(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}i(ii,"safeStringify");function Ug(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 ze(e);case"array":return Array.isArray(e);case"null":return e===null;default:return!0}}i(Ug,"matchesType");function cR(e,t){return e.some(n=>n===t?!0:typeof n!="object"||typeof t!="object"?!1:ii(n)===ii(t))}i(cR,"enumMatches");function ni(e,t){return e?`${e}.${t}`:t}i(ni,"joinPath");function ri(e,t,n=""){if(!ze(t))return[];let r=[],o=n||"(root)",s=t.type;if(typeof s=="string"&&!Ug(e,s))return[`${o}: expected type ${s}`];if(Array.isArray(s)&&!s.some(a=>typeof a=="string"&&Ug(e,a)))return[`${o}: expected one of types ${s.join("|")}`];if(Array.isArray(t.enum)&&!cR(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=>ri(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(ze(e)){let a=ze(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(`${ni(n,c)}: required field is missing`);if(a){for(let[c,l]of Object.entries(e))c in a&&r.push(...ri(l,a[c],ni(n,c)));if(t.additionalProperties===!1)for(let c of Object.keys(e))c in a||r.push(`${ni(n,c)}: unexpected property (additionalProperties is false)`)}}return Array.isArray(e)&&ze(t.items)&&e.forEach((a,c)=>{r.push(...ri(a,t.items,`${o}[${c}]`))}),r}i(ri,"validateAgainstSchema");var lR=["$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 oi(e,t,n){if(ze(e)){for(let r of lR)r in e&&!n.has(r)&&n.set(r,t||"(root)");if(ze(e.properties))for(let[r,o]of Object.entries(e.properties))oi(o,ni(t,r),n);if(ze(e.items)&&oi(e.items,`${t||"(root)"}[]`,n),Array.isArray(e.oneOf))for(let r of e.oneOf)oi(r,`${t||"(root)"}(oneOf)`,n);ze(e.additionalProperties)&&!n.has("additionalProperties (schema form)")&&n.set("additionalProperties (schema form)",t||"(root)")}}i(oi,"collectUnsupportedKeywords");function lH(e){if(!ze(e))return;let t=new Map;if(oi(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(lH,"assertSupportedOutputSchema");function dR(e){let t=e.indexOf("{"),n=e.indexOf("[");return t<0?n:n<0?t:Math.min(t,n)}i(dR,"firstStructureStart");function qg(e){let t=dR(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(qg,"balancedStructure");function uR(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?qg(r)??r:qg(e)}i(uR,"extractJsonCandidate");function El(e,t){let n=uR(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: ${aR(s)}`]}}let o=ri(r,t);return{ok:o.length===0,value:r,errors:o}}i(El,"evaluateStructuredOutput");function Bg(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",ii(e),"```"].join(`
349
349
  `)}i(Bg,"buildStructuredOutputInstruction");function Wg(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",ii(t),"```"].join(`
350
- `)}i(Wg,"buildStructuredOutputRepairPrompt");var Hg={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 ci(e){if(!ai(e)||!Sl(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=Kg(e.assertedCoverage);if(t===void 0)return;let n=[];for(let r of e.outcomes){let o=fR(r);if(o===void 0)return;n.push(o)}return{schemaVersion:1,outcomes:n,assertedCoverage:[...new Set(t)]}}i(ci,"parsePatternDispositionEnvelope");function Nn(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=Nn(r);if(o===void 0)return;n.push(o)}return n}if(!ai(e))return;let t={};for(let[n,r]of Object.entries(e)){let o=Nn(r);if(o===void 0)return;t[n]=o}return t}i(Nn,"toAgentMetadataValue");function fR(e){if(!ai(e)||!Sl(e,["target","disposition","evidenceRefs"])||!ai(e.target)||!Sl(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=Kg(e.evidenceRefs);if(t===void 0)return;let n=si(e.target.actorPath),r=si(e.target.turnId),o=si(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(fR,"parseOutcome");function Kg(e){let t=[];for(let n of e){let r=si(n);if(r===void 0)return;t.push(r)}return t}i(Kg,"stringArray");function si(e){if(typeof e!="string")return;let t=e.trim();return t.length>0&&t.length<=512?t:void 0}i(si,"boundedString");function ai(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ai,"isRecord");function Sl(e,t){let n=new Set(t);return Object.keys(e).every(r=>n.has(r))}i(Sl,"hasOnlyKeys");var Tl,li;async function Jg(){if(Tl)return Tl;if(!li){let e="./agent.js";li=import("./agent-5PHGNFW3.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 Tl=n,n}).catch(t=>{if(li=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 li}i(Jg,"getRunKodaX");var gR=["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(`
350
+ `)}i(Wg,"buildStructuredOutputRepairPrompt");var Hg={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 ci(e){if(!ai(e)||!Sl(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=Kg(e.assertedCoverage);if(t===void 0)return;let n=[];for(let r of e.outcomes){let o=fR(r);if(o===void 0)return;n.push(o)}return{schemaVersion:1,outcomes:n,assertedCoverage:[...new Set(t)]}}i(ci,"parsePatternDispositionEnvelope");function Nn(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=Nn(r);if(o===void 0)return;n.push(o)}return n}if(!ai(e))return;let t={};for(let[n,r]of Object.entries(e)){let o=Nn(r);if(o===void 0)return;t[n]=o}return t}i(Nn,"toAgentMetadataValue");function fR(e){if(!ai(e)||!Sl(e,["target","disposition","evidenceRefs"])||!ai(e.target)||!Sl(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=Kg(e.evidenceRefs);if(t===void 0)return;let n=si(e.target.actorPath),r=si(e.target.turnId),o=si(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(fR,"parseOutcome");function Kg(e){let t=[];for(let n of e){let r=si(n);if(r===void 0)return;t.push(r)}return t}i(Kg,"stringArray");function si(e){if(typeof e!="string")return;let t=e.trim();return t.length>0&&t.length<=512?t:void 0}i(si,"boundedString");function ai(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ai,"isRecord");function Sl(e,t){let n=new Set(t);return Object.keys(e).every(r=>n.has(r))}i(Sl,"hasOnlyKeys");var Tl,li;async function Jg(){if(Tl)return Tl;if(!li){let e="./agent.js";li=import("./agent-4UTCCMD5.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 Tl=n,n}).catch(t=>{if(li=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 li}i(Jg,"getRunKodaX");var gR=["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(`
351
351
  `),yR=["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(`
352
352
  `),Qg=4,Zg=1e4,wR=45e3,bR=40;function ey(e,t){return e.historyStorage?{id:`worker-${mR()}`,scope:"managed-task-worker",storage:e.historyStorage,...t&&t.length>0?{initialMessages:[...t]}:{}}:t&&t.length>0?{initialMessages:[...t]}:void 0}i(ey,"buildChildRunSession");function ui(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(ui,"inheritRepoIntelligenceContext");async function ty(e,t,n){if(e.length===0)return Yg;let r=e.filter(f=>f.readOnly),o=e.filter(f=>!f.readOnly),s=XR(o,n.parentRole,n.parentHarness),a=[...r,...s];if(a.length===0)return Yg;let c=[],l=[],d=n.onProgress??(()=>{});d(`Starting ${a.length} child tasks in parallel`);let u=await zl({bundles:a,runOne:i(f=>f.readOnly?DR(f,t,n):FR(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(rn(f.bundle,`[Crash] ${f.reason.message}`,"failed"));for(let f of u.cancelled)l.push(f.id);return GR(a,c,l)}i(ty,"executeChildAgents");function ny(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(ny,"buildChildPermissionIntent");var vR=["list_dispatchable_agents","spawn_agent","run_workflow","send_message","followup_task","wait_agent","interrupt_agent","list_agents","agent_output","emit_managed_protocol"];function xR(e,t){if(!t)return e;let n=new Set(t.tools),r=n.has("*"),o=new Set(e);for(let s of At()){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(xR,"restrictToolsForActor");function ry(e,t,n){let r=xR(e,t);return n!==void 0?r:[...new Set([...r,...vR])]}i(ry,"restrictToolsForChildRuntime");function fi(e,t){return t.contextAgentId??e.id}i(fi,"childContextAgentId");function pi(e,t){return t.contextParentAgentId??(t.actorControl!==void 0?t.actorParentAgentId:e.currentAgentId)}i(pi,"childContextParentAgentId");function di(e,t,n){if(t.includes(e))return!1;let r=At().find(o=>o.name===e);return r?n.toolVisibilityPolicy?.({name:r.name,sideEffect:r.sideEffect,planModeAllowed:r.planModeAllowed===!0})??!0:!1}i(di,"isChildToolVisible");function Al(e,t){return t===void 0||t.providers.includes("*")||t.providers.includes(e)}i(Al,"isProviderAllowed");function oy(e,t){if(!Al(e,t))throw new Error(`Child Actor is not authorized to use provider ${e}.`)}i(oy,"assertChildProviderAllowed");function kR(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(kR,"readWorktreePath");async function iy(e,t){if(e.isolation!=="worktree")return{ctx:t};let n=await dr({description:`workflow-${e.id}`,...t.workflowWorktreeBaseDir?{base_dir:t.workflowWorktreeBaseDir}:{}},t),r=kR(n);return{ctx:{...t,gitRoot:r,executionCwd:r},worktreePath:r}}i(iy,"prepareChildIsolationScope");function sy(e,t){return t.worktreePath?[`[Workflow worktree: ${t.worktreePath}]`,e].join(`
353
353
  `):e}i(sy,"annotateWorktreeSummary");async function Gg(e,t){if(e.worktreePath)try{await ur({action:"remove",worktree_path:e.worktreePath,discard_changes:!1},t);return}catch(n){return`[Workflow worktree cleanup failed: ${n instanceof Error?n.message:String(n)}]`}}i(Gg,"cleanupChildIsolationScope");function _R(e,t){return t?{...e,summary:`${e.summary}
@@ -372,7 +372,7 @@ ${o}
372
372
  ${s}
373
373
  ${o}`}return`- [evidence_refs error] unrecognized prefix in "${e}" \u2014 valid prefixes: file:, diff:, finding:, agent-turn:, agent:`}i(BR,"resolveEvidenceRef");var Il=["You are a focused sub-agent executing a specific task assigned by a parent agent.","Use the available tools to complete the task fully. Do not gold-plate, but do not leave it half-done.","","## Tool Use \u2014 Prefer Parallel Calls","","When multiple tool calls are independent of each other, emit them all in the SAME response. The execution engine runs non-bash tools concurrently via Promise.all, so serial calls add real wall-clock latency the parent waits on.","","Concrete rules:","- For module exploration or change review, lead with pull-tools (`module_context` / `symbol_context` / `changed_scope` / `changed_diff_bundle`) \u2014 each replaces several read+grep calls so the same investigation finishes in fewer turns.","- For single-file lookup or byte-exact verification, use `glob` + `grep` + targeted `read`.","- When you need multiple independent tool calls (pull-tools, reads, or greps), emit them all in one response. Only serialize when a later call genuinely depends on an earlier result (e.g., you need a file path from grep before you can read it).","- Open broad with a parallel fan-out covering the obvious scope axes, then narrow on follow-up turns. Prefer a few targeted calls over many tiny sequential probes.","","## Execution Guidelines","- Focus on the objective described in the user message. Do not deviate.","- Write your final report in the same natural language as the objective you were given, so it reaches the user in their language. Keep code, file paths, and quoted evidence in their source language.","- When you have sufficient evidence, stop investigating and synthesize your findings.","- Your final response MUST be text only \u2014 the parent reads your text directly as the dispatch result, and a final tool call would re-open the turn and force another LLM round without giving the parent new information.","","## Output Format","Respond with a concise report covering:","- Key findings with specific file:line references","- Severity or priority assessment (if applicable)","- Concrete recommendations","","Keep the report focused \u2014 the parent will relay it to the user."].join(`
374
374
  `);function WR(e,t=Il){let n=ug({cwd:e,projectRoot:e}),r=fg(n);return r?[t,"","Project rules apply to your mutations. Follow them as the parent agent would:",r].join(`
375
- `):t}i(WR,"buildWriteSystemPrompt");var Ol=["ask_user_question","worktree_create","worktree_remove","exit_plan_mode"],by=[...Ol,"write","edit","multi_edit","insert_after_anchor","undo"],HR=new Set(Ol),KR=new Set(by);function zR(e,t,n){return{...t!==void 0?{workflowCorrelation:t}:{},childAgentId:e,childAgentName:n??e,liveOnly:!0}}i(zR,"childActivityEventMeta");function vy(e,t,n,r){t?.onChildActivityEnd?.(zR(e,n,r))}i(vy,"emitChildActivityEnd");function xy(e,t,n,r,o,s,a,c=200,l=!1){let d=0,u=c,f=0,p=l?KR:HR,m=150,h=i((y,b=!1)=>{if(!t)return;let k=Date.now();!b&&k-f<m||(f=k,t(y))},"throttledProgress"),g=i((y,b={})=>{let k=s??y?.workflowCorrelation,v={...y??{},...k!==void 0?{workflowCorrelation:k}:{},...y?.childAgentId!==void 0?{childAgentId:y.childAgentId}:{childAgentId:e},...y?.childAgentName!==void 0?{childAgentName:y.childAgentName}:{childAgentName:a??e},...y?.parentToolId!==void 0?{parentToolId:y.parentToolId}:{},...b.liveOnly!==void 0?{liveOnly:b.liveOnly}:{}};return v.workflowCorrelation===void 0&&v.childAgentId===void 0&&v.childAgentName===void 0&&v.parentToolId===void 0&&v.liveOnly===void 0?void 0:v},"activityEventMeta"),w=i((y,b={})=>{let v={...g(y,b)??{},...y?.toolId!==void 0?{toolId:y.toolId}:{}};return v.toolId===void 0&&v.workflowCorrelation===void 0&&v.childAgentId===void 0&&v.childAgentName===void 0&&v.parentToolId===void 0&&v.liveOnly===void 0?void 0:v},"toolEventMeta");return{...s?{workflowCorrelation:s}:{},onTextDelta:i((y,b)=>{o?.onTextDelta?.(y,g(b,{liveOnly:!0}))},"onTextDelta"),onThinkingDelta:i((y,b)=>{o?.onThinkingDelta?.(y,g(b,{liveOnly:!0}))},"onThinkingDelta"),onThinkingEnd:i((y,b)=>{o?.onThinkingEnd?.(y,g(b,{liveOnly:!0}))},"onThinkingEnd"),onStreamEnd:i(y=>{o?.onStreamEnd?.(g(y,{liveOnly:!0}))},"onStreamEnd"),onProviderRateLimit:i((y,b,k,v)=>{o?.onProviderRateLimit?.(y,b,k,g(v,{liveOnly:!0}))},"onProviderRateLimit"),onRetryAfter:i((y,b)=>{o?.onRetryAfter?.(y,g(b,{liveOnly:!0}))},"onRetryAfter"),onRetry:i((y,b,k,v)=>{o?.onRetry?.(y,b,k,g(v,{liveOnly:!0}))},"onRetry"),onProviderRecovery:i((y,b)=>{o?.onProviderRecovery?.(y,g(b,{liveOnly:!0}))},"onProviderRecovery"),onCompactStart:i(y=>{o?.onCompactStart?.(g(y,{liveOnly:!0}))},"onCompactStart"),onCompactStats:i(y=>{o?.onCompactStats?.(y)},"onCompactStats"),onCompact:i((y,b)=>{o?.onCompact?.(y,g(b,{liveOnly:!0}))},"onCompact"),onContextCompactionFinished:i(y=>{o?.onContextCompactionFinished?.(y)},"onContextCompactionFinished"),onContextBudgetSnapshot:i(y=>{o?.onContextBudgetSnapshot?.(y)},"onContextBudgetSnapshot"),onPromptCacheDiagnostics:i(y=>{o?.onPromptCacheDiagnostics?.(y)},"onPromptCacheDiagnostics"),onToolExposurePlanned:i(y=>{o?.onToolExposurePlanned?.(y)},"onToolExposurePlanned"),onContextCompactionSkipped:i(y=>{o?.onContextCompactionSkipped?.(y)},"onContextCompactionSkipped"),onCompactEnd:i(y=>{o?.onCompactEnd?.(g(y,{liveOnly:!0}))},"onCompactEnd"),beforeToolExecute:i(async(y,b,k)=>{if(p.has(y))return`[Tool Error] ${y}: Not available in child agent context.`;if(n){let v=n(y,b);if(v)return`${v} You are a child agent inheriting plan-mode constraints. Complete investigation and return findings as text \u2014 the parent agent will request user approval for any implementation.`}return o?.beforeToolExecute?o.beforeToolExecute(y,b,w(k)):!0},"beforeToolExecute"),onIterationStart:i((y,b)=>{d=y,u=b},"onIterationStart"),onIterationEnd:i(y=>{o?.onIterationEnd?.({...y,scope:"worker"})},"onIterationEnd"),onToolUseStart:i((y,b)=>{o?.onToolUseStart?.(y,w({...b?.toolId!==void 0?{toolId:b.toolId}:{toolId:y.id},...b?.workflowCorrelation!==void 0?{workflowCorrelation:b.workflowCorrelation}:{}},{liveOnly:!0}));let k=y.input&&typeof y.input=="object"?y.input.path??y.input.pattern??y.input.command??"":"",v=typeof k=="string"?k.slice(0,60):"",S=v?` ${v}`:"";h(`${e} [${d}/${u}] \u2192 ${y.name}${S}`)},"onToolUseStart"),onToolInputDelta:i((y,b,k)=>{o?.onToolInputDelta?.(y,b,w(k,{liveOnly:!0}))},"onToolInputDelta"),onToolProgress:i((y,b)=>{o?.onToolProgress?.(y,w({...b?.toolId!==void 0?{toolId:b.toolId}:{toolId:y.id},...b?.workflowCorrelation!==void 0?{workflowCorrelation:b.workflowCorrelation}:{}},{liveOnly:!0}))},"onToolProgress"),onToolResult:i((y,b)=>{o?.onToolResult?.(y,w({...b?.toolId!==void 0?{toolId:b.toolId}:{toolId:y.id},...b?.workflowCorrelation!==void 0?{workflowCorrelation:b.workflowCorrelation}:{}},{liveOnly:!0}))},"onToolResult"),...o?.askUser?{askUser:i((y,b)=>o.askUser(y,w(b,{liveOnly:!0})),"askUser")}:{},...o?.askUserMulti?{askUserMulti:i((y,b)=>o.askUserMulti(y,w(b,{liveOnly:!0})),"askUserMulti")}:{},...o?.askUserInput?{askUserInput:i((y,b)=>o.askUserInput(y,w(b,{liveOnly:!0})),"askUserInput")}:{}}}i(xy,"buildChildEvents");function ky(e){let t=new Set(["file_modified","file_created","file_deleted"]);return[...new Set((e.artifactLedger??[]).filter(n=>t.has(n.kind)).map(n=>n.target).filter(n=>n.trim().length>0))]}i(ky,"extractMutationArtifactPaths");function rn(e,t,n,r={}){return{childId:e.id,fanoutClass:e.fanoutClass,status:n,disposition:n==="completed"?"valid":"needs-more-evidence",summary:t,evidenceRefs:e.evidenceRefs,contradictions:[],actualIterations:r.actualIterations,...r.totalTokensUsed!==void 0&&r.totalTokensUsed>0?{totalTokensUsed:r.totalTokensUsed}:{},...r.digestTokensUsed!==void 0&&r.digestTokensUsed>0?{digestTokensUsed:r.digestTokensUsed}:{},...r.digestUsage?{digestUsage:r.digestUsage}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.artifactPaths!==void 0&&r.artifactPaths.length>0?{artifactPaths:[...r.artifactPaths]}:{},...r.digest?{digest:r.digest}:{},...r.digestFailed?{digestFailed:!0}:{},...r.digestPending?{digestPending:!0}:{},...r.provider?{provider:r.provider}:{},...r.model?{model:r.model}:{},...r.routeFacts?{routeFacts:r.routeFacts}:{},...r.structured!==void 0?{structured:r.structured}:{},interrupted:r.interrupted,...r.limitReached?{limitReached:!0}:{}}}i(rn,"extractChildResult");function GR(e,t,n){let r=new Map(e.map(l=>[l.id,l])),o=new Map(t.map(l=>[l.childId,l])),s=e.map(l=>o.get(l.id)).filter(l=>l!==void 0&&(l.status==="completed"||l.summary.length>0)).map(l=>({childId:l.childId,objective:r.get(l.childId)?.objective??"",evidence:[l.summary,...l.evidenceRefs],artifacts:l.artifactPaths??[]})),a=[...new Set(t.flatMap(l=>l.artifactPaths??[]))],c=t.reduce((l,d)=>l+(d.totalTokensUsed??0),0);return{results:t,mergedFindings:s,mergedArtifacts:a,totalTokensUsed:c,cancelledChildren:[...n]}}i(GR,"mergeChildResults");function XR(e,t,n){return e.length===0?[]:t!=="worker"?[]:n!=="tool-dispatch"?[]:e}i(XR,"validateWriteBundles");var Yg={results:[],mergedFindings:[],mergedArtifacts:[],totalTokensUsed:0,cancelledChildren:[]};var YR=200,Cr=class{static{i(this,"CodingActorSession")}sessionOptions;controller;turnExecutors=new Map;environment;activeBudget;constructor(t={}){this.sessionOptions=t,this.activeBudget=t.budget;let n={execute:i(r=>{let o=Re(r.turn.metadata?.executionKey),s=o?this.turnExecutors.get(o):void 0;if(s)return s.execute(r);if(r.actor.kind==="external"&&t.executor)return t.executor.execute(r);let a=this.environment;if(!a)throw new Error("Actor session is not attached to an active KodaX run.");return QR(r,a.parentCtx,a.options,this.controller.bind(r.actor.path))},"execute")};this.controller=new rd({maxConcurrentThreadsPerSession:t.maxConcurrentThreadsPerSession,store:t.store,owner:t.owner,isOwnerAlive:t.isOwnerAlive,executor:n,budget:{admit:i(r=>this.activeBudget?.admit(r)??Promise.resolve({admitted:!0}),"admit"),refund:i(r=>this.activeBudget?.refund?.(r)??Promise.resolve(),"refund"),snapshot:i(()=>this.activeBudget?.snapshot?.(),"snapshot")},warn:i(r=>P({source:"coding:actors",level:"warn",message:r}),"warn"),onBackgroundError:i(r=>P({source:"coding:actors",level:"error",message:r instanceof Error?r.message:String(r)}),"onBackgroundError"),onHealthChanged:t.onHealthChanged,onMessageCommitted:i(r=>JR(this.controller,r,t.sessionId),"onMessageCommitted")})}async initialize(){await this.controller.initialize()}attach(t,n,r="/root"){return this.environment={parentCtx:t,options:n},this.activeBudget=n.context?.managedWorkBudget?lI(n.context.managedWorkBudget):this.sessionOptions.budget,this.controller.bind(r)}rootControl(){return this.controller.bind("/root")}health(){return this.controller.healthSnapshot()}ownerId(){return this.sessionOptions.owner?.ownerId}ownsDurableFence(){return this.controller.ownsDurableFence()}createWorkflowOwner(t,n){return this.controller.createProtocolOwner(t,n)}workflowOwnerSignal(t){return this.controller.protocolOwnerSignal(t)}settleWorkflowOwner(t,n,r){return this.controller.settleProtocolOwner(t,n,r)}bindActor(t){return this.controller.bind(t)}closeActor(t,n){return this.controller.close("/root",t,n)}registerTurnExecutor(t,n){if(this.turnExecutors.has(t))throw new Error(`Actor turn executor is already registered: ${t}`);return this.turnExecutors.set(t,n),()=>{this.turnExecutors.get(t)===n&&this.turnExecutors.delete(t)}}async waitForAgentCapacity(t){let n=this.controller.bind("/root"),r=n.eventSnapshot().at(-1)?.sequence??0;for(;;){if(t?.aborted)return!1;let o=n.list();if(o.maxConcurrentThreads<=1)return!1;if(o.activeNonRootTurns<o.maxConcurrentThreads-1)return!0;let s=await n.wait(r,250);s&&(r=s.sequence)}}async close(t="runtime closed"){await this.controller.shutdown(t),this.turnExecutors.clear(),this.environment=void 0}quiesce(t="runtime quiesced"){return this.controller.quiesce(t)}disposeAfterStoreRemoval(t="session removed"){this.controller.disposeAfterStoreRemoval(t),this.turnExecutors.clear(),this.environment=void 0}};function KH(e,t){return new Cr({maxConcurrentThreadsPerSession:t.maxConcurrentThreadsPerSession,sessionId:e.sessionId}).attach(e,t)}i(KH,"createLocalCodingActorControl");function zH(e){return{execute(t){if(t.actor.kind!=="external")throw new Error("Detached Runtime Actor execution only supports external actors.");return Sy(t,e)}}}i(zH,"createExternalActorTurnExecutor");function JR(e,t,n){if(t.recipientPath!=="/root")return;if(t.kind!=="completion"||!t.turnId){st().enqueue({priority:t.kind==="followup"?"user":"background",mode:"agent-message",agentId:ke(n,"/root"),content:$l(t)});return}let r=e.output("/root",t.senderPath,t.turnId),o=st(),s=ke(n,"/root");if(o.has({agentId:s,maxPriority:"background",mode:"task-notification",predicate:i(l=>l.taskResult?.source==="child_task"&&l.taskResult.taskId===t.turnId,"predicate")}))return;let a=r.state==="completed"?"completed":r.state==="failed"?"failed":"cancelled",c=r.output??r.error??a;o.enqueue({priority:"background",mode:"task-notification",agentId:s,content:`<agent-completed id="${ye(t.messageId)}" path="${ye(t.senderPath)}" turn_id="${ye(t.turnId)}" state="${a}">
375
+ `):t}i(WR,"buildWriteSystemPrompt");var Ol=["ask_user_question","worktree_create","worktree_remove","exit_plan_mode"],by=[...Ol,"write","edit","multi_edit","insert_after_anchor","undo"],HR=new Set(Ol),KR=new Set(by);function zR(e,t,n){return{...t!==void 0?{workflowCorrelation:t}:{},childAgentId:e,childAgentName:n??e,liveOnly:!0}}i(zR,"childActivityEventMeta");function vy(e,t,n,r){t?.onChildActivityEnd?.(zR(e,n,r))}i(vy,"emitChildActivityEnd");function xy(e,t,n,r,o,s,a,c=200,l=!1){let d=0,u=c,f=0,p=l?KR:HR,m=150,h=i((y,b=!1)=>{if(!t)return;let k=Date.now();!b&&k-f<m||(f=k,t(y))},"throttledProgress"),g=i((y,b={})=>{let k=s??y?.workflowCorrelation,v={...y??{},...k!==void 0?{workflowCorrelation:k}:{},...y?.childAgentId!==void 0?{childAgentId:y.childAgentId}:{childAgentId:e},...y?.childAgentName!==void 0?{childAgentName:y.childAgentName}:{childAgentName:a??e},...y?.parentToolId!==void 0?{parentToolId:y.parentToolId}:{},...b.liveOnly!==void 0?{liveOnly:b.liveOnly}:{}};return v.workflowCorrelation===void 0&&v.childAgentId===void 0&&v.childAgentName===void 0&&v.parentToolId===void 0&&v.liveOnly===void 0?void 0:v},"activityEventMeta"),w=i((y,b={})=>{let v={...g(y,b)??{},...y?.toolId!==void 0?{toolId:y.toolId}:{}};return v.toolId===void 0&&v.workflowCorrelation===void 0&&v.childAgentId===void 0&&v.childAgentName===void 0&&v.parentToolId===void 0&&v.liveOnly===void 0?void 0:v},"toolEventMeta");return{...s?{workflowCorrelation:s}:{},onTextDelta:i((y,b)=>{o?.onTextDelta?.(y,g(b,{liveOnly:!0}))},"onTextDelta"),onThinkingDelta:i((y,b)=>{o?.onThinkingDelta?.(y,g(b,{liveOnly:!0}))},"onThinkingDelta"),onThinkingEnd:i((y,b)=>{o?.onThinkingEnd?.(y,g(b,{liveOnly:!0}))},"onThinkingEnd"),onStreamEnd:i(y=>{o?.onStreamEnd?.(g(y,{liveOnly:!0}))},"onStreamEnd"),onProviderRateLimit:i((y,b,k,v)=>{o?.onProviderRateLimit?.(y,b,k,g(v,{liveOnly:!0}))},"onProviderRateLimit"),onRetryAfter:i((y,b)=>{o?.onRetryAfter?.(y,g(b,{liveOnly:!0}))},"onRetryAfter"),onRetry:i((y,b,k,v)=>{o?.onRetry?.(y,b,k,g(v,{liveOnly:!0}))},"onRetry"),onProviderRecovery:i((y,b)=>{o?.onProviderRecovery?.(y,g(b,{liveOnly:!0}))},"onProviderRecovery"),onCompactStart:i(y=>{o?.onCompactStart?.(g(y,{liveOnly:!0}))},"onCompactStart"),onCompactStats:i(y=>{o?.onCompactStats?.(y)},"onCompactStats"),onCompact:i((y,b)=>{o?.onCompact?.(y,g(b,{liveOnly:!0}))},"onCompact"),onContextCompactionFinished:i(y=>{o?.onContextCompactionFinished?.(y)},"onContextCompactionFinished"),onContextBudgetSnapshot:i(y=>{o?.onContextBudgetSnapshot?.(y)},"onContextBudgetSnapshot"),onPromptCacheDiagnostics:i(y=>{o?.onPromptCacheDiagnostics?.(y)},"onPromptCacheDiagnostics"),onToolExposurePlanned:i(y=>{o?.onToolExposurePlanned?.(y)},"onToolExposurePlanned"),onContextCompactionSkipped:i(y=>{o?.onContextCompactionSkipped?.(y)},"onContextCompactionSkipped"),onCompactEnd:i(y=>{o?.onCompactEnd?.(g(y,{liveOnly:!0}))},"onCompactEnd"),beforeToolExecute:i(async(y,b,k)=>{if(p.has(y))return`[Tool Error] ${y}: Not available in child agent context.`;if(n){let v=n(y,b);if(v)return`${v} You are a child agent inheriting plan-mode constraints. Complete investigation and return findings as text \u2014 the parent agent will request user approval for any implementation.`}return o?.beforeToolExecute?o.beforeToolExecute(y,b,w(k)):!0},"beforeToolExecute"),onIterationStart:i((y,b)=>{d=y,u=b},"onIterationStart"),onIterationEnd:i(y=>{o?.onIterationEnd?.({...y,scope:"worker"})},"onIterationEnd"),onToolUseStart:i((y,b)=>{o?.onToolUseStart?.(y,w({...b?.toolId!==void 0?{toolId:b.toolId}:{toolId:y.id},...b?.workflowCorrelation!==void 0?{workflowCorrelation:b.workflowCorrelation}:{}},{liveOnly:!0}));let k=y.input&&typeof y.input=="object"?y.input.path??y.input.pattern??y.input.command??"":"",v=typeof k=="string"?k.slice(0,60):"",S=v?` ${v}`:"";h(`${e} [${d}/${u}] \u2192 ${y.name}${S}`)},"onToolUseStart"),onToolInputDelta:i((y,b,k)=>{o?.onToolInputDelta?.(y,b,w(k,{liveOnly:!0}))},"onToolInputDelta"),onToolProgress:i((y,b)=>{o?.onToolProgress?.(y,w({...b?.toolId!==void 0?{toolId:b.toolId}:{toolId:y.id},...b?.workflowCorrelation!==void 0?{workflowCorrelation:b.workflowCorrelation}:{}},{liveOnly:!0}))},"onToolProgress"),onToolResult:i((y,b)=>{o?.onToolResult?.(y,w({...b?.toolId!==void 0?{toolId:b.toolId}:{toolId:y.id},...b?.workflowCorrelation!==void 0?{workflowCorrelation:b.workflowCorrelation}:{}},{liveOnly:!0}))},"onToolResult"),...o?.askUser?{askUser:i((y,b)=>o.askUser(y,w(b,{liveOnly:!0})),"askUser")}:{},...o?.askUserMulti?{askUserMulti:i((y,b)=>o.askUserMulti(y,w(b,{liveOnly:!0})),"askUserMulti")}:{},...o?.askUserInput?{askUserInput:i((y,b)=>o.askUserInput(y,w(b,{liveOnly:!0})),"askUserInput")}:{}}}i(xy,"buildChildEvents");function ky(e){let t=new Set(["file_modified","file_created","file_deleted"]);return[...new Set((e.artifactLedger??[]).filter(n=>t.has(n.kind)).map(n=>n.target).filter(n=>n.trim().length>0))]}i(ky,"extractMutationArtifactPaths");function rn(e,t,n,r={}){return{childId:e.id,fanoutClass:e.fanoutClass,status:n,disposition:n==="completed"?"valid":"needs-more-evidence",summary:t,evidenceRefs:e.evidenceRefs,contradictions:[],actualIterations:r.actualIterations,...r.totalTokensUsed!==void 0&&r.totalTokensUsed>0?{totalTokensUsed:r.totalTokensUsed}:{},...r.digestTokensUsed!==void 0&&r.digestTokensUsed>0?{digestTokensUsed:r.digestTokensUsed}:{},...r.digestUsage?{digestUsage:r.digestUsage}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.artifactPaths!==void 0&&r.artifactPaths.length>0?{artifactPaths:[...r.artifactPaths]}:{},...r.digest?{digest:r.digest}:{},...r.digestFailed?{digestFailed:!0}:{},...r.digestPending?{digestPending:!0}:{},...r.provider?{provider:r.provider}:{},...r.model?{model:r.model}:{},...r.routeFacts?{routeFacts:r.routeFacts}:{},...r.structured!==void 0?{structured:r.structured}:{},interrupted:r.interrupted,...r.limitReached?{limitReached:!0}:{}}}i(rn,"extractChildResult");function GR(e,t,n){let r=new Map(e.map(l=>[l.id,l])),o=new Map(t.map(l=>[l.childId,l])),s=e.map(l=>o.get(l.id)).filter(l=>l!==void 0&&(l.status==="completed"||l.summary.length>0)).map(l=>({childId:l.childId,objective:r.get(l.childId)?.objective??"",evidence:[l.summary,...l.evidenceRefs],artifacts:l.artifactPaths??[]})),a=[...new Set(t.flatMap(l=>l.artifactPaths??[]))],c=t.reduce((l,d)=>l+(d.totalTokensUsed??0),0);return{results:t,mergedFindings:s,mergedArtifacts:a,totalTokensUsed:c,cancelledChildren:[...n]}}i(GR,"mergeChildResults");function XR(e,t,n){return e.length===0?[]:t!=="worker"?[]:n!=="tool-dispatch"?[]:e}i(XR,"validateWriteBundles");var Yg={results:[],mergedFindings:[],mergedArtifacts:[],totalTokensUsed:0,cancelledChildren:[]};var YR=200,Cr=class{static{i(this,"CodingActorSession")}sessionOptions;controller;turnExecutors=new Map;environment;activeBudget;constructor(t={}){this.sessionOptions=t,this.activeBudget=t.budget;let n={execute:i(r=>{let o=Re(r.turn.metadata?.executionKey),s=o?this.turnExecutors.get(o):void 0;if(s)return s.execute(r);if(r.actor.kind==="external"&&t.executor)return t.executor.execute(r);let a=this.environment;if(!a)throw new Error("Actor session is not attached to an active KodaX run.");return QR(r,a.parentCtx,a.options,this.controller.bind(r.actor.path))},"execute")};this.controller=new rd({maxConcurrentThreadsPerSession:t.maxConcurrentThreadsPerSession,store:t.store,owner:t.owner,isOwnerAlive:t.isOwnerAlive,executor:n,budget:{admit:i(r=>this.activeBudget?.admit(r)??Promise.resolve({admitted:!0}),"admit"),refund:i(r=>this.activeBudget?.refund?.(r)??Promise.resolve(),"refund"),snapshot:i(()=>this.activeBudget?.snapshot?.(),"snapshot")},warn:i(r=>P({source:"coding:actors",level:"warn",message:r}),"warn"),onBackgroundError:i(r=>P({source:"coding:actors",level:"error",message:r instanceof Error?r.message:String(r)}),"onBackgroundError"),onHealthChanged:t.onHealthChanged,onMessageCommitted:i(r=>JR(this.controller,r,t.sessionId),"onMessageCommitted")})}async initialize(){await this.controller.initialize()}attach(t,n,r="/root"){return this.environment={parentCtx:t,options:n},this.activeBudget=n.context?.managedWorkBudget?lI(n.context.managedWorkBudget):this.sessionOptions.budget,this.controller.bind(r)}rootControl(){return this.controller.bind("/root")}health(){return this.controller.healthSnapshot()}ownerId(){return this.sessionOptions.owner?.ownerId}ownsDurableFence(){return this.controller.ownsDurableFence()}createWorkflowOwner(t,n){return this.controller.createProtocolOwner(t,n)}workflowOwnerSignal(t){return this.controller.protocolOwnerSignal(t)}settleWorkflowOwner(t,n,r){return this.controller.settleProtocolOwner(t,n,r)}bindActor(t){return this.controller.bind(t)}closeActor(t,n){return this.controller.close("/root",t,n)}registerTurnExecutor(t,n){if(this.turnExecutors.has(t))throw new Error(`Actor turn executor is already registered: ${t}`);return this.turnExecutors.set(t,n),()=>{this.turnExecutors.get(t)===n&&this.turnExecutors.delete(t)}}async waitForAgentCapacity(t){let n=this.controller.bind("/root"),r=n.eventSnapshot().at(-1)?.sequence??0;for(;;){if(t?.aborted)return!1;let o=n.list();if(o.maxConcurrentThreads<=1)return!1;if(o.activeNonRootTurns<o.maxConcurrentThreads-1)return!0;let s=await n.wait(r,250);s&&(r=s.sequence)}}async close(t="runtime closed"){await this.controller.shutdown(t),this.turnExecutors.clear(),this.environment=void 0}quiesce(t="runtime quiesced",n){return this.controller.quiesce(t,n)}disposeAfterStoreRemoval(t="session removed"){this.controller.disposeAfterStoreRemoval(t),this.turnExecutors.clear(),this.environment=void 0}};function KH(e,t){return new Cr({maxConcurrentThreadsPerSession:t.maxConcurrentThreadsPerSession,sessionId:e.sessionId}).attach(e,t)}i(KH,"createLocalCodingActorControl");function zH(e){return{execute(t){if(t.actor.kind!=="external")throw new Error("Detached Runtime Actor execution only supports external actors.");return Sy(t,e)}}}i(zH,"createExternalActorTurnExecutor");function JR(e,t,n){if(t.recipientPath!=="/root")return;if(t.kind!=="completion"||!t.turnId){st().enqueue({priority:t.kind==="followup"?"user":"background",mode:"agent-message",agentId:ke(n,"/root"),content:$l(t)});return}let r=e.output("/root",t.senderPath,t.turnId),o=st(),s=ke(n,"/root");if(o.has({agentId:s,maxPriority:"background",mode:"task-notification",predicate:i(l=>l.taskResult?.source==="child_task"&&l.taskResult.taskId===t.turnId,"predicate")}))return;let a=r.state==="completed"?"completed":r.state==="failed"?"failed":"cancelled",c=r.output??r.error??a;o.enqueue({priority:"background",mode:"task-notification",agentId:s,content:`<agent-completed id="${ye(t.messageId)}" path="${ye(t.senderPath)}" turn_id="${ye(t.turnId)}" state="${a}">
376
376
  ${ye(c)}
377
377
  </agent-completed>`,taskResult:{type:"task_result",source:"child_task",taskId:t.turnId,status:a,summary:c,title:t.senderPath,...r.artifacts.length>0?{artifactRefs:[...r.artifacts]}:{}}})}i(JR,"publishRootMailboxMessage");async function QR(e,t,n,r){if(e.actor.kind==="external"){let g=`external-actor:${e.turn.turnId}`,w={childAgentId:e.actor.path,childAgentName:e.actor.taskName,toolId:g,liveOnly:!0};try{return await Sy(e,t.agentExecutorPlane,y=>{t.reportToolProgress?.(`[agent ${e.actor.path}] ${y}`),t.parentEvents?.onToolProgress?.({id:g,message:y},w)})}finally{t.parentEvents?.onChildActivityEnd?.(w)}}let o=rI(e),s=t.parentAgentConfig;cI(e,o.provider??s?.provider??n.provider);let a=await e.drainMailbox(),c=[...oI(e.priorTurns,e.turn.forkTurns),...a.map(g=>iI(g,Ty(r,g)))],l=new AbortController,d=sI(e,t.sessionId,r,l.signal),u;try{u=await ty([o],t,{maxParallel:1,maxIterationsPerChild:YR,abortSignal:e.signal,...n.session?.storage!==void 0?{historyStorage:n.session.storage}:{},parentOptions:{provider:s?.provider??n.provider,model:s?.model??n.modelOverride??n.model,effort:s?.effort??n.effort,reasoningMode:s?.reasoningMode??n.reasoningMode,repoIntelligenceMode:s?.repoIntelligenceMode,repoIntelligenceTrace:s?.repoIntelligenceTrace,compaction:s?.compaction??n.compaction,contextDiagnostics:s?.contextDiagnostics??n.context?.contextDiagnostics,disablePromptCache:s?.disablePromptCache??n.disablePromptCache,shellExecution:s?.shellExecution??n.context?.shellExecution,sandbox:s?.sandbox??n.sandbox,permissionIntent:s?.permissionIntent??n.context?.permissionIntent,extensionRuntime:t.extensionRuntime,events:t.parentEvents},parentRole:"worker",parentHarness:"tool-dispatch",planModeBlockCheck:t.planModeBlockCheck,guardrails:t.guardrails,actorControl:r,actorHost:t.actorHost,...e.actor.parentPath!==void 0&&e.actor.parentPath!=="/root"?{actorParentAgentId:e.actor.parentPath}:{},actorTurnId:e.turn.turnId,initialMessages:c,actorCapabilities:e.actor.capabilities,onProgress:i(g=>{e.reportProgress({kind:"status",summary:g}).catch(w=>{P({source:"coding:actors",level:"warn",message:`Actor progress projection failed: ${w instanceof Error?w.message:String(w)}`})}),t.reportToolProgress?.(`[agent ${e.actor.path}] ${g}`)},"onProgress")})}finally{l.abort(),await d}let f=u.results[0];if(!f||f.status!=="completed")throw new Error(f?.summary||`Agent turn ${e.turn.turnId} failed without output.`);let p=za(e.turn.metadata?.qualityStrategy),m=p===void 0?{structured:Nn(f.structured),degradedReasons:[]}:await ZR(f.structured,p,t,r);p!==void 0&&P({source:"coding:actors",level:"debug",message:[`strategy stage=${p.stageId}`,`pattern=${p.pattern}`,`role=${p.role}`,`turn=${e.turn.turnId}`,`status=${m.degradedReasons.length===0?"completed":"degraded"}`].join(" ")});let h={...f.provider===void 0?{}:{effectiveProvider:f.provider},...f.model===void 0?{}:{effectiveModel:f.model},...m.degradedReasons.length===0?{}:{qualityStrategyDegradedReasons:m.degradedReasons}};return{output:f.summary,...f.artifactPaths&&f.artifactPaths.length>0?{artifacts:f.artifactPaths}:{},...m.structured===void 0?{}:{structured:m.structured},...Object.keys(h).length===0?{}:{turnMetadata:h}}}i(QR,"executeCodingActorTurn");async function ZR(e,t,n,r){let o=ci(e);if(o===void 0)return{structured:Nn(e),degradedReasons:[]};let s=new Set(t.targetEvidenceRefs??[]),a=new Set,c=[],l={...n,actorControl:r};for(let u of o.outcomes){let f="evidenceRef"in u.target?u.target.evidenceRef:`agent-turn:${u.target.actorPath}#turn=${u.target.turnId}`;if(!s.has(f)){a.add("undeclared_disposition_target");continue}try{await Lo(f,n);for(let p of u.evidenceRefs)await Lo(p,l);c.push(u)}catch{a.add("invalid_disposition_evidence")}}let d={schemaVersion:1,outcomes:c,assertedCoverage:a.size===0?o.assertedCoverage:[]};return{structured:Nn(d),degradedReasons:[...a].sort()}}i(ZR,"validatePatternDispositionResult");async function Sy(e,t,n){let r=Re(e.turn.metadata?.agentId);if(!t||!r)throw new Error("External Agent execution is not bound to this Runtime.");if(e.signal.aborted)throw new Error("External Agent execution was interrupted before start.");let o=nI(t.context.actorId,e.turn.turnId),s,a,c=i(()=>{if(a)return a;let d=t.plane.tasks.cancel(o,String(e.signal.reason??"interrupted"));return a=d,d.catch(()=>{a===d&&(a=void 0)}),d},"requestCancellation"),l=i(()=>{s!==void 0&&Dn(s.state)||c().catch(d=>P({source:"coding:actors",level:"warn",message:`External Agent cancellation failed: ${d instanceof Error?d.message:String(d)}`}))},"cancel");e.signal.addEventListener("abort",l,{once:!0}),e.signal.aborted&&l();try{try{s=await t.plane.tasks.start({taskId:o,agentId:r,objective:e.turn.objective,context:{...t.context,parentTaskId:e.actor.parentPath??t.context.parentTaskId,...Re(e.turn.metadata?.workflowRunId)?{workflowId:Re(e.turn.metadata?.workflowRunId)}:{}},readOnly:e.turn.metadata?.readOnly!==!1,...Re(e.turn.metadata?.expectedConfigurationRevision)?{expectedConfigurationRevision:Re(e.turn.metadata?.expectedConfigurationRevision)}:{}},e.signal)}catch(u){if(e.signal.aborted)try{await c()}catch(f){P({source:"coding:actors",level:"warn",message:`External Agent cancellation after an ambiguous start failed: ${f instanceof Error?f.message:String(f)}`})}throw u}if(s.state==="failed"||s.state==="rejected")throw new Error(s.error??`External Agent entered ${s.state}.`);if(e.signal.aborted&&eI(s.cancellation))throw new Error(s.cancellationError??`External Agent cancellation cannot converge (${s.cancellation}).`);let d=_y(e,s.progress,void 0,n);for(;!Dn(s.state);){if(e.signal.aborted&&(s=await c(),!Dn(s.state)&&s.cancellation!=="requested"&&s.cancellation!=="confirmed"))throw new Error(`External Agent cancellation was not accepted (${s.cancellation}).`);if(!e.signal.aborted)for(let u of await e.drainMailbox()){if(e.signal.aborted)break;u.kind!=="completion"&&(s=await t.plane.tasks.sendInput(o,{content:u.content}))}Dn(s.state)||(await new Promise(u=>setTimeout(u,25)),s=await t.plane.tasks.get(o),d=_y(e,s.progress,d,n),e.signal.aborted&&!Dn(s.state)&&tI(s))}if(s.state!=="completed")throw new Error(s.error??s.cancellationError??`External Agent ended in ${s.state}.`);return{output:s.output??"",...s.artifacts&&s.artifacts.length>0?{artifacts:s.artifacts.map(u=>u.uri??u.name),artifactDetails:s.artifacts.map(u=>({...u}))}:{}}}finally{e.signal.removeEventListener("abort",l)}}i(Sy,"executeExternalActorTurn");function Dn(e){return e==="completed"||e==="failed"||e==="canceled"||e==="rejected"}i(Dn,"isExternalTerminal");function eI(e){return e==="unknown"||e==="failed"||e==="unsupported"}i(eI,"isExternalCancellationFailure");function tI(e){if(!(Dn(e.state)||e.cancellation==="requested"||e.cancellation==="confirmed"))throw new Error(e.cancellationError??`External Agent cancellation was not accepted (${e.cancellation}).`)}i(tI,"assertExternalCancellationAccepted");function _y(e,t,n,r){let o=t?.message?.trim()||(t?.percent===void 0?void 0:`${t.percent}% complete`);return!o||o===n?n:(e.reportProgress({kind:"status",summary:o}).catch(s=>{P({source:"coding:actors",level:"warn",message:`External Actor progress projection failed: ${s instanceof Error?s.message:String(s)}`})}),r?.(o),o)}i(_y,"reportExternalProgress");function nI(e,t){return`actor-${VR("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24)}`}i(nI,"externalTaskId");function rI(e){let t=e.turn.metadata??{},n=za(t.qualityStrategy),r=n?.role==="filter"||n?.role==="judge"||n?.role==="challenger";return{id:e.actor.path,fanoutClass:"evidence-scan",objective:e.turn.objective,scopeSummary:Re(t.scope),evidenceRefs:[...new Set([...Ey(t.evidenceRefs),...n?.targetEvidenceRefs??[]])],constraints:Ey(t.constraints),readOnly:e.actor.capabilities.filesystem!=="write",modelHint:uI(t.modelHint),isolation:t.isolation==="worktree"?"worktree":void 0,specialistName:dI(t,e),provider:Re(t.provider),model:Re(t.model),effort:fI(t.effort),...r?{outputSchema:Hg,structuredOutputContract:"pattern-disposition-parse-only"}:{}}}i(rI,"actorBundle");function oI(e,t){return(t==="none"?[]:t==="all"?e:e.slice(-t)).flatMap(r=>{let o=r.output??r.error??r.state;return[{role:"user",content:`<actor-prior-turn id="${ye(r.turnId)}">
378
378
  ${ye(r.objective)}
@@ -382,4 +382,4 @@ ${ye(o)}
382
382
  ${ye(e.content)}
383
383
  </agent-completed>`}return`<agent-message id="${ye(e.messageId)}" from="${ye(e.senderPath)}" classification="${e.classification}">
384
384
  ${ye(e.content)}
385
- </agent-message>`}i($l,"renderMailboxMessage");function cI(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(cI,"assertProviderAuthority");function ye(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}i(ye,"escapeXml");function lI(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(lI,"managedWorkBudgetPort");function dI(e,t){let n=Re(e.specialistName);if(n)return n;let r=Re(e.agentId);if(!(!r||t.actor.kind==="native"))throw new Error(`Agent selector ${r} was not resolved before execution.`)}i(dI,"specialistName");function uI(e){return e==="fast"||e==="balanced"||e==="deep"?e:void 0}i(uI,"modelHint");function fI(e){let t=Re(e);if(!t)return;let n=on(t);return n==="auto"?void 0:n}i(fI,"effort");function Re(e){return typeof e=="string"&&e.length>0?e:void 0}i(Re,"metadataString");function Ey(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}i(Ey,"metadataStringArray");import Ay from"node:path";var pI=80;function mI(e){let t=e.trim().replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,pI);return!t||t==="."||t===".."?"session":t}i(mI,"sanitizeScratchSessionId");function Cy(e){let t=e.session?.id?.trim();if(!t)return;let n=e.context?.gitRoot?.trim(),r=n?Ay.resolve(n):le(e.context);return Ay.resolve(r,".agent","tmp","sessions",mI(t))}i(Cy,"getSessionScratchDir");var hI="emit_managed_protocol",eK="kodax-task-contract",gI="kodax-task-verdict",tK="kodax-task-scout",nK="kodax-task-handoff";function yI(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}i(yI,"asRecord");function Ry(e){return e.trim().toLowerCase()===hI}i(Ry,"isManagedProtocolToolName");function Iy(e,t){if(!(!e&&!t))return{verdict:t?.verdict?{...e?.verdict??{},...t.verdict}:e?.verdict}}i(Iy,"mergeManagedProtocolPayload");function wI(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(wI,"normalizeManagedVerdictStatus");function bI(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(bI,"normalizeManagedNextHarness");function vI(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(vI,"normalizeStringListValue");function rK(e,t,n=""){let r=yI(t);if(!r||e!=="evaluator")return;let o=typeof r.status=="string"?wI(r.status):void 0;if(o)return{verdict:{source:"evaluator",status:o,reason:typeof r.reason=="string"&&r.reason.trim()||void 0,followups:vI(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"?bI(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(rK,"coerceManagedProtocolToolPayload");function oK(e){if(e==="evaluator")return gI}i(oK,"getManagedBlockNameForRole");function iK(e,t){return e&&t==="evaluator"?!!e.verdict:!1}i(iK,"hasManagedProtocolForRole");function sK(e,t){return new RegExp(String.raw`\`\`\`${t}\s*[\s\S]*?\`\`\``,"i").test(e)}i(sK,"textContainsManagedBlock");function Oy(e,t){if(!t||t.length===0)return e;let n=new Set(t);return e.filter(r=>!n.has(r))}i(Oy,"filterExcludedTools");function $y(e,t){return t?e.filter(n=>{let r=Se(n);return r?t({name:r.name,sideEffect:r.sideEffect,planModeAllowed:r.planModeAllowed===!0}):!1}):e}i($y,"applyToolVisibilityPolicy");function xI(e,t,n=!1,r,o=!1){let s=ta(t)==="off"?Yc(e):e;return n||(s=Jc(s)),s=jc(s,r),s=zc(s,r),o||(s=s.filter(a=>a!=="list_dispatchable_agents")),s}i(xI,"getRuntimeActiveToolNames");function mK(e,t,n=!1,r=!1,o,s,a,c=!1){let l=Vc();if(e.length===0)return[];let d=new Set(xI(e,t,r,o,c));return l.filter(u=>d.has(u.name)&&(n||!Ry(u.name))).map(u=>{let f=Gr(u,a);if(!Xo(f.name)||s&&s.has(f.name))return f;let p=en[f.name];return p?{...f,description:p}:f})}i(mK,"getActiveToolDefinitions");import{join as kI}from"node:path";function _I(e,t){if(t&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return kI(e,t)}i(_I,"resolveResumeFromRunDir");function AK(e){let{options:t,runtime:n,managedProtocolPayloadRef:r,sessionId:o}=e,s=t.events??{},a=le(t.context),c=Cy(t),l=$y(Oy([...vt],t.context?.excludeTools),t.context?.toolVisibilityPolicy),d=vt.every(f=>l.includes(f))?_a({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??Lg(),executionCwd:a,shellExecution:t.context?.shellExecution,sandbox:t.sandbox,shellSandbox:t.context?.shellSandbox,providerCredentialEnvironmentNames:Dl(),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=Iy(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 Cr({maxConcurrentThreadsPerSession:t.maxConcurrentThreadsPerSession,sessionId:o});u.actorHost=f,u.actorControl=f.attach(u,t)}return u.workflowHost=SI(t,o,u.actorControl,u.actorHost),u}i(AK,"buildToolExecutionContext");function EI(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(EI,"buildWorkflowHostMetadata");function SI(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";P({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-OGS2R5J4.js"),import("./run-manager-2YMM3BOT.js")]),m=[e.abortSignal,u].filter(k=>k!==void 0),h=m.length===0?void 0:m.length===1?m[0]:AbortSignal.any(m),g=n&&r?{...e,context:{...e.context,actorControl:n,actorHost:r}}:e,w=await f({source:{kind:"inline",manifest:a,source:c},args:l,options:g,runsBaseDir:o,manager:p(),...(()=>{let k=_I(o,d);return k?{resumeFromRunDir:k}:{}})(),...h?{signal:h}:{},processMetadata:{hostMetadata:EI(e,t)}});if(w.kind==="declined")return{kind:"declined",reason:w.reason};let y=w.qualityWarnings?.map(k=>`${k.code}: ${k.message}`),b=w.managed.done.then(k=>{let v=w.managed.getSnapshot?.(),S=k.kind==="completed"?k.state.events.reduce((_,R)=>{if(R.type==="agent_unverified"){let A=R.data?.name??R.data?.taskId;_.push(typeof A=="string"&&A.length>0?A:"agent")}return _},[]):[];return{kind:"started",runId:w.runId,...v?.status!==void 0?{status:v.status}:{},...v?.resultText!==void 0?{resultText:v.resultText}:{},...v?.error!==void 0?{error:v.error}:{},...S.length>0?{verificationWarnings:S}:{},...y&&y.length>0?{workflowQualityWarnings:y}:{}}});return{kind:"started",runId:w.runId,done:b,...y&&y.length>0?{workflowQualityWarnings:y}:{}}},"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(SI,"buildWorkflowToolHost");export{le as a,K as b,Ii as c,hd as d,Fr as e,Ur as f,Wn as g,BI as h,Nd as i,Dd as j,ZI as k,eO as l,tO as m,nO as n,qi as o,Bi as p,bt as q,a_ as r,ba as s,YO as t,qd as u,an as v,Wr as w,Wi as x,Hi as y,Ue as z,Hn as A,Kn as B,Dw as C,Hr as D,Ot as E,Gi as F,ar as G,J0 as H,Q0 as I,To as J,rN as K,oN as L,cN as M,g_ as N,lN as O,zd as P,l$ as Q,Gd as R,Jd as S,Yi as T,Gr as U,Ep as V,yN as W,Sp as X,wN as Y,bN as Z,vN as _,xN as $,Ro as aa,EN as ba,Tp as ca,_$ as da,Qi as ea,es as fa,Cb as ga,Rb as ha,ts as ia,cs as ja,ls as ka,_u as la,Jn as ma,Vn as na,Xn as oa,ns as pa,bu as qa,gs as ra,ys as sa,Qn as ta,bs as ua,vs as va,Xe as wa,gn as xa,YM as ya,df as za,Is as Aa,Os as Ba,uf as Ca,$s as Da,Ps as Ea,Ms as Fa,Ls as Ga,Ds as Ha,js as Ia,Fs as Ja,Us as Ka,nr as La,se as Ma,rk as Na,ta as Oa,KL as Pa,zL as Qa,GL as Ra,or as Sa,xo as Ta,ko as Ua,ir as Va,wk as Wa,bk as Xa,XL as Ya,na as Za,ra as _a,oa as $a,ia as ab,Ft as bb,aa as cb,vn as db,ca as eb,sp as fb,te as gb,la as hb,da as ib,ua as jb,fa as kb,D0 as lb,j0 as mb,F0 as nb,Zk as ob,Eo as pb,U0 as qb,mr as rb,Pe as sb,$o as tb,lg as ub,dT as vb,uT as wb,fr as xb,im as yb,Ka as zb,za as Ab,VD as Bb,xm as Cb,km as Db,ej as Eb,_m as Fb,ij as Gb,sj as Hb,aj as Ib,cj as Jb,lj as Kb,dj as Lb,Em as Mb,Cm as Nb,tc as Ob,eS as Pb,en as Qb,Xo as Rb,qq as Sb,jh as Tb,Fh as Ub,UT as Vb,Kh as Wb,zh as Xb,kr as Yb,cA as Zb,ol as _b,il as $b,s1 as ac,uA as bc,fA as cc,a1 as dc,pr as ec,jo as fc,kt as gc,_t as hc,ic,pc as jc,gr as kc,yr as lc,Km as mc,zm as nc,gc as oc,Ze as pc,_S as qc,bc as rc,zt as sc,Rn as tc,TS as uc,wr as vc,CS as wc,MS as xc,LS as yc,Xt as zc,br as Ac,vr as Bc,BS as Cc,Ac as Dc,Vt as Ec,Yt as Fc,WS as Gc,HS as Hc,KS as Ic,JS as Jc,ZS as Kc,oT as Lc,Ko as Mc,sh as Nc,aT as Oc,cT as Pc,sl as Qc,al as Rc,_1 as Sc,E1 as Tc,S1 as Uc,T1 as Vc,A1 as Wc,_r as Xc,Yo as Yc,tg as Zc,og as _c,IT as $c,On as ad,OT as bd,Pn as cd,Se as dd,Jt as ed,$T as fd,Xc as gd,PT as hd,MT as id,At as jd,LT as kd,NT as ld,DT as md,jT as nd,FT as od,et as pd,Vc as qd,BA as rd,sc as sd,Th as td,Ah as ud,xT as vd,kT as wd,ST as xd,TT as yd,AT as zd,eC as Ad,ug as Bd,fg as Cd,Cy as Dd,hI as Ed,eK as Fd,gI as Gd,tK as Hd,nK as Id,Ry as Jd,Iy as Kd,rK as Ld,oK as Md,iK as Nd,sK as Od,Sr as Pd,pg as Qd,kg as Rd,xl as Sd,Lg as Td,QW as Ud,jg as Vd,Fg as Wd,ri as Xd,lH as Yd,ci as Zd,ty as _d,LH as $d,Cr as ae,KH as be,zH as ce,Oy as de,$y as ee,xI as fe,mK as ge,AK as he};
385
+ </agent-message>`}i($l,"renderMailboxMessage");function cI(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(cI,"assertProviderAuthority");function ye(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}i(ye,"escapeXml");function lI(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(lI,"managedWorkBudgetPort");function dI(e,t){let n=Re(e.specialistName);if(n)return n;let r=Re(e.agentId);if(!(!r||t.actor.kind==="native"))throw new Error(`Agent selector ${r} was not resolved before execution.`)}i(dI,"specialistName");function uI(e){return e==="fast"||e==="balanced"||e==="deep"?e:void 0}i(uI,"modelHint");function fI(e){let t=Re(e);if(!t)return;let n=on(t);return n==="auto"?void 0:n}i(fI,"effort");function Re(e){return typeof e=="string"&&e.length>0?e:void 0}i(Re,"metadataString");function Ey(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}i(Ey,"metadataStringArray");import Ay from"node:path";var pI=80;function mI(e){let t=e.trim().replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,pI);return!t||t==="."||t===".."?"session":t}i(mI,"sanitizeScratchSessionId");function Cy(e){let t=e.session?.id?.trim();if(!t)return;let n=e.context?.gitRoot?.trim(),r=n?Ay.resolve(n):le(e.context);return Ay.resolve(r,".agent","tmp","sessions",mI(t))}i(Cy,"getSessionScratchDir");var hI="emit_managed_protocol",eK="kodax-task-contract",gI="kodax-task-verdict",tK="kodax-task-scout",nK="kodax-task-handoff";function yI(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}i(yI,"asRecord");function Ry(e){return e.trim().toLowerCase()===hI}i(Ry,"isManagedProtocolToolName");function Iy(e,t){if(!(!e&&!t))return{verdict:t?.verdict?{...e?.verdict??{},...t.verdict}:e?.verdict}}i(Iy,"mergeManagedProtocolPayload");function wI(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(wI,"normalizeManagedVerdictStatus");function bI(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(bI,"normalizeManagedNextHarness");function vI(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(vI,"normalizeStringListValue");function rK(e,t,n=""){let r=yI(t);if(!r||e!=="evaluator")return;let o=typeof r.status=="string"?wI(r.status):void 0;if(o)return{verdict:{source:"evaluator",status:o,reason:typeof r.reason=="string"&&r.reason.trim()||void 0,followups:vI(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"?bI(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(rK,"coerceManagedProtocolToolPayload");function oK(e){if(e==="evaluator")return gI}i(oK,"getManagedBlockNameForRole");function iK(e,t){return e&&t==="evaluator"?!!e.verdict:!1}i(iK,"hasManagedProtocolForRole");function sK(e,t){return new RegExp(String.raw`\`\`\`${t}\s*[\s\S]*?\`\`\``,"i").test(e)}i(sK,"textContainsManagedBlock");function Oy(e,t){if(!t||t.length===0)return e;let n=new Set(t);return e.filter(r=>!n.has(r))}i(Oy,"filterExcludedTools");function $y(e,t){return t?e.filter(n=>{let r=Se(n);return r?t({name:r.name,sideEffect:r.sideEffect,planModeAllowed:r.planModeAllowed===!0}):!1}):e}i($y,"applyToolVisibilityPolicy");function xI(e,t,n=!1,r,o=!1){let s=ta(t)==="off"?Yc(e):e;return n||(s=Jc(s)),s=jc(s,r),s=zc(s,r),o||(s=s.filter(a=>a!=="list_dispatchable_agents")),s}i(xI,"getRuntimeActiveToolNames");function mK(e,t,n=!1,r=!1,o,s,a,c=!1){let l=Vc();if(e.length===0)return[];let d=new Set(xI(e,t,r,o,c));return l.filter(u=>d.has(u.name)&&(n||!Ry(u.name))).map(u=>{let f=Gr(u,a);if(!Xo(f.name)||s&&s.has(f.name))return f;let p=en[f.name];return p?{...f,description:p}:f})}i(mK,"getActiveToolDefinitions");import{join as kI}from"node:path";function _I(e,t){if(t&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return kI(e,t)}i(_I,"resolveResumeFromRunDir");function AK(e){let{options:t,runtime:n,managedProtocolPayloadRef:r,sessionId:o}=e,s=t.events??{},a=le(t.context),c=Cy(t),l=$y(Oy([...vt],t.context?.excludeTools),t.context?.toolVisibilityPolicy),d=vt.every(f=>l.includes(f))?_a({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??Lg(),executionCwd:a,shellExecution:t.context?.shellExecution,sandbox:t.sandbox,shellSandbox:t.context?.shellSandbox,providerCredentialEnvironmentNames:Dl(),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=Iy(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 Cr({maxConcurrentThreadsPerSession:t.maxConcurrentThreadsPerSession,sessionId:o});u.actorHost=f,u.actorControl=f.attach(u,t)}return u.workflowHost=SI(t,o,u.actorControl,u.actorHost),u}i(AK,"buildToolExecutionContext");function EI(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(EI,"buildWorkflowHostMetadata");function SI(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";P({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-RF2IX3N6.js"),import("./run-manager-WE2KPAKZ.js")]),m=[e.abortSignal,u].filter(k=>k!==void 0),h=m.length===0?void 0:m.length===1?m[0]:AbortSignal.any(m),g=n&&r?{...e,context:{...e.context,actorControl:n,actorHost:r}}:e,w=await f({source:{kind:"inline",manifest:a,source:c},args:l,options:g,runsBaseDir:o,manager:p(),...(()=>{let k=_I(o,d);return k?{resumeFromRunDir:k}:{}})(),...h?{signal:h}:{},processMetadata:{hostMetadata:EI(e,t)}});if(w.kind==="declined")return{kind:"declined",reason:w.reason};let y=w.qualityWarnings?.map(k=>`${k.code}: ${k.message}`),b=w.managed.done.then(k=>{let v=w.managed.getSnapshot?.(),S=k.kind==="completed"?k.state.events.reduce((_,R)=>{if(R.type==="agent_unverified"){let A=R.data?.name??R.data?.taskId;_.push(typeof A=="string"&&A.length>0?A:"agent")}return _},[]):[];return{kind:"started",runId:w.runId,...v?.status!==void 0?{status:v.status}:{},...v?.resultText!==void 0?{resultText:v.resultText}:{},...v?.error!==void 0?{error:v.error}:{},...S.length>0?{verificationWarnings:S}:{},...y&&y.length>0?{workflowQualityWarnings:y}:{}}});return{kind:"started",runId:w.runId,done:b,...y&&y.length>0?{workflowQualityWarnings:y}:{}}},"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(SI,"buildWorkflowToolHost");export{le as a,K as b,Ii as c,hd as d,Fr as e,Ur as f,Wn as g,BI as h,Nd as i,Dd as j,ZI as k,eO as l,tO as m,nO as n,qi as o,Bi as p,bt as q,a_ as r,ba as s,YO as t,qd as u,an as v,Wr as w,Wi as x,Hi as y,Ue as z,Hn as A,Kn as B,Dw as C,Hr as D,Ot as E,Gi as F,ar as G,J0 as H,Q0 as I,To as J,rN as K,oN as L,cN as M,g_ as N,lN as O,zd as P,l$ as Q,Gd as R,Jd as S,Yi as T,Gr as U,Ep as V,yN as W,Sp as X,wN as Y,bN as Z,vN as _,xN as $,Ro as aa,EN as ba,Tp as ca,_$ as da,Qi as ea,es as fa,Cb as ga,Rb as ha,ts as ia,cs as ja,ls as ka,_u as la,Jn as ma,Vn as na,Xn as oa,ns as pa,bu as qa,gs as ra,ys as sa,Qn as ta,bs as ua,vs as va,Xe as wa,gn as xa,YM as ya,df as za,Is as Aa,Os as Ba,uf as Ca,$s as Da,Ps as Ea,Ms as Fa,Ls as Ga,Ds as Ha,js as Ia,Fs as Ja,Us as Ka,nr as La,se as Ma,rk as Na,ta as Oa,KL as Pa,zL as Qa,GL as Ra,or as Sa,xo as Ta,ko as Ua,ir as Va,wk as Wa,bk as Xa,XL as Ya,na as Za,ra as _a,oa as $a,ia as ab,Ft as bb,aa as cb,vn as db,ca as eb,sp as fb,te as gb,la as hb,da as ib,ua as jb,fa as kb,D0 as lb,j0 as mb,F0 as nb,Zk as ob,Eo as pb,U0 as qb,mr as rb,Pe as sb,$o as tb,lg as ub,dT as vb,uT as wb,fr as xb,im as yb,Ka as zb,za as Ab,VD as Bb,xm as Cb,km as Db,ej as Eb,_m as Fb,ij as Gb,sj as Hb,aj as Ib,cj as Jb,lj as Kb,dj as Lb,Em as Mb,Cm as Nb,tc as Ob,eS as Pb,en as Qb,Xo as Rb,qq as Sb,jh as Tb,Fh as Ub,UT as Vb,Kh as Wb,zh as Xb,kr as Yb,cA as Zb,ol as _b,il as $b,s1 as ac,uA as bc,fA as cc,a1 as dc,pr as ec,jo as fc,kt as gc,_t as hc,ic,pc as jc,gr as kc,yr as lc,Km as mc,zm as nc,gc as oc,Ze as pc,_S as qc,bc as rc,zt as sc,Rn as tc,TS as uc,wr as vc,CS as wc,MS as xc,LS as yc,Xt as zc,br as Ac,vr as Bc,BS as Cc,Ac as Dc,Vt as Ec,Yt as Fc,WS as Gc,HS as Hc,KS as Ic,JS as Jc,ZS as Kc,oT as Lc,Ko as Mc,sh as Nc,aT as Oc,cT as Pc,sl as Qc,al as Rc,_1 as Sc,E1 as Tc,S1 as Uc,T1 as Vc,A1 as Wc,_r as Xc,Yo as Yc,tg as Zc,og as _c,IT as $c,On as ad,OT as bd,Pn as cd,Se as dd,Jt as ed,$T as fd,Xc as gd,PT as hd,MT as id,At as jd,LT as kd,NT as ld,DT as md,jT as nd,FT as od,et as pd,Vc as qd,BA as rd,sc as sd,Th as td,Ah as ud,xT as vd,kT as wd,ST as xd,TT as yd,AT as zd,eC as Ad,ug as Bd,fg as Cd,Cy as Dd,hI as Ed,eK as Fd,gI as Gd,tK as Hd,nK as Id,Ry as Jd,Iy as Kd,rK as Ld,oK as Md,iK as Nd,sK as Od,Sr as Pd,pg as Qd,kg as Rd,xl as Sd,Lg as Td,QW as Ud,jg as Vd,Fg as Wd,ri as Xd,lH as Yd,ci as Zd,ty as _d,LH as $d,Cr as ae,KH as be,zH as ce,Oy as de,$y as ee,xI as fe,mK as ge,AK as he};