@kodax-ai/kodax 0.7.80 → 0.7.81

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 (59) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +14 -3
  3. package/README_CN.md +12 -3
  4. package/dist/chunks/{agent-5PHGNFW3.js → agent-UMBMZLCW.js} +1 -1
  5. package/dist/chunks/argument-completer-MHRFNBWB.js +2 -0
  6. package/dist/chunks/{chunk-PMKAG4SZ.js → chunk-5XCQGFGP.js} +1 -1
  7. package/dist/chunks/{chunk-CDCCTM5I.js → chunk-BNFUIZKY.js} +2 -2
  8. package/dist/chunks/{chunk-GC4JBMBS.js → chunk-D66EWPAX.js} +4 -4
  9. package/dist/chunks/{chunk-RXXKDR6Y.js → chunk-FGQZUN7C.js} +1 -1
  10. package/dist/chunks/{chunk-UZSHBQER.js → chunk-FUK6OUCW.js} +16 -16
  11. package/dist/chunks/{chunk-IHPH3444.js → chunk-ITY7HLSS.js} +2 -2
  12. package/dist/chunks/{chunk-T5U4OP2N.js → chunk-LLWRPP6U.js} +1 -1
  13. package/dist/chunks/{chunk-CEB5FDND.js → chunk-QMPJJCBE.js} +57 -57
  14. package/dist/chunks/{chunk-BWX4YZX3.js → chunk-RX3X3PER.js} +2 -2
  15. package/dist/chunks/{chunk-FQ7NVMSU.js → chunk-THBWLOA3.js} +136 -136
  16. package/dist/chunks/chunk-VTFG3B7U.js +348 -0
  17. package/dist/chunks/{chunk-RPF5RGWZ.js → chunk-WLGQ6XI2.js} +151 -151
  18. package/dist/chunks/{compaction-config-6J6XCBJS.js → compaction-config-SSPH4V36.js} +1 -1
  19. package/dist/chunks/{construction-bootstrap-KPCAE3VN.js → construction-bootstrap-P5ZKDLTM.js} +1 -1
  20. package/dist/chunks/{dist-RWEVZOFK.js → dist-7J763N5L.js} +1 -1
  21. package/dist/chunks/{host-OGS2R5J4.js → host-22ITM5E3.js} +1 -1
  22. package/dist/chunks/{run-manager-2YMM3BOT.js → run-manager-ABNHISGD.js} +1 -1
  23. package/dist/chunks/{utils-2YHRUZYC.js → utils-ATKWKEDP.js} +1 -1
  24. package/dist/index.d.ts +9 -9
  25. package/dist/index.js +1 -1
  26. package/dist/kodax_bootstrap.js +1 -1
  27. package/dist/kodax_cli.js +1155 -1155
  28. package/dist/kodax_resume.js +4 -4
  29. package/dist/runtime-worker.js +1067 -1067
  30. package/dist/sandbox-workspace-session.js +4 -4
  31. package/dist/sdk-a2a.d.ts +5 -5
  32. package/dist/sdk-a2a.js +1 -1
  33. package/dist/sdk-agent.d.ts +4 -4
  34. package/dist/sdk-agent.js +1 -1
  35. package/dist/sdk-coding.d.ts +9 -9
  36. package/dist/sdk-coding.js +1 -1
  37. package/dist/sdk-mcp.js +1 -1
  38. package/dist/sdk-repl.d.ts +9 -9
  39. package/dist/sdk-repl.js +1 -1
  40. package/dist/sdk-runtime.d.ts +12 -5
  41. package/dist/sdk-runtime.js +1 -1
  42. package/dist/sdk-sandbox.js +1 -1
  43. package/dist/sdk-session.d.ts +3 -3
  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-D_bvmnHs.d.ts} +2 -0
  48. package/dist/types-chunks/{capsule.d-BuFJaYxA.d.ts → capsule.d-BFpbFq-C.d.ts} +3 -1
  49. package/dist/types-chunks/{guardrail.d-DM-OK0m3.d.ts → guardrail.d-CrSR1T_a.d.ts} +1 -1
  50. package/dist/types-chunks/{public-api.d-CewTvUKV.d.ts → public-api.d-C-lVOhdt.d.ts} +1 -1
  51. package/dist/types-chunks/{repl.d-DvXQtgr7.d.ts → repl.d-DGi0nhpl.d.ts} +4 -4
  52. package/dist/types-chunks/{sdk-session-C59RUrri.d.ts → sdk-session-D5Ffq4h-.d.ts} +1 -1
  53. package/dist/types-chunks/{shell-command-sets.d-Dp4UvPLL.d.ts → shell-command-sets.d-jmXn8K7r.d.ts} +1 -1
  54. package/dist/types-chunks/{types.d-yuJzE82x.d.ts → types.d-BqYq_ljy.d.ts} +1 -1
  55. package/dist/types-chunks/{utils.d-BpACJmzt.d.ts → utils.d-Z-YpaiUS.d.ts} +3 -3
  56. package/docs/SDK_EMBEDDER_GUIDE.md +13 -4
  57. package/package.json +1 -1
  58. package/dist/chunks/argument-completer-FXRZFMTC.js +0 -2
  59. 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-QMPJJCBE.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(`
@@ -33,7 +33,7 @@ ${t.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.","","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
 
@@ -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-UMBMZLCW.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}
@@ -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-22ITM5E3.js"),import("./run-manager-ABNHISGD.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};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{D as N,J as C}from"./chunk-BWX4YZX3.js";import{Vd as q,Wd as j,ca as _}from"./chunk-GC4JBMBS.js";import{Pa as E,gb as T,m as x,n as R}from"./chunk-TRNAWSXP.js";import{Ad as g,Bd as k,Ed as I,Fd as y,Gd as b,zd as $}from"./chunk-CEB5FDND.js";import{$a as O,ab as W,fb as M}from"./chunk-EVXIJPZ6.js";import{a as o}from"./chunk-ONUPGMER.js";import{join as Pe}from"node:path";var ne=["You generate KodaX Dynamic Workflow scripts.","Return JSON only. Do not wrap the answer in prose.","For simple tasks that do not benefit from multiple agents, return:",'{"action":"decline","reason":"..."}',"For complex tasks, return:",'{"action":"generate","manifest":{...},"source":"async function run(wf, args) { ... }","approvalSummary":"..."}',"Generated source may only coordinate agents through wf and args.","Generated source must return displayable final text for the user.","Never use import, require, process, fs, child_process, network APIs, shell commands, or direct file access."].join(`
2
+ import{D as N,J as C}from"./chunk-RX3X3PER.js";import{Vd as q,Wd as j,ca as _}from"./chunk-D66EWPAX.js";import{Pa as E,gb as T,m as x,n as R}from"./chunk-TRNAWSXP.js";import{Ad as $,Bd as g,Cd as k,Fd as I,Gd as y,Hd as b}from"./chunk-QMPJJCBE.js";import{$a as O,ab as W,fb as M}from"./chunk-EVXIJPZ6.js";import{a as o}from"./chunk-ONUPGMER.js";import{join as Pe}from"node:path";var ne=["You generate KodaX Dynamic Workflow scripts.","Return JSON only. Do not wrap the answer in prose.","For simple tasks that do not benefit from multiple agents, return:",'{"action":"decline","reason":"..."}',"For complex tasks, return:",'{"action":"generate","manifest":{...},"source":"async function run(wf, args) { ... }","approvalSummary":"..."}',"Generated source may only coordinate agents through wf and args.","Generated source must return displayable final text for the user.","Never use import, require, process, fs, child_process, network APIs, shell commands, or direct file access."].join(`
3
3
  `),P=12e4,re="KODAX_WORKFLOW_GENERATION_TIMEOUT_SEC",se="KODAX_WORKFLOW_GENERATION_TIMEOUT_MS",oe=64,ie=2,ae=2e3,le=[{name:"default"},{name:"variant-results",finalText:o((e,n)=>`Variant smoke child report from ${e} (${n}).`,"finalText"),synthesizeText:"Variant smoke synthesis report."},{name:"unverified-success",status:o(()=>"completed_unverified","status"),finalText:o(e=>`Smoke result for ${e}: completed with verification warnings.`,"finalText"),synthesizeText:"Smoke synthesis: completed with verification warnings."},{name:"empty-args-rerun",args:o(()=>({}),"args")}],ce=[{id:"import",pattern:/\bimport\s*(?:\(|['"*{]|\w+\s+from\b)/},{id:"require",pattern:/\brequire\s*\(/},{id:"process",pattern:/\bprocess\s*(?:\.|\[)/},{id:"fs",pattern:/\b(?:node:)?fs\b/},{id:"child_process",pattern:/\bchild_process\b/},{id:"shell",pattern:/\b(?:exec|spawn|execFile)\s*\(/},{id:"fetch",pattern:/\bfetch\s*\(/},{id:"Deno",pattern:/\bDeno\s*(?:\.|\[)/},{id:"Bun",pattern:/\bBun\s*(?:\.|\[)/},{id:"globalThis-index",pattern:/\bglobalThis\s*\[/}];function ue(e=process.env,n){let t=x(n?.workflow?.generationTimeoutSec,"timeouts.workflow.generationTimeoutSec");if(t!==void 0)return t;let r=R(e[re]);if(r!==void 0)return r;let s=e[se];if(s===void 0||s.trim().length===0)return P;let i=Number(s);return!Number.isFinite(i)||i<=0?P:Math.floor(i)}o(ue,"resolveWorkflowGenerationTimeoutMs");function fe(e,n){if(typeof e!="object"||e===null)throw new Error(`${n} must be an object`);return e}o(fe,"readRecord");function D(e,n){let t=e[n];if(typeof t!="string"||t.trim().length===0)throw new Error(`workflow generation ${n} must be a non-empty string`);return t}o(D,"readNonEmptyString");function de(e){let n=e.trim(),t=/^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(n);if(t?.[1])return t[1].trim();let r=n.indexOf("{"),s=n.lastIndexOf("}");if(r>=0&&s>r)return n.slice(r,s+1);throw new Error("workflow generation output did not contain a JSON object")}o(de,"extractJsonText");function pe(e){let n=de(e);return fe(JSON.parse(n),"workflow generation output")}o(pe,"parseGenerationJson");function me(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(typeof e!="object"||e===null)return;let n=e;for(let t of["name","id","title","phase"]){let r=n[t];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}o(me,"normalizePhaseEntry");function we(e){return e.split(/(?:->|\u2192|,|\n)/).map(n=>n.trim()).filter(n=>n.length>0)}o(we,"splitPhaseString");function he(e){if(typeof e!="object"||e===null)return e;let n=e,t=n.phases,r;if(Array.isArray(t)){let s=t.map(me);s.every(i=>i!==void 0)&&(r=s)}else if(typeof t=="string"){let s=we(t);s.length>0&&(r=s)}return r?{...n,phases:r}:e}o(he,"normalizeGeneratedManifestCandidate");function ge(e){return e.match(/\bwf\.(?:runAgent|spawnAgent|synthesize)\s*\(/g)?.length??0}o(ge,"estimateDirectAgentCalls");function ke(e,n){let t=e.maxConcurrency*Math.max(1,e.phases.length)+2,r=ge(n)+2,s=Math.min(oe,Math.max(e.maxAgents,t,r));return s>e.maxAgents?{...e,maxAgents:s}:e}o(ke,"reserveGeneratedWorkflowAgentCapacity");function w(e){let n="",t=0,r=["code"],s=[0];for(;t<e.length;){let i=e[t],a=e[t+1];if(r[r.length-1]==="template"){if(i==="\\"){n+=" ",t+=2;continue}if(i==="`"){n+=" ",t+=1,r.pop(),s.pop();continue}if(i==="$"&&a==="{"){n+=" ",t+=2,r.push("code"),s.push(0);continue}n+=i===`
4
4
  `?`
5
5
  `:" ",t+=1;continue}if(i==="/"&&a==="/"){for(n+=" ",t+=2;t<e.length&&e[t]!==`