@kodax-ai/kodax 0.7.86 → 0.7.87

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 (86) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +16 -4
  3. package/README_CN.md +6 -4
  4. package/dist/chunks/{agent-IO6TXNCV.js → agent-Z64QF7KG.js} +1 -1
  5. package/dist/chunks/argument-completer-HIJBXRUT.js +2 -0
  6. package/dist/chunks/{chunk-Q6UAGROD.js → chunk-3PGNESV3.js} +2 -2
  7. package/dist/chunks/{chunk-B36G256E.js → chunk-4OLXWSCQ.js} +2 -2
  8. package/dist/chunks/{chunk-2RAXDUC7.js → chunk-7XTUXMAI.js} +2 -2
  9. package/dist/chunks/{chunk-AAFFS6RU.js → chunk-ASFCAPIG.js} +3 -3
  10. package/dist/chunks/{chunk-XA4ENCAH.js → chunk-BCYJIACJ.js} +2 -2
  11. package/dist/chunks/{chunk-U6HNMLNN.js → chunk-DB4O33RR.js} +5 -5
  12. package/dist/chunks/{chunk-GVGLYVG4.js → chunk-GRJ7NKWP.js} +1 -1
  13. package/dist/chunks/{chunk-G5FGIRDJ.js → chunk-ITP7J5HX.js} +1 -1
  14. package/dist/chunks/{chunk-HTVLCHWH.js → chunk-JS4RSF4B.js} +1 -1
  15. package/dist/chunks/chunk-SKELDH3G.js +123 -0
  16. package/dist/chunks/{chunk-A5VQGXH2.js → chunk-U44C5STU.js} +1 -1
  17. package/dist/chunks/{chunk-R4EHASEN.js → chunk-UWKM3HNY.js} +4 -4
  18. package/dist/chunks/chunk-XH7UM4GO.js +92 -0
  19. package/dist/chunks/{chunk-UKCDCVMD.js → chunk-XKLVC7F6.js} +1 -1
  20. package/dist/chunks/{chunk-MFCPQZ7E.js → chunk-YB7YVAPL.js} +1 -1
  21. package/dist/chunks/{chunk-XUKLF26Q.js → chunk-ZQNOEKOB.js} +2 -2
  22. package/dist/chunks/compaction-config-E4TFBCDJ.js +2 -0
  23. package/dist/chunks/{construction-bootstrap-4DGAYOWH.js → construction-bootstrap-YTFOT4M2.js} +1 -1
  24. package/dist/chunks/{dist-DFW7MXT7.js → dist-M3JV4PNA.js} +1 -1
  25. package/dist/chunks/{dist-WWL2DNIJ.js → dist-X55TWIK4.js} +1 -1
  26. package/dist/chunks/host-SJHHJBPB.js +2 -0
  27. package/dist/chunks/run-manager-T5QGWNON.js +2 -0
  28. package/dist/chunks/{utils-LV7FHKYN.js → utils-2FHVIO6X.js} +1 -1
  29. package/dist/index.d.ts +19 -19
  30. package/dist/index.js +1 -1
  31. package/dist/kodax_bootstrap.js +1 -1
  32. package/dist/kodax_cli.js +762 -762
  33. package/dist/kodax_resume.js +1 -1
  34. package/dist/provider-capabilities.json +239 -133
  35. package/dist/runtime-worker.js +716 -716
  36. package/dist/sandbox-workspace-session.js +4 -4
  37. package/dist/sdk-a2a.d.ts +12 -12
  38. package/dist/sdk-a2a.js +1 -1
  39. package/dist/sdk-agent.d.ts +17 -17
  40. package/dist/sdk-agent.js +1 -1
  41. package/dist/sdk-coding.d.ts +21 -21
  42. package/dist/sdk-coding.js +1 -1
  43. package/dist/sdk-experimental-memory.d.ts +4 -4
  44. package/dist/sdk-experimental-memory.js +1 -1
  45. package/dist/sdk-llm.d.ts +7 -7
  46. package/dist/sdk-llm.js +1 -1
  47. package/dist/sdk-mcp.js +1 -1
  48. package/dist/sdk-media.d.ts +1 -1
  49. package/dist/sdk-media.js +1 -1
  50. package/dist/sdk-repl.d.ts +16 -16
  51. package/dist/sdk-repl.js +1 -1
  52. package/dist/sdk-runtime.d.ts +13 -13
  53. package/dist/sdk-runtime.js +1 -1
  54. package/dist/sdk-sandbox.js +1 -1
  55. package/dist/sdk-session.d.ts +7 -7
  56. package/dist/sdk-session.js +1 -1
  57. package/dist/sdk-skills.js +1 -1
  58. package/dist/semantic-worker.js +1 -1
  59. package/dist/types-chunks/{base.d-DxG0m09Z.d.ts → base.d-vopO1rml.d.ts} +1 -1
  60. package/dist/types-chunks/{bash-prefix-extractor.d-QqKtuLZm.d.ts → bash-prefix-extractor.d-B36OQwNA.d.ts} +4 -4
  61. package/dist/types-chunks/{capability-learning.d-iPSiAmc_.d.ts → capability-learning.d-CE1tm29C.d.ts} +1 -1
  62. package/dist/types-chunks/{capsule.d-CN_iMqAS.d.ts → capsule.d-DEncDNzD.d.ts} +3 -3
  63. package/dist/types-chunks/{controller.d-A73Kf6tH.d.ts → controller.d-C1YdP_pQ.d.ts} +1 -1
  64. package/dist/types-chunks/{controller.d-Dzxz22X-.d.ts → controller.d-Dif9pbC9.d.ts} +2 -2
  65. package/dist/types-chunks/{guardrail.d-Y_AIh8-I.d.ts → guardrail.d-DhpnJv4Y.d.ts} +5 -5
  66. package/dist/types-chunks/{history-retrieval.d-Debbzn1z.d.ts → history-retrieval.d-YJQpQt7h.d.ts} +2 -2
  67. package/dist/types-chunks/{public-api.d-Cg-4GTbK.d.ts → public-api.d-D4q3WxKq.d.ts} +4 -4
  68. package/dist/types-chunks/{repl.d-Bhrbueab.d.ts → repl.d-D4ye29Kk.d.ts} +5 -5
  69. package/dist/types-chunks/{resolver.d-C9IW4fmU.d.ts → resolver.d-RyPo99tB.d.ts} +2 -2
  70. package/dist/types-chunks/{review-inbox.d-DuZqFX-z.d.ts → review-inbox.d-C1_xZ-yg.d.ts} +1 -1
  71. package/dist/types-chunks/{run-manager.d-BS4lJfL3.d.ts → run-manager.d-D30IvnwV.d.ts} +1 -1
  72. package/dist/types-chunks/{sdk-session-fQ_KENev.d.ts → sdk-session-DIU6sHa2.d.ts} +3 -3
  73. package/dist/types-chunks/{shell-command-sets.d-DRGjd_7Q.d.ts → shell-command-sets.d-rIHkZ_VR.d.ts} +1 -1
  74. package/dist/types-chunks/{side-query.d-CP1LiRiH.d.ts → side-query.d-iH0P9ASy.d.ts} +2 -2
  75. package/dist/types-chunks/{types.d-BRrJU4pb.d.ts → types.d-Bz5Y-PD9.d.ts} +4 -4
  76. package/dist/types-chunks/{types.d-CgrXrFrq.d.ts → types.d-CK9A9rpP.d.ts} +1 -1
  77. package/dist/types-chunks/{types.d-Bo4fyMLu.d.ts → types.d-COhAF5Xo.d.ts} +2 -2
  78. package/dist/types-chunks/{types.d-DlLBRqZ9.d.ts → types.d-sW-OqiFt.d.ts} +1 -1
  79. package/dist/types-chunks/{utils.d-BIhh_BqE.d.ts → utils.d-B65ozSTV.d.ts} +6 -6
  80. package/package.json +1 -1
  81. package/dist/chunks/argument-completer-JMICSGL6.js +0 -2
  82. package/dist/chunks/chunk-TRNAWSXP.js +0 -123
  83. package/dist/chunks/chunk-UH5WNJXF.js +0 -92
  84. package/dist/chunks/compaction-config-5RMG22CY.js +0 -2
  85. package/dist/chunks/host-6MMHYTI5.js +0 -2
  86. package/dist/chunks/run-manager-ISQSWCAM.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{a as hu,b as gu,c as yu,d as wu,e as bu,f as vu,g as ks}from"./chunk-GVGLYVG4.js";import{C as jn,Ja as ys,Pa as ws,S as yo,Sa as Gd,e as ps,f as ms,g as hs,ka as wo,ma as gs}from"./chunk-TRNAWSXP.js";import{$a as jt,Aa as ve,Ac as ko,Bb as ru,Fd as Eo,Gd as _o,Ia as Ie,Ja as dn,Ka as Te,Ld as cu,Pd as xs,Q as Vd,Qd as So,Sb as ou,Sd as To,Sf as du,Vf as uu,Wa as Jd,Xa as vs,Zb as iu,_ as Yd,_g as pu,aa as ln,ac as xo,ah as mu,b as bs,c as xr,db as kr,eb as Ft,eg as fu,fb as Qd,gc as su,ib as ye,jb as Fn,kb as Ut,l as ee,lb as Zd,mb as vo,mc as au,nb as eu,ob as tu,pb as nu,r as bo,se as rt,t as I,te as lu,v as Xd}from"./chunk-G5FGIRDJ.js";import{h as qt,j as je}from"./chunk-UH5WNJXF.js";import{a as i}from"./chunk-ONUPGMER.js";import Er from"node:fs";import Es from"node:os";import se from"node:path";var xb=new Set(["runtime","mcp-tokens","mcp-clients","integrations","sandbox-runtime","processes","learned",".ssh",".aws",".azure",".gnupg",".kube",".docker",".agents",".codex",".claude",".gemini",".direnv",".terraform.d",".password-store"]),kb=new Set(["config.json","auth.json","custom-providers.json","trusted-project-rules.json",".env",".envrc",".pgpass",".npmrc",".pypirc",".netrc",".git-credentials","credentials","credentials.json","application_default_credentials.json","id_rsa","id_ed25519",".gitconfig",".gitmodules",".terraformrc",".condarc",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".bash_history",".zsh_history"]),Eb=new Set([".env.example",".env.sample",".env.template"]);function qn(e){return(e==="~"?Es.homedir():/^~[\\/]/.test(e)?se.join(Es.homedir(),e.slice(2)):e).replace(/^(?:\$\{HOME\}|\$HOME|\$env:(?:home|userprofile)|%userprofile%)(?=$|[\\/])/i,Es.homedir())}i(qn,"expandHome");function xe(e,t=process.cwd()){if(!e.trim()||e.includes("\0"))return;let n=qn(e);if(process.platform==="win32"&&/^[a-z]:[^\\/]/i.test(n))return;let r=[],o=se.resolve(t,n);for(;;){try{Er.lstatSync(o)}catch(s){if(s.code!=="ENOENT")return;let a=se.dirname(o);if(a===o)return;r.unshift(se.basename(o)),o=a;continue}try{return se.join(Er.realpathSync.native(o),...r)}catch{return}}}i(xe,"canonicalizeAgentHomePolicyPath");function _r(e,t){let n=se.relative(t,e);if(!(!n||n.startsWith("..")||se.isAbsolute(n)))return n.split(/[\\/]+/).map(r=>{let o=r.toLowerCase();if(process.platform!=="win32")return o;let s=o.indexOf(":");return(s>=0?o.slice(0,s):o).replace(/[ .]+$/g,"")}).join("/")}i(_r,"normalizedRelative");function xu(e){let t=e.split("/"),n=t.at(-1)??"";return t.some(r=>xb.has(r))||t.some(r=>kb.has(r))||!Eb.has(n)&&(n===".env"||n.startsWith(".env."))||t.some(r=>/^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$/.test(r))?!0:t.some((r,o)=>r===".git"&&["config","config.worktree"].includes(t[o+1]??"")||r===".config"&&t[o+1]==="git"&&t[o+2]==="config"||r===".cargo"&&t[o+1]==="credentials.toml"||r===".m2"&&["settings.xml","settings-security.xml"].includes(t[o+1]??"")||r===".gradle"&&t[o+1]==="gradle.properties"||r===".nuget"&&t.slice(o+1).includes("nuget.config")||r===".pip"&&t[o+1]==="pip.conf"||r===".huggingface"&&t[o+1]==="token"||r===".cache"&&t[o+1]==="huggingface"&&t[o+2]==="token"||r===".config"&&["gcloud","gh","openai","anthropic"].includes(t[o+1]??"")||r===".config"&&t[o+1]==="pip"&&t[o+2]==="pip.conf"||r===".config"&&t[o+1]==="rclone"&&t[o+2]==="rclone.conf"||r===".config"&&t[o+1]==="pypoetry"&&t[o+2]==="auth.toml"||r===".config"&&t[o+1]==="fish"&&["config.fish","fish_variables"].includes(t[o+2]??"")||r===".local"&&t[o+1]==="share"&&t[o+2]==="keyrings"||r==="library"&&t[o+1]==="keychains"||r==="appdata"&&["local","roaming"].includes(t[o+1]??"")&&t[o+2]==="microsoft"&&["credentials","protect","vault"].includes(t[o+3]??""))}i(xu,"isProtectedRelativePath");function _s(e,t){let n=_r(e,t);return n!==void 0&&!xu(n)}i(_s,"isAutoWritableAgentHomePath");function _b(e,t){let n=_r(e,t);if(n===void 0)return!1;if(n==="custom-providers.json")return!0;if(n==="runtime"||n==="runtime/permission-grants.json"||n.startsWith("runtime/daemon/"))return!1;let r=n.startsWith("runtime/")?n.slice(8):n;return!xu(r)}i(_b,"isAutoReadableAgentHomePath");function XP(e,t=process.cwd()){let n;try{n=Ie()}catch{return!0}let r=se.resolve(n),o=se.resolve(t,qn(e)),s=xe(n)??r,a=xe(e,t);return a===void 0?Te(o,r):Te(a,s)&&!_b(a,s)}i(XP,"isProtectedAgentHomeReadTarget");function Sb(e,t=process.cwd()){let n;try{n=Ie()}catch{return!1}let r=se.resolve(n),o=se.resolve(t,qn(e)),s=xe(n)??r,a=xe(e,t);return a===void 0?Te(o,r):Te(a,s)&&!_s(a,s)}i(Sb,"isProtectedAgentHomeMutationTarget");function Un(e,t=process.cwd()){let n;try{n=Ie()}catch{return!1}let r=se.resolve(n),o=se.resolve(t,qn(e));if(Te(o,r)){let l=_r(o,r);if(Ss(l))return!0}let s=xe(n)??r,a=xe(e,t);if(a===void 0)return Te(o,r);if(!Te(a,s))return!1;let c=_r(a,s);return Ss(c)}i(Un,"isAgentHomeHardMutationTarget");function Ss(e){return e===void 0||e==="runtime"||e.startsWith("runtime/")||e==="processes"||e.startsWith("processes/")||e==="learned"||e.startsWith("learned/")}i(Ss,"isHardAgentHomeRelativePath");function ku(e,t=process.cwd()){let n;try{n=Ie()}catch{return!1}let r=se.resolve(t,qn(e));try{if(!Er.lstatSync(r).isSymbolicLink()){let a=se.resolve(n),c=xe(n)??a,l=xe(r);return Te(a,r)||l!==void 0&&Te(c,l)?!0:Un(e,t)}}catch(a){return a.code!=="ENOENT"?!0:Un(e,t)}let o=se.resolve(n);if(!Te(r,o))return!1;let s=_r(r,o);return Ss(s)}i(ku,"isAgentHomeHardRemovalTarget");function VP(e,t=process.cwd()){let n;try{n=Ie()}catch{return!0}let r=se.resolve(n),o=xe(n)??r,s=se.resolve(t,qn(e)),a=xe(s);return Te(r,s)||a!==void 0&&Te(o,a)||Sb(s,t)?!0:Tb(s,o)}i(VP,"isProtectedAgentHomeRemovalTarget");function Tb(e,t){let n;try{n=Er.lstatSync(e)}catch(a){return a.code!=="ENOENT"}let r=n.isSymbolicLink()?se.resolve(e):xe(e);if(r===void 0||Te(r,t)&&!_s(r,t))return!0;if(n.isSymbolicLink()||!n.isDirectory())return!1;let o=[e],s=0;for(;o.length>0;){let a=o.pop(),c;try{c=Er.readdirSync(a,{withFileTypes:!0})}catch{return!0}for(let l of c){if(++s>2e4)return!0;let d=se.join(a,l.name),u=l.isSymbolicLink()?se.resolve(d):xe(d);if(u===void 0||Te(u,t)&&!_s(u,t))return!0;l.isDirectory()&&o.push(d)}}return!1}i(Tb,"removalTreeContainsProtectedPath");import{randomUUID as Tu}from"node:crypto";import{mkdir as Ab,readFile as Cb,rename as Rb,rm as Eu,writeFile as Ib}from"node:fs/promises";import Io from"node:path";var Ao=new Map,Ob=3e4,$b=1e3,Pb=3e4,Co=3,Mb="model-filesystem-effects.json",Lb="model-filesystem-effects.lock",Cs=kr(process.pid),_u=process.env.VITEST_WORKER_ID===void 0?void 0:`${process.env.VITEST_WORKER_ID}-${process.pid}`.replace(/[^a-z0-9_-]/gi,"_");function Su(e,t){return Io.join(e,"runtime",..._u===void 0?[]:[`test-filesystem-effects-${_u}`],t)}i(Su,"effectRuntimePath");function Nb(){let e=process.platform==="win32"?Io.join(Io.resolve(process.env.PROGRAMDATA??"C:\\ProgramData"),"KodaX","sandbox-runtime"):Ie();return{coordinatorPath:Su(e,Lb),statePath:Su(e,Mb)}}i(Nb,"captureEffectLeaseStorage");function Ts(e){if(typeof e!="object"||e===null)return!1;let t=e;return Number.isInteger(t.pid)&&typeof t.token=="string"&&(t.effectPid===void 0||Number.isInteger(t.effectPid))&&(t.effectProcessStartIdentity===void 0||typeof t.effectProcessStartIdentity=="string")&&(t.effectFinished===void 0||typeof t.effectFinished=="boolean")&&(t.processStartIdentity===void 0||typeof t.processStartIdentity=="string")&&(t.sandboxPolicyKey===void 0||typeof t.sandboxPolicyKey=="string")&&(t.posixProcessGroup===void 0||typeof t.posixProcessGroup=="boolean")&&(t.windowsJobContained===void 0||typeof t.windowsJobContained=="boolean")}i(Ts,"isEffectLeaseOwner");async function Sr(e){let t;try{t=await Cb(e.statePath,"utf8")}catch(s){if(s.code==="ENOENT")return{direct:[],namespaces:[],shells:[]};throw s}let n=JSON.parse(t);if(typeof n!="object"||n===null)throw new Error("Invalid filesystem effect lease state.");let r=n;if(!Array.isArray(r.direct)||!r.direct.every(Ts))throw new Error("Invalid direct filesystem effect state.");if(!Array.isArray(r.shells)||!r.shells.every(Ts))throw new Error("Invalid shell filesystem effect state.");let o=r.namespaces??[];if(!Array.isArray(o)||!o.every(Ts))throw new Error("Invalid namespace filesystem effect state.");return{direct:r.direct,namespaces:o,shells:r.shells}}i(Sr,"readEffectLeaseState");function Db(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}i(Db,"isProcessAlive");function Au(e){if(!Db(e.pid))return!1;let t=e.pid===process.pid?Cs:kr(e.pid);return e.processStartIdentity===void 0||t===void 0||t===e.processStartIdentity}i(Au,"isEffectLeaseOwnerAlive");function jb(e,t){if(e.effectFinished===!0)return"absent";if(e.effectPid===void 0)return t?"unknown":"absent";if(e.posixProcessGroup===!0)try{return process.kill(-e.effectPid,0),"alive"}catch(r){return r.code==="ESRCH"?"absent":"unknown"}let n=kr(e.effectPid);return n!==void 0&&(e.effectProcessStartIdentity===void 0||n===e.effectProcessStartIdentity)?"alive":process.platform!=="win32"||e.windowsJobContained===!0||!t?"absent":"unknown"}i(jb,"modelEffectTreeState");function Fb(e,t){let n=new Map;for(let o of[...e.direct,...e.namespaces,...e.shells])n.set(o,Au(o));let r=i(o=>n.get(o)===!0||jb(o,t)!=="absent","keepExternalEffect");return{direct:e.direct.filter(o=>n.get(o)===!0),namespaces:e.namespaces.filter(r),shells:e.shells.filter(r)}}i(Fb,"removeStaleEffectLeases");async function Ub(e){return await Tr(e,async()=>{let r=await Sr(e);return[...r.namespaces,...r.shells].some(o=>!Au(o))})?(await Zd()).skipped>0:!0}i(Ub,"reconcileAbandonedManagedEffects");async function Ro(e,t){let{statePath:n}=e;if(t.direct.length===0&&t.namespaces.length===0&&t.shells.length===0){await Eu(n,{force:!0});return}await Ab(Io.dirname(n),{recursive:!0});let r=`${n}.${process.pid}.${Tu()}.tmp`;await Ib(r,`${JSON.stringify(t)}
2
+ import{a as hu,b as gu,c as yu,d as wu,e as bu,f as vu,g as ks}from"./chunk-GRJ7NKWP.js";import{C as jn,Ja as ys,Pa as ws,S as yo,Sa as Gd,e as ps,f as ms,g as hs,ka as wo,ma as gs}from"./chunk-SKELDH3G.js";import{$a as jt,Aa as ve,Ac as ko,Bb as ru,Fd as Eo,Gd as _o,Ia as Ie,Ja as dn,Ka as Te,Ld as cu,Pd as xs,Q as Vd,Qd as So,Sb as ou,Sd as To,Sf as du,Vf as uu,Wa as Jd,Xa as vs,Zb as iu,_ as Yd,_g as pu,aa as ln,ac as xo,ah as mu,b as bs,c as xr,db as kr,eb as Ft,eg as fu,fb as Qd,gc as su,ib as ye,jb as Fn,kb as Ut,l as ee,lb as Zd,mb as vo,mc as au,nb as eu,ob as tu,pb as nu,r as bo,se as rt,t as I,te as lu,v as Xd}from"./chunk-ITP7J5HX.js";import{h as qt,j as je}from"./chunk-XH7UM4GO.js";import{a as i}from"./chunk-ONUPGMER.js";import Er from"node:fs";import Es from"node:os";import se from"node:path";var xb=new Set(["runtime","mcp-tokens","mcp-clients","integrations","sandbox-runtime","processes","learned",".ssh",".aws",".azure",".gnupg",".kube",".docker",".agents",".codex",".claude",".gemini",".direnv",".terraform.d",".password-store"]),kb=new Set(["config.json","auth.json","custom-providers.json","trusted-project-rules.json",".env",".envrc",".pgpass",".npmrc",".pypirc",".netrc",".git-credentials","credentials","credentials.json","application_default_credentials.json","id_rsa","id_ed25519",".gitconfig",".gitmodules",".terraformrc",".condarc",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".bash_history",".zsh_history"]),Eb=new Set([".env.example",".env.sample",".env.template"]);function qn(e){return(e==="~"?Es.homedir():/^~[\\/]/.test(e)?se.join(Es.homedir(),e.slice(2)):e).replace(/^(?:\$\{HOME\}|\$HOME|\$env:(?:home|userprofile)|%userprofile%)(?=$|[\\/])/i,Es.homedir())}i(qn,"expandHome");function xe(e,t=process.cwd()){if(!e.trim()||e.includes("\0"))return;let n=qn(e);if(process.platform==="win32"&&/^[a-z]:[^\\/]/i.test(n))return;let r=[],o=se.resolve(t,n);for(;;){try{Er.lstatSync(o)}catch(s){if(s.code!=="ENOENT")return;let a=se.dirname(o);if(a===o)return;r.unshift(se.basename(o)),o=a;continue}try{return se.join(Er.realpathSync.native(o),...r)}catch{return}}}i(xe,"canonicalizeAgentHomePolicyPath");function _r(e,t){let n=se.relative(t,e);if(!(!n||n.startsWith("..")||se.isAbsolute(n)))return n.split(/[\\/]+/).map(r=>{let o=r.toLowerCase();if(process.platform!=="win32")return o;let s=o.indexOf(":");return(s>=0?o.slice(0,s):o).replace(/[ .]+$/g,"")}).join("/")}i(_r,"normalizedRelative");function xu(e){let t=e.split("/"),n=t.at(-1)??"";return t.some(r=>xb.has(r))||t.some(r=>kb.has(r))||!Eb.has(n)&&(n===".env"||n.startsWith(".env."))||t.some(r=>/^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$/.test(r))?!0:t.some((r,o)=>r===".git"&&["config","config.worktree"].includes(t[o+1]??"")||r===".config"&&t[o+1]==="git"&&t[o+2]==="config"||r===".cargo"&&t[o+1]==="credentials.toml"||r===".m2"&&["settings.xml","settings-security.xml"].includes(t[o+1]??"")||r===".gradle"&&t[o+1]==="gradle.properties"||r===".nuget"&&t.slice(o+1).includes("nuget.config")||r===".pip"&&t[o+1]==="pip.conf"||r===".huggingface"&&t[o+1]==="token"||r===".cache"&&t[o+1]==="huggingface"&&t[o+2]==="token"||r===".config"&&["gcloud","gh","openai","anthropic"].includes(t[o+1]??"")||r===".config"&&t[o+1]==="pip"&&t[o+2]==="pip.conf"||r===".config"&&t[o+1]==="rclone"&&t[o+2]==="rclone.conf"||r===".config"&&t[o+1]==="pypoetry"&&t[o+2]==="auth.toml"||r===".config"&&t[o+1]==="fish"&&["config.fish","fish_variables"].includes(t[o+2]??"")||r===".local"&&t[o+1]==="share"&&t[o+2]==="keyrings"||r==="library"&&t[o+1]==="keychains"||r==="appdata"&&["local","roaming"].includes(t[o+1]??"")&&t[o+2]==="microsoft"&&["credentials","protect","vault"].includes(t[o+3]??""))}i(xu,"isProtectedRelativePath");function _s(e,t){let n=_r(e,t);return n!==void 0&&!xu(n)}i(_s,"isAutoWritableAgentHomePath");function _b(e,t){let n=_r(e,t);if(n===void 0)return!1;if(n==="custom-providers.json")return!0;if(n==="runtime"||n==="runtime/permission-grants.json"||n.startsWith("runtime/daemon/"))return!1;let r=n.startsWith("runtime/")?n.slice(8):n;return!xu(r)}i(_b,"isAutoReadableAgentHomePath");function XP(e,t=process.cwd()){let n;try{n=Ie()}catch{return!0}let r=se.resolve(n),o=se.resolve(t,qn(e)),s=xe(n)??r,a=xe(e,t);return a===void 0?Te(o,r):Te(a,s)&&!_b(a,s)}i(XP,"isProtectedAgentHomeReadTarget");function Sb(e,t=process.cwd()){let n;try{n=Ie()}catch{return!1}let r=se.resolve(n),o=se.resolve(t,qn(e)),s=xe(n)??r,a=xe(e,t);return a===void 0?Te(o,r):Te(a,s)&&!_s(a,s)}i(Sb,"isProtectedAgentHomeMutationTarget");function Un(e,t=process.cwd()){let n;try{n=Ie()}catch{return!1}let r=se.resolve(n),o=se.resolve(t,qn(e));if(Te(o,r)){let l=_r(o,r);if(Ss(l))return!0}let s=xe(n)??r,a=xe(e,t);if(a===void 0)return Te(o,r);if(!Te(a,s))return!1;let c=_r(a,s);return Ss(c)}i(Un,"isAgentHomeHardMutationTarget");function Ss(e){return e===void 0||e==="runtime"||e.startsWith("runtime/")||e==="processes"||e.startsWith("processes/")||e==="learned"||e.startsWith("learned/")}i(Ss,"isHardAgentHomeRelativePath");function ku(e,t=process.cwd()){let n;try{n=Ie()}catch{return!1}let r=se.resolve(t,qn(e));try{if(!Er.lstatSync(r).isSymbolicLink()){let a=se.resolve(n),c=xe(n)??a,l=xe(r);return Te(a,r)||l!==void 0&&Te(c,l)?!0:Un(e,t)}}catch(a){return a.code!=="ENOENT"?!0:Un(e,t)}let o=se.resolve(n);if(!Te(r,o))return!1;let s=_r(r,o);return Ss(s)}i(ku,"isAgentHomeHardRemovalTarget");function VP(e,t=process.cwd()){let n;try{n=Ie()}catch{return!0}let r=se.resolve(n),o=xe(n)??r,s=se.resolve(t,qn(e)),a=xe(s);return Te(r,s)||a!==void 0&&Te(o,a)||Sb(s,t)?!0:Tb(s,o)}i(VP,"isProtectedAgentHomeRemovalTarget");function Tb(e,t){let n;try{n=Er.lstatSync(e)}catch(a){return a.code!=="ENOENT"}let r=n.isSymbolicLink()?se.resolve(e):xe(e);if(r===void 0||Te(r,t)&&!_s(r,t))return!0;if(n.isSymbolicLink()||!n.isDirectory())return!1;let o=[e],s=0;for(;o.length>0;){let a=o.pop(),c;try{c=Er.readdirSync(a,{withFileTypes:!0})}catch{return!0}for(let l of c){if(++s>2e4)return!0;let d=se.join(a,l.name),u=l.isSymbolicLink()?se.resolve(d):xe(d);if(u===void 0||Te(u,t)&&!_s(u,t))return!0;l.isDirectory()&&o.push(d)}}return!1}i(Tb,"removalTreeContainsProtectedPath");import{randomUUID as Tu}from"node:crypto";import{mkdir as Ab,readFile as Cb,rename as Rb,rm as Eu,writeFile as Ib}from"node:fs/promises";import Io from"node:path";var Ao=new Map,Ob=3e4,$b=1e3,Pb=3e4,Co=3,Mb="model-filesystem-effects.json",Lb="model-filesystem-effects.lock",Cs=kr(process.pid),_u=process.env.VITEST_WORKER_ID===void 0?void 0:`${process.env.VITEST_WORKER_ID}-${process.pid}`.replace(/[^a-z0-9_-]/gi,"_");function Su(e,t){return Io.join(e,"runtime",..._u===void 0?[]:[`test-filesystem-effects-${_u}`],t)}i(Su,"effectRuntimePath");function Nb(){let e=process.platform==="win32"?Io.join(Io.resolve(process.env.PROGRAMDATA??"C:\\ProgramData"),"KodaX","sandbox-runtime"):Ie();return{coordinatorPath:Su(e,Lb),statePath:Su(e,Mb)}}i(Nb,"captureEffectLeaseStorage");function Ts(e){if(typeof e!="object"||e===null)return!1;let t=e;return Number.isInteger(t.pid)&&typeof t.token=="string"&&(t.effectPid===void 0||Number.isInteger(t.effectPid))&&(t.effectProcessStartIdentity===void 0||typeof t.effectProcessStartIdentity=="string")&&(t.effectFinished===void 0||typeof t.effectFinished=="boolean")&&(t.processStartIdentity===void 0||typeof t.processStartIdentity=="string")&&(t.sandboxPolicyKey===void 0||typeof t.sandboxPolicyKey=="string")&&(t.posixProcessGroup===void 0||typeof t.posixProcessGroup=="boolean")&&(t.windowsJobContained===void 0||typeof t.windowsJobContained=="boolean")}i(Ts,"isEffectLeaseOwner");async function Sr(e){let t;try{t=await Cb(e.statePath,"utf8")}catch(s){if(s.code==="ENOENT")return{direct:[],namespaces:[],shells:[]};throw s}let n=JSON.parse(t);if(typeof n!="object"||n===null)throw new Error("Invalid filesystem effect lease state.");let r=n;if(!Array.isArray(r.direct)||!r.direct.every(Ts))throw new Error("Invalid direct filesystem effect state.");if(!Array.isArray(r.shells)||!r.shells.every(Ts))throw new Error("Invalid shell filesystem effect state.");let o=r.namespaces??[];if(!Array.isArray(o)||!o.every(Ts))throw new Error("Invalid namespace filesystem effect state.");return{direct:r.direct,namespaces:o,shells:r.shells}}i(Sr,"readEffectLeaseState");function Db(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}i(Db,"isProcessAlive");function Au(e){if(!Db(e.pid))return!1;let t=e.pid===process.pid?Cs:kr(e.pid);return e.processStartIdentity===void 0||t===void 0||t===e.processStartIdentity}i(Au,"isEffectLeaseOwnerAlive");function jb(e,t){if(e.effectFinished===!0)return"absent";if(e.effectPid===void 0)return t?"unknown":"absent";if(e.posixProcessGroup===!0)try{return process.kill(-e.effectPid,0),"alive"}catch(r){return r.code==="ESRCH"?"absent":"unknown"}let n=kr(e.effectPid);return n!==void 0&&(e.effectProcessStartIdentity===void 0||n===e.effectProcessStartIdentity)?"alive":process.platform!=="win32"||e.windowsJobContained===!0||!t?"absent":"unknown"}i(jb,"modelEffectTreeState");function Fb(e,t){let n=new Map;for(let o of[...e.direct,...e.namespaces,...e.shells])n.set(o,Au(o));let r=i(o=>n.get(o)===!0||jb(o,t)!=="absent","keepExternalEffect");return{direct:e.direct.filter(o=>n.get(o)===!0),namespaces:e.namespaces.filter(r),shells:e.shells.filter(r)}}i(Fb,"removeStaleEffectLeases");async function Ub(e){return await Tr(e,async()=>{let r=await Sr(e);return[...r.namespaces,...r.shells].some(o=>!Au(o))})?(await Zd()).skipped>0:!0}i(Ub,"reconcileAbandonedManagedEffects");async function Ro(e,t){let{statePath:n}=e;if(t.direct.length===0&&t.namespaces.length===0&&t.shells.length===0){await Eu(n,{force:!0});return}await Ab(Io.dirname(n),{recursive:!0});let r=`${n}.${process.pid}.${Tu()}.tmp`;await Ib(r,`${JSON.stringify(t)}
3
3
  `,"utf8");try{await Rb(r,n)}catch(o){try{await Eu(r,{force:!0})}catch(s){throw new AggregateError([o,s],"Filesystem effect state update and cleanup both failed.")}throw o}}i(Ro,"writeEffectLeaseState");async function Tr(e,t){let n=await ko(e.coordinatorPath,Ob);try{return await t()}finally{await n()}}i(Tr,"withEffectLeaseCoordinator");function qb(e,t){return e.sandboxPolicyKey===void 0||t===void 0?!0:e.sandboxPolicyKey!==t}i(qb,"namespaceConflictsWithShell");function As(e,t){return t===void 0||e.sandboxPolicyKey===void 0?!0:e.sandboxPolicyKey!==t}i(As,"shellConflictsWithNamespace");async function Oo(e,t){let n=Nb(),r=Tu(),o={pid:process.pid,token:r,...Cs===void 0?{}:{processStartIdentity:Cs},...t===void 0?{}:{sandboxPolicyKey:t}},s=Date.now()+$b,a=Date.now()+Pb,c=await Ub(n);for(;;){let k=await Tr(n,async()=>{let E=Fb(await Sr(n),c);return(e==="shell"?E.direct.length>0||E.namespaces.some(Y=>qb(Y,t)):e==="direct"?E.shells.length>0||E.namespaces.length>0:E.direct.length>0||E.namespaces.length>0||E.shells.some(Y=>As(Y,t)))?t!==void 0&&(e==="namespace"?E.namespaces.some(L=>L.sandboxPolicyKey!==t)||E.shells.some(L=>As(L,t)):e==="shell"&&E.namespaces.some(L=>L.sandboxPolicyKey!==void 0&&L.sandboxPolicyKey!==t))?"sandbox-policy-conflict":E.direct.length===0&&(e==="namespace"?t!==void 0&&E.shells.every(L=>!As(L,t))&&E.namespaces.length>0&&E.namespaces.every(L=>L.sandboxPolicyKey===t):e==="shell"&&t===void 0&&E.namespaces.length>0&&E.namespaces.every(L=>L.sandboxPolicyKey!==void 0))?"sandbox-acl-transition":!1:(await Ro(n,e==="shell"?{direct:E.direct,namespaces:E.namespaces,shells:[...E.shells,o]}:e==="direct"?{direct:[...E.direct,o],namespaces:E.namespaces,shells:E.shells}:{direct:E.direct,namespaces:[...E.namespaces,o],shells:E.shells}),!0)});if(k===!0)break;if(k==="sandbox-policy-conflict")throw new Error("A different sandbox policy is already active.");let T=k==="sandbox-acl-transition"?a:s;if(Date.now()>=T)throw new Error("A model filesystem effect is already active; retry after it finishes.");await new Promise(E=>setTimeout(E,20))}let l=!1,d,u=!1,f=!1,p=i(()=>Tr(n,async()=>{let k=await Sr(n),T=(e==="shell"?k.shells:e==="direct"?k.direct:k.namespaces).find(E=>E.token===r);if(T===void 0){if(f)return;throw new Error("Filesystem effect lease ownership was lost.")}if(T.effectPid!==void 0&&T.effectFinished!==!0)throw new Error("Filesystem effect process tree has not been proven drained.");f=!0,await Ro(n,e==="shell"?{direct:k.direct,namespaces:k.namespaces,shells:k.shells.filter(E=>E.token!==r)}:e==="direct"?{direct:k.direct.filter(E=>E.token!==r),namespaces:k.namespaces,shells:k.shells}:{direct:k.direct,namespaces:k.namespaces.filter(E=>E.token!==r),shells:k.shells})}),"releaseOnce"),m=i(()=>{if(l||u)return;u=!0;let k=i(()=>{setTimeout(()=>{p().then(()=>{l=!0,u=!1}).catch(()=>{k()})},250).unref?.()},"retry");k()},"scheduleBackgroundRelease"),h=i(async()=>{let k;for(let T=1;T<=Co;T+=1)try{await p();return}catch(E){k=E,T<Co&&await new Promise(D=>setTimeout(D,20))}throw m(),k},"releaseReliably"),y=i(async()=>{l||(d??=h().then(()=>{l=!0}).finally(()=>{d=void 0}),await d)},"release"),w=i(async(k,T)=>{if(!Number.isInteger(k)||k<=0)throw new Error(`Invalid filesystem effect process id: ${k}`);await Tr(n,async()=>{let E=await Sr(n);if(!(e==="shell"?E.shells:e==="direct"?E.direct:E.namespaces).some(ie=>ie.token===r))throw new Error("Filesystem effect lease ownership was lost before process binding.");let Y=kr(k),J={...o,effectPid:k,effectFinished:!1,...Y===void 0?{}:{effectProcessStartIdentity:Y},posixProcessGroup:process.platform!=="win32",windowsJobContained:T},L=i(ie=>ie.token===r?J:ie,"replaceOwner");await Ro(n,{direct:e==="direct"?E.direct.map(L):E.direct,namespaces:e==="namespace"?E.namespaces.map(L):E.namespaces,shells:e==="shell"?E.shells.map(L):E.shells})}),g=!1},"bindEffectProcess"),g=!1,b,v=!1,x=i(()=>Tr(n,async()=>{let k=await Sr(n),T=i(D=>D.token===r?{...D,effectFinished:!0}:D,"replaceOwner");if(!(e==="shell"?k.shells:e==="direct"?k.direct:k.namespaces).some(D=>D.token===r))throw new Error("Filesystem effect lease ownership was lost before tree completion.");await Ro(n,{direct:e==="direct"?k.direct.map(T):k.direct,namespaces:e==="namespace"?k.namespaces.map(T):k.namespaces,shells:e==="shell"?k.shells.map(T):k.shells})}),"finishEffectProcessOnce"),$=i(()=>{if(g||v)return;v=!0;let k=i(()=>{setTimeout(()=>{x().then(()=>{g=!0,v=!1}).catch(()=>{k()})},250).unref?.()},"retry");k()},"scheduleBackgroundFinish");return Object.assign(y,{bindEffectProcess:w,finishEffectProcess:i(async()=>{g||(b??=(async()=>{let k;for(let T=1;T<=Co;T+=1)try{await x(),g=!0;return}catch(E){k=E,T<Co&&await new Promise(D=>setTimeout(D,20))}throw $(),k})().finally(()=>{b=void 0}),await b)},"finishEffectProcess")})}i(Oo,"acquireEffectLease");function Cu(e){return Oo("shell",e)}i(Cu,"acquireFileSystemMutationLease");function rM(e){return Oo("namespace",e)}i(rM,"acquireExclusiveFileSystemEffectLease");function Wb(){return Oo("direct")}i(Wb,"acquireDirectFileMutationLease");async function Bb(e){let t=await Wb();try{return await e()}finally{await t()}}i(Bb,"withHostFileSystemMutation");async function Rs(e){let t=await Oo("namespace");try{return await e(t.bindEffectProcess,t.finishEffectProcess)}finally{await t()}}i(Rs,"withHostFileSystemNamespaceMutation");function Wt(e,t,n){let r=xe(t);if(r===void 0)throw new Error(`Cannot identify backup path: ${t}`);e.delete(r),e.set(r,n)}i(Wt,"recordFileBackup");function Hb(){let e=process.env.KODAX_PATH_KEY_PLATFORM;return e==="win32"?!0:e==="posix"?!1:process.platform==="win32"}i(Hb,"isWindowsPathPlatform");function $o(e){if(typeof e!="string"||e.length===0)return"";let t=e.replace(/\\/g,"/");return t.startsWith("//")?t="//"+t.slice(2).replace(/\/+/g,"/"):t=t.replace(/\/+/g,"/"),Hb()?t=t.toLowerCase():t.length>=2&&/^[A-Za-z]:/.test(t)&&(t=t[0].toLowerCase()+t.slice(1)),t.length>1&&t.endsWith("/")&&(t=t.replace(/\/+$/g,"")),t}i($o,"normalizePathForKey");async function H(e,t){let n=$o(e),o=(Ao.get(n)??Promise.resolve()).catch(()=>{}).then(async()=>Bb(async()=>{if(Un(e))throw new Error(`Mutation targets protected KodaX state: ${e}`);return await t()})),s=o.catch(()=>{}).finally(()=>{Ao.get(n)===s&&Ao.delete(n)});return Ao.set(n,s),o}i(H,"withFileMutation");import{createHash as Kb}from"node:crypto";import Ru from"node:path";var Iu=32,zb=4096,Ou=128,Gb=65536,Xb=262144,Vb=65536,$u=64,Yb=6e5,Jb=6e4,Qb=new Set(["pwsh","powershell","cmd","bash","zsh"]),Zb=new Set(["default","none","login","interactive","login-interactive"]),Pu=3e4,Os=1e4;function $s(e){let t=Ar(e,"shellExecution");if(Po(t,["version","shell","environment","cache","probeTimeoutMs"],"shellExecution"),t.version!==1)throw new Error("shellExecution.version must be 1");let n=Ar(t.shell,"shellExecution.shell");if(Po(n,["kind","executable","args","profile"],"shellExecution.shell"),!Qb.has(n.kind))throw new Error("shellExecution.shell.kind is not supported");let r=n.kind,o=Nu(n.executable,"shellExecution.shell.executable",4096);if(o!==void 0&&!Ru.isAbsolute(o)&&!Ru.win32.isAbsolute(o)&&/[\\/]/.test(o))throw new Error("shellExecution.shell.executable must be absolute or a bare executable name");let s=ev(n.args,r),a=rv(n.profile,r),c=ov(t.environment),l=av(t.cache),d=Lu(t.probeTimeoutMs,"shellExecution.probeTimeoutMs",100,Jb);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($s,"normalizeShellExecutionContract");function Mu(e){return Kb("sha256").update(Is($s(e))).digest("hex")}i(Mu,"shellExecutionContractFingerprint");function Mo(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(Mo,"isSensitiveShellEnvironmentName");function ev(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length>Iu)throw new Error(`shellExecution.shell.args must contain at most ${Iu} strings`);let n=e.map((o,s)=>Ps(o,`shellExecution.shell.args[${s}]`,zb)),r=nv(t);if(n.some(o=>tv(t,o,r)))throw new Error("shellExecution.shell.args cannot override KodaX command or persistence flags");return n}i(ev,"normalizeShellArgs");function tv(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(tv,"isShellControlArgument");function nv(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(nv,"commandControlArgs");function rv(e,t){if(e===void 0)return;if(!Zb.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(rv,"normalizeProfileMode");function ov(e){if(e===void 0)return;let t=Ar(e,"shellExecution.environment");Po(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=iv(t.set),o=sv(t.denyPatterns),s=Nu(t.setup,"shellExecution.environment.setup",Vb),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(ov,"normalizeEnvironment");function iv(e){if(e===void 0)return;let t=Object.entries(Ar(e,"shellExecution.environment.set"));if(t.length>Ou)throw new Error(`shellExecution.environment.set must contain at most ${Ou} 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(Mo(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=cv(s,`shellExecution.environment.set.${o}`,Gb);if(n+=o.length+a.length,n>Xb)throw new Error("shellExecution.environment.set exceeds the size limit");r[o]=a}return r}i(iv,"normalizeEnvironmentSet");function sv(e){if(e!==void 0){if(!Array.isArray(e)||e.length>$u)throw new Error(`shellExecution.environment.denyPatterns must contain at most ${$u} strings`);return e.map((t,n)=>{let r=Ps(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(sv,"normalizeDenyPatterns");function av(e){if(e===void 0)return;let t=Ar(e,"shellExecution.cache");Po(t,["ttlMs","refreshToken"],"shellExecution.cache");let n=Lu(t.ttlMs,"shellExecution.cache.ttlMs",0,Yb),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(av,"normalizeCache");function Lu(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(Lu,"optionalInteger");function Nu(e,t,n){return e===void 0?void 0:Ps(e,t,n)}i(Nu,"optionalBoundedString");function Ps(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(Ps,"boundedString");function cv(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(cv,"boundedStringAllowEmpty");function Ar(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}i(Ar,"requireRecord");function Po(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(Po,"assertOnlyKeys");function Is(e){if(e===null||typeof e!="object")return JSON.stringify(e)??"undefined";if(Array.isArray(e))return`[${e.map(Is).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Is(t[n])}`).join(",")}}`}i(Is,"stableSerialize");import Du from"node:path";var lv=new Set(["COMSPEC","HOMEDRIVE","HOMEPATH","HOME","LOCALAPPDATA","OS","PATH","PATHEXT","PROGRAMDATA","PROGRAMFILES","PROGRAMFILES(X86)","SYSTEMDRIVE","SYSTEMROOT","TEMP","TMP","USERPROFILE","WINDIR"]),dv=new Set(["HOME","LANG","LC_ALL","LOGNAME","PATH","SHELL","TERM","TMPDIR","USER"]),uv=new Set(["BASH_ENV","NODE_OPTIONS","RIPGREP_CONFIG_PATH"]),fv=4096,pv=2*1024*1024;function No(e,t,n=process.platform,r=[],o,s=[]){let a={...e};for(let c of Object.keys(a)){let l=mv(c,s,n);(js(c)||!l&&(Mo(c)||r.some(d=>d.toUpperCase()===c.toUpperCase())))&&hv(a,c,n)}return Ns(a,n,o),n!=="win32"||t!=="cmd"||Fe(a,"NoDefaultCurrentDirectoryInExePath","1",n),a}i(No,"hardenShellCommandEnvironment");function Do(e){return e?Cr(e.split(",")):[]}i(Do,"parseSandboxEnvironmentPass");function Cr(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(Cr,"normalizeSandboxEnvironmentPass");function Fu(e,t,n,r=process.platform){let o={...t};for(let s of n){if(js(s))continue;let a=Object.keys(e).find(c=>Uu(c,s,r));a===void 0||e[a]===void 0||Fe(o,a,e[a],r)}return o}i(Fu,"applyShellEnvironmentPass");function mv(e,t,n){return t.some(r=>Uu(e,r,n))}i(mv,"environmentNameIsListed");function Uu(e,t,n){return n==="win32"?e.toUpperCase()===t.toUpperCase():e===t}i(Uu,"environmentNamesEqual");function Ns(e,t,n){let r=Object.keys(e).find(l=>l.toUpperCase()==="PATH");if(!r||e[r]===void 0)return;let o=t==="win32"?Du.win32:Du.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(Ns,"sanitizeCommandPath");function hv(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(hv,"deleteEnvironmentValue");function Ds(e,t,n,r=process.platform,o=[],s){let a=t.environment?.inherit??"filtered",c=r==="win32"?lv:dv,l={};for(let[d,u]of Object.entries(e))u===void 0||Lo(d,t,o)||a==="none"&&!c.has(d.toUpperCase())||Fe(l,d,u,r);for(let[d,u]of Object.entries(t.environment?.set??{})){if(o.some(f=>f.toUpperCase()===d.toUpperCase()))throw new Error(`shellExecution.environment.set cannot contain active Provider credential variable ${d}`);if(Lo(d,t,o))throw new Error(`shellExecution.environment.set cannot contain denied variable ${d}`);Fe(l,d,u,r)}return n!==void 0&&!Lo("KODAX_SESSION_TMP",t,o)&&Fe(l,"KODAX_SESSION_TMP",n,r),Ns(l,r,s),Hu(l),l}i(Ds,"buildShellProbeEnvironment");function qu(e,t,n=process.platform,r=[],o){let s={};for(let[a,c]of Object.entries(e))Lo(a,t,r)||Fe(s,a,c,n);return Ns(s,n,o),Hu(s),s}i(qu,"sanitizeResolvedShellEnvironment");function Lo(e,t,n=[]){return Mo(e)||js(e)||n.some(r=>r.toUpperCase()===e.toUpperCase())?!0:(t.environment?.denyPatterns??[]).some(r=>gv(e,r))}i(Lo,"isDeniedEnvironmentName");function js(e){return uv.has(e.toUpperCase())||/^BASH_FUNC_.+(?:%%|\(\))$/i.test(e)}i(js,"isExecutionControlEnvironmentName");function gv(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(gv,"environmentNameMatchesPattern");function Wu(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(Wu,"parseWindowsRegistryEnvironment");function Bu(e,t,n){let r=ju(t,"PATH"),o=ju(n,"PATH");if(r===void 0&&o===void 0)return{...e};let s={...e};Ls(s,t),Ls(s,n);let a={...e};Ls(a,t),Fe(a,"PATH","","win32");let c=r===void 0?"":Ms(r,a),l={...s};Fe(l,"PATH",c,"win32");for(let[m,h]of[...Object.entries(t),...Object.entries(n)])m.toUpperCase()!=="PATH"&&Fe(s,m,Ms(h,l),"win32");let d={...s};Fe(d,"PATH",c,"win32");let u=o===void 0?"":Ms(o,d),p=/%PATH%/i.test(o??"")?u:[c,u].filter(m=>m.length>0).join(";");return Fe(s,"PATH",p,"win32"),s}i(Bu,"mergeWindowsRegistryEnvironment");function Ms(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(Ms,"expandWindowsEnvironmentReferences");function Ls(e,t){for(let[n,r]of Object.entries(t))n.toUpperCase()!=="PATH"&&Fe(e,n,r,"win32")}i(Ls,"overlayWindowsRegistryValues");function ju(e,t){return Object.entries(e).find(([n])=>n.toUpperCase()===t.toUpperCase())?.[1]}i(ju,"recordEnvironmentValue");function Fe(e,t,n,r){if(r==="win32"){let o=Object.keys(e).find(s=>s.toUpperCase()===t.toUpperCase());o!==void 0&&o!==t&&delete e[o]}e[t]=n}i(Fe,"setEnvironmentValue");function Hu(e){let t=Object.entries(e);if(t.length>fv)throw new Error("resolved shell environment contains too many variables");if(t.reduce((r,[o,s])=>r+Buffer.byteLength(o)+Buffer.byteLength(s??""),0)>pv)throw new Error("resolved shell environment exceeds the size limit")}i(Hu,"validateEnvironmentSize");import{spawn as yv}from"node:child_process";import{randomBytes as wv}from"node:crypto";import{accessSync as bv,constants as Ku,realpathSync as vv,statSync as xv}from"node:fs";import{delimiter as kv,isAbsolute as zu,join as Fo,resolve as Zu,win32 as Fs}from"node:path";import Us from"iconv-lite";var Ev=3*1024*1024,_v=64,Sv=[`delete process.env.${vs};`,"const s=process.argv[1];","process.stdout.write(s+Buffer.from(JSON.stringify(process.env)).toString('base64')+s);"].join(""),Tv=`eval(Buffer.from('${Buffer.from(Sv).toString("base64")}','base64').toString())`,Bt=new Map,mt=new Map,ef=0;function kM(){ef+=1,Bt.clear();for(let e of mt.values())e.controller.abort();mt.clear()}i(kM,"clearShellExecutionEnvironmentCache");async function tf(e,t,n,r=[],o){if(o?.aborted)throw ot();let s=$s(e),a=Zu(t),c=Vu(a),l=Mu(s),d=n===void 0?"":Vu(n),u=[...r].map(g=>g.toUpperCase()).sort().join("\0"),f=[ef,l,c,d,u].join("\0"),p=Bt.get(f);if(p!==void 0&&p.expiresAt>Date.now())return p.value;p!==void 0&&Bt.delete(f);let m=mt.get(f);if(m?.controller.signal.aborted&&(mt.get(f)===m&&mt.delete(f),m=void 0),m!==void 0)return Gu(m,o);let h=new AbortController,y,w=Av(s,l,a,n,r,h.signal).then(g=>{if(h.signal.aborted||mt.get(f)!==y)throw ot();let b=s.cache?.ttlMs??Pu;return b>0&&qv(f,g,b),g}).finally(()=>{y.settled=!0,mt.get(f)===y&&mt.delete(f)});return y={controller:h,promise:w,waiters:0,settled:!1},mt.set(f,y),Gu(y,o)}i(tf,"resolveShellExecution");function Gu(e,t){return t?.aborted?(e.waiters===0&&!e.settled&&e.controller.abort(),Promise.reject(ot())):(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(ot());return}e.controller.abort(),e.promise.then(()=>r(ot()),()=>r(ot()))},"onAbort");t?.addEventListener("abort",c,{once:!0}),e.promise.then(l=>a({value:l}),l=>a({error:l})),t?.aborted&&c()}))}i(Gu,"waitForInFlightResolution");function ot(){return Object.assign(new Error("shell environment resolution cancelled"),{name:"AbortError"})}i(ot,"shellResolutionAbortError");function nf(e,t,n){let r=n===void 0?Do(process.env.KODAX_SANDBOX_ENV_PASS):Cr(n),o=No(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:Fu(process.env,o,r,process.platform),...e.contract.shell.kind==="cmd"?{windowsVerbatimArguments:!0}:{}}}i(nf,"createShellCommandInvocation");async function Av(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=Ds(process.env,e,r,process.platform,o,n);e.shell.kind==="bash"&&a==="none"&&(c=Wv(c,"BASH_ENV")),process.platform==="win32"&&e.environment?.windowsPath==="registry"&&(c=await Fv(c,n,e,s),c=Ds(c,e,r,process.platform,o,n));let l=Lv(e,c),d=await Cv(l,e,n,c,s);return{executable:l,commandArgs:Pv(e.shell.kind,e.shell.args),env:qu(d,e,process.platform,o),contract:e,contractFingerprint:t}}i(Av,"resolveFreshShellExecution");async function Cv(e,t,n,r,o){let s=`__KODAX_ENV_${wv(16).toString("hex")}__`,a=Iv(t.shell.kind,s),c=t.environment?.setup,l=Ov(t.shell.kind,c,a),d=$v(t.shell.kind,t.shell.args,t.shell.profile??"default",l),u=await Ws({executable:e,args:d,cwd:n,env:r,timeoutMs:t.probeTimeoutMs??Os,kind:"shell-environment-probe",windowsVerbatimArguments:t.shell.kind==="cmd",signal:o});return Rv(u.stdout,s)}i(Cv,"probeShellEnvironment");function Rv(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(Rv,"parseEnvironmentProbeOutput");function Iv(e,t,n=process.execPath,r=process.versions.electron!==void 0,o=process.env.KODAX_BUNDLED==="true"){let s=jt({args:["-e",Tv,t],env:{},executable:n,isBundled:o,isElectron:r}),a;e==="pwsh"||e==="powershell"?a=`& ${Ju(s.command)} ${s.args.map(Ju).join(" ")}`:e==="cmd"?a=[Qu(s.command),...s.args.map(Qu)].join(" "):a=[Yu(s.command),...s.args.map(Yu)].join(" ");let c=[vs,Jd].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(Iv,"buildNodeEnvironmentHelper");function Ov(e,t,n){return t===void 0?e==="cmd"?`"${n}"`:n:e==="pwsh"||e==="powershell"?`$ErrorActionPreference='Stop'; ${t}
4
4
  ${n}`:e==="cmd"?`(${t}) && ${n}`:`set -e
5
5
  ${t}
@@ -17,7 +17,7 @@ ${t.join(`
17
17
  `),sources:[{label:"README",path:"README.md"}],nextTopics:["license","install","quickstart"]},{id:"license",title:"License & commercial-use boundary",aliases:["licensing","kai-fcl","fair core","commercial use","non-commercial","\u8BB8\u53EF\u8BC1","\u8BB8\u53EF\u534F\u8BAE","\u5546\u4E1A\u4F7F\u7528","\u5546\u7528"],summary:"KAI-FCL from v0.7.70, community use, commercial authorization, and historical Apache copies.",body:["Official KodaX 0.7.70 and later distributions use the KodaX-AI Fair Core","License (KAI-FCL) 1.0 or accompanying KodaX-AI customer terms.","KAI-FCL is source-available / fair-core, not OSI open source.","","Community Use covers individual personal learning, individual non-commercial work,","classroom instruction, non-production research, and contribution development/testing.","Commercial or Managed Use is not granted by the community license. Company, team,","institutional, government, production, intranet, managed-device, paid-service, hosted,","or customer redistribution use requires a Customer Agreement with KodaX-AI and, where","required, a valid License Entitlement.","","This change is not retroactive: historical tags, archives, binaries, npm packages, or","other specific copies already distributed under Apache-2.0 keep that Apache-2.0 grant.","Third-party components remain under their own licenses. The repository LICENSE file is","the governing text; this topic is only a concise product summary."].join(`
18
18
  `),sources:[{label:"license",path:"LICENSE"},{label:"README license summary",path:"README.md"}],nextTopics:["overview","install","sdk"]},{id:"install",title:"Install & start KodaX",aliases:["setup","getting started","\u5B89\u88C5","\u542F\u52A8","\u600E\u4E48\u88C5"],summary:"npm install, Node version, secure first-run setup, updating.",body:["Install (Node >= 20):"," npm install -g @kodax-ai/kodax","Then run `kodax` in any project directory to start the interactive REPL.","","On a bare interactive first launch with no selected provider, KodaX opens setup","before it starts the Runtime or REPL, even when a supported credential environment","variable already exists. Setup initializes every missing core/MCP/Extensions/A2A","active file plus its annotated template without overwriting existing files.","It never asks for or stores an API key: it saves only provider/model selection (and validated","public custom-provider metadata), shows the exact required environment-variable name,","then exits. Set that variable, restart terminal, and run `kodax` again.","Use `kodax setup` to rerun the flow, `kodax setup --custom` for the explained custom","provider writer, and `kodax setup --help` or REPL `/setup --help` for the complete","paths/provider/CLI/REPL/shortcut guide. An explicitly","configured provider with a missing key stays an actionable credential error; scripts,","JSON/print/ACP modes, resume, and non-TTY runs never open setup automatically.","","Native binaries (no Node needed) are published per release on GitHub Releases","(darwin/linux/win, arm64/x64).","Update: re-run the npm install, or download the new binary."].join(`
19
19
  `),sources:[{label:"package",path:"package.json"},{label:"setup guide",path:"packages/repl/src/common/setup-guide.ts"},{label:"setup initialization",path:"packages/repl/src/common/setup-config.ts"}],nextTopics:["quickstart","providers","config"]},{id:"quickstart",title:"Quickstart workflow",aliases:["workflow","first task","\u5FEB\u901F\u5F00\u59CB","\u4E0A\u624B","\u600E\u4E48\u7528"],summary:"Open a project, give a task, review, run tests, continue a session.",body:["1. `cd` into your repo and run `kodax`.","2. Describe the task in plain language; KodaX plans, edits, and runs tools.","3. Review proposed edits (permission mode controls auto-accept vs prompt).","4. Ask it to run tests / build to verify.","5. Continue later: `kodax -c` (continue last) or `kodax -r` (resume a picker)."].join(`
20
- `),sources:[{label:"commands",path:"packages/repl/src/interactive/commands.ts"}],nextTopics:["commands","permissions","sessions"]},{id:"providers",title:"Providers & models",aliases:["provider","model","models","llm","\u4F9B\u5E94\u5546","\u6A21\u578B","\u63D0\u4F9B\u5546"],summary:"Built-in providers, choosing a model, credential check, cross-provider fallback.",body:[`KodaX ships ${Ys.length} built-in provider aliases:`,` ${ix}`,"",`Default provider: ${gs} (override with KODAX_PROVIDER env or`,'"provider" in ~/.kodax/config.json). Switch model live with the /model command.',"","Credential variable by built-in alias:",sx,"Set the named variable from the provider console, close and restart the terminal,","then run `kodax doctor`. `kodax setup --help` prints the same complete list.","","Public Kimi uses KIMI_API_KEY and defaults to `kimi-k2.7-code`; select `kimi-k3`","(1,048,576 tokens), `kimi-k2.7-code-highspeed`, `kimi-k2.6`, or `kimi-k2.5`","explicitly. Public K3 shares the Kimi Code K3 reasoning profile. The K2 routes","have a 262,144-token context. K2.7 cannot disable thinking; K2.6 sends its required","wire toggle when thinking is disabled. `kimi-code` is the separate Kimi For Coding","subscription endpoint with KIMI_CODE_API_KEY. It defaults to the direct `k3-256k`","Model ID (Moderato+) and offers Kimi K3 as `k3` (1,048,576 tokens, Allegretto+),","`kimi-for-coding` (K2.7 Code), and `kimi-for-coding-highspeed`. K3 reasoning uses","`thinking.effort`, defaults to high, and supports explicit disable. Public Kimi","and Kimi For Coding credentials are not interchangeable.","","Qwen Token Plan is the separate `qwen-token-plan` alias. It uses","`QWEN_TOKEN_API_KEY`, defaults to `qwen3.8-max`, and speaks the","Anthropic-compatible protocol. `/model` can select the legacy","`qwen3.8-max-preview`, `qwen3.7-max`,","`qwen3.7-plus`, `qwen3.6-flash`, `glm-5.2`, or `deepseek-v4-pro`; these Token","Plan routes have a 1M-token context. Both Qwen 3.8 IDs, 3.7 Plus, and 3.6","Flash accept image input. Qwen 3.8 Max allows up to 131,072 output tokens.","It is distinct from the standard `qwen` alias and its `QWEN_API_KEY`.","","DeepSeek uses DEEPSEEK_API_KEY and defaults to the 1M-context","`deepseek-v4-flash`; select `deepseek-v4-pro` for the Pro reasoning profile.","Both DeepSeek V4 routes are text-only. Flash exposes low/high/max reasoning","while Pro maps low/medium to high and xhigh to max. The built-in cost tracker","uses the current USD-per-1M-token base rates: Flash 0.14 input / 0.28 output /","0.0028 cache read; Pro 0.435 input / 0.87 output / 0.003625 cache read.","","Check a key works: `verifyCredential` (SDK) / a configured provider is validated via","its verifyStrategy in provider-capabilities.json.","Cross-provider fallback on hard errors: /fallback slash + KODAX_FALLBACK_PROVIDERS.","Cheap/strong tiers for dispatched children: KODAX_FAST_* / KODAX_DEEP_*."].join(`
20
+ `),sources:[{label:"commands",path:"packages/repl/src/interactive/commands.ts"}],nextTopics:["commands","permissions","sessions"]},{id:"providers",title:"Providers & models",aliases:["provider","model","models","llm","\u4F9B\u5E94\u5546","\u6A21\u578B","\u63D0\u4F9B\u5546"],summary:"Built-in providers, choosing a model, credential check, cross-provider fallback.",body:[`KodaX ships ${Ys.length} built-in provider aliases:`,` ${ix}`,"",`Default provider: ${gs} (override with KODAX_PROVIDER env or`,'"provider" in ~/.kodax/config.json). Switch model live with the /model command.',"","Credential variable by built-in alias:",sx,"Set the named variable from the provider console, close and restart the terminal,","then run `kodax doctor`. `kodax setup --help` prints the same complete list.","","Public Kimi uses KIMI_API_KEY and defaults to `kimi-k2.7-code`; select `kimi-k3`","(1,048,576 tokens), `kimi-k2.7-code-highspeed`, `kimi-k2.6`, or `kimi-k2.5`","explicitly. Public K3 shares the Kimi Code K3 reasoning profile. The K2 routes","have a 262,144-token context. K2.7 cannot disable thinking; K2.6 sends its required","wire toggle when thinking is disabled. `kimi-code` is the separate Kimi For Coding","subscription endpoint with KIMI_CODE_API_KEY. It defaults to the direct `k3-256k`","Model ID (Moderato+) and offers Kimi K3 as `k3` (1,048,576 tokens, Allegretto+),","`kimi-for-coding` (K2.7 Code), and `kimi-for-coding-highspeed`. K3 reasoning uses","`thinking.effort`, defaults to high, and supports explicit disable. Public Kimi","and Kimi For Coding credentials are not interchangeable.","","Qwen Token Plan is the separate `qwen-token-plan` alias. It uses","`QWEN_TOKEN_API_KEY`, defaults to `qwen3.8-max`, and speaks the","Anthropic-compatible protocol. `/model` can select the legacy","`qwen3.8-max-preview`, `qwen3.7-max`,","`qwen3.7-plus`, `qwen3.6-flash`, `glm-5.2`, or `deepseek-v4-pro`; these Token","Plan routes have a 1M-token context. Both Qwen 3.8 IDs, 3.7 Plus, and 3.6","Flash accept image input. Qwen 3.8 Max allows up to 131,072 output tokens.","It is distinct from the standard `qwen` alias and its `QWEN_API_KEY`.","","`zhipu-coding` defaults to `glm-5.3` and keeps `glm-5.2` as an explicit","rollback route. `zai-coding` defaults to `glm-5.2` and keeps `glm-5.3`","selectable for overseas Coding Plan accounts with access. Both model IDs are","sent verbatim as `glm-5.3` / `glm-5.2`; never append `[1m]` to the wire name.","GLM-5.3 cannot disable thinking: none/minimal/light/low map to low,","medium/high map to high, and xhigh/max/ultra map to max. An off/none intent","therefore becomes enabled low-effort thinking instead of a disabled request.","","DeepSeek uses DEEPSEEK_API_KEY and defaults to the 1M-context","`deepseek-v4-flash`; select `deepseek-v4-pro` for the Pro reasoning profile.","Both DeepSeek V4 routes are text-only. Flash exposes low/high/max reasoning","while Pro maps low/medium to high and xhigh to max. The built-in cost tracker","uses the current USD-per-1M-token base rates: Flash 0.14 input / 0.28 output /","0.0028 cache read; Pro 0.435 input / 0.87 output / 0.003625 cache read.","","Check a key works: `verifyCredential` (SDK) / a configured provider is validated via","its verifyStrategy in provider-capabilities.json.","Cross-provider fallback on hard errors: /fallback slash + KODAX_FALLBACK_PROVIDERS.","Cheap/strong tiers for dispatched children: KODAX_FAST_* / KODAX_DEEP_*."].join(`
21
21
  `),sources:[{label:"provider capabilities",path:"packages/llm/src/providers/provider-capabilities.json"}],nextTopics:["custom-providers","config","troubleshooting"]},{id:"custom-providers",title:"Custom providers",aliases:["custom provider","baseurl","openai compatible","\u81EA\u5B9A\u4E49\u4F9B\u5E94\u5546","\u81EA\u5B9A\u4E49\u6A21\u578B"],summary:"Point KodaX at an OpenAI/Anthropic-compatible endpoint, incl. thinking config.",body:["Run `kodax setup --custom` for an explained interactive writer, or add a","`customProviders` entry in ~/.kodax/config.json for an OpenAI/Anthropic-compatible","endpoint: specify the protocol, baseUrl, API-key environment-variable name, and model.","The wizard explains the local alias, protocol family, provider-documentation Base URL,","environment-variable name, and model identifier; it never asks for a credential value.","KodaX infers a verifyStrategy from the protocol; you can override it explicitly.","Once added, the custom provider is selectable like any built-in one.","","Thinking / reasoning (set on the provider, or per-model in models[]):","- supportsThinking: true is enough for most non-Claude models. With a bare"," supportsThinking: true (no explicit reasoningPreset/reasoningProfile), openai-compat"," stays passive \u2014 KodaX sends no thinking toggle and just surfaces the reasoning the",' model emits; anthropic-compat sends thinking:{type:"enabled"}, which is what the'," Anthropic-compatible endpoints of zhipu / kimi / minimax / deepseek expect. (An"," explicit reasoningPreset/reasoningProfile can send a toggle on openai-compat too.)","- openai-compat multi-turn caveat: some reasoning models (notably DeepSeek V4) reject a"," later turn whose history drops the prior reasoning_content. If thinking shows on the"," first turn but a follow-up errors, also set replayReasoningContent: true (per-provider"," or per-model).","- OpenAI-compatible relays that reject the default `max_completion_tokens` field can"," set maxOutputTokensField: `max_tokens`. The only accepted values are `max_tokens`"," and `max_completion_tokens`; a per-model value overrides the provider-level default.","- DeepSeek V4 OpenAI-compatible configs use the model-specific"," `deepseek-v4-flash-openai` or `deepseek-v4-pro-openai` reasoning preset. Legacy"," `deepseek-v4-openai` configs migrate by model id and keep Pro-like behavior when"," the model cannot be identified.",'- reasoning: { efforts: ["low","high"], default: "high" } adds a tunable effort level.'," On openai-compat it sends reasoning_effort; on anthropic-compat it sends",' thinking:{type:"enabled"} + reasoning_effort (the non-Claude dialect). Include "off"'," in efforts to allow disabling thinking.","- Pointing anthropic-compat at REAL Claude (4.6+)? Claude needs adaptive thinking, not",' the enable toggle \u2014 set reasoningCapability: "native-adaptive" (or an explicit',' reasoningProfile with effortStrategy "anthropic-output-effort").',"- reasoningCapability is the low-level override: native-toggle / native-budget /"," native-effort / native-adaptive / none. It is ignored when supportsThinking is false.","If a relay rejects the chosen thinking shape, KodaX retries the turn once without it, so","it still completes (you just see no thinking) instead of erroring."].join(`
22
22
  `),sources:[{label:"config loader",path:"packages/repl/src/common/utils.ts"},{label:"custom provider reasoning",path:"packages/llm/src/providers/custom-provider.ts"}],nextTopics:["providers","config"]},{id:"config",title:"Configuration",aliases:["settings","config.json","env","\u914D\u7F6E","\u8BBE\u7F6E","\u73AF\u5883\u53D8\u91CF"],summary:"Core config, split integration files, migration, and KODAX_* env precedence.",body:["KodaX config is JSON + env vars \u2014 there is no YAML and no single loader entry.","Core file: ~/.kodax/config.json. Common keys: provider, model, effort,","planModeEffort, permissionMode, customProviders, repoIntelligenceMode, compaction,","fallbackProviders, autoMode, verifierLog, stallLog, runtimeMode, sandbox, worker, and workflow.","`worker.configuredA2A` opts a Worker-hosted embedded Runtime into the configured A2A","plane (see the a2a topic); the CLI reads it from this file.","`autoMode` configures the Runtime-owned Auto Mode engine, optional classifier model,","timeout, and speculative window. In Auto Mode an omitted engine means `llm`; if no","effective classifier model exists, KodaX reports a recoverable configuration error","before it calls a provider or opens a permission prompt. It never silently falls back","to rules for that error.","The active config.json remains strict JSON. Its complete commented reference is","~/.kodax/config.example.jsonc; the template first line points to all split files.","`kodax setup` creates missing active files and all four *.example.jsonc references,","preserves existing files, and migrates readable legacy MCP/Extensions declarations","before installing an otherwise-empty authoritative split file. It validates existing","active files first and stops without writing if any is invalid. `kodax config paths`","prints every active and example path.","Interactive/first-run setup also checks optional ASRT sandbox readiness once. Windows","may show a one-time UAC prompt; macOS/Linux print exact dependency guidance. Ordinary","startup and tool calls do not repeat this reminder or invoke setup automatically.","","User integration declarations are versioned separately:","- MCP: ~/.kodax/integrations/mcp.json","- A2A: ~/.kodax/integrations/a2a.json","- Extensions: ~/.kodax/integrations/extensions.json","Run `kodax integrations migrate` for a dry run, then","`kodax integrations migrate --apply` to create missing split files. Migration imports","MCP and Extensions from config.json#mcpServers and config.json#extensions; A2A has no","legacy source. It does not overwrite an existing destination. The first MCP/Extension mutation","also stages readable legacy entries before applying the change. Review literal-secret warnings,","then add `--cleanup-legacy` with `--apply` only after the destination validates; cleanup removes","a legacy field only when its split destination exists. Initialize A2A with `a2a add` or an empty",'version-2 `{ "version": 2, "agents": {} }` document.',"Long-lived owners hot-reload","valid changes and retain last-known-good state on failure; inbound A2A execution/store","authority changes are reported as restart-required.","If an optional integration file is invalid during cold start, only that domain uses its","safe empty document (no MCP servers, no A2A agents, or no configured Extension paths).","The daemon remains ready, reports structured degraded status, and hot-recovers after a","valid replacement. While a split MCP/Extensions file is absent, both that destination and","the legacy config.json source are watched and polled; status points at the file that is","actually invalid. KodaX does not delete or rewrite the invalid file.","A pre-health child-process failure is captured in","~/.kodax/runtime/daemon/<profile>/bootstrap.log; the active file and bootstrap.log.1 are","both bounded. Use this before deleting configuration or integration directories.","","Env mirrors / extras: KODAX_PROVIDER, KODAX_EFFORT, KODAX_FALLBACK_PROVIDERS, KODAX_FAST_*/KODAX_DEEP_*,","KODAX_REPO_INTELLIGENCE. Env generally overrides file. Project vs user config:","user config is ~/.kodax; project-scoped state lives under <repo>/.kodax/."].join(`
23
23
  `),sources:[{label:"config loader",path:"packages/repl/src/common/utils.ts"},{label:"integration config",path:"packages/repl/src/common/integration-config.ts"},{label:"canonical templates",path:"config-templates/"},{label:"setup guide",path:"packages/repl/src/common/setup-guide.ts"},{label:"setup initialization",path:"packages/repl/src/common/setup-config.ts"},{label:"permission config",path:"packages/repl/src/common/permission-config.ts"}],nextTopics:["providers","permissions","mcp","compaction"]},{id:"permissions",title:"Permission modes",aliases:["permission","approval","dangerous","\u6743\u9650","\u5BA1\u6279","\u6743\u9650\u6A21\u5F0F"],summary:"File/command permission modes, Runtime-owned Auto Mode, and exact grants.",body:["permissionMode controls when KodaX asks before file/command actions:","- accept-edits: auto-apply edits, still gate risky commands.","- plan: read-only planning, no mutations until you switch.","- auto: the Runtime-owned LLM/rules guardrail decides per action before it calls"," the shared permission broker. A safe allow creates no prompt; only an escalate does.",'Set via ~/.kodax/config.json "permissionMode" or the relevant slash command.',"","For a Runtime-backed prompt, choose allow once, a session-scoped exact grant, or (when","offered) a persistent exact grant. The Runtime creates the opaque suggestion; never","construct or widen a scope from the displayed input. Exact command grants include the","normalized command, cwd, shell, and background setting; path grants cover one tool and","one normalized absolute path. Dynamic shell commands deliberately do not get a","persistent suggestion. Persistent grants are daemon-owned and revisioned; use the SDK","permission service to inspect or revoke them.","Legacy grants without a Runtime-issued matcher remain visible and revocable but never","authorize a concrete call. A legacy `allow_always.scope` response is mapped only to a","current Runtime-issued concrete candidate; KodaX never persists its coarse scope.","","Loading static Skill instructions is allowed in Edit and Plan without a client approval","prompt. The Skill's later file, shell, network, or external actions keep their own policy","checks. Skill dynamic-context commands are blocked while Plan is active; outside Plan","they require an explicit host-controlled executor and never fall back to legacy `execSync`.","","Auto Mode defaults to the `llm` engine. If no effective classifier model is available,","it fails with a recoverable configuration error before provider access or approval; it","does not quietly downgrade to rules. Exactly modeled ordinary reads and workspace/temp","mutations bypass classifier latency. Remaining actions are reviewed with bounded genuine","user intent plus exact operation facts; command category alone is not a hazard.","Classifier context is bounded and redacted before it reaches a provider. A timeout or","provider/response failure is retried once, then uses the Accept-edits safety boundary","without switching to Auto[RULES].","Shift-Tab cycles Plan -> Edits -> Auto; Shift+Enter inserts a newline. Entering Auto","shows the configured engine immediately as Auto[LLM] or Auto[RULES], while Runtime","settings updates are serialized so rapid cycling cannot let an older mode win.","Auto[RULES] is an explicit/manual engine; use `/auto-engine llm` to select LLM review.","Critical patterns and classifier/rules concerns request user approval rather than","permanently policy-blocking. Approval timeout cancels only that operation and tells the","main model to try a safer/narrower/reversible approach or wait for explicit approval.","Threat model: KodaX is a single-user CLI; workspace integrity is the user\u2019s responsibility."].join(`
@@ -34,7 +34,7 @@ ${t.join(`
34
34
  `),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(`
35
35
  `),sources:[{label:"v0.7.74 design",path:"docs/features/v0.7.74.md"},{label:"compaction config",path:"packages/coding/src/compaction-config.ts"},{label:"shared policy",path:"packages/agent/src/session-lineage/compaction/policy.ts"},{label:"history recovery",path:"packages/agent/src/session-lineage/history-retrieval.ts"},{label:"durable storage",path:"packages/repl/src/interactive/storage.ts"},{label:"SDK guide",path:"docs/SDK_EMBEDDER_GUIDE.md"}],nextTopics:["config","sessions","sdk"]},{id:"memory",title:"Governed memory",aliases:["memory","remember","recall","memory agent","memory_recall","memory_intent","\u8BB0\u5FC6","\u8BB0\u4F4F","\u4E0B\u6B21\u8BB0\u5F97","\u56DE\u5FC6"],summary:"F228 memory governance, automatic recall, deliberate query, and the experimental SDK.",body:["Top-level coding runs use the existing F228 Memory Control Plane. At session start KodaX","builds an exact-scoped memory pack; passive recall stays on the zero-wait hot path. When","the current context cannot answer a specific question about prior execution experience or","a user preference, the Action LLM may call the read-only memory_recall tool. Current","repository facts must still come from current tools, not memory.","","Memory management is conversation-first. When the user asks what KodaX remembers, or","explicitly asks it to remember, correct, or forget something, the root Action LLM calls","memory_intent. Mutations carry an exact quote from the current user turn. Safe explicit","requests apply immediately through the governed preview/fingerprint/apply controller and","do not create a duplicate episode review. Ordinary narration, quoted examples, temporary","task instructions, ambiguous targets, and sensitive content are not silently stored.","Ambiguous, conflicting, broad, or sensitive requests return clarification or an explained","decision. Autonomous episode review remains separate: verified low-risk changes may","auto-apply, while exceptional inferred changes remain reviewable and restart-recoverable.","","Recalled text is low-authority evidence, never an instruction override. Scope, secret","filtering, source evidence, lifecycle, and mutation protection are deterministic code gates.","Use /memory list|remember|forget|decisions|show|approve|reject|doctor|open as an advanced","escape hatch. MEMORY.md is a derived projection; open launches an external application and","the hidden rebuild command only repairs that projection. Durable changes still pass the","proposal/preview/fingerprint/apply controller;","KodaX does not expose filesystem memory actions or auto-edit prompts, policy, code, or weights.","","For `tool_failure`, `verification_failure`, or a durably committed `context_compacted`","event, `MemorySession.intervene()` rebuilds a closed prompt-safe candidate set and may","inject at most three low-authority evidence items before the next Action-LLM request.","Deterministic exact matches run without a model call. An in-process host may opt into the","bounded `memoryRecallRunner`; malformed, unknown, stale, timed-out, cancelled, or failed","selector output fails silent. The default runtime makes no selector call, and daemon DTOs","reject this function binding.","","SDK hosts can opt into @kodax-ai/kodax/experimental-memory. MemorySession.recall() is","synchronous; query() is deliberate and read-only; observe(), complete(), rewind(), and close()","provide bounded episode lifecycle. Decision receipts are trace-only and do not store hidden","reasoning. This subpath is experimental; the F228 control plane remains the only durable store."].join(`
36
36
  `),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(`
37
- `),sources:[{label:"doctor CLI",path:"src/kodax_doctor.ts"}],nextTopics:["troubleshooting","providers","config"]},{id:"sdk",title:"SDK",aliases:["embed","library","api","sdk\u5165\u95E8","\u5D4C\u5165"],summary:"Published subpaths, shared Runtime hosting, packaged Electron, A2A, and memory.",body:["The source monorepo has 4 workspace packages: @kodax-ai/llm, @kodax-ai/agent,","@kodax-ai/coding, and @kodax-ai/repl. The published @kodax-ai/kodax bundle exposes","12 SDK subpaths: /agent, /llm, /coding, /media, /repl, /skills, /mcp, /session,","/runtime, /sandbox, /a2a, and /experimental-memory.","Use @kodax-ai/kodax/coding for coding tasks; @kodax-ai/kodax/runtime for embedded,","Worker-hosted, or local-daemon sessions/runs/events/permissions;","@kodax-ai/kodax/sandbox for explicit host-owned ASRT containment;","@kodax-ai/kodax/a2a for the A2A 1.0 JSON-RPC/SSE client/server edge; and","@kodax-ai/kodax/experimental-memory for the opt-in MemoryAgent/MemorySession contract.","For an A2A server, listen() waits for durable recovery; a host wiring handle() directly","can await server.whenReady() before accepting traffic.","External Agent owner planes bound close to a 30-second default across admitted work","and executor disposal; hosts may set a positive finite `closeTimeoutMs` override.","","The shared local daemon is authoritative for one Coder profile. Join a session atomically","with sessions.observe(); replace local projection after runtime change/resync_required.","Use sessions.status() for the authoritative Session lifecycle projection and","captureRuntimeSessionDiagnostics() / sessions.diagnostics() for one bounded, read-only","support record. Diagnostics never take ownership, resume, repair, or migrate the Session.","Use sessions.conversation(), sessions.conversationPage(), and","sessions.conversationEntryChunk() for the same immutable ordinary-conversation projection","across embedded and daemon modes; require conversationHistory:1 when that contract is needed.","Control mutations use durable operation identities and settings/permission revisions.","AskUser and permissions are transport-safe. Provider credentials are requested just in","time and scoped to a run/provider; run-bound Host Tools never leak into unrelated CLI","runs. Daemon/inline ownership is fenced, and inline rollback remains sticky. Partner","products keep their separate private embedded Runtime.","","Require `learningCenter:1` and `skillLearningLoop:1` when a host depends on the complete","F263 project-canary contract. `runtime.learning` exposes list/get/snapshot/events/subscribe","plus explicit acknowledge, snooze, reject, disable, rollback, review, trust, and user-scope","promotion controls. Inventory and lifecycle state remain Runtime-owned; clients render","the Learning Center and never infer activation from files alone.","","Packaged/asar Electron hosts may use daemon auto-start when the default-enabled","RunAsNode fuse is available. `homeDir` is the CLI-style base directory that owns","`.kodax`; `KODAX_HOME` is the lower-level `.kodax` path. ELECTRON_RUN_AS_NODE exists","only at the detached child exec boundary and is removed before daemon or user child","code loads. If the fuse is disabled, start the daemon with ordinary Node/CLI and use","attach-only mode; KodaX does not reopen the GUI or silently fall back to inline mode.","","Windows child cleanup identity-checks observed processes and exposes indeterminate outcomes","instead of using bare-PID success. Snapshot ancestry is not Job Object containment: an","intermediate parent can exit before a later snapshot and hide a running descendant. Until","Issue 256 is resolved with spawn-time Job Object assignment and a host-issued Worker owner","lease, do not treat Runtime/Worker close as proof that every descendant terminated.","","Runtime Auto Mode is a durable Session setting, not a UI-side classifier. Query","sessions.getAutoModeStats() for current state and configure the engine/model/timeout","through Session settings. A missing LLM classifier model is a recoverable typed error,","not a fallback to rules or a permission prompt. Permission requests can include opaque","`grantSuggestions`; return a suggestion id for allow_session/allow_always rather than","building a scope. `RuntimePermissionMatcher` describes the Runtime-generated exact","command/path/call matcher, while persistent grants are revisioned through","permissions.listGrants() and revokeGrant(). Daemon capability","`runtimeAutoModeGuardrail` v4 advertises this concrete-grant and intent-aligned fallback contract.","Daemon auto-start requires v4 and safely replaces an idle v3 owner; v4 reports","`fallbackPersistsEngine:false`, so classifier degradation cannot silently select Rules.","","Hosts that depend on bounded source-level streaming batches can require","`runtimeEventCoalescing:1`. Auto-start safely upgrades an idle legacy daemon; busy or","otherwise unsafe owners fail closed instead of being stopped. Text and reasoning deltas","remain reconstructable and each accumulated merge stays within 8 KiB before sequence","allocation, durable event persistence, and subscriber delivery.","","Persisted Actor Sessions have one exclusive Runtime owner. Current owners publish a","loopback identity challenge in addition to their PID, so an unrelated process that reuses","the PID cannot pin crashed ownership. Ambiguous probes and legacy owners remain fail-closed.","","Model `wait_agent` and SDK `runtime.agents.wait()` are intentionally different.","The model tool waits for mailbox/user/interruption/timeout activity and receives only","an acknowledgement. SDK hosts use `runtime.agents.events()` for Actor event snapshots","and `runtime.agents.wait(sessionId, afterSequence, timeoutMs)` for sequence-based","telemetry long-poll; progress remains observable without resampling the action model.","For user input during an active Run, require `interruptInput:1` and call","`runtime.runs.submitInput()`; the Runtime delivers the ordered batch at a safe Runner","boundary rather than creating a continuation Run. A terminal candidate closes the input","window atomically, drains every already-accepted item, and reserves one same-Run model","turn even at the iteration limit. Failure, cancellation, and terminal cleanup keep the","window closed so undelivered input cannot leak into another Run.","","For a Runtime-owned Session, every delivered interrupt is first persisted as its own","canonical user entry. `runtime.runs.get().interruptInputs` and `run.input.delivered` expose","the delivered item's `entryId`, an exact canonical session-entry reference; compaction,","event replay, and Runtime restart preserve it. Treat the field as absent only for legacy","records and never invent an entry id: missing/ambiguous provenance or required persistence","failure fails the current delivery closed.","Since v0.7.82, submitInput resolves the admitted authoritative Run before reading mutable","Session history. Active interrupt and after-turn admission therefore avoid transient","`data_changed`; after-turn still waits for predecessor settlement and an exact operation","id produces one admission and one queue item.","An observed daemon Stop is cooperative: it fences later provider retries, continuations,","guardrails, tools, and Run-admitted Actor work while preserving turns already admitted.","Trusted Stop/Abort causality is classified before credential redaction; completion races","and independent failures remain factual terminal outcomes.","Since v0.7.83, a Windows daemon starts suspended and is assigned to a kill-on-close","Job Object before user code runs. An out-of-Job supervisor waits for daemon exit and","Job emptiness. `waitForRuntimeDaemonShutdown()` requires the exact durable cleanup","outcome plus daemon and supervisor exit; the `daemonShutdownVerification:1` capability","advertises this contract. A legacy daemon without containment is not reported as verified","and cannot be migrated safely in place for this requirement: stop and relaunch it.","This daemon-owned slice narrows Issue 256 but does not close its Worker owner-lease gap,","which remains open and is scheduled for v0.7.87.","Since v0.7.84, Agent progress persistence is bounded to one in-flight","durable projection plus one latest replacement, so terminal settlement does not","wait behind an unbounded progress backlog. If Actor durability becomes unknown,","a same-owner Stop can reconcile and validate the late snapshot, quiesce remaining","turns, and retry the repair. Promise terminal facts outrank fallback callbacks","after repair; foreign owners and unresolved stores remain fail-closed. A no-op","quiesce does not rewrite the Session.","","Since v0.7.85, Runtime event order belongs to one Session journal. Every event","carries a { sessionId, journalEpoch, seq } cursor, and events.subscribe()/replay()","require sessionId or runId; numeric Runtime-global sequences are not resumable.","A2A binds one Runtime Session to each Task, daemon clients require","sessionEventJournal:1, and corrupt journal indexes or ambiguous retention evidence","fail closed. A terminal Run with authoritative status and no queued interrupt input","is restored at startup without replaying its complete event journal.","The semantic repo-intelligence Worker retires after its idle warm-cache window;","a later cache miss starts a fresh Worker.","","F289/F290 keep Memory review draining and lesson/verdict admission bounded and","observable. F292 makes explicit Memory management conversation-first: safe explicit","remember, correction, forget, and recall requests are host-governed, while","ambiguous or inferred changes remain reviewable. The experimental SDK exposes","MemoryManagementAgent only when the supplied controller supports that capability.","","Since v0.7.86, inline daemon-enable recovery removes only a provably abandoned","owner fence; live, malformed, legacy, and ambiguous owners remain fail-closed.","Runtime owner and learning-file lock records include an OS process-start identity,","so PID reuse cannot preserve stale ownership. Windows sandbox ACL owner markers are","durable and recovery is serialized across Runtime profiles. Sandbox stop waits for","process-tree termination proof before ACL recovery; missing attestation fences later","filesystem effects and never replays the command. Spawn, lease-release, and cleanup","failures remain combined in a lifecycle safety diagnostic. POSIX workspace sessions","initialize fresh KODAX_HOME policy roots before identity capture, settle only workspace-local","warm-up within the Shell abort/deadline, retire","invalid cached sessions after lease-cleanup failure, and block replacement after unconfirmed","process-tree or cleanup failure. Issue 256 remains open","and its Worker owner-lease portion is scheduled for v0.7.87.","","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
+ `),sources:[{label:"doctor CLI",path:"src/kodax_doctor.ts"}],nextTopics:["troubleshooting","providers","config"]},{id:"sdk",title:"SDK",aliases:["embed","library","api","sdk\u5165\u95E8","\u5D4C\u5165"],summary:"Published subpaths, shared Runtime hosting, packaged Electron, A2A, and memory.",body:["The source monorepo has 4 workspace packages: @kodax-ai/llm, @kodax-ai/agent,","@kodax-ai/coding, and @kodax-ai/repl. The published @kodax-ai/kodax bundle exposes","12 SDK subpaths: /agent, /llm, /coding, /media, /repl, /skills, /mcp, /session,","/runtime, /sandbox, /a2a, and /experimental-memory.","Use @kodax-ai/kodax/coding for coding tasks; @kodax-ai/kodax/runtime for embedded,","Worker-hosted, or local-daemon sessions/runs/events/permissions;","@kodax-ai/kodax/sandbox for explicit host-owned ASRT containment;","@kodax-ai/kodax/a2a for the A2A 1.0 JSON-RPC/SSE client/server edge; and","@kodax-ai/kodax/experimental-memory for the opt-in MemoryAgent/MemorySession contract.","For an A2A server, listen() waits for durable recovery; a host wiring handle() directly","can await server.whenReady() before accepting traffic.","External Agent owner planes bound close to a 30-second default across admitted work","and executor disposal; hosts may set a positive finite `closeTimeoutMs` override.","","The shared local daemon is authoritative for one Coder profile. Join a session atomically","with sessions.observe(); replace local projection after runtime change/resync_required.","Use sessions.status() for the authoritative Session lifecycle projection and","captureRuntimeSessionDiagnostics() / sessions.diagnostics() for one bounded, read-only","support record. Diagnostics never take ownership, resume, repair, or migrate the Session.","Use sessions.conversation(), sessions.conversationPage(), and","sessions.conversationEntryChunk() for the same immutable ordinary-conversation projection","across embedded and daemon modes; require conversationHistory:1 when that contract is needed.","Control mutations use durable operation identities and settings/permission revisions.","AskUser and permissions are transport-safe. Provider credentials are requested just in","time and scoped to a run/provider; run-bound Host Tools never leak into unrelated CLI","runs. Daemon/inline ownership is fenced, and inline rollback remains sticky. Partner","products keep their separate private embedded Runtime.","","Require `learningCenter:1` and `skillLearningLoop:1` when a host depends on the complete","F263 project-canary contract. `runtime.learning` exposes list/get/snapshot/events/subscribe","plus explicit acknowledge, snooze, reject, disable, rollback, review, trust, and user-scope","promotion controls. Inventory and lifecycle state remain Runtime-owned; clients render","the Learning Center and never infer activation from files alone.","","Packaged/asar Electron hosts may use daemon auto-start when the default-enabled","RunAsNode fuse is available. `homeDir` is the CLI-style base directory that owns","`.kodax`; `KODAX_HOME` is the lower-level `.kodax` path. ELECTRON_RUN_AS_NODE exists","only at the detached child exec boundary and is removed before daemon or user child","code loads. If the fuse is disabled, start the daemon with ordinary Node/CLI and use","attach-only mode; KodaX does not reopen the GUI or silently fall back to inline mode.","","Windows child cleanup identity-checks observed processes and exposes indeterminate outcomes","instead of using bare-PID success. Snapshot ancestry is not Job Object containment: an","intermediate parent can exit before a later snapshot and hide a running descendant. Until","Issue 256 is resolved with spawn-time Job Object assignment and a host-issued Worker owner","lease, do not treat Runtime/Worker close as proof that every descendant terminated.","","Runtime Auto Mode is a durable Session setting, not a UI-side classifier. Query","sessions.getAutoModeStats() for current state and configure the engine/model/timeout","through Session settings. A missing LLM classifier model is a recoverable typed error,","not a fallback to rules or a permission prompt. Permission requests can include opaque","`grantSuggestions`; return a suggestion id for allow_session/allow_always rather than","building a scope. `RuntimePermissionMatcher` describes the Runtime-generated exact","command/path/call matcher, while persistent grants are revisioned through","permissions.listGrants() and revokeGrant(). Daemon capability","`runtimeAutoModeGuardrail` v4 advertises this concrete-grant and intent-aligned fallback contract.","Daemon auto-start requires v4 and safely replaces an idle v3 owner; v4 reports","`fallbackPersistsEngine:false`, so classifier degradation cannot silently select Rules.","","Hosts that depend on bounded source-level streaming batches can require","`runtimeEventCoalescing:1`. Auto-start safely upgrades an idle legacy daemon; busy or","otherwise unsafe owners fail closed instead of being stopped. Text and reasoning deltas","remain reconstructable and each accumulated merge stays within 8 KiB before sequence","allocation, durable event persistence, and subscriber delivery.","","Persisted Actor Sessions have one exclusive Runtime owner. Current owners publish a","loopback identity challenge in addition to their PID, so an unrelated process that reuses","the PID cannot pin crashed ownership. Ambiguous probes and legacy owners remain fail-closed.","","Model `wait_agent` and SDK `runtime.agents.wait()` are intentionally different.","The model tool waits for mailbox/user/interruption/timeout activity and receives only","an acknowledgement. SDK hosts use `runtime.agents.events()` for Actor event snapshots","and `runtime.agents.wait(sessionId, afterSequence, timeoutMs)` for sequence-based","telemetry long-poll; progress remains observable without resampling the action model.","For user input during an active Run, require `interruptInput:1` and call","`runtime.runs.submitInput()`; the Runtime delivers the ordered batch at a safe Runner","boundary rather than creating a continuation Run. A terminal candidate closes the input","window atomically, drains every already-accepted item, and reserves one same-Run model","turn even at the iteration limit. Failure, cancellation, and terminal cleanup keep the","window closed so undelivered input cannot leak into another Run.","","For a Runtime-owned Session, every delivered interrupt is first persisted as its own","canonical user entry. `runtime.runs.get().interruptInputs` and `run.input.delivered` expose","the delivered item's `entryId`, an exact canonical session-entry reference; compaction,","event replay, and Runtime restart preserve it. Treat the field as absent only for legacy","records and never invent an entry id: missing/ambiguous provenance or required persistence","failure fails the current delivery closed.","Since v0.7.82, submitInput resolves the admitted authoritative Run before reading mutable","Session history. Active interrupt and after-turn admission therefore avoid transient","`data_changed`; after-turn still waits for predecessor settlement and an exact operation","id produces one admission and one queue item.","An observed daemon Stop is cooperative: it fences later provider retries, continuations,","guardrails, tools, and Run-admitted Actor work while preserving turns already admitted.","Trusted Stop/Abort causality is classified before credential redaction; completion races","and independent failures remain factual terminal outcomes.","Since v0.7.83, a Windows daemon starts suspended and is assigned to a kill-on-close","Job Object before user code runs. An out-of-Job supervisor waits for daemon exit and","Job emptiness. `waitForRuntimeDaemonShutdown()` requires the exact durable cleanup","outcome plus daemon and supervisor exit; the `daemonShutdownVerification:1` capability","advertises this contract. A legacy daemon without containment is not reported as verified","and cannot be migrated safely in place for this requirement: stop and relaunch it.","This daemon-owned slice narrows Issue 256 but does not close its Worker owner-lease gap,","which remains open after v0.7.87; this release assigns no replacement target.","Since v0.7.84, Agent progress persistence is bounded to one in-flight","durable projection plus one latest replacement, so terminal settlement does not","wait behind an unbounded progress backlog. If Actor durability becomes unknown,","a same-owner Stop can reconcile and validate the late snapshot, quiesce remaining","turns, and retry the repair. Promise terminal facts outrank fallback callbacks","after repair; foreign owners and unresolved stores remain fail-closed. A no-op","quiesce does not rewrite the Session.","","Since v0.7.85, Runtime event order belongs to one Session journal. Every event","carries a { sessionId, journalEpoch, seq } cursor, and events.subscribe()/replay()","require sessionId or runId; numeric Runtime-global sequences are not resumable.","A2A binds one Runtime Session to each Task, daemon clients require","sessionEventJournal:1, and corrupt journal indexes or ambiguous retention evidence","fail closed. A terminal Run with authoritative status and no queued interrupt input","is restored at startup without replaying its complete event journal.","The semantic repo-intelligence Worker retires after its idle warm-cache window;","a later cache miss starts a fresh Worker.","","F289/F290 keep Memory review draining and lesson/verdict admission bounded and","observable. F292 makes explicit Memory management conversation-first: safe explicit","remember, correction, forget, and recall requests are host-governed, while","ambiguous or inferred changes remain reviewable. The experimental SDK exposes","MemoryManagementAgent only when the supplied controller supports that capability.","","Since v0.7.86, inline daemon-enable recovery removes only a provably abandoned","owner fence; live, malformed, legacy, and ambiguous owners remain fail-closed.","Runtime owner and learning-file lock records include an OS process-start identity,","so PID reuse cannot preserve stale ownership. Windows sandbox ACL owner markers are","durable and recovery is serialized across Runtime profiles. Sandbox stop waits for","process-tree termination proof before ACL recovery; missing attestation fences later","filesystem effects and never replays the command. Spawn, lease-release, and cleanup","failures remain combined in a lifecycle safety diagnostic. POSIX workspace sessions","initialize fresh KODAX_HOME policy roots before identity capture, settle only workspace-local","warm-up within the Shell abort/deadline, retire","invalid cached sessions after lease-cleanup failure, and block replacement after unconfirmed","process-tree or cleanup failure. Issue 256 remains open","after v0.7.87; this release assigns no replacement target.","","Coding hosts may pass `memoryRecallRunner` to opt into F275 semantic candidate selection;","without it, sparse governed intervention remains deterministic and adds zero selector calls.","Because the runner is a function binding, Worker/daemon DTO options reject it; configure it","inside the Runtime owner or use inline mode.","","The SDK is ESM-only. Capability queries such as per-model context/limits, credential","verification, and agent discovery can support embedder UIs without starting a coding run."].join(`
38
38
  `),sources:[{label:"published exports",path:"package.json"},{label:"Runtime facade",path:"src/sdk-runtime.ts"},{label:"A2A facade",path:"src/sdk-a2a.ts"},{label:"SDK embedder guide",path:"public_docs/sdk/embedder-guide.md"},{label:"known issues",path:"docs/KNOWN_ISSUES.md"}],nextTopics:["providers","agents","tools"]},{id:"troubleshooting",title:"Troubleshooting",aliases:["error","problem","401","429","fix","\u6392\u969C","\u62A5\u9519","\u95EE\u9898"],summary:"First run kodax doctor; provider 401/429, network, Windows paths, Node/npm.",body:["First: run `kodax doctor --ping` to localize the problem.","- 401 / unauthorized: key missing/invalid \u2014 check provider env var or config.json.","- 429 / rate limit: back off, or set KODAX_FALLBACK_PROVIDERS for cross-provider fallback.","- Network: corporate proxy / region blocks can fail provider endpoints.","- Windows: paths use forward slashes internally; case-insensitive workspace match is handled.","- Node/npm: ensure Node >= 20; reinstall the global package if the CLI is stale.","- Daemon exits before healthy: inspect ~/.kodax/runtime/daemon/<profile>/bootstrap.log.","- Integration degraded: validate only the named integrations/*.json domain. The core"," daemon remains usable and hot-recovers; do not delete config.json or the whole directory."].join(`
39
39
  `),sources:[{label:"doctor CLI",path:"src/kodax_doctor.ts"}],nextTopics:["doctor","providers","config"]}],pf=Object.freeze(Object.fromEntries(ax.map(e=>[e.id,e])));var cx="KodaX";function lx(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(lx,"normalizeInjected");function dx(e,t){let n=new Map,r=[],o=t??ff;for(let s of o){if(n.has(s))continue;let a=pf[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,lx(s));return{ids:r,byId:n}}i(dx,"buildEntries");function ux(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(ux,"scopeAnchor");function gf(e){return e.toLowerCase().split(/[^a-z0-9一-鿿]+/u).filter(t=>t.length>0)}i(gf,"tokenize");function fx(e,t,n){return e.includes(n)?t.get(n):void 0}i(fx,"findByExactId");function px(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(px,"findByAlias");function mx(e,t,n){if(t.length===0)return 0;let r=new Set(gf([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(mx,"scoreTopic");function mf(e,t,n){let r=gf(n),o=n.toLowerCase();return e.map(s=>t.get(s)).map(s=>({topic:s,score:mx(s,r,o)})).filter(s=>s.score>0).sort((s,a)=>a.score-s.score).map(s=>s.topic)}i(mf,"rankByQuery");function hf(e,t){return{matchedTopic:e.id,title:e.title,content:`${ux(e.id,t)}
40
40
 
@@ -372,7 +372,7 @@ LSP errors detected in this file, please fix:
372
372
  ${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(Ce.resolve(t),n).catch(()=>[]);return Yi(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(Ce.resolve(t),n).catch(()=>null);return aw(s)}async getReferences(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.references(Ce.resolve(t),n).catch(()=>[]);return Yi(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(Ce.resolve(t)).catch(()=>[]);return cw(o,"No symbols found in this file.")}async getWorkspaceSymbols(t,n={}){let r=await this.workspaceClients(n);if(r.length===0)return"No language server is available for workspace symbol search.";let o=await Promise.all(r.map(s=>s.workspaceSymbols(t).catch(()=>[])));return lw(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(Ce.resolve(t),n).catch(()=>[]);return Yi(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(Ce.resolve(t),n).catch(()=>[]);return uw(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=Ce.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 fw(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=Ce.resolve(t),a=await o.client.prepareCallHierarchy(s,n).catch(()=>[]);if(a.length===0)return"No call hierarchy item found at that position.";let c=await Promise.all(a.map(l=>o.client.outgoingCalls(l).catch(()=>[])));return pw(c.flat(),"No outgoing calls found for that symbol.")}async navClient(t,n){let r=lo(t);if(!r)return{kind:"message",message:`No language server is configured for ${Ce.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 ${Ce.basename(t)}.`};let s=Ce.resolve(t),a=n.gitRoot??Ce.dirname(s);for(let c of o){let l=vd(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(`
373
373
  `)}}async workspaceClients(t){let n=Ce.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=`${Ze(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??gw)({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||!kd()))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}}},fo,yw=!1;function ww(){let e=yo()?.lsp;if(!(e===!1||e===void 0&&process.env.KODAX_LSP==="0"))return fo||(fo=new Ad({moduleUrl:import.meta.url,debug:process.env.KODAX_DEBUG_LSP?t=>I({source:"coding:lsp",level:"debug",message:t}):void 0}),!yw&&!Ft()&&(yw=!0,process.once("exit",()=>fo?.killAllSync()))),fo}i(ww,"getDefaultLspService");async function Hz(){await fo?.shutdownAll()}i(Hz,"shutdownDefaultLspService");import{createHash as fP}from"node:crypto";import{execFileSync as I$}from"child_process";import{randomUUID as O$}from"node:crypto";import $$ from"fs/promises";import Rw from"os";function bw(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(bw,"resolveTier");function Cd(e,t){let n=yo()?.modelTiers;if(e==="fast")return t?bw(n?.fast,"KODAX_FAST_PROVIDER","KODAX_FAST_MODEL"):void 0;if(e==="deep")return bw(n?.deep,"KODAX_DEEP_PROVIDER","KODAX_DEEP_MODEL")}i(Cd,"resolveModelHintTier");function v$(){let e=process.env.KODAX_FALLBACK_PROVIDERS?.trim();return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}i(v$,"resolveFallbackChain");function vw(e){return e instanceof ms||e instanceof hs||e instanceof ps}i(vw,"isFallbackEligibleError");function x$(e){return e instanceof ms?"rate-limit exhausted":e instanceof hs?"network error":e instanceof ps?"provider error":e instanceof Error?e.message:String(e)}i(x$,"errorReason");async function Rd(e,t,n,r){let o=e.provider??"anthropic";try{return await n(e,t)}catch(s){if(e.abortSignal?.aborted||!vw(s))throw s;let a=v$().filter(l=>l!==o&&(r?.isProviderAllowed?.(l)??!0)),c=s;for(let l of a){r?.onFallback?.({fromProvider:o,toProvider:l,reason:x$(c)});try{return await n({...e,provider:l,model:void 0},t)}catch(d){if(e.abortSignal?.aborted||!vw(d))throw d;c=d}}throw c}}i(Rd,"invokeChildWithFallback");function k$(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(k$,"parseInlineSkillReferences");function E$(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(E$,"parseBareInlineSlashReferences");function xw(e){return Array.from(new Set(k$(e).map(t=>t.name)))}i(xw,"uniqueInlineSkillNames");function kw(e){return Array.from(new Set(E$(e).map(t=>t.name)))}i(kw,"uniqueBareInlineSlashNames");function ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ut,"isRecord");function _$(e){return e instanceof Error?e.message:String(e)}i(_$,"errorMessage");function es(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}i(es,"safeStringify");function Ew(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 ut(e);case"array":return Array.isArray(e);case"null":return e===null;default:return!0}}i(Ew,"matchesType");function S$(e,t){return e.some(n=>n===t?!0:typeof n!="object"||typeof t!="object"?!1:es(n)===es(t))}i(S$,"enumMatches");function Ji(e,t){return e?`${e}.${t}`:t}i(Ji,"joinPath");function Qi(e,t,n=""){if(!ut(t))return[];let r=[],o=n||"(root)",s=t.type;if(typeof s=="string"&&!Ew(e,s))return[`${o}: expected type ${s}`];if(Array.isArray(s)&&!s.some(a=>typeof a=="string"&&Ew(e,a)))return[`${o}: expected one of types ${s.join("|")}`];if(Array.isArray(t.enum)&&!S$(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=>Qi(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(ut(e)){let a=ut(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(`${Ji(n,c)}: required field is missing`);if(a){for(let[c,l]of Object.entries(e))c in a&&r.push(...Qi(l,a[c],Ji(n,c)));if(t.additionalProperties===!1)for(let c of Object.keys(e))c in a||r.push(`${Ji(n,c)}: unexpected property (additionalProperties is false)`)}}return Array.isArray(e)&&ut(t.items)&&e.forEach((a,c)=>{r.push(...Qi(a,t.items,`${o}[${c}]`))}),r}i(Qi,"validateAgainstSchema");var T$=["$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 Zi(e,t,n){if(ut(e)){for(let r of T$)r in e&&!n.has(r)&&n.set(r,t||"(root)");if(ut(e.properties))for(let[r,o]of Object.entries(e.properties))Zi(o,Ji(t,r),n);if(ut(e.items)&&Zi(e.items,`${t||"(root)"}[]`,n),Array.isArray(e.oneOf))for(let r of e.oneOf)Zi(r,`${t||"(root)"}(oneOf)`,n);ut(e.additionalProperties)&&!n.has("additionalProperties (schema form)")&&n.set("additionalProperties (schema form)",t||"(root)")}}i(Zi,"collectUnsupportedKeywords");function tG(e){if(!ut(e))return;let t=new Map;if(Zi(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(tG,"assertSupportedOutputSchema");function A$(e){let t=e.indexOf("{"),n=e.indexOf("[");return t<0?n:n<0?t:Math.min(t,n)}i(A$,"firstStructureStart");function _w(e){let t=A$(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(_w,"balancedStructure");function C$(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?_w(r)??r:_w(e)}i(C$,"extractJsonCandidate");function Id(e,t){let n=C$(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: ${_$(s)}`]}}let o=Qi(r,t);return{ok:o.length===0,value:r,errors:o}}i(Id,"evaluateStructuredOutput");function Sw(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",es(e),"```"].join(`
374
374
  `)}i(Sw,"buildStructuredOutputInstruction");function Tw(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",es(t),"```"].join(`
375
- `)}i(Tw,"buildStructuredOutputRepairPrompt");var Aw={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 rs(e){if(!ns(e)||!Od(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=Cw(e.assertedCoverage);if(t===void 0)return;let n=[];for(let r of e.outcomes){let o=R$(r);if(o===void 0)return;n.push(o)}return{schemaVersion:1,outcomes:n,assertedCoverage:[...new Set(t)]}}i(rs,"parsePatternDispositionEnvelope");function wr(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=wr(r);if(o===void 0)return;n.push(o)}return n}if(!ns(e))return;let t={};for(let[n,r]of Object.entries(e)){let o=wr(r);if(o===void 0)return;t[n]=o}return t}i(wr,"toAgentMetadataValue");function R$(e){if(!ns(e)||!Od(e,["target","disposition","evidenceRefs"])||!ns(e.target)||!Od(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=Cw(e.evidenceRefs);if(t===void 0)return;let n=ts(e.target.actorPath),r=ts(e.target.turnId),o=ts(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(R$,"parseOutcome");function Cw(e){let t=[];for(let n of e){let r=ts(n);if(r===void 0)return;t.push(r)}return t}i(Cw,"stringArray");function ts(e){if(typeof e!="string")return;let t=e.trim();return t.length>0&&t.length<=512?t:void 0}i(ts,"boundedString");function ns(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ns,"isRecord");function Od(e,t){let n=new Set(t);return Object.keys(e).every(r=>n.has(r))}i(Od,"hasOnlyKeys");var $d,os;async function Mw(){if($d)return $d;if(!os){let e="./agent.js";os=import("./agent-IO6TXNCV.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 $d=n,n}).catch(t=>{if(os=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 os}i(Mw,"getRunKodaX");var P$=["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(`
375
+ `)}i(Tw,"buildStructuredOutputRepairPrompt");var Aw={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 rs(e){if(!ns(e)||!Od(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=Cw(e.assertedCoverage);if(t===void 0)return;let n=[];for(let r of e.outcomes){let o=R$(r);if(o===void 0)return;n.push(o)}return{schemaVersion:1,outcomes:n,assertedCoverage:[...new Set(t)]}}i(rs,"parsePatternDispositionEnvelope");function wr(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=wr(r);if(o===void 0)return;n.push(o)}return n}if(!ns(e))return;let t={};for(let[n,r]of Object.entries(e)){let o=wr(r);if(o===void 0)return;t[n]=o}return t}i(wr,"toAgentMetadataValue");function R$(e){if(!ns(e)||!Od(e,["target","disposition","evidenceRefs"])||!ns(e.target)||!Od(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=Cw(e.evidenceRefs);if(t===void 0)return;let n=ts(e.target.actorPath),r=ts(e.target.turnId),o=ts(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(R$,"parseOutcome");function Cw(e){let t=[];for(let n of e){let r=ts(n);if(r===void 0)return;t.push(r)}return t}i(Cw,"stringArray");function ts(e){if(typeof e!="string")return;let t=e.trim();return t.length>0&&t.length<=512?t:void 0}i(ts,"boundedString");function ns(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ns,"isRecord");function Od(e,t){let n=new Set(t);return Object.keys(e).every(r=>n.has(r))}i(Od,"hasOnlyKeys");var $d,os;async function Mw(){if($d)return $d;if(!os){let e="./agent.js";os=import("./agent-Z64QF7KG.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 $d=n,n}).catch(t=>{if(os=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 os}i(Mw,"getRunKodaX");var P$=["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(`
376
376
  `),M$=["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(`
377
377
  `),Lw=4,Nw=1e4,L$=45e3,N$=40;function Dw(e,t){return e.historyStorage?{id:`worker-${O$()}`,scope:"managed-task-worker",storage:e.historyStorage,...t&&t.length>0?{initialMessages:[...t]}:{}}:t&&t.length>0?{initialMessages:[...t]}:void 0}i(Dw,"buildChildRunSession");function ss(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(ss,"inheritRepoIntelligenceContext");async function jw(e,t,n){if(e.length===0)return Pw;let r=e.filter(f=>f.readOnly),o=e.filter(f=>!f.readOnly),s=uP(o,n.parentRole,n.parentHarness),a=[...r,...s];if(a.length===0)return Pw;let c=[],l=[],d=n.onProgress??(()=>{});d(`Starting ${a.length} child tasks in parallel`);let u=await ru({bundles:a,runOne:i(f=>f.readOnly?eP(f,t,n):nP(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(Nn(f.bundle,`[Crash] ${f.reason.message}`,"failed"));for(let f of u.cancelled)l.push(f.id);return dP(a,c,l)}i(jw,"executeChildAgents");function Fw(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(Fw,"buildChildPermissionIntent");var D$=["list_dispatchable_agents","spawn_agent","run_workflow","send_message","followup_task","wait_agent","interrupt_agent","list_agents","agent_output","emit_managed_protocol"];function j$(e,t){if(!t)return e;let n=new Set(t.tools),r=n.has("*"),o=new Set(e);for(let s of on()){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(j$,"restrictToolsForActor");function Uw(e,t,n){let r=j$(e,t);return n!==void 0?r:[...new Set([...r,...D$])]}i(Uw,"restrictToolsForChildRuntime");function as(e,t){return t.contextAgentId??e.id}i(as,"childContextAgentId");function cs(e,t){return t.contextParentAgentId??(t.actorControl!==void 0?t.actorParentAgentId:e.currentAgentId)}i(cs,"childContextParentAgentId");function is(e,t,n){if(t.includes(e))return!1;let r=on().find(o=>o.name===e);return r?n.toolVisibilityPolicy?.({name:r.name,sideEffect:r.sideEffect,planModeAllowed:r.planModeAllowed===!0})??!0:!1}i(is,"isChildToolVisible");function Pd(e,t){return t===void 0||t.providers.includes("*")||t.providers.includes(e)}i(Pd,"isProviderAllowed");function qw(e,t){if(!Pd(e,t))throw new Error(`Child Actor is not authorized to use provider ${e}.`)}i(qw,"assertChildProviderAllowed");function F$(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(F$,"readWorktreePath");async function Ww(e,t){if(e.isolation!=="worktree")return{ctx:t};let n=await Dh({description:`workflow-${e.id}`},t),r=F$(n);return{ctx:{...t,gitRoot:r,executionCwd:r},worktreePath:r}}i(Ww,"prepareChildIsolationScope");function Bw(e,t){return t.worktreePath?[`[Workflow worktree: ${t.worktreePath}]`,e].join(`
378
378
  `):e}i(Bw,"annotateWorktreeSummary");async function Iw(e,t){if(e.worktreePath)try{await Fh(e.worktreePath,t);return}catch(n){return`[Workflow worktree cleanup failed: ${n instanceof Error?n.message:String(n)}]`}}i(Iw,"cleanupChildIsolationScope");function U$(e,t){return t?{...e,summary:`${e.summary}
@@ -407,4 +407,4 @@ ${Pe(o)}
407
407
  ${Pe(e.content)}
408
408
  </agent-completed>`}return`<agent-message id="${Pe(e.messageId)}" from="${Pe(e.senderPath)}" classification="${e.classification}">
409
409
  ${Pe(e.content)}
410
- </agent-message>`}i(jd,"renderMailboxMessage");function SP(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(SP,"assertProviderAuthority");function Pe(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}i(Pe,"escapeXml");function TP(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(TP,"managedWorkBudgetPort");function AP(e,t){let n=ze(e.specialistName);if(n)return n;let r=ze(e.agentId);if(!(!r||t.actor.kind==="native"))throw new Error(`Agent selector ${r} was not resolved before execution.`)}i(AP,"specialistName");function CP(e){return e==="fast"||e==="balanced"||e==="deep"?e:void 0}i(CP,"modelHint");function RP(e){let t=ze(e);if(!t)return;let n=jn(t);return n==="auto"?void 0:n}i(RP,"effort");function ze(e){return typeof e=="string"&&e.length>0?e:void 0}i(ze,"metadataString");function cb(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}i(cb,"metadataStringArray");import ub from"node:path";var IP=80;function OP(e){let t=e.trim().replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,IP);return!t||t==="."||t===".."?"session":t}i(OP,"sanitizeScratchSessionId");function fb(e){let t=e.session?.id?.trim();if(!t)return;let n=e.context?.gitRoot?.trim(),r=n?ub.resolve(n):ke(e.context);return ub.resolve(r,".agent","tmp","sessions",OP(t))}i(fb,"getSessionScratchDir");var $P="emit_managed_protocol",zG="kodax-task-contract",PP="kodax-task-verdict",GG="kodax-task-scout",XG="kodax-task-handoff";function MP(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}i(MP,"asRecord");function pb(e){return e.trim().toLowerCase()===$P}i(pb,"isManagedProtocolToolName");function mb(e,t){if(!(!e&&!t))return{verdict:t?.verdict?{...e?.verdict??{},...t.verdict}:e?.verdict}}i(mb,"mergeManagedProtocolPayload");function LP(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(LP,"normalizeManagedVerdictStatus");function NP(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(NP,"normalizeManagedNextHarness");function DP(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(DP,"normalizeStringListValue");function VG(e,t,n=""){let r=MP(t);if(!r||e!=="evaluator")return;let o=typeof r.status=="string"?LP(r.status):void 0;if(o)return{verdict:{source:"evaluator",status:o,reason:typeof r.reason=="string"&&r.reason.trim()||void 0,followups:DP(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"?NP(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(VG,"coerceManagedProtocolToolPayload");function YG(e){if(e==="evaluator")return PP}i(YG,"getManagedBlockNameForRole");function JG(e,t){return e&&t==="evaluator"?!!e.verdict:!1}i(JG,"hasManagedProtocolForRole");function QG(e,t){return new RegExp(String.raw`\`\`\`${t}\s*[\s\S]*?\`\`\``,"i").test(e)}i(QG,"textContainsManagedBlock");function hb(e,t){if(!t||t.length===0)return e;let n=new Set(t);return e.filter(r=>!n.has(r))}i(hb,"filterExcludedTools");function gb(e,t){return t?e.filter(n=>{let r=We(n);return r?t({name:r.name,sideEffect:r.sideEffect,planModeAllowed:r.planModeAllowed===!0}):!1}):e}i(gb,"applyToolVisibilityPolicy");function jP(e,t,n=!1,r,o=!1){let s=rc(t)==="off"?nd(e):e;return n||(s=rd(s)),s=Hl(s,r),s=Ql(s,r),o||(s=s.filter(a=>a!=="list_dispatchable_agents")),s}i(jP,"getRuntimeActiveToolNames");function sX(e,t,n=!1,r=!1,o,s,a,c=!1){let l=td();if(e.length===0)return[];let d=new Set(jP(e,t,r,o,c));return l.filter(u=>d.has(u.name)&&(n||!pb(u.name))).map(u=>{let f=Ho(u,a);if(!Bi(f.name)||s&&s.has(f.name))return f;let p=Pn[f.name];return p?{...f,description:p}:f})}i(sX,"getActiveToolDefinitions");import{join as FP}from"node:path";function UP(e,t){if(t&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return FP(e,t)}i(UP,"resolveResumeFromRunDir");function bX(e){let{options:t,runtime:n,managedProtocolPayloadRef:r,sessionId:o}=e,s=t.events??{},a=ke(t.context),c=fb(t),l=gb(hb([...Zt],t.context?.excludeTools),t.context?.toolVisibilityPolicy),d=Zt.every(f=>l.includes(f))?Rc({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??ww(),executionCwd:a,shellExecution:t.context?.shellExecution,sandbox:t.sandbox,shellSandbox:t.context?.shellSandbox,providerCredentialEnvironmentNames:Gd(),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=mb(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 po({maxConcurrentThreadsPerSession:t.maxConcurrentThreadsPerSession,sessionId:o});u.actorHost=f,u.actorControl=f.attach(u,t)}return u.workflowHost=WP(t,o,u.actorControl,u.actorHost),u}i(bX,"buildToolExecutionContext");function qP(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(qP,"buildWorkflowHostMetadata");function WP(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";I({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-6MMHYTI5.js"),import("./run-manager-ISQSWCAM.js")]),m=[e.abortSignal,u].filter(v=>v!==void 0),h=m.length===0?void 0:m.length===1?m[0]:AbortSignal.any(m),y=n&&r?{...e,context:{...e.context,actorControl:n,actorHost:r}}:e,w=await f({source:{kind:"inline",manifest:a,source:c},args:l,options:y,runsBaseDir:o,manager:p(),...(()=>{let v=UP(o,d);return v?{resumeFromRunDir:v}:{}})(),...h?{signal:h}:{},processMetadata:{hostMetadata:qP(e,t)}});if(w.kind==="declined")return{kind:"declined",reason:w.reason};let g=w.qualityWarnings?.map(v=>`${v.code}: ${v.message}`),b=w.managed.done.then(v=>{let x=w.managed.getSnapshot?.(),$=v.kind==="completed"?v.state.events.reduce((S,k)=>{if(k.type==="agent_unverified"){let T=k.data?.name??k.data?.taskId;S.push(typeof T=="string"&&T.length>0?T:"agent")}return S},[]):[];return{kind:"started",runId:w.runId,...x?.status!==void 0?{status:x.status}:{},...x?.resultText!==void 0?{resultText:x.resultText}:{},...x?.error!==void 0?{error:x.error}:{},...$.length>0?{verificationWarnings:$}:{},...g&&g.length>0?{workflowQualityWarnings:g}:{}}});return{kind:"started",runId:w.runId,done:b,...g&&g.length>0?{workflowQualityWarnings:g}:{}}},"startInline");return{startInline:s,runInline:i(async a=>{let c=await s(a);return c.kind==="declined"?{kind:"declined",reason:c.reason}:await c.done},"runInline")}}i(WP,"buildWorkflowToolHost");export{ke as a,X as b,xe as c,_s as d,_b as e,XP as f,Sb as g,Un as h,ku as i,VP as j,rM as k,H as l,$s as m,Mu as n,No as o,Do as p,Cr as q,kM as r,tf as s,nf as t,PM as u,MM as v,LM as w,NM as x,Bs as y,Hs as z,Qt as A,bS as B,xc as C,O0 as D,af as E,Wn as F,Uo as G,Ks as H,zs as I,it as J,Rr as K,Ir as L,Gv as M,qo as N,un as O,Vs as P,Kr as Q,$F as R,PF as S,zr as T,jF as U,FF as V,UF as W,HF as X,vT as Y,KF as Z,ff as _,H0 as $,pf as aa,yf as ba,Qs as ca,Ho as da,rh as ea,ZF as fa,oh as ga,eU as ha,tU as ia,nU as ja,rU as ka,Ei as la,sU as ma,ih as na,nL as oa,ea as pa,na as qa,Nx as ra,Dx as sa,ra as ta,da as ua,ua as va,Wf as wa,Nr as xa,Mr as ya,Pr as za,oa as Aa,jf as Ba,ya as Ca,wa as Da,Dr as Ea,va as Fa,xa as Ga,gt as Ha,Qn as Ia,ID as Ja,Op as Ka,$a as La,Pa as Ma,$p as Na,Ma as Oa,La as Pa,Na as Qa,Da as Ra,Fa as Sa,Ua as Ta,qa as Ua,Wa as Va,Ur as Wa,we as Xa,h_ as Ya,rc as Za,Tj as _a,Aj as $a,Cj as ab,Wr as bb,gi as cb,yi as db,Br as eb,I_ as fb,O_ as gb,Rj as hb,oc as ib,ic as jb,sc as kb,ac as lb,bn as mb,lc as nb,nr as ob,dc as pb,Rm as qb,ce as rb,uc as sb,fc as tb,pc as ub,mc as vb,wF as wb,bF as xb,vF as yb,uS as zb,bi as Ab,xF as Bb,Jr as Cb,Ye as Db,Ti as Eb,zy as Fb,SR as Gb,TR as Hb,Vr as Ib,Wh as Jb,Qc as Kb,Zc as Lb,Pq as Mb,og as Nb,ig as Ob,jq as Pb,sg as Qb,Bq as Rb,Hq as Sb,Kq as Tb,zq as Ub,Gq as Vb,Xq as Wb,ag as Xb,ug as Yb,cl as Zb,uC as _b,Pn as $b,Bi as ac,PH as bc,xy as cc,ky as dc,rI as ec,Cy as fc,Ry as gc,so as hc,SI as ic,dd as jc,ud as kc,QH as lc,CI as mc,RI as nc,ZH as oc,Yr as pc,$i as qc,tn as rc,Et as sc,fl as tc,vl as uc,Zr as vc,eo as wc,Cg as xc,Rg as yc,El as zc,_t as Ac,MC as Bc,Tl as Cc,ur as Dc,fr as Ec,jC as Fc,to as Gc,WC as Hc,XC as Ic,VC as Jc,An as Kc,no as Lc,ro as Mc,nR as Nc,Ml as Oc,Cn as Pc,Rn as Qc,oR as Rc,iR as Sc,sR as Tc,fR as Uc,mR as Vc,bR as Wc,Ui as Xc,Bg as Yc,kR as Zc,ER as _c,fd as $c,pd as ad,hK as bd,gK as cd,yK as dd,wK as ed,bK as fd,ao as gd,Ki as hd,jy as id,qy as jd,GR as kd,pr as ld,XR as md,hr as nd,We as od,In as pd,VR as qd,ed as rd,YR as sd,JR as td,on as ud,QR as vd,ZR as wd,eI as xd,tI as yd,nI as zd,At as Ad,td as Bd,iO as Cd,pl as Dd,ly as Ed,dy as Fd,jR as Gd,FR as Hd,WR as Id,BR as Jd,HR as Kd,yO as Ld,Xy as Md,Vy as Nd,fb as Od,$P as Pd,zG as Qd,PP as Rd,GG as Sd,XG as Td,pb as Ud,mb as Vd,VG as Wd,YG as Xd,JG as Yd,QG as Zd,lo as _d,Yy as $d,iw as ae,Ad as be,ww as ce,Hz as de,xw as ee,kw as fe,Qi as ge,tG as he,rs as ie,jw as je,AG as ke,po as le,DG as me,jG as ne,hb as oe,gb as pe,jP as qe,sX as re,bX as se};
410
+ </agent-message>`}i(jd,"renderMailboxMessage");function SP(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(SP,"assertProviderAuthority");function Pe(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}i(Pe,"escapeXml");function TP(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(TP,"managedWorkBudgetPort");function AP(e,t){let n=ze(e.specialistName);if(n)return n;let r=ze(e.agentId);if(!(!r||t.actor.kind==="native"))throw new Error(`Agent selector ${r} was not resolved before execution.`)}i(AP,"specialistName");function CP(e){return e==="fast"||e==="balanced"||e==="deep"?e:void 0}i(CP,"modelHint");function RP(e){let t=ze(e);if(!t)return;let n=jn(t);return n==="auto"?void 0:n}i(RP,"effort");function ze(e){return typeof e=="string"&&e.length>0?e:void 0}i(ze,"metadataString");function cb(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}i(cb,"metadataStringArray");import ub from"node:path";var IP=80;function OP(e){let t=e.trim().replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,IP);return!t||t==="."||t===".."?"session":t}i(OP,"sanitizeScratchSessionId");function fb(e){let t=e.session?.id?.trim();if(!t)return;let n=e.context?.gitRoot?.trim(),r=n?ub.resolve(n):ke(e.context);return ub.resolve(r,".agent","tmp","sessions",OP(t))}i(fb,"getSessionScratchDir");var $P="emit_managed_protocol",zG="kodax-task-contract",PP="kodax-task-verdict",GG="kodax-task-scout",XG="kodax-task-handoff";function MP(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}i(MP,"asRecord");function pb(e){return e.trim().toLowerCase()===$P}i(pb,"isManagedProtocolToolName");function mb(e,t){if(!(!e&&!t))return{verdict:t?.verdict?{...e?.verdict??{},...t.verdict}:e?.verdict}}i(mb,"mergeManagedProtocolPayload");function LP(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(LP,"normalizeManagedVerdictStatus");function NP(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(NP,"normalizeManagedNextHarness");function DP(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(DP,"normalizeStringListValue");function VG(e,t,n=""){let r=MP(t);if(!r||e!=="evaluator")return;let o=typeof r.status=="string"?LP(r.status):void 0;if(o)return{verdict:{source:"evaluator",status:o,reason:typeof r.reason=="string"&&r.reason.trim()||void 0,followups:DP(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"?NP(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(VG,"coerceManagedProtocolToolPayload");function YG(e){if(e==="evaluator")return PP}i(YG,"getManagedBlockNameForRole");function JG(e,t){return e&&t==="evaluator"?!!e.verdict:!1}i(JG,"hasManagedProtocolForRole");function QG(e,t){return new RegExp(String.raw`\`\`\`${t}\s*[\s\S]*?\`\`\``,"i").test(e)}i(QG,"textContainsManagedBlock");function hb(e,t){if(!t||t.length===0)return e;let n=new Set(t);return e.filter(r=>!n.has(r))}i(hb,"filterExcludedTools");function gb(e,t){return t?e.filter(n=>{let r=We(n);return r?t({name:r.name,sideEffect:r.sideEffect,planModeAllowed:r.planModeAllowed===!0}):!1}):e}i(gb,"applyToolVisibilityPolicy");function jP(e,t,n=!1,r,o=!1){let s=rc(t)==="off"?nd(e):e;return n||(s=rd(s)),s=Hl(s,r),s=Ql(s,r),o||(s=s.filter(a=>a!=="list_dispatchable_agents")),s}i(jP,"getRuntimeActiveToolNames");function sX(e,t,n=!1,r=!1,o,s,a,c=!1){let l=td();if(e.length===0)return[];let d=new Set(jP(e,t,r,o,c));return l.filter(u=>d.has(u.name)&&(n||!pb(u.name))).map(u=>{let f=Ho(u,a);if(!Bi(f.name)||s&&s.has(f.name))return f;let p=Pn[f.name];return p?{...f,description:p}:f})}i(sX,"getActiveToolDefinitions");import{join as FP}from"node:path";function UP(e,t){if(t&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return FP(e,t)}i(UP,"resolveResumeFromRunDir");function bX(e){let{options:t,runtime:n,managedProtocolPayloadRef:r,sessionId:o}=e,s=t.events??{},a=ke(t.context),c=fb(t),l=gb(hb([...Zt],t.context?.excludeTools),t.context?.toolVisibilityPolicy),d=Zt.every(f=>l.includes(f))?Rc({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??ww(),executionCwd:a,shellExecution:t.context?.shellExecution,sandbox:t.sandbox,shellSandbox:t.context?.shellSandbox,providerCredentialEnvironmentNames:Gd(),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=mb(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 po({maxConcurrentThreadsPerSession:t.maxConcurrentThreadsPerSession,sessionId:o});u.actorHost=f,u.actorControl=f.attach(u,t)}return u.workflowHost=WP(t,o,u.actorControl,u.actorHost),u}i(bX,"buildToolExecutionContext");function qP(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(qP,"buildWorkflowHostMetadata");function WP(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";I({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-SJHHJBPB.js"),import("./run-manager-T5QGWNON.js")]),m=[e.abortSignal,u].filter(v=>v!==void 0),h=m.length===0?void 0:m.length===1?m[0]:AbortSignal.any(m),y=n&&r?{...e,context:{...e.context,actorControl:n,actorHost:r}}:e,w=await f({source:{kind:"inline",manifest:a,source:c},args:l,options:y,runsBaseDir:o,manager:p(),...(()=>{let v=UP(o,d);return v?{resumeFromRunDir:v}:{}})(),...h?{signal:h}:{},processMetadata:{hostMetadata:qP(e,t)}});if(w.kind==="declined")return{kind:"declined",reason:w.reason};let g=w.qualityWarnings?.map(v=>`${v.code}: ${v.message}`),b=w.managed.done.then(v=>{let x=w.managed.getSnapshot?.(),$=v.kind==="completed"?v.state.events.reduce((S,k)=>{if(k.type==="agent_unverified"){let T=k.data?.name??k.data?.taskId;S.push(typeof T=="string"&&T.length>0?T:"agent")}return S},[]):[];return{kind:"started",runId:w.runId,...x?.status!==void 0?{status:x.status}:{},...x?.resultText!==void 0?{resultText:x.resultText}:{},...x?.error!==void 0?{error:x.error}:{},...$.length>0?{verificationWarnings:$}:{},...g&&g.length>0?{workflowQualityWarnings:g}:{}}});return{kind:"started",runId:w.runId,done:b,...g&&g.length>0?{workflowQualityWarnings:g}:{}}},"startInline");return{startInline:s,runInline:i(async a=>{let c=await s(a);return c.kind==="declined"?{kind:"declined",reason:c.reason}:await c.done},"runInline")}}i(WP,"buildWorkflowToolHost");export{ke as a,X as b,xe as c,_s as d,_b as e,XP as f,Sb as g,Un as h,ku as i,VP as j,rM as k,H as l,$s as m,Mu as n,No as o,Do as p,Cr as q,kM as r,tf as s,nf as t,PM as u,MM as v,LM as w,NM as x,Bs as y,Hs as z,Qt as A,bS as B,xc as C,O0 as D,af as E,Wn as F,Uo as G,Ks as H,zs as I,it as J,Rr as K,Ir as L,Gv as M,qo as N,un as O,Vs as P,Kr as Q,$F as R,PF as S,zr as T,jF as U,FF as V,UF as W,HF as X,vT as Y,KF as Z,ff as _,H0 as $,pf as aa,yf as ba,Qs as ca,Ho as da,rh as ea,ZF as fa,oh as ga,eU as ha,tU as ia,nU as ja,rU as ka,Ei as la,sU as ma,ih as na,nL as oa,ea as pa,na as qa,Nx as ra,Dx as sa,ra as ta,da as ua,ua as va,Wf as wa,Nr as xa,Mr as ya,Pr as za,oa as Aa,jf as Ba,ya as Ca,wa as Da,Dr as Ea,va as Fa,xa as Ga,gt as Ha,Qn as Ia,ID as Ja,Op as Ka,$a as La,Pa as Ma,$p as Na,Ma as Oa,La as Pa,Na as Qa,Da as Ra,Fa as Sa,Ua as Ta,qa as Ua,Wa as Va,Ur as Wa,we as Xa,h_ as Ya,rc as Za,Tj as _a,Aj as $a,Cj as ab,Wr as bb,gi as cb,yi as db,Br as eb,I_ as fb,O_ as gb,Rj as hb,oc as ib,ic as jb,sc as kb,ac as lb,bn as mb,lc as nb,nr as ob,dc as pb,Rm as qb,ce as rb,uc as sb,fc as tb,pc as ub,mc as vb,wF as wb,bF as xb,vF as yb,uS as zb,bi as Ab,xF as Bb,Jr as Cb,Ye as Db,Ti as Eb,zy as Fb,SR as Gb,TR as Hb,Vr as Ib,Wh as Jb,Qc as Kb,Zc as Lb,Pq as Mb,og as Nb,ig as Ob,jq as Pb,sg as Qb,Bq as Rb,Hq as Sb,Kq as Tb,zq as Ub,Gq as Vb,Xq as Wb,ag as Xb,ug as Yb,cl as Zb,uC as _b,Pn as $b,Bi as ac,PH as bc,xy as cc,ky as dc,rI as ec,Cy as fc,Ry as gc,so as hc,SI as ic,dd as jc,ud as kc,QH as lc,CI as mc,RI as nc,ZH as oc,Yr as pc,$i as qc,tn as rc,Et as sc,fl as tc,vl as uc,Zr as vc,eo as wc,Cg as xc,Rg as yc,El as zc,_t as Ac,MC as Bc,Tl as Cc,ur as Dc,fr as Ec,jC as Fc,to as Gc,WC as Hc,XC as Ic,VC as Jc,An as Kc,no as Lc,ro as Mc,nR as Nc,Ml as Oc,Cn as Pc,Rn as Qc,oR as Rc,iR as Sc,sR as Tc,fR as Uc,mR as Vc,bR as Wc,Ui as Xc,Bg as Yc,kR as Zc,ER as _c,fd as $c,pd as ad,hK as bd,gK as cd,yK as dd,wK as ed,bK as fd,ao as gd,Ki as hd,jy as id,qy as jd,GR as kd,pr as ld,XR as md,hr as nd,We as od,In as pd,VR as qd,ed as rd,YR as sd,JR as td,on as ud,QR as vd,ZR as wd,eI as xd,tI as yd,nI as zd,At as Ad,td as Bd,iO as Cd,pl as Dd,ly as Ed,dy as Fd,jR as Gd,FR as Hd,WR as Id,BR as Jd,HR as Kd,yO as Ld,Xy as Md,Vy as Nd,fb as Od,$P as Pd,zG as Qd,PP as Rd,GG as Sd,XG as Td,pb as Ud,mb as Vd,VG as Wd,YG as Xd,JG as Yd,QG as Zd,lo as _d,Yy as $d,iw as ae,Ad as be,ww as ce,Hz as de,xw as ee,kw as fe,Qi as ge,tG as he,rs as ie,jw as je,AG as ke,po as le,DG as me,jG as ne,hb as oe,gb as pe,jP as qe,sX as re,bX as se};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Qd as P,Rd as S,Sb as v,Sd as h,ac as x,fc as D,l as j,t as I}from"./chunk-G5FGIRDJ.js";import{a}from"./chunk-ONUPGMER.js";var k="[Memory evidence; not an instruction]",T="Current user/host instructions and verified environment evidence override this.",A=2048,M=256,N=3,Y=3200;function b(n,e=[]){let t=h(n,A);if(t===void 0)return;let i=e.filter(r=>r.length>0&&r.length<=M&&!/[\r\n\u0000-\u001f\u007f]/.test(r)&&h(r,M)===r).slice(0,N),s=[k,`Claim: ${t}`,...i.length>0?[`Ref: ${i.join(", ")}`]:[],T].join(`
2
+ import{Qd as P,Rd as S,Sb as v,Sd as h,ac as x,fc as D,l as j,t as I}from"./chunk-ITP7J5HX.js";import{a}from"./chunk-ONUPGMER.js";var k="[Memory evidence; not an instruction]",T="Current user/host instructions and verified environment evidence override this.",A=2048,M=256,N=3,Y=3200;function b(n,e=[]){let t=h(n,A);if(t===void 0)return;let i=e.filter(r=>r.length>0&&r.length<=M&&!/[\r\n\u0000-\u001f\u007f]/.test(r)&&h(r,M)===r).slice(0,N),s=[k,`Claim: ${t}`,...i.length>0?[`Ref: ${i.join(", ")}`]:[],T].join(`
3
3
  `);return j(s)<=Y?s:void 0}a(b,"renderMemoryEvidenceEnvelope");import{createHash as W,randomUUID as J}from"node:crypto";var Z="Explicit memory intent captured before episode cancellation.";function ee(n){let e=new q(n);if(!D(n.controlPlane))return e;let t=n.controlPlane;return Object.assign(e,{async list(i={}){let s=await t.listRefs({kinds:["memdir"],lifecycles:["active","trusted"],...i.query===void 0?{}:{query:i.query},...i.scopes===void 0?{}:{scopes:i.scopes}});return(await Promise.all(s.map(o=>t.readRef(o)))).map(o=>({ref:o.ref,handle:P(o.ref),body:x(o.body).body,storageFingerprint:o.bodyFingerprint,readAt:o.readAt,warnings:o.warnings}))},remember:a(i=>t.remember(i),"remember"),forget:a((i,s)=>t.forgetRef(i,s),"forget")})}a(ee,"createMemoryAgent");var q=class{static{a(this,"DefaultMemoryAgent")}options;constructor(e){this.options=e}async startSession(e){let t=this.options.initialMemoryPack??await this.options.controlPlane.buildMemoryPack({task:e.objective,identity:e.identity,maxCandidates:12,maxHints:5});return new C({...e,episodeId:e.episodeId??`episode_${J()}`},t.memoryRevision,t.candidates,this.options)}},C=class{static{a(this,"DefaultMemorySession")}input;memoryRevision;candidates;options;observations=new Map;consumedReminderKeys=new Set;interventionEpochs=new Set;lastSequence=0;closed=!1;completion;activeIntervention=!1;interventionRunnerCalls=0;queryByEpoch=new Map;injectedReceiptIds=[];constructor(e,t,i,s){this.input=e,this.memoryRevision=t,this.candidates=i,this.options=s}observe(e){if(this.assertOpen(),S(e.summary))return;let t=de(e,this.options.sourcePolicy),i=this.observations.get(e.id);if(i!==void 0){if(i.sequence===t.sequence&&F(i)===F(t))return;throw new Error(`conflicting duplicate memory observation: ${e.id}`)}if(!Number.isSafeInteger(e.sequence)||e.sequence<=this.lastSequence)throw new Error(`memory observation sequence must be strictly monotonic after ${this.lastSequence}`);if(e.summary.trim().length===0)throw new Error("memory observation summary must not be empty");this.observations.set(e.id,t),this.lastSequence=e.sequence}recall(e){this.assertOpen();let t=[...this.observations.values()].filter(f=>f.sequence<=e.throughSequence).filter(V).filter(f=>ne(f,e)).sort((f,l)=>l.sequence-f.sequence).map($),i=this.candidates.filter(H).filter(f=>te(f,e)).map(_),s=E([...t,...i]).slice(0,3);if(s.length===0){this.emitDecisionReceipt(e,[],[],[],[]);return}let r=s.map(f=>f.refId),o=p(s.flatMap(f=>f.evidenceRefs??[])),u=g(`${r.join("\0")}\0${e.actionSignature??e.decisionIntent}`);if(this.consumedReminderKeys.has(u)){this.emitDecisionReceipt(e,s,r,[],["exact"]);return}this.consumedReminderKeys.add(u);let m=w(s.map(f=>f.claim),o);return this.emitDecisionReceipt(e,s,r,m?.evidenceRefs??[],["exact"]),m}async intervene(e){if(this.assertOpen(),e.triggers.length===0||e.signal?.aborted)return;let t=L(e);if(this.interventionEpochs.has(t)||this.activeIntervention)return;this.interventionEpochs.add(t),this.activeIntervention=!0;let i=this.lastSequence;try{let s=await this.buildInterventionCandidates(e);if(e.signal?.aborted)return;if(this.lastSequence!==i||e.throughSequence!==i){this.options.onTrace?.({type:"recall.intervention.discarded",key:t,detail:"state_revision_changed"});return}if(s.length===0){this.emitDecisionReceipt(e,[],[],[],[],e.triggers);return}let r=p([...e.triggers.includes("context_compacted")?s.filter(c=>c.source==="current").filter(c=>c.claimKind==="objective").slice(0,1).map(c=>c.refId):[],...s.filter(c=>c.source!=="current").filter(c=>K(c,e)).map(c=>c.refId)]).slice(0,3),o=r.length>=3?[]:await this.selectInterventionCandidates(e,s,t);if(e.signal?.aborted)return;if(this.lastSequence!==i){this.options.onTrace?.({type:"recall.intervention.discarded",key:t,detail:"state_revision_changed"});return}let u=p([...r,...o]).slice(0,3),m=u.map(c=>s.find(U=>U.refId===c)).filter(c=>c!==void 0),f=p(m.flatMap(c=>c.evidenceRefs??[])),l=[...r.length>0?["exact"]:[],...o.length>0?["semantic_intervention"]:[]];if(m.length===0){this.emitDecisionReceipt(e,s,[],[],l,e.triggers);return}let d=g([t,...u].join("\0"));if(this.consumedReminderKeys.has(d)){this.emitDecisionReceipt(e,s,u,[],l,e.triggers);return}this.consumedReminderKeys.add(d);let y=w(m.map(c=>c.claim),f);return this.emitDecisionReceipt(e,s,u,y?.evidenceRefs??[],l,e.triggers),y}finally{this.activeIntervention=!1}}query(e){this.assertOpen();let t=R(e.decisionRevision,e.throughSequence),i=ce(e.need),s=g([t,this.memoryRevision,i??"",e.actionSignature??"",v].join("\0")),r=this.queryByEpoch.get(t);if(r!==void 0)return r.key===s?r.result:Promise.resolve(void 0);let o=i===void 0?Promise.resolve(void 0):this.queryOnce(e,i);return this.queryByEpoch.set(t,{key:s,result:o}),i===void 0&&this.emitDecisionReceipt(e,[],[],[],["deliberate_query"]),o}rewind(e){if(this.assertOpen(),!Number.isSafeInteger(e.throughSequence)||e.throughSequence<0)throw new Error("rewind sequence must be a non-negative safe integer");for(let[t,i]of this.observations)i.sequence>e.throughSequence&&this.observations.delete(t);for(this.lastSequence=e.throughSequence,this.consumedReminderKeys.clear(),this.interventionEpochs.clear(),this.queryByEpoch.clear();this.injectedReceiptIds.length>0;)this.injectedReceiptIds.pop()}complete(e){return this.assertOpen(),this.completion!==void 0?this.completion:(this.completion=this.completeOnce(e),this.completion)}async close(e={}){e.drain!==!1&&this.completion!==void 0&&await this.completion,this.closed=!0}async completeOnce(e){let t=e.evidence.map(c=>Q(c,this.options.sourcePolicy)),i=e.memoryIntent===void 0?void 0:h(e.memoryIntent.candidateStatement,512),s=e.memoryIntent===void 0?void 0:h(e.memoryIntent.userQuote,512),r=e.memoryIntent!==void 0&&i!==void 0&&s!==void 0&&t.some(c=>c.ref===e.memoryIntent?.evidenceRef&&c.requestedGrade==="authoritative"&&c.source==="user")?{operation:e.memoryIntent.operation,evidenceRef:e.memoryIntent.evidenceRef,candidateStatement:i,userQuote:s}:void 0,o=oe(e.handledMemoryOperations??[]),u=e.status==="cancelled";if(u&&r===void 0)return;let m=u?r?.candidateStatement:this.input.objective;if(m===void 0)return;let f=h(m,512),l=h(u?Z:e.summary,512);if(f===void 0||l===void 0)return;let d=u&&r!==void 0?t.filter(c=>c.ref===r.evidenceRef&&c.requestedGrade==="authoritative"&&c.source==="user").slice(0,1):t,y=se({...this.input,objective:f},[...this.observations.values()],{status:e.status,summary:l,evidence:d,...r===void 0?{}:{memoryIntent:r},...o.length===0?{}:{handledMemoryOperations:o}},this.options.now?.()??new Date().toISOString(),this.injectedReceiptIds);if(await this.options.persistOutcomeDigest?.(y),e.status==="cancelled"){this.reviewDetached(y);return}await this.reviewWithTimeout(y)}reviewDetached(e){this.reviewWithTimeout(e,{unrefTimeout:!0}).catch(t=>{let i=t instanceof Error?t.message:String(t);I({source:"memory.agent",level:"warn",message:"Detached episode review failed.",detail:{reviewKey:e.reviewKey,error:i}});try{this.options.onTrace?.({type:"review.failed",key:e.reviewKey,detail:i})}catch(s){I({source:"memory.agent",level:"warn",message:"Detached episode review trace callback failed.",detail:{reviewKey:e.reviewKey,error:s instanceof Error?s.message:String(s)}})}})}async reviewWithTimeout(e,t={}){let i=this.options.reviewEpisode;if(i===void 0)return;let s=new AbortController,r=Math.max(1,this.options.reviewTimeoutMs??3e4),o,u=await Promise.race([i(e,s.signal).then(()=>!1),new Promise(m=>{o=setTimeout(()=>{s.abort(),m(!0)},r),t.unrefTimeout&&o.unref()})]);o!==void 0&&clearTimeout(o),u&&this.options.onTrace?.({type:"review.timed_out",key:e.reviewKey,detail:`${r}ms`})}assertOpen(){if(this.closed)throw new Error("memory session is closed")}async buildInterventionCandidates(e){let t=e.currentCandidates.map(ie).filter(r=>r!==void 0),i=z([...this.observations.values()].filter(r=>r.sequence<=e.throughSequence).filter(V).sort((r,o)=>o.sequence-r.sequence).map($),e),s=[];try{let r=await this.options.controlPlane.buildMemoryPack({task:this.input.objective,identity:this.input.identity,decisionIntent:e.decisionIntent,...e.actionSignature!==void 0?{actionSignature:e.actionSignature}:{},maxCandidates:12,maxHints:12,includeSnippets:!0,purpose:"intervention"});s=z(r.promptHints.filter(H).map(_),e)}catch(r){this.options.onTrace?.({type:"recall.intervention.failed",key:L(e),detail:r instanceof Error?r.message:String(r)})}return re(t,i,s)}async selectInterventionCandidates(e,t,i){let s=this.options.recallRunner;if(s===void 0||this.interventionRunnerCalls>=3)return[];this.interventionRunnerCalls+=1;let r=new AbortController,o=a(()=>r.abort(e.signal?.reason),"forwardAbort");e.signal?.addEventListener("abort",o,{once:!0}),e.signal?.aborted&&o();let u=t.map((f,l)=>({alias:`candidate:${l+1}`,candidate:{...f,refId:`candidate:${l+1}`,evidenceRefs:[]}})),m;try{let f=await Promise.race([s({objective:O(e.objective),decisionContext:O(e.decisionContext,2048),decisionIntent:O(e.decisionIntent),triggers:e.triggers,candidates:u.map(({candidate:d})=>d),signal:r.signal}),new Promise(d=>{m=setTimeout(()=>{r.abort(),d({selectedRefIds:[]})},5e3)})]),l=new Map(u.map(({alias:d},y)=>[d,t[y].refId]));return p(f.selectedRefIds.map(d=>l.get(d)).filter(d=>d!==void 0)).slice(0,3)}catch(f){return this.options.onTrace?.({type:"recall.intervention.failed",key:i,detail:f instanceof Error?f.message:String(f)}),[]}finally{m!==void 0&&clearTimeout(m),e.signal?.removeEventListener("abort",o)}}async queryOnce(e,t){try{let i=await this.options.controlPlane.buildMemoryPack({task:this.input.objective,identity:this.input.identity,decisionIntent:t,...e.actionSignature!==void 0?{actionSignature:e.actionSignature}:{},maxCandidates:3,maxHints:3,includeSnippets:!0,purpose:"deliberate_query"}),s=i.promptHints.filter(X).map(l=>({hint:l,claim:h(l.bodySnippet??"")})).filter(l=>l.claim!==void 0).slice(0,3),r=s.map(({hint:l})=>l.ref.id),o=w(s.map(({claim:l})=>l),r),u=o?.content??"",m=o?.evidenceRefs??[],f=i.candidates.map(_);return this.emitDecisionReceipt(e,f,r,m,["deliberate_query"]),o}catch(i){this.emitDecisionReceipt(e,[],[],[],["deliberate_query"]),this.options.onTrace?.({type:"query.failed",key:R(e.decisionRevision,e.throughSequence),detail:i instanceof Error?i.message:String(i)});return}}emitDecisionReceipt(e,t,i,s,r,o){let u=R(e.decisionRevision,e.throughSequence),m=t.map(c=>c.refId),f=new Set(i),l=p(t.filter(c=>f.has(c.refId)).flatMap(c=>c.evidenceRefs).filter(B)),d=g(t.map(c=>[c.refId,c.source??"",c.claim,...c.evidenceRefs??[]].join("\0")).join(`
4
4
  `)),y={id:`memory-decision:${g([u,v,d,i.join(","),s.join(","),r.join(","),o?.join(",")??""].join("\0")).slice(0,24)}`,decisionEpoch:u,decisionRevision:e.decisionRevision,policyVersion:v,candidateSetFingerprint:d,candidateIds:[...m],selectedCandidateIds:[...i],injectedEvidenceRefs:[...s],...o!==void 0&&o.length>0?{triggers:[...o]}:{},candidateRefs:[...m],selectedRefs:[...l],injectedRefs:[...s],selectionModes:[...r],...e.actionSignature!==void 0?{actionSignature:e.actionSignature}:{},throughSequence:e.throughSequence};s.length>0&&!this.injectedReceiptIds.includes(y.id)&&this.injectedReceiptIds.push(y.id),this.options.onTrace?.({type:"memory.decision",receipt:y})}};function ne(n,e){return n.actionSignature!==void 0&&e.actionSignature!==void 0?n.actionSignature===e.actionSignature:n.claimKey!==void 0&&n.claimKey===e.decisionIntent}a(ne,"exactObservationMatch");function te(n,e){return n.ref.actionSignature!==void 0&&e.actionSignature!==void 0?n.ref.actionSignature===e.actionSignature:n.ref.claimKey!==void 0&&n.ref.claimKey===e.decisionIntent}a(te,"exactCandidateMatch");function ie(n){let e=h(n.claim);if(e!==void 0)return{...n,claim:e,source:"current",evidenceRefs:p(n.evidenceRefs??[n.refId])}}a(ie,"currentCandidate");function $(n){let e=h(n.summary)??`Prior observation is available at ${n.evidence[0]?.ref??n.id}.`;return{refId:`observation:${n.id}`,claim:e,claimKind:n.kind,source:"session",evidenceRefs:p(n.evidence.map(t=>t.ref)),...n.actionSignature!==void 0?{actionSignature:n.actionSignature}:{},...n.claimKey!==void 0?{claimKey:n.claimKey}:{}}}a($,"observationCandidate");function _(n){let e=h(n.bodySnippet??n.hook)??`Governed memory is available at ${n.ref.id}.`;return{refId:n.ref.id,claim:e,...n.ref.claimKind!==void 0?{claimKind:n.ref.claimKind}:{},source:"durable",evidenceRefs:[n.ref.id],...n.ref.actionSignature!==void 0?{actionSignature:n.ref.actionSignature}:{},...n.ref.claimKey!==void 0?{claimKey:n.ref.claimKey}:{}}}a(_,"durableCandidate");function V(n){return n.visibility!=="prompt_safe"||h(n.summary)===void 0?!1:n.evidence.some(e=>e.source!=="agent")}a(V,"isAutomaticObservation");function H(n){return X(n)&&h(n.bodySnippet??n.hook)!==void 0}a(H,"isGovernedHint");function K(n,e){return n.actionSignature!==void 0&&e.actionSignature!==void 0?n.actionSignature===e.actionSignature:n.claimKey!==void 0&&n.claimKey===e.decisionIntent}a(K,"candidateMatchesInput");function z(n,e){return[...n.filter(t=>K(t,e)),...n.filter(t=>!K(t,e))]}a(z,"prioritizeExactCandidates");function re(n,e,t){let i=n.filter(u=>u.claimKind==="objective").slice(0,1),s=n.filter(u=>u.claimKind==="todo"),r=E([...i,...s.slice(0,3),...e.slice(0,4),...t.slice(0,4)]),o=E([...s.slice(3),...e.slice(4),...t.slice(4)]);return E([...r,...o]).slice(0,12)}a(re,"admitInterventionCandidates");function E(n){let e=new Set;return n.filter(t=>e.has(t.refId)?!1:(e.add(t.refId),!0))}a(E,"uniqueCandidates");function se(n,e,t,i,s){let r=t.status==="cancelled"?void 0:[...e].reverse().find(d=>d.kind==="outcome"),o=typeof r?.metadata?.reusableLesson=="string"?h(r.metadata.reusableLesson,512):void 0,u=t.status==="cancelled"?[]:e.filter(d=>d.metadata?.verification===!0).flatMap(d=>d.evidence).filter(d=>d.verdict==="passed"||d.verdict==="failed").filter(d=>!t.evidence.some(y=>y.ref===d.ref)),m=[...t.evidence,...u],f=e.at(-1)?.sequence??0,l=g([n.identity.sessionId,n.episodeId,String(f),t.status,t.summary].join("\0"));return{id:`memory-outcome:${l.slice(0,24)}`,reviewKey:l,episodeId:n.episodeId,sessionId:n.identity.sessionId,branchId:n.identity.sessionId,sequence:f,objective:n.objective,...r?.actionSignature!==void 0?{actionSignature:r.actionSignature}:{},...o===void 0?{}:{lesson:o},approach:r?.summary??"episode completion",outcome:t.status,summary:t.summary.trim(),evidenceRefs:p(m.map(d=>d.ref)),evidence:m.map(d=>({ref:d.ref,grade:d.requestedGrade,source:d.source,...d.verdict!==void 0?{verdict:d.verdict}:{},observedAt:d.observedAt})),...t.memoryIntent===void 0?{}:{memoryIntent:t.memoryIntent},...t.handledMemoryOperations===void 0?{}:{handledMemoryOperations:t.handledMemoryOperations},...t.status!=="cancelled"&&s.length>0?{memoryInfluence:p(s).map(d=>({decisionReceiptRef:d,grade:"exposed"}))}:{},visibility:r?.visibility??"prompt_safe",createdAt:i}}a(se,"buildOutcomeDigest");function oe(n){return n.slice(-20).flatMap(e=>{let t=e.statement===void 0?void 0:h(e.statement,1024),i=e.claimKey?.trim(),s=p(e.targetRefIds).map(o=>h(o,256)).filter(o=>o!==void 0),r=i!==void 0&&/^[a-z0-9._:-]{1,160}$/i.test(i)?i:void 0;return t===void 0&&r===void 0&&s.length===0?[]:[{operation:e.operation,...e.disposition===void 0?{}:{disposition:e.disposition},...t===void 0?{}:{statement:t},...r===void 0?{}:{claimKey:r},targetRefIds:s}]})}a(oe,"sanitizeHandledMemoryOperations");function ce(n){let e=n.replace(/\s+/g," ").trim();if(!(e.length===0||G(e)>512||S(e))&&!/^(?:list|show|dump|enumerate)\s+(?:all|every)\s+(?:the\s+)?memor(?:y|ies)\b/i.test(e)&&!/\b(?:all|every)\s+(?:project|workspace|tenant|user|agent)(?:s|'s)?\b/i.test(e))return e}a(ce,"normalizeQueryNeed");function G(n){let e=0,t=0;for(let i of n)i.codePointAt(0)<=127?e+=1:t+=1;return Math.ceil(e/4)+t}a(G,"estimateMemoryTokens");function X(n){return n.ref.visibility==="prompt_safe"&&n.ref.authority!=="proposal_only"&&(n.ref.lifecycle==="active"||n.ref.lifecycle==="trusted"||n.ref.lifecycle==="readonly")}a(X,"isGovernedQueryHint");function w(n,e){let t=n.map(r=>h(r,512)).filter(r=>r!==void 0),i=t.join(`
5
5
  `).slice(0,2048);if(t.length!==n.length||h(i,2048)===void 0||G(i)>512)return;let s={content:i,evidenceRefs:p(e.filter(B)).slice(0,3)};return b(s.content,s.evidenceRefs)===void 0?void 0:s}a(w,"buildSafeReminder");function O(n,e=512){return h(n,e)??"[withheld by prompt-safety policy]"}a(O,"promptSafeSelectorText");function B(n){return n.length>0&&n.length<=256&&!/[\r\n\u0000-\u001f\u007f]/.test(n)&&h(n,256)===n}a(B,"isSafeEvidenceRef");function R(n,e){return g(`${n}\0${e}`).slice(0,24)}a(R,"decisionEpoch");function L(n){return g([R(n.decisionRevision,n.throughSequence),...n.triggers].join("\0")).slice(0,24)}a(L,"interventionEpoch");function de(n,e){return Object.freeze({...n,evidence:Object.freeze(n.evidence.map(t=>Object.freeze(Q(t,e)))),...n.metadata!==void 0?{metadata:Object.freeze({...n.metadata})}:{}})}a(de,"freezeObservation");function Q(n,e){let t=e?.(n)??"inferred";return{...n,requestedGrade:ae(n.requestedGrade,t)}}a(Q,"applySourcePolicy");function ae(n,e){let t=["inferred","observed","corroborated","verified","authoritative"];return t[Math.min(t.indexOf(n),t.indexOf(e))]??"inferred"}a(ae,"lowerEvidenceGrade");function F(n){return JSON.stringify(n)}a(F,"stableObservation");function p(n){return[...new Set(n)]}a(p,"unique");function g(n){return W("sha256").update(n).digest("hex")}a(g,"digest");export{k as a,T as b,A as c,M as d,N as e,Y as f,b as g,ee as h};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{a as Na,b as bf,c as If,d as Sf,e as xf,f as Ef}from"./chunk-UH5WNJXF.js";import{a as s}from"./chunk-ONUPGMER.js";var ck=32768,dk=60,uk=300,lk=3,fk=2,pk=2,mk=3,hk=1,gk=.5,wk=/<promise>(COMPLETE|BLOCKED|DECIDE)(?::(.*?))?<\/promise>/is;function yk(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(t=r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||r===43||r===45||r===47||r===61||r===95?t+1:0,t>=512)return!0}return!1}s(yk,"looksLikeDenseEncodedData");function vk(e){if(!e)return 0;let t=e.length,n=Buffer.byteLength(e,"utf8");return Math.ceil((3*n-t)/8)}s(vk,"estimateMultilingualTokens");function Nt(e){if(!e)return 0;let t=vk(e),n=yk(e)?e.length*.75:0;return Math.ceil(Math.max(t,n))}s(Nt,"countTextTokens");function kk(e){let t=4;if(typeof e.content=="string")t+=Nt(e.content);else for(let n of e.content)n.type==="text"?t+=Nt(n.text):n.type==="tool_use"?(t+=Nt(n.name),t+=Nt(JSON.stringify(n.input))):n.type==="tool_result"?(t+=4,t+=typeof n.content=="string"?Nt(n.content):n.content.reduce((r,i)=>r+(i.type==="text"?Nt(i.text):1500),0)):n.type==="thinking"?t+=Nt(n.thinking):n.type==="image"&&(t+=1500);return t}s(kk,"countMessageTokens");var _f=new WeakMap;function ke(e){let t=0;for(let n of e){let r=_f.get(n);if(r!==void 0){t+=r;continue}let i=kk(n);_f.set(n,i),t+=i}return t}s(ke,"estimateTokens");function ze(e){return Nt(e)}s(ze,"countTokens");var bk=2048,Ik=.03,ct=class extends Error{static{s(this,"ContextCapacityError")}code="KODAX_CONTEXT_CAPACITY_EXCEEDED";contextWindow;currentTokens;reservedResponseTokens;constructor(t,n="LLM request"){let r=Math.max(0,Math.floor(t.contextWindow)),i=Math.max(0,Math.floor(t.currentTokens)),o=Math.max(0,Math.floor(t.reservedResponseTokens??0)),a=ja(i);super(`${n} cannot fit the complete input: ${i} input + ${o} reserved output + ${a} safety > ${r} context tokens.`),this.name="ContextCapacityError",this.contextWindow=r,this.currentTokens=i,this.reservedResponseTokens=o}};function ja(e){let t=Math.max(0,Math.floor(e));return Math.max(2048,Math.ceil(t*.03))}s(ja,"calculateContextSafetyMargin");function jt(e){let t=Math.max(0,Math.floor(e.contextWindow)),n=Math.max(0,Math.floor(e.currentTokens)),r=Math.max(0,Math.floor(e.reservedResponseTokens??0));return n+r+ja(n)>t}s(jt,"exceedsContextCapacity");function _n(e,t=0){let n=Math.max(0,Math.floor(e)),r=Math.max(0,Math.floor(t)),i=0,o=Math.max(0,n-r),a=0;for(;i<=o;){let c=Math.floor((i+o)/2);jt({contextWindow:n,currentTokens:c,reservedResponseTokens:r})?o=c-1:(a=c,i=c+1)}return a}s(_n,"calculateMaxContextInputTokens");var io=[];function Sk(e){let t={id:Symbol("kodax-diagnostic-sink"),sink:e};io.push(t);let n=!1;return()=>{if(n)return;n=!0;let r=io.findIndex(i=>i.id===t.id);r>=0&&io.splice(r,1)}}s(Sk,"setKodaXDiagnosticSink");function z(e){let t=Na(e),n=io.at(-1)?.sink;if(n){try{n(t)}catch{}return}if(process.env.KODAX_DIAGNOSTICS_STDERR==="1")try{process.stderr.write(`${Af(t)}
2
+ import{a as Na,b as bf,c as If,d as Sf,e as xf,f as Ef}from"./chunk-XH7UM4GO.js";import{a as s}from"./chunk-ONUPGMER.js";var ck=32768,dk=60,uk=300,lk=3,fk=2,pk=2,mk=3,hk=1,gk=.5,wk=/<promise>(COMPLETE|BLOCKED|DECIDE)(?::(.*?))?<\/promise>/is;function yk(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(t=r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||r===43||r===45||r===47||r===61||r===95?t+1:0,t>=512)return!0}return!1}s(yk,"looksLikeDenseEncodedData");function vk(e){if(!e)return 0;let t=e.length,n=Buffer.byteLength(e,"utf8");return Math.ceil((3*n-t)/8)}s(vk,"estimateMultilingualTokens");function Nt(e){if(!e)return 0;let t=vk(e),n=yk(e)?e.length*.75:0;return Math.ceil(Math.max(t,n))}s(Nt,"countTextTokens");function kk(e){let t=4;if(typeof e.content=="string")t+=Nt(e.content);else for(let n of e.content)n.type==="text"?t+=Nt(n.text):n.type==="tool_use"?(t+=Nt(n.name),t+=Nt(JSON.stringify(n.input))):n.type==="tool_result"?(t+=4,t+=typeof n.content=="string"?Nt(n.content):n.content.reduce((r,i)=>r+(i.type==="text"?Nt(i.text):1500),0)):n.type==="thinking"?t+=Nt(n.thinking):n.type==="image"&&(t+=1500);return t}s(kk,"countMessageTokens");var _f=new WeakMap;function ke(e){let t=0;for(let n of e){let r=_f.get(n);if(r!==void 0){t+=r;continue}let i=kk(n);_f.set(n,i),t+=i}return t}s(ke,"estimateTokens");function ze(e){return Nt(e)}s(ze,"countTokens");var bk=2048,Ik=.03,ct=class extends Error{static{s(this,"ContextCapacityError")}code="KODAX_CONTEXT_CAPACITY_EXCEEDED";contextWindow;currentTokens;reservedResponseTokens;constructor(t,n="LLM request"){let r=Math.max(0,Math.floor(t.contextWindow)),i=Math.max(0,Math.floor(t.currentTokens)),o=Math.max(0,Math.floor(t.reservedResponseTokens??0)),a=ja(i);super(`${n} cannot fit the complete input: ${i} input + ${o} reserved output + ${a} safety > ${r} context tokens.`),this.name="ContextCapacityError",this.contextWindow=r,this.currentTokens=i,this.reservedResponseTokens=o}};function ja(e){let t=Math.max(0,Math.floor(e));return Math.max(2048,Math.ceil(t*.03))}s(ja,"calculateContextSafetyMargin");function jt(e){let t=Math.max(0,Math.floor(e.contextWindow)),n=Math.max(0,Math.floor(e.currentTokens)),r=Math.max(0,Math.floor(e.reservedResponseTokens??0));return n+r+ja(n)>t}s(jt,"exceedsContextCapacity");function _n(e,t=0){let n=Math.max(0,Math.floor(e)),r=Math.max(0,Math.floor(t)),i=0,o=Math.max(0,n-r),a=0;for(;i<=o;){let c=Math.floor((i+o)/2);jt({contextWindow:n,currentTokens:c,reservedResponseTokens:r})?o=c-1:(a=c,i=c+1)}return a}s(_n,"calculateMaxContextInputTokens");var io=[];function Sk(e){let t={id:Symbol("kodax-diagnostic-sink"),sink:e};io.push(t);let n=!1;return()=>{if(n)return;n=!0;let r=io.findIndex(i=>i.id===t.id);r>=0&&io.splice(r,1)}}s(Sk,"setKodaXDiagnosticSink");function z(e){let t=Na(e),n=io.at(-1)?.sink;if(n){try{n(t)}catch{}return}if(process.env.KODAX_DIAGNOSTICS_STDERR==="1")try{process.stderr.write(`${Af(t)}
3
3
  `)}catch{}}s(z,"emitKodaXDiagnostic");function Af(e){let t=Na(e),n=xk(t.detail);return`[${t.source}] ${t.level}: ${t.message}${n?` ${n}`:""}`}s(Af,"formatKodaXDiagnostic");function xk(e){if(e===void 0)return"";if(e instanceof Error)return e.stack??e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}s(xk,"formatDiagnosticDetail");function Ek(e){return Object.freeze({...e})}s(Ek,"createAgent");function _k(e){return Object.freeze({...e})}s(_k,"createHandoff");var Rf=0,Ak=s(()=>{Rf+=1;let e=Math.random().toString(36).slice(2,8);return`session-${Date.now()}-${Rf}-${e}`},"_nextSessionId");function Tf(e={}){let t=e.id??Ak(),n=e.metadata??new Map,r=e.initialEntries?e.initialEntries.map(o=>({...o})):[];return{id:t,async append(o){r.push({...o})},async*entries(){for(let o of r.slice())yield o},async fork(o){let a=new Map(n);return o?.name&&a.set("name",o.name),Tf({metadata:a,initialEntries:r})},metadata:n}}s(Tf,"createInMemorySession");var Cf=0,Da=class{static{s(this,"DefaultSummaryCompaction")}name="default-summary";thresholdRatio;keepRecent;now;randomSuffix;constructor(t={}){let n=t.thresholdRatio??.8;if(n<=0||n>1)throw new Error(`DefaultSummaryCompaction.thresholdRatio must be in (0, 1]; got ${n}`);let r=t.keepRecent??10;if(!Number.isFinite(r)||r<0)throw new Error(`DefaultSummaryCompaction.keepRecent must be >= 0; got ${r}`);this.thresholdRatio=n,this.keepRecent=r,this.now=t.now??(()=>Date.now()),this.randomSuffix=t.randomSuffix??(()=>Math.random().toString(36).slice(2,8))}shouldCompact(t,n,r){return!Number.isFinite(n)||!Number.isFinite(r)||r<=0?!1:n>=r*this.thresholdRatio}async compact(t,n){let r=[];for await(let d of t.entries())d.type==="message"&&r.push(d);if(r.length<=this.keepRecent)return{summary:"",replacedMessageEntryIds:[]};let i=r.slice(0,r.length-this.keepRecent),o=i.map(d=>({role:d.payload.role,content:d.payload.content})),a=await n.summarize(o);Cf+=1;let c={id:`compaction-${this.now()}-${Cf}-${this.randomSuffix()}`,ts:this.now(),type:"compaction",payload:{summary:a,replacedMessageEntryIds:i.map(d=>d.id)}};return await t.append(c),{summary:a,replacedMessageEntryIds:i.map(d=>d.id)}}};var br=class e{static{s(this,"SpanImpl")}id;traceId;parentId;name;data;startedAt;_endedAt;_error;_children=[];now;nextSpanId;onChildCreated;onSpanEnd;_ended=!1;constructor(t){this.id=t.id,this.traceId=t.traceId,this.parentId=t.parentId,this.name=t.name,this.data=t.data,this.now=t.now??(()=>Date.now()),this.startedAt=t.startedAt??this.now(),this.nextSpanId=t.nextSpanId??Rk,this.onChildCreated=t.onChildCreated,this.onSpanEnd=t.onSpanEnd}get endedAt(){return this._endedAt}get error(){return this._error}get children(){return this._children}addChild(t,n){let r=new e({id:this.nextSpanId(),traceId:this.traceId,parentId:this.id,name:t,data:n,now:this.now,nextSpanId:this.nextSpanId,onChildCreated:this.onChildCreated,onSpanEnd:this.onSpanEnd});return this._children.push(r),this.onChildCreated&&this.onChildCreated(r),r}setError(t){t instanceof Error?this._error={message:t.message,stack:t.stack}:this._error=t}end(){this._ended||(this._ended=!0,this._endedAt=this.now(),this.onSpanEnd&&this.onSpanEnd(this))}},Pf=0;function Rk(){Pf+=1;let e=Math.random().toString(36).slice(2,8);return`span-${Date.now()}-${Pf}-${e}`}s(Rk,"defaultNextSpanId");var Mf=0;function Tk(){Mf+=1;let e=Math.random().toString(36).slice(2,8);return`trace-${Date.now()}-${Mf}-${e}`}s(Tk,"defaultNextTraceId");function Fa(e={}){let t=e.now??(()=>Date.now()),n=e.id??(e.nextTraceId??Tk)(),r=t(),i=e.name??"trace",o=e.metadata??new Map,a=e.rootSpanData??{kind:"agent",agentName:i},c=!1,d,u,f=new br({id:`${n}-root`,traceId:n,name:i,data:a,startedAt:r,now:t,nextSpanId:e.nextSpanId,onChildCreated:e.onSpanStart,onSpanEnd:e.onSpanEnd});e.onSpanStart&&e.onSpanStart(f);let l={id:n,startedAt:r,rootSpan:f,metadata:o,get endedAt(){return d},get error(){return u??f.error},end(){c||(c=!0,d=t(),f.end(),e.onTraceEnd&&e.onTraceEnd(l))}};return l}s(Fa,"createTrace");var dt=[];function Ck(e){return dt.push(e),()=>{let t=dt.indexOf(e);t>=0&&dt.splice(t,1)}}s(Ck,"addTracingProcessor");function Pk(e){dt.splice(0,dt.length,...e)}s(Pk,"setTracingProcessors");function Mk(){return dt}s(Mk,"_getRegisteredProcessors");function Ua(e){for(let t of dt)try{t.onSpanStart(e)}catch{}}s(Ua,"_emitSpanStart");function Ka(e){for(let t of dt)try{t.onSpanEnd(e)}catch{}}s(Ka,"_emitSpanEnd");function Ba(e){for(let t of dt)try{t.onTraceEnd(e)}catch{}}s(Ba,"_emitTraceEnd");async function Ok(){await Promise.all(dt.map(async e=>{if(e.shutdown)try{await e.shutdown()}catch{}}))}s(Ok,"shutdownTracing");var oo=class{static{s(this,"Tracer")}options;constructor(t={}){this.options=t}startTrace(t={}){return Fa({id:t.id,name:t.name,rootSpanData:t.rootSpanData,metadata:t.metadata,now:this.options.now,nextSpanId:this.options.nextSpanId,nextTraceId:this.options.nextTraceId,onSpanStart:Ua,onSpanEnd:Ka,onTraceEnd:Ba})}},qa=new oo;var Wa=class{static{s(this,"ConsoleTracingProcessor")}write;constructor(t={}){this.write=t.write??(n=>{typeof process<"u"&&process.stdout&&process.stdout.write(n+`
4
4
  `)})}onSpanStart(t){this.write(`[span:start] traceId=${t.traceId} spanId=${t.id} name=${t.name} kind=${t.data.kind}`)}onSpanEnd(t){let n=t.endedAt!==void 0?t.endedAt-t.startedAt:0,r=t.error?` error=${$k(t.error.message)}`:"";this.write(`[span:end] traceId=${t.traceId} spanId=${t.id} name=${t.name} kind=${t.data.kind} durationMs=${n}${r}`)}onTraceEnd(t){let n=t.endedAt!==void 0?t.endedAt-t.startedAt:0;this.write(`[trace:end] traceId=${t.id} rootName=${t.rootSpan.name} durationMs=${n}`)}};function $k(e){return e.replace(/\s+/g," ").trim()}s($k,"safe");import{promises as Of}from"node:fs";import $f from"node:path";var Ha=class{static{s(this,"FileTracingProcessor")}traceDir;queues=new Map;writeChain=Promise.resolve();ensuredDir=!1;constructor(t={}){this.traceDir=t.traceDir??$f.join(process.cwd(),".kodax",".traces")}onSpanStart(t){this.enqueue(t.traceId,{event:"span:start",traceId:t.traceId,spanId:t.id,parentId:t.parentId,name:t.name,startedAt:t.startedAt,data:t.data})}onSpanEnd(t){this.enqueue(t.traceId,{event:"span:end",traceId:t.traceId,spanId:t.id,parentId:t.parentId,name:t.name,startedAt:t.startedAt,endedAt:t.endedAt,durationMs:t.endedAt!==void 0?t.endedAt-t.startedAt:void 0,data:t.data,error:t.error?{message:t.error.message,stack:t.error.stack}:void 0})}onTraceEnd(t){this.enqueue(t.id,{event:"trace:end",traceId:t.id,rootName:t.rootSpan.name,startedAt:t.startedAt,endedAt:t.endedAt,durationMs:t.endedAt!==void 0?t.endedAt-t.startedAt:void 0}),this.scheduleFlush(t.id)}async shutdown(){for(let t of this.queues.keys())this.scheduleFlush(t);await this.writeChain}scheduleFlush(t){this.writeChain=this.writeChain.then(()=>this.flushTrace(t).catch(()=>{}))}enqueue(t,n){let r=JSON.stringify(n),i=this.queues.get(t)??[];i.push({traceId:t,line:r}),this.queues.set(t,i)}async flushTrace(t){let n=this.queues.get(t);if(!n||n.length===0)return;this.queues.delete(t),this.ensuredDir||(await Of.mkdir(this.traceDir,{recursive:!0}),this.ensuredDir=!0);let r=$f.join(this.traceDir,`${t}.jsonl`),i=n.map(o=>o.line).join(`
5
5
  `)+`
@@ -1,2 +1,2 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{o}from"./chunk-TRNAWSXP.js";import{a as i}from"./chunk-ONUPGMER.js";function r(u){let e=o(u?.llm);if(!e)return;let t={};return e.requestTimeoutMs!==void 0&&(t.requestTimeoutMs=e.requestTimeoutMs),e.streamIdleTimeoutMs!==void 0&&(t.streamIdleTimeoutMs=e.streamIdleTimeoutMs),e.chunkTimeoutMs!==void 0&&(t.chunkTimeoutMs=e.chunkTimeoutMs),e.maxRetryDelayMs!==void 0&&(t.maxRetryDelayMs=e.maxRetryDelayMs),Object.keys(t).length>0?t:void 0}i(r,"providerResilienceConfigFromTimeouts");export{r as a};
2
+ import{o}from"./chunk-SKELDH3G.js";import{a as i}from"./chunk-ONUPGMER.js";function r(u){let e=o(u?.llm);if(!e)return;let t={};return e.requestTimeoutMs!==void 0&&(t.requestTimeoutMs=e.requestTimeoutMs),e.streamIdleTimeoutMs!==void 0&&(t.streamIdleTimeoutMs=e.streamIdleTimeoutMs),e.chunkTimeoutMs!==void 0&&(t.chunkTimeoutMs=e.chunkTimeoutMs),e.maxRetryDelayMs!==void 0&&(t.maxRetryDelayMs=e.maxRetryDelayMs),Object.keys(t).length>0?t:void 0}i(r,"providerResilienceConfigFromTimeouts");export{r as a};