@kodax-ai/kodax 0.7.90 → 0.7.92

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 (82) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +43 -0
  3. package/README_CN.md +28 -0
  4. package/dist/chunks/{agent-W35WYLTH.js → agent-YHHFIH7N.js} +1 -1
  5. package/dist/chunks/argument-completer-6ZTRBNZM.js +2 -0
  6. package/dist/chunks/{chunk-DBFWNUGB.js → chunk-5CIKWSCA.js} +2 -2
  7. package/dist/chunks/{chunk-R3BXINQ2.js → chunk-7XSZVOG7.js} +135 -135
  8. package/dist/chunks/chunk-A6GNPNGB.js +383 -0
  9. package/dist/chunks/{chunk-NCK7ASJL.js → chunk-AGZNXFHZ.js} +206 -205
  10. package/dist/chunks/chunk-BV3SVH36.js +519 -0
  11. package/dist/chunks/chunk-FBL7IVMK.js +123 -0
  12. package/dist/chunks/{chunk-6FLHNFYV.js → chunk-GH3KBC2H.js} +1 -1
  13. package/dist/chunks/{chunk-4KJQ7QGO.js → chunk-GRWUC6H7.js} +1 -1
  14. package/dist/chunks/chunk-OSQIYUGD.js +408 -0
  15. package/dist/chunks/{chunk-KG3QIIDU.js → chunk-PKPBII4F.js} +2 -2
  16. package/dist/chunks/{chunk-5247AKGN.js → chunk-QFV6YCIH.js} +2 -2
  17. package/dist/chunks/chunk-QKLS4BYA.js +320 -0
  18. package/dist/chunks/{chunk-7KPBUO2F.js → chunk-QPBN3J4E.js} +2 -2
  19. package/dist/chunks/chunk-RJIYXB62.js +415 -0
  20. package/dist/chunks/{chunk-JNBAIFJR.js → chunk-THZVJ6R7.js} +1 -1
  21. package/dist/chunks/{chunk-O2ZV775M.js → chunk-X75UGXP3.js} +1 -1
  22. package/dist/chunks/{chunk-ZVICRZVA.js → chunk-YVG6OKN7.js} +1 -1
  23. package/dist/chunks/{client-RWXK22GN.js → client-OVYKC3ND.js} +1 -1
  24. package/dist/chunks/compaction-config-2TVSYSB4.js +2 -0
  25. package/dist/chunks/{construction-bootstrap-KB6GB6IY.js → construction-bootstrap-QVLJPFTL.js} +1 -1
  26. package/dist/chunks/{dist-WILA35IA.js → dist-WNMK42WE.js} +1 -1
  27. package/dist/chunks/dist-XC5M7UYX.js +2 -0
  28. package/dist/chunks/host-B3TK2U43.js +2 -0
  29. package/dist/chunks/run-manager-5AV3MR4W.js +2 -0
  30. package/dist/chunks/{utils-SDMYKIZG.js → utils-HPVZCR2J.js} +1 -1
  31. package/dist/index.d.ts +15 -15
  32. package/dist/index.js +5 -5
  33. package/dist/kodax_bootstrap.js +1 -1
  34. package/dist/kodax_cli.js +1550 -1552
  35. package/dist/runtime-worker.js +1421 -1423
  36. package/dist/sandbox-workspace-session.js +269 -268
  37. package/dist/sdk-a2a.d.ts +11 -11
  38. package/dist/sdk-a2a.js +1 -1
  39. package/dist/sdk-agent.d.ts +15 -8
  40. package/dist/sdk-agent.js +1 -1
  41. package/dist/sdk-coding.d.ts +12 -12
  42. package/dist/sdk-coding.js +1 -1
  43. package/dist/sdk-experimental-memory.js +1 -1
  44. package/dist/sdk-llm.d.ts +1 -1
  45. package/dist/sdk-llm.js +1 -1
  46. package/dist/sdk-mcp.js +1 -1
  47. package/dist/sdk-media.js +1 -1
  48. package/dist/sdk-repl.d.ts +8 -8
  49. package/dist/sdk-repl.js +2 -2
  50. package/dist/sdk-runtime.d.ts +112 -11
  51. package/dist/sdk-runtime.js +1 -1
  52. package/dist/sdk-sandbox.d.ts +1 -1
  53. package/dist/sdk-sandbox.js +1 -1
  54. package/dist/sdk-session.d.ts +4 -4
  55. package/dist/sdk-session.js +1 -1
  56. package/dist/sdk-skills.js +1 -1
  57. package/dist/semantic-worker.js +77 -76
  58. package/dist/types-chunks/{bash-prefix-extractor.d-DBxWweqC.d.ts → bash-prefix-extractor.d-BMi_TJIY.d.ts} +53 -6
  59. package/dist/types-chunks/{capsule.d-Bc1-UYaj.d.ts → capsule.d-nYbM4MNL.d.ts} +1 -1
  60. package/dist/types-chunks/{controller.d-CnQqfSI5.d.ts → controller.d-Bm1i9RVj.d.ts} +13 -5
  61. package/dist/types-chunks/{guardrail.d-DqP4s46f.d.ts → guardrail.d-CKkoea7y.d.ts} +2 -2
  62. package/dist/types-chunks/{public-api.d-CrBB7m8F.d.ts → public-api.d-BsZWOq3P.d.ts} +4 -2
  63. package/dist/types-chunks/{repl.d-qijzfmA1.d.ts → repl.d-DxD0Olm0.d.ts} +10 -5
  64. package/dist/types-chunks/{resolver.d-bKttRr1V.d.ts → resolver.d-DparsV6Y.d.ts} +6 -4
  65. package/dist/types-chunks/{run-manager.d-PEct-5KE.d.ts → run-manager.d-BeSEc2OL.d.ts} +1 -1
  66. package/dist/types-chunks/{sdk-session-BIeiLU8G.d.ts → sdk-session-BTzblJTQ.d.ts} +1 -1
  67. package/dist/types-chunks/{shell-command-sets.d-RvEIrqHQ.d.ts → shell-command-sets.d-C2cc9Hwi.d.ts} +1 -1
  68. package/dist/types-chunks/{types.d-B9Fhknxd.d.ts → types.d-Dc3kwcjC.d.ts} +1 -1
  69. package/dist/types-chunks/{types.d-Do_AsIIs.d.ts → types.d-DrtP1ceI.d.ts} +1 -1
  70. package/dist/types-chunks/{utils.d-BvayexqQ.d.ts → utils.d-50Q24Few.d.ts} +4 -4
  71. package/package.json +5 -2
  72. package/dist/chunks/argument-completer-SRCHPEMA.js +0 -2
  73. package/dist/chunks/chunk-KINDGE7G.js +0 -382
  74. package/dist/chunks/chunk-T256QEDN.js +0 -412
  75. package/dist/chunks/chunk-TDSTNXNR.js +0 -519
  76. package/dist/chunks/chunk-UNEC2WXJ.js +0 -123
  77. package/dist/chunks/chunk-ZACJCRHT.js +0 -415
  78. package/dist/chunks/chunk-ZDOLJSTE.js +0 -320
  79. package/dist/chunks/compaction-config-MD2PQSAM.js +0 -2
  80. package/dist/chunks/dist-2NRXEHLI.js +0 -2
  81. package/dist/chunks/host-JAXBBRCV.js +0 -2
  82. package/dist/chunks/run-manager-EI264JTO.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 Be,C as hi,D as yi,E as vi,F as nt,I as en,K as ki,O as bi,Q as on,Y as Re,ba as $i,c as ui,d as fi,da as Si,ea as xi,f as mi,fa as Ai,h as et,i as ot,m as pi,n as gi,y as wi}from"./chunk-DBFWNUGB.js";import{a as Ri}from"./chunk-4KJQ7QGO.js";import{ea as ai,fa as li,ja as ci,la as di}from"./chunk-T256QEDN.js";import{i as Vo}from"./chunk-JNBAIFJR.js";import{Ab as Zn,Cb as yo,Gb as vo,Hb as Qn,Ua as ii,Va as si,_ as Qr,hb as Ke,i as Xn,n as Gr,xb as Qo,yb as Ae}from"./chunk-ZACJCRHT.js";import{A as ri,D as xe,J as He,m as Yo,n as Jo,o as Fe,q as wo,r as Zo,s as ei,t as oi,v as ni,w as Jn,x as ti,y as ho}from"./chunk-7KPBUO2F.js";import{Rb as Xr,Tb as Vr,Ub as Yr,Xb as Vn,Ya as zo,ba as zr,hd as Zr,jd as se,pc as Yn,qc as Xo,tc as Jr}from"./chunk-NCK7ASJL.js";import{C as Er,Pa as po,Qa as Ne,Ra as De,ka as mo,ma as Bn,ya as qn}from"./chunk-UNEC2WXJ.js";import{Bc as Ko,Cg as qr,Dc as Bo,Ec as Nr,Fd as Se,Gc as Dr,Gd as je,Ia as ge,Ja as W,Ka as ie,La as Ir,Ld as jr,Pd as Ur,Qa as Pr,Qd as qo,Ra as Tr,Sa as Gn,Td as Fr,Wb as Mr,Yb as _r,Yf as Ue,Zf as Br,ac as go,bg as zn,je as Hr,k as Ho,lg as Go,mc as Lr,nc as Wr,oc as Or,of as Kr,t as G}from"./chunk-R3BXINQ2.js";import{a}from"./chunk-ONUPGMER.js";import*as Dn from"fs";import*as jo from"path";import*as Ln from"fs";import _n from"path";import i from"chalk";var nn=["plan","accept-edits","auto","auto-in-project"];function Xa(e){return e==="auto"||e==="auto-in-project"}a(Xa,"isAutoMode");function Am(e,o){return Xa(e)&&o==="llm"}a(Am,"isAutoLlmMode");function Va(e){switch(e){case"plan":return"Plan";case"accept-edits":return"Edits";case"auto":case"auto-in-project":return"Auto"}}a(Va,"permissionModeDisplayName");var Ya='[deprecated] permissionMode "auto-in-project" is now an alias for "auto" (FEATURE_092, v0.7.33). The alias will be removed in v0.7.38 \u2014 please update ~/.kodax/config.json to use "auto".';function Rm(e=o=>{G({source:"repl:permission",level:"warn",message:o})}){let o=!1;return()=>{o||(o=!0,e(Ya))}}a(Rm,"createAutoInProjectDeprecationEmitter");function tn(e){switch(e){case"plan":return new Set(["bash","write","edit","undo"]);case"accept-edits":return new Set(["bash"]);case"auto":case"auto-in-project":return new Set}}a(tn,"computeConfirmTools");function Ei(e){return e!==void 0&&nn.includes(e)}a(Ei,"isPermissionMode");function ko(e,o){return Ei(e)?e:o}a(ko,"normalizePermissionMode");import{createHash as Ja,randomUUID as Za}from"node:crypto";import qe from"node:fs";import Ii from"node:path";var $o=class extends Error{static{a(this,"ProviderSetupConfigConflictError")}constructor(o){super(`KodaX configuration changed while setup was open: ${o}. Re-run \`kodax setup\`.`),this.name="ProviderSetupConfigConflictError"}},Ge=class extends Error{static{a(this,"ProviderSetupInvalidConfigError")}constructor(o,n){super(`KodaX configuration cannot be safely updated: ${o}. ${n}`),this.name="ProviderSetupInvalidConfigError"}},Wi=/^[A-Za-z_][A-Za-z0-9_]*$/,Qa=new Set(["accesskey","apikey","accesstoken","auth","authorization","bearertoken","clientsecret","credential","key","password","privatekey","refreshtoken","secret","sig","signature","token","xapikey"]);function ze(){return Object.entries(mo).filter(([,e])=>e.capabilityProfile.transport!=="cli-bridge").map(([e,o])=>({name:e,apiKeyEnv:o.apiKeyEnv,defaultModel:o.model,models:[...new Set(o.models?[o.model,...o.models.map(n=>n.id)]:[o.model])]})).sort((e,o)=>e.name===Bn?-1:o.name===Bn?1:e.name.localeCompare(o.name))}a(ze,"getProviderSetupCatalog");function Oi(e={}){let o=e.configPath??W("config.json"),n=e.catalog??ze(),t=e.environment??process.env,r=tt(o);if(!r.config)return{status:"invalid-config",configPath:o,configRevision:r.revision,reason:r.error??"config.json is not a JSON object."};let s=ji(r.config);if(s)return{status:"invalid-config",configPath:o,configRevision:r.revision,reason:s};let l=Mi(e.explicitProvider);if(l){let d=Li(r.config,l,n);return d&&(!d.requiresCredential||_i(t,d.apiKeyEnv))?Pi(o,r.revision,l):Ti(o,r.revision,l,d?.apiKeyEnv)}if(!r.exists)return{status:"needs-provider",configPath:o,configRevision:r.revision};let c=Mi(r.config.provider);if(c){let d=Li(r.config,c,n);return d?!d.requiresCredential||_i(t,d.apiKeyEnv)?Pi(o,r.revision,c):Ti(o,r.revision,c,d.apiKeyEnv):{status:"invalid-config",configPath:o,configRevision:r.revision,reason:`provider "${c}" is not a valid built-in or custom provider.`}}return{status:"needs-provider",configPath:o,configRevision:r.revision}}a(Oi,"inspectProviderSetupReadiness");function Ni(e){let o=e.configPath??W("config.json"),n=e.catalog??ze();try{return mi(o,()=>{let t=tt(o);if(!t.config)throw new Ge(o,t.error??"config.json is invalid JSON.");if(t.revision!==e.expectedRevision)throw new $o(o);el(t.config,o);let r=nl(e.choice,n,t.config),s={...t.config,provider:r.provider,model:r.model,...r.customProviders?{customProviders:r.customProviders}:{}};if(tt(o).revision!==e.expectedRevision)throw new $o(o);return tl(o,s),{provider:r.provider,model:r.model,apiKeyEnv:r.apiKeyEnv,configPath:o}})}catch(t){throw t instanceof fi?new $o(o):t}}a(Ni,"persistProviderSetupChoice");function Di(e){let n=(e.platform??process.platform)==="win32"?`Required next step: use this provider's API key as the value of the user environment variable "${e.apiKeyEnv}" in Windows Environment Variables.`:`Required next step: use this provider's API key as the value of the environment variable "${e.apiKeyEnv}" in your shell profile.`;return[`config.json stores the environment-variable name only: "${e.apiKeyEnv}"; it never stores the API key.`,n,"KodaX cannot set this environment variable for you.","Close and restart this terminal so the environment is refreshed.","Then run `kodax` again.","Optional: run `kodax doctor` to verify local configuration without an LLM request."]}a(Di,"providerSetupRestartInstructions");function Pi(e,o,n){return{status:"ready",configPath:e,configRevision:o,...n?{provider:n}:{}}}a(Pi,"ready");function Ti(e,o,n,t){return{status:"needs-credential",configPath:e,configRevision:o,provider:n,...t?{apiKeyEnv:t}:{}}}a(Ti,"needsCredential");function Mi(e){return typeof e=="string"&&e.trim()?e.trim():void 0}a(Mi,"normalizedString");function _i(e,o){return o!==void 0&&!!e[o]?.trim()}a(_i,"hasEnvironmentValue");function Li(e,o,n){let t=n.find(l=>l.name===o);if(t)return{apiKeyEnv:t.apiKeyEnv,requiresCredential:!0};if(Object.entries(mo).find(([l])=>l===o)?.[1]?.capabilityProfile.transport==="cli-bridge")return{requiresCredential:!1};let s=ol(e,o);return s?{apiKeyEnv:s.apiKeyEnv,requiresCredential:!0}:void 0}a(Li,"resolveConfiguredProvider");function el(e,o){let n=ji(e);if(n)throw new Ge(o,n)}a(el,"assertCustomProvidersPreservable");function ji(e){let o=e.customProviders;if(o===void 0)return;if(!Array.isArray(o))return"Existing customProviders must be an array; repair it before running setup.";let n=new Set;for(let t of o){let r=rt(t);if(!r)return"Existing customProviders contains an invalid entry; repair it before running setup.";let s=Ui(r.baseUrl);if(s)return`Existing customProviders entry "${r.name}" is unsafe: ${s}`;if(n.has(r.name))return`Existing customProviders contains duplicate name "${r.name}"; repair it before running setup.`;n.add(r.name)}}a(ji,"existingCustomProvidersError");function ol(e,o){let n=e.customProviders;if(Array.isArray(n))for(let t of n){let r=rt(t);if(r?.name===o)return r}}a(ol,"findValidCustomProvider");function rt(e){if(!Fi(e))return;let{name:o,protocol:n,baseUrl:t,apiKeyEnv:r,model:s}=e;if(typeof o!="string"||n!=="openai"&&n!=="anthropic"||typeof t!="string"||typeof r!="string"||typeof s!="string")return;let l={...e,name:o,protocol:n,baseUrl:t,apiKeyEnv:r,model:s};try{return qn(l),Wi.test(l.apiKeyEnv)?l:void 0}catch{return}}a(rt,"toValidCustomProvider");function nl(e,o,n){if(e.kind==="builtin"){let d=o.find(u=>u.name===e.provider);if(!d||!d.models.includes(e.model))throw new Error("Choose a supported built-in provider and model.");return{provider:d.name,model:e.model,apiKeyEnv:d.apiKeyEnv}}let t=it(e.provider);if(o.some(d=>d.name===t.name))throw new Error(`Custom provider name "${t.name}" conflicts with a built-in provider.`);let r=n.customProviders,s=Array.isArray(r)?r.flatMap(d=>{let u=rt(d);return u?[u]:[]}):[],c=s.find(d=>d.name===t.name)?s.map(d=>d.name===t.name?t:d):[...s,t];return{provider:t.name,model:t.model,apiKeyEnv:t.apiKeyEnv,customProviders:c}}a(nl,"normalizeProviderSetupChoice");function it(e){let o={name:e.name.trim(),protocol:e.protocol,baseUrl:e.baseUrl.trim(),apiKeyEnv:e.apiKeyEnv.trim(),model:e.model.trim()},n=Ui(o.baseUrl);if(n)throw new Error(n);if(qn(o),!Wi.test(o.apiKeyEnv))throw new Error("Custom provider API key environment variable name is invalid.");return o}a(it,"validateProviderSetupCustomMetadata");function Ui(e){let o;try{o=new URL(e)}catch{return"Custom provider Base URL must be a valid absolute URL."}if(o.protocol!=="https:"&&o.protocol!=="http:")return"Custom provider Base URL must use http or https.";if(o.username||o.password)return"Custom provider Base URL must not contain credentials.";let n=[...o.searchParams.keys()].find(t=>Qa.has(t.toLowerCase().replace(/[-_.]/g,"")));return n===void 0?void 0:`Custom provider Base URL must not contain credential query parameter "${n}".`}a(Ui,"customProviderEndpointError");function tt(e){if(!qe.existsSync(e))return{configPath:e,revision:bo(void 0),exists:!1,config:{}};let o;try{o=qe.readFileSync(e,"utf8")}catch(n){return{configPath:e,revision:bo(void 0),exists:!0,error:n instanceof Error?n.message:"config.json cannot be read."}}try{let n=JSON.parse(o);return Fi(n)?{configPath:e,revision:bo(o),exists:!0,config:n}:{configPath:e,revision:bo(o),exists:!0,error:"config.json must contain a JSON object."}}catch(n){return{configPath:e,revision:bo(o),exists:!0,error:n instanceof Error?n.message:"config.json is invalid JSON."}}}a(tt,"readConfig");function bo(e){return Ja("sha256").update(e??"<missing>","utf8").digest("hex")}a(bo,"revisionFor");function Fi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Fi,"isRecord");function tl(e,o){let n=Ii.dirname(e);qe.mkdirSync(n,{recursive:!0});let t=Ii.join(n,`.config.${process.pid}.${Za()}.tmp`);try{qe.writeFileSync(t,`${JSON.stringify(o,null,2)}
2
+ import{A as Be,C as hi,D as yi,E as vi,F as nt,I as en,K as ki,O as bi,Q as on,Y as Re,ba as $i,c as ui,d as fi,da as Si,ea as xi,f as mi,fa as Ai,h as et,i as ot,m as pi,n as gi,y as wi}from"./chunk-5CIKWSCA.js";import{a as Ri}from"./chunk-GRWUC6H7.js";import{ha as ai,ia as li,ma as ci,oa as di}from"./chunk-OSQIYUGD.js";import{i as Vo}from"./chunk-THZVJ6R7.js";import{Ab as Zn,Cb as yo,Gb as vo,Hb as Qn,Ua as ii,Va as si,_ as Qr,hb as Ke,i as Xn,n as Gr,xb as Qo,yb as Ae}from"./chunk-RJIYXB62.js";import{A as ri,D as xe,J as He,m as Yo,n as Jo,o as Fe,q as wo,r as Zo,s as ei,t as oi,v as ni,w as Jn,x as ti,y as ho}from"./chunk-QPBN3J4E.js";import{Rb as Xr,Tb as Vr,Ub as Yr,Xb as Vn,Ya as zo,ba as zr,hd as Zr,jd as se,pc as Yn,qc as Xo,tc as Jr}from"./chunk-AGZNXFHZ.js";import{C as Er,Pa as po,Qa as Ne,Ra as De,ka as mo,ma as Bn,ya as qn}from"./chunk-FBL7IVMK.js";import{$f as Br,Dc as Ko,Eg as qr,Fc as Bo,Gc as Nr,Hd as Se,Ia as ge,Ic as Dr,Id as je,Ja as W,Ka as ie,La as Ir,Nd as jr,Qa as Pr,Ra as Tr,Rd as Ur,Sa as Gn,Sd as qo,Vd as Fr,Wb as Mr,Yb as _r,_f as Ue,ac as go,dg as zn,k as Ho,le as Hr,mc as Lr,nc as Wr,ng as Go,oc as Or,qf as Kr,t as G}from"./chunk-7XSZVOG7.js";import{a}from"./chunk-ONUPGMER.js";import*as Dn from"fs";import*as jo from"path";import*as Ln from"fs";import _n from"path";import i from"chalk";var nn=["plan","accept-edits","auto","auto-in-project"];function Xa(e){return e==="auto"||e==="auto-in-project"}a(Xa,"isAutoMode");function Am(e,o){return Xa(e)&&o==="llm"}a(Am,"isAutoLlmMode");function Va(e){switch(e){case"plan":return"Plan";case"accept-edits":return"Edits";case"auto":case"auto-in-project":return"Auto"}}a(Va,"permissionModeDisplayName");var Ya='[deprecated] permissionMode "auto-in-project" is now an alias for "auto" (FEATURE_092, v0.7.33). The alias will be removed in v0.7.38 \u2014 please update ~/.kodax/config.json to use "auto".';function Rm(e=o=>{G({source:"repl:permission",level:"warn",message:o})}){let o=!1;return()=>{o||(o=!0,e(Ya))}}a(Rm,"createAutoInProjectDeprecationEmitter");function tn(e){switch(e){case"plan":return new Set(["bash","write","edit","undo"]);case"accept-edits":return new Set(["bash"]);case"auto":case"auto-in-project":return new Set}}a(tn,"computeConfirmTools");function Ei(e){return e!==void 0&&nn.includes(e)}a(Ei,"isPermissionMode");function ko(e,o){return Ei(e)?e:o}a(ko,"normalizePermissionMode");import{createHash as Ja,randomUUID as Za}from"node:crypto";import qe from"node:fs";import Ii from"node:path";var $o=class extends Error{static{a(this,"ProviderSetupConfigConflictError")}constructor(o){super(`KodaX configuration changed while setup was open: ${o}. Re-run \`kodax setup\`.`),this.name="ProviderSetupConfigConflictError"}},Ge=class extends Error{static{a(this,"ProviderSetupInvalidConfigError")}constructor(o,n){super(`KodaX configuration cannot be safely updated: ${o}. ${n}`),this.name="ProviderSetupInvalidConfigError"}},Wi=/^[A-Za-z_][A-Za-z0-9_]*$/,Qa=new Set(["accesskey","apikey","accesstoken","auth","authorization","bearertoken","clientsecret","credential","key","password","privatekey","refreshtoken","secret","sig","signature","token","xapikey"]);function ze(){return Object.entries(mo).filter(([,e])=>e.capabilityProfile.transport!=="cli-bridge").map(([e,o])=>({name:e,apiKeyEnv:o.apiKeyEnv,defaultModel:o.model,models:[...new Set(o.models?[o.model,...o.models.map(n=>n.id)]:[o.model])]})).sort((e,o)=>e.name===Bn?-1:o.name===Bn?1:e.name.localeCompare(o.name))}a(ze,"getProviderSetupCatalog");function Oi(e={}){let o=e.configPath??W("config.json"),n=e.catalog??ze(),t=e.environment??process.env,r=tt(o);if(!r.config)return{status:"invalid-config",configPath:o,configRevision:r.revision,reason:r.error??"config.json is not a JSON object."};let s=ji(r.config);if(s)return{status:"invalid-config",configPath:o,configRevision:r.revision,reason:s};let l=Mi(e.explicitProvider);if(l){let d=Li(r.config,l,n);return d&&(!d.requiresCredential||_i(t,d.apiKeyEnv))?Pi(o,r.revision,l):Ti(o,r.revision,l,d?.apiKeyEnv)}if(!r.exists)return{status:"needs-provider",configPath:o,configRevision:r.revision};let c=Mi(r.config.provider);if(c){let d=Li(r.config,c,n);return d?!d.requiresCredential||_i(t,d.apiKeyEnv)?Pi(o,r.revision,c):Ti(o,r.revision,c,d.apiKeyEnv):{status:"invalid-config",configPath:o,configRevision:r.revision,reason:`provider "${c}" is not a valid built-in or custom provider.`}}return{status:"needs-provider",configPath:o,configRevision:r.revision}}a(Oi,"inspectProviderSetupReadiness");function Ni(e){let o=e.configPath??W("config.json"),n=e.catalog??ze();try{return mi(o,()=>{let t=tt(o);if(!t.config)throw new Ge(o,t.error??"config.json is invalid JSON.");if(t.revision!==e.expectedRevision)throw new $o(o);el(t.config,o);let r=nl(e.choice,n,t.config),s={...t.config,provider:r.provider,model:r.model,...r.customProviders?{customProviders:r.customProviders}:{}};if(tt(o).revision!==e.expectedRevision)throw new $o(o);return tl(o,s),{provider:r.provider,model:r.model,apiKeyEnv:r.apiKeyEnv,configPath:o}})}catch(t){throw t instanceof fi?new $o(o):t}}a(Ni,"persistProviderSetupChoice");function Di(e){let n=(e.platform??process.platform)==="win32"?`Required next step: use this provider's API key as the value of the user environment variable "${e.apiKeyEnv}" in Windows Environment Variables.`:`Required next step: use this provider's API key as the value of the environment variable "${e.apiKeyEnv}" in your shell profile.`;return[`config.json stores the environment-variable name only: "${e.apiKeyEnv}"; it never stores the API key.`,n,"KodaX cannot set this environment variable for you.","Close and restart this terminal so the environment is refreshed.","Then run `kodax` again.","Optional: run `kodax doctor` to verify local configuration without an LLM request."]}a(Di,"providerSetupRestartInstructions");function Pi(e,o,n){return{status:"ready",configPath:e,configRevision:o,...n?{provider:n}:{}}}a(Pi,"ready");function Ti(e,o,n,t){return{status:"needs-credential",configPath:e,configRevision:o,provider:n,...t?{apiKeyEnv:t}:{}}}a(Ti,"needsCredential");function Mi(e){return typeof e=="string"&&e.trim()?e.trim():void 0}a(Mi,"normalizedString");function _i(e,o){return o!==void 0&&!!e[o]?.trim()}a(_i,"hasEnvironmentValue");function Li(e,o,n){let t=n.find(l=>l.name===o);if(t)return{apiKeyEnv:t.apiKeyEnv,requiresCredential:!0};if(Object.entries(mo).find(([l])=>l===o)?.[1]?.capabilityProfile.transport==="cli-bridge")return{requiresCredential:!1};let s=ol(e,o);return s?{apiKeyEnv:s.apiKeyEnv,requiresCredential:!0}:void 0}a(Li,"resolveConfiguredProvider");function el(e,o){let n=ji(e);if(n)throw new Ge(o,n)}a(el,"assertCustomProvidersPreservable");function ji(e){let o=e.customProviders;if(o===void 0)return;if(!Array.isArray(o))return"Existing customProviders must be an array; repair it before running setup.";let n=new Set;for(let t of o){let r=rt(t);if(!r)return"Existing customProviders contains an invalid entry; repair it before running setup.";let s=Ui(r.baseUrl);if(s)return`Existing customProviders entry "${r.name}" is unsafe: ${s}`;if(n.has(r.name))return`Existing customProviders contains duplicate name "${r.name}"; repair it before running setup.`;n.add(r.name)}}a(ji,"existingCustomProvidersError");function ol(e,o){let n=e.customProviders;if(Array.isArray(n))for(let t of n){let r=rt(t);if(r?.name===o)return r}}a(ol,"findValidCustomProvider");function rt(e){if(!Fi(e))return;let{name:o,protocol:n,baseUrl:t,apiKeyEnv:r,model:s}=e;if(typeof o!="string"||n!=="openai"&&n!=="anthropic"||typeof t!="string"||typeof r!="string"||typeof s!="string")return;let l={...e,name:o,protocol:n,baseUrl:t,apiKeyEnv:r,model:s};try{return qn(l),Wi.test(l.apiKeyEnv)?l:void 0}catch{return}}a(rt,"toValidCustomProvider");function nl(e,o,n){if(e.kind==="builtin"){let d=o.find(u=>u.name===e.provider);if(!d||!d.models.includes(e.model))throw new Error("Choose a supported built-in provider and model.");return{provider:d.name,model:e.model,apiKeyEnv:d.apiKeyEnv}}let t=it(e.provider);if(o.some(d=>d.name===t.name))throw new Error(`Custom provider name "${t.name}" conflicts with a built-in provider.`);let r=n.customProviders,s=Array.isArray(r)?r.flatMap(d=>{let u=rt(d);return u?[u]:[]}):[],c=s.find(d=>d.name===t.name)?s.map(d=>d.name===t.name?t:d):[...s,t];return{provider:t.name,model:t.model,apiKeyEnv:t.apiKeyEnv,customProviders:c}}a(nl,"normalizeProviderSetupChoice");function it(e){let o={name:e.name.trim(),protocol:e.protocol,baseUrl:e.baseUrl.trim(),apiKeyEnv:e.apiKeyEnv.trim(),model:e.model.trim()},n=Ui(o.baseUrl);if(n)throw new Error(n);if(qn(o),!Wi.test(o.apiKeyEnv))throw new Error("Custom provider API key environment variable name is invalid.");return o}a(it,"validateProviderSetupCustomMetadata");function Ui(e){let o;try{o=new URL(e)}catch{return"Custom provider Base URL must be a valid absolute URL."}if(o.protocol!=="https:"&&o.protocol!=="http:")return"Custom provider Base URL must use http or https.";if(o.username||o.password)return"Custom provider Base URL must not contain credentials.";let n=[...o.searchParams.keys()].find(t=>Qa.has(t.toLowerCase().replace(/[-_.]/g,"")));return n===void 0?void 0:`Custom provider Base URL must not contain credential query parameter "${n}".`}a(Ui,"customProviderEndpointError");function tt(e){if(!qe.existsSync(e))return{configPath:e,revision:bo(void 0),exists:!1,config:{}};let o;try{o=qe.readFileSync(e,"utf8")}catch(n){return{configPath:e,revision:bo(void 0),exists:!0,error:n instanceof Error?n.message:"config.json cannot be read."}}try{let n=JSON.parse(o);return Fi(n)?{configPath:e,revision:bo(o),exists:!0,config:n}:{configPath:e,revision:bo(o),exists:!0,error:"config.json must contain a JSON object."}}catch(n){return{configPath:e,revision:bo(o),exists:!0,error:n instanceof Error?n.message:"config.json is invalid JSON."}}}a(tt,"readConfig");function bo(e){return Ja("sha256").update(e??"<missing>","utf8").digest("hex")}a(bo,"revisionFor");function Fi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Fi,"isRecord");function tl(e,o){let n=Ii.dirname(e);qe.mkdirSync(n,{recursive:!0});let t=Ii.join(n,`.config.${process.pid}.${Za()}.tmp`);try{qe.writeFileSync(t,`${JSON.stringify(o,null,2)}
3
3
  `,{encoding:"utf8",mode:384}),qe.renameSync(t,e)}catch(r){throw qe.rmSync(t,{force:!0}),r}}a(tl,"writeConfigAtomically");import{existsSync as Hi,mkdirSync as rl,readFileSync as Ki,writeFileSync as il}from"node:fs";import Xe from"node:path";var sl={core:{},mcp:{version:1,servers:{}},extensions:{version:1,paths:[]},a2a:{version:2,agents:{}}},al=["core","mcp","extensions","a2a"];function st(e,o){return o==="core"?Xe.join(e,"config.json"):Xe.join(e,"integrations",`${o}.json`)}a(st,"activePath");function ll(e,o){return o==="core"?Xe.join(e,"config.example.jsonc"):Xe.join(e,"integrations",`${o}.example.jsonc`)}a(ll,"templatePath");function cl(e){let o=e.replaceAll("\\","/");return al.flatMap(n=>[{domain:n,kind:"active",path:st(e,n),content:`${JSON.stringify(sl[n],null,2)}
4
4
  `},{domain:n,kind:"template",path:ll(e,n),content:ui(n).replaceAll("~/.kodax",o)}])}a(cl,"configFiles");function So(e,o){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${o} must contain a JSON object.`);return e}a(So,"requireRecord");function dl(e,o){let n=So(e,"A2A config"),t=Object.keys(n).find(s=>!["version","agents","server"].includes(s));if(t)throw new Error(`A2A config contains unknown field "${t}".`);if(n.version!==1&&n.version!==2)throw new Error("A2A config version must be 1 or 2.");let r=So(n.agents,"A2A config agents");if(n.server!==void 0&&So(n.server,"A2A config server"),o)o(e);else if(Object.keys(r).length>0||n.server!==void 0)throw new Error("A2A config contains active declarations that require the KodaX host validator.")}a(dl,"validateA2ADocument");function ul(e,o){let n=Ki(e.path,"utf8"),t;try{t=JSON.parse(n)}catch{throw new Error(`${e.domain} config is invalid JSON.`)}e.domain==="core"?So(t,"Core config"):e.domain==="mcp"?et(t):e.domain==="extensions"?ot(t):dl(t,o)}a(ul,"validateActiveFile");function Bi(e,o){if(!Hi(e.path))return{domain:e.domain,kind:e.kind,path:e.path,status:"missing"};if(e.kind==="template")return{domain:e.domain,kind:e.kind,path:e.path,status:"existing"};try{return ul(e,o),{domain:e.domain,kind:e.kind,path:e.path,status:"existing"}}catch(n){return{domain:e.domain,kind:e.kind,path:e.path,status:"invalid",diagnostic:n instanceof Error?n.message:`${e.domain} config is invalid.`}}}a(Bi,"existingFileResult");function fl(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}a(fl,"isAlreadyExists");function ml(e,o){rl(Xe.dirname(e.path),{recursive:!0,mode:448});try{return il(e.path,e.content,{encoding:"utf8",flag:"wx",mode:384}),{domain:e.domain,kind:e.kind,path:e.path,status:"created"}}catch(n){if(fl(n))return Bi(e,o);throw n}}a(ml,"createIfMissing");function pl(e){let o=st(e,"core");if(Hi(o))try{let n=So(JSON.parse(Ki(o,"utf8")),"Core config"),t=pi(e);t.mcp.action==="create"&&et({version:1,servers:n.mcpServers}),t.extensions.action==="create"&&ot({version:1,paths:n.extensions})}catch(n){return`Legacy integration configuration is invalid: ${n instanceof Error?n.message:"Legacy integration config is invalid."}`}}a(pl,"legacyIntegrationDiagnostic");function qi(e={}){let o=Xe.resolve(e.configHome??ge()),n=cl(o),t=n.map(s=>Bi(s,e.validateA2A));if(t.some(s=>s.status==="invalid"))return{configHome:o,files:t};let r=pl(o);if(r){let s=st(o,"core");return t=t.map(l=>l.path===s?{...l,status:"invalid",diagnostic:r}:l),{configHome:o,files:t}}return gi({configHome:o}),{configHome:o,files:n.map(s=>ml(s,e.validateA2A))}}a(qi,"initializeSetupConfiguration");import Ce from"node:path";var Gi=[{id:"interrupt",name:"Interrupt",description:"Interrupt the current streaming response",defaultBindings:[{key:"c",ctrl:!0}],context:"global",priority:200,category:"global",configurable:!1},{id:"showHelp",name:"Toggle Help",description:"Show or hide shortcut help when the input is empty",defaultBindings:[{key:"?"}],context:"global",priority:150,category:"global",configurable:!0},{id:"toggleThinking",name:"Cycle Reasoning Effort",description:"Cycle reasoning effort for the active model: off, low \u2026 max, auto",defaultBindings:[{key:"t",ctrl:!0}],context:"global",priority:150,category:"mode",configurable:!0},{id:"toggleTranscriptMode",name:"Toggle Transcript Mode",description:"Toggle transcript mode on or off",defaultBindings:[{key:"o",ctrl:!0}],context:"global",priority:150,category:"mode",configurable:!0},{id:"openTranscriptSearch",name:"Search Transcript",description:"Open transcript search",defaultBindings:[{key:"f",ctrl:!0}],context:"global",priority:150,category:"navigation",configurable:!0},{id:"togglePermissionMode",name:"Cycle Permissions",description:"Cycle permission mode: plan, accept-edits, auto-in-project",defaultBindings:[{key:"tab",shift:!0}],context:"global",priority:150,category:"mode",configurable:!0},{id:"toggleAgentMode",name:"Cycle Agent Mode",description:"Cycle agent mode: AMA, SA",defaultBindings:[{key:"m",meta:!0}],context:"global",priority:150,category:"mode",configurable:!0},{id:"submitInput",name:"Submit Input",description:"Submit the current input",defaultBindings:[{key:"enter"}],context:"input",priority:50,category:"global",configurable:!1},{id:"acceptCompletion",name:"Accept Completion",description:"Accept the current autocomplete suggestion",defaultBindings:[{key:"tab"}],context:"input",priority:60,category:"editing",configurable:!0},{id:"cancelInput",name:"Cancel Input",description:"Cancel or clear the current input",defaultBindings:[{key:"escape"}],context:"input",priority:70,category:"editing",configurable:!0},{id:"newline",name:"Insert Newline",description:"Insert a newline in the current input",defaultBindings:[{key:"enter",shift:!0},{key:"j",ctrl:!0}],context:"input",priority:40,category:"editing",configurable:!0},{id:"historyUp",name:"History Up",description:"Browse previous input history",defaultBindings:[{key:"up"}],context:"input",priority:30,category:"navigation",configurable:!0},{id:"historyDown",name:"History Down",description:"Browse next input history",defaultBindings:[{key:"down"}],context:"input",priority:30,category:"navigation",configurable:!0},{id:"moveLeft",name:"Move Left",description:"Move the cursor left",defaultBindings:[{key:"left"}],context:"input",priority:20,category:"navigation",configurable:!1},{id:"moveRight",name:"Move Right",description:"Move the cursor right",defaultBindings:[{key:"right"}],context:"input",priority:20,category:"navigation",configurable:!1},{id:"moveToStart",name:"Move To Start",description:"Move the cursor to the start of the line",defaultBindings:[{key:"a",ctrl:!0}],context:"input",priority:25,category:"navigation",configurable:!0},{id:"moveToEnd",name:"Move To End",description:"Move the cursor to the end of the line",defaultBindings:[{key:"e",ctrl:!0}],context:"input",priority:25,category:"navigation",configurable:!0},{id:"killLineRight",name:"Delete To End",description:"Delete from the cursor to the end of the current line",defaultBindings:[{key:"k",ctrl:!0}],context:"input",priority:25,category:"editing",configurable:!0},{id:"killLineLeft",name:"Delete To Start",description:"Delete from the start of the line to the cursor",defaultBindings:[{key:"u",ctrl:!0}],context:"input",priority:25,category:"editing",configurable:!0},{id:"deleteWordLeft",name:"Delete Word Left",description:"Delete the word before the cursor",defaultBindings:[{key:"w",ctrl:!0},{key:"backspace",meta:!0}],context:"input",priority:25,category:"editing",configurable:!0},{id:"moveLineUp",name:"Move Line Up",description:"Move to the previous visual line in multiline input",defaultBindings:[{key:"up",ctrl:!0}],context:"input",priority:20,category:"navigation",configurable:!0},{id:"moveLineDown",name:"Move Line Down",description:"Move to the next visual line in multiline input",defaultBindings:[{key:"down",ctrl:!0}],context:"input",priority:20,category:"navigation",configurable:!0},{id:"backspace",name:"Backspace",description:"Delete the previous character",defaultBindings:[{key:"backspace"}],context:"input",priority:10,category:"editing",configurable:!1},{id:"delete",name:"Delete",description:"Delete the next character",defaultBindings:[{key:"delete"}],context:"input",priority:10,category:"editing",configurable:!1}];function gl(e){let o=[];e.ctrl&&o.push("Ctrl"),e.meta&&o.push("Alt"),e.shift&&o.push("Shift");let n={tab:"Tab",escape:"Esc",enter:"Enter",backspace:"Backspace"};return o.push(n[e.key]??(e.key.length===1?e.key.toUpperCase():e.key)),o.join("+")}a(gl,"formatBinding");function at(e){let n=Gi.find(t=>t.id===e)?.defaultBindings[0];return n?gl(n):"<unavailable>"}a(at,"shortcut");function wl(){return Object.entries(mo).filter(([,e])=>e.capabilityProfile.transport==="cli-bridge").map(([e])=>e).sort()}a(wl,"defaultCliBridges");function lt(e={}){let o=Ce.resolve(e.configHome??ge()),n=e.catalog??ze(),t=e.cliBridges??wl(),r=n.map(s=>` ${s.name.padEnd(18)} ${s.apiKeyEnv} (default model: ${s.defaultModel})`);return["KodaX setup guide","","Configuration files (existing files are never overwritten by setup):",` Core: ${Ce.join(o,"config.json")}`,` Annotated template: ${Ce.join(o,"config.example.jsonc")}`,` MCP: ${Ce.join(o,"integrations","mcp.json")}`,` Extensions: ${Ce.join(o,"integrations","extensions.json")}`,` A2A: ${Ce.join(o,"integrations","a2a.json")}`,` Integration templates: ${Ce.join(o,"integrations","*.example.jsonc")}`," Existing active files are validated first. If one is invalid, setup reports"," it and stops without creating or overwriting any configuration file."," The annotated core template includes `sandbox.envPass` for exact command-target"," environment passthrough; setup never stores an environment-variable value.","","Built-in API providers and credential environment variables:",...r,...t.length>0?[` CLI bridges: ${t.join(", ")} (authenticate with the provider CLI; no KodaX API-key variable)`]:[],"","Set the variable named for your provider; keep the credential out of config.json:"," Custom providers: `apiKeyEnv` is the environment-variable name stored in config.json,"," never the API key value."," Put the provider's actual API key in the value of that exact environment variable."," KodaX does not set this environment variable for you."," Windows PowerShell (persistent user variable):",' [Environment]::SetEnvironmentVariable("OPENAI_API_KEY", "<your-key>", "User")'," macOS/Linux shell profile:",' export OPENAI_API_KEY="<your-key>"'," Obtain the key from the provider console, then close and restart the terminal."," Run `kodax doctor` to verify local configuration without sending an LLM request.","","Setup commands:"," kodax setup Initialize missing files and choose a built-in or custom provider"," kodax setup --custom Configure only a custom OpenAI/Anthropic-compatible provider"," kodax setup --help Show this guide without changing files","","Sandbox containment (optional; permission decisions still work when it is unavailable):"," `kodax setup`, first-run setup, and `/setup` check sandbox readiness once."," Windows: setup can launch the one-time UAC provisioning flow; the terminal itself"," does not need to run as Administrator. Declining UAC is non-fatal."," macOS: ASRT uses Seatbelt/sandbox-exec; install ripgrep with `brew install ripgrep`."," Linux: ASRT uses bubblewrap; install bubblewrap, socat, and ripgrep with apt,"," dnf, or pacman. KodaX never invokes sudo or a package manager automatically."," Ordinary startup and tool calls do not repeat setup reminders or trigger UAC."," Inspect/activate explicitly: `kodax sandbox doctor` / `kodax sandbox setup`."," Model-issued commands filter credential-shaped variables by default. Add exact names"," such as GH_TOKEN to user-level `sandbox.envPass` only when command access is intended."," The default list is empty; NODE_OPTIONS and BASH_ENV remain blocked."," Restart KodaX (and any persistent daemon) after changing the list or host variables."," SDK: `@kodax-ai/kodax/sandbox` exposes doctor, activation, capability metadata,"," and policy-controlled command execution independent of Auto[LLM].","","CLI basics:"," kodax Enter the interactive REPL",' kodax -p "task" Run one task and exit'," kodax -r Search and resume a saved session"," kodax -c Continue the most recent non-empty session","","Inside the REPL:"," /model [provider[/model]] List or switch provider/model"," /mode [plan|accept-edits|auto] Switch permission mode"," /effort [off|auto|low|medium|high|xhigh|max] Set reasoning depth"," /agent-mode [ama|sa|toggle] Switch AMA/SA execution"," /setup --help Show this guide","","Default shortcuts:",` ${at("toggleThinking")} Cycle reasoning effort`,` ${at("togglePermissionMode")} Cycle permission mode`,` ${at("toggleAgentMode")} Cycle AMA/SA`," Tab Accept completion"," Esc Cancel or clear input"].join(`
5
5
  `)}a(lt,"renderSetupGuide");import*as zi from"node:readline";import ct from"chalk";async function Xi(e={}){let o=e.catalog??ze(),n=Oi({...e.configPath?{configPath:e.configPath}:{},catalog:o});if(n.status==="invalid-config")throw new Ge(n.configPath,n.reason);if(o.length===0)throw new Error("No built-in API providers are available for setup.");let t=e.interaction===void 0,r=e.interaction??kl({input:e.input??process.stdin,output:e.output??process.stdout});try{let s=e.customOnly?"custom":await r.choose("Choose a provider. KodaX will save metadata only and will never ask for an API key.",[...o.map(u=>({value:`builtin:${u.name}`,label:`${u.name} \u2014 ${u.defaultModel} (set ${u.apiKeyEnv})`})),{value:"custom",label:"Custom OpenAI/Anthropic-compatible provider"},{value:"cancel",label:"Cancel"}]);if(!s||s==="cancel")return{status:"cancelled"};let l=s==="custom"?await yl(r):await hl(r,o,s.slice(8));if(!l)return{status:"cancelled"};let c=vl(l,o);return await r.confirm(`Save ${c}? config.json will store the environment-variable name only. You must set that variable to the provider's API key after setup. No credential value will be written.`)?{status:"configured",selection:Ni({configPath:n.configPath,expectedRevision:n.configRevision,catalog:o,choice:l})}:{status:"cancelled"}}finally{t&&r.close?.()}}a(Xi,"runProviderSetupWizard");async function hl(e,o,n){let t=o.find(l=>l.name===n);if(!t)throw new Error(`Unknown setup provider: ${n}`);let r=[...new Set(t.models)],s=await e.choose(`Choose a model for ${t.name}.`,r.map(l=>({value:l,label:l===t.defaultModel?`${l} (default)`:l})));return s?{kind:"builtin",provider:t.name,model:s}:void 0}a(hl,"collectBuiltinChoice");async function yl(e){let o=await rn(e,"Custom provider name (a unique local alias used by /model and config.json)");if(!o)return;let n=await e.choose("Protocol family (check the provider API documentation for OpenAI or Anthropic compatibility)",[{value:"openai",label:"OpenAI-compatible"},{value:"anthropic",label:"Anthropic-compatible"}]);if(n!=="openai"&&n!=="anthropic")return;let t=await rn(e,"API Base URL from the provider documentation, for example https://example.com/v1");if(!t)return;let r=await rn(e,["Environment-variable name only (for example MY_PROVIDER_API_KEY).","Do not paste an API key here.","config.json stores this name only.","After setup, set this environment variable's value to this provider's API key."].join(" "));if(!r)return;let s=await rn(e,"Model identifier from the provider documentation, for example provider/model-name");if(s)return{kind:"custom",provider:it({name:o,protocol:n,baseUrl:t,apiKeyEnv:r,model:s})}}a(yl,"collectCustomChoice");async function rn(e,o){let t=(await e.text(o))?.trim();return t||void 0}a(rn,"requiredText");function vl(e,o){if(e.kind==="custom"){let t=e.provider;return`provider=${t.name}, protocol=${t.protocol}, baseUrl=${t.baseUrl}, model=${t.model}, apiKeyEnv=${t.apiKeyEnv}`}let n=o.find(t=>t.name===e.provider);return`provider=${e.provider}, model=${e.model}, apiKeyEnv=${n?.apiKeyEnv??"<unknown>"}`}a(vl,"summarizeChoice");function kl(e){let o=zi.createInterface({input:e.input,output:e.output}),n=!1;o.on("close",()=>{n=!0}),o.on("SIGINT",()=>o.close());let t=a(r=>new Promise((s,l)=>{let c=!1,d=a(f=>{c||(c=!0,o.removeListener("close",u),s(f))},"finish"),u=a(()=>d(void 0),"onClose");if(n){d(void 0);return}o.once("close",u);try{o.question(r,f=>d(f))}catch(f){o.removeListener("close",u),n?d(void 0):l(f)}}),"question");return{async choose(r,s){for(e.output.write(`
@@ -676,4 +676,4 @@ Available Skills:
676
676
  [Skill "${t}" is not user-invocable]`)),!1;console.log(i.cyan(`
677
677
  [Invoking skill: ${t}]`)),s.argumentHint&&console.log(i.dim(`Arguments: ${r||"(none)"}`)),console.log();let l=await n.loadFull(t),c={workingDirectory:process.cwd(),projectRoot:o.gitRoot??void 0,sessionId:o.sessionId,environment:{},executeDynamicContext:o.skillDynamicContext?.execute,disableDynamicContext:o.skillDynamicContext?.disable},d=await jr(l,r,c);return console.log(i.green(`Skill activated: ${t}`)),console.log(i.dim("The skill context has been prepared for the AI.")),console.log(),{invocation:{prompt:d.content,source:"skill",displayName:t,path:l.skillFilePath,disableModelInvocation:d.disableModelInvocation,userInvocable:l.userInvocable,allowedTools:l.allowedTools,context:l.context,agent:l.agent,argumentHint:l.argumentHint,model:l.model,hooks:l.hooks,skillInvocation:{name:t,path:l.skillFilePath,description:l.description,arguments:r||void 0,allowedTools:l.allowedTools,context:l.context,agent:l.agent,argumentHint:l.argumentHint,model:l.model,hookEvents:l.hooks?Object.entries(l.hooks).filter(([,u])=>Array.isArray(u)&&u.length>0).map(([u])=>u):void 0,expandedContent:d.content}}}}catch(s){return console.log(i.red(`
678
678
  [Error invoking skill: ${s instanceof Error?s.message:String(s)}]`)),!1}}a(pr,"executeSkillCommand");var Nn=class{static{a(this,"SkillCompleter")}gitRoot;constructor(o){this.gitRoot=o}canComplete(o,n){return this.parseTrigger(o.slice(0,n))!==void 0}async getCompletions(o,n){let t=this.parseTrigger(o.slice(0,n));if(!t)return[];let r=t.partial.toLowerCase();return(await this.getSkills()).filter(l=>{let c=l.name.toLowerCase();return c.includes(r)||this.fuzzyIncludes(r,c)}).map(l=>({text:`${t.invocationPrefix}${l.name}`,display:l.name,description:this.truncateDescription(l.description),type:"skill"})).sort((l,c)=>{let d=l.display.toLowerCase().startsWith(r),u=c.display.toLowerCase().startsWith(r);return d&&!u?-1:!d&&u?1:l.display.length-c.display.length})}setGitRoot(o){this.gitRoot!==o&&(this.gitRoot=o)}parseTrigger(o){let n=o.match(/(^|\s)\/skill:([^\s]*)$/);if(n)return{partial:n[2]??"",invocationPrefix:"/skill:"};let t=o.match(/(^|\s)\/([^\s]*)$/);if(t)return{partial:t[2]??"",invocationPrefix:"/"}}async getSkills(){try{let o=Se(this.gitRoot);return o.size===0&&await je(this.gitRoot),o.listUserInvocable()}catch{return[]}}fuzzyIncludes(o,n){let t=0;for(let r=0;r<n.length&&t<o.length;r+=1)n[r]===o[t]&&(t+=1);return t===o.length}truncateDescription(o,n=50){return o.length<=n?o:o.slice(0,n-3)+"..."}};import{exec as Lf}from"node:child_process";import*as so from"node:path";import{promisify as Wf}from"node:util";var Da=Wf(Lf);function Of(e){let o=e.slice(3);if(!o)return;let n=o.indexOf(" -> ");return(n===-1?o:o.slice(n+4)).replace(/^"(.*)"$/,"$1").trim()||void 0}a(Of,"pathFromPorcelainLine");async function ja(e,o=10){try{let[{stdout:n},{stdout:t}]=await Promise.all([Da("git rev-parse --show-toplevel",{cwd:e,windowsHide:!0}),Da("git status --porcelain=v1 -uall",{cwd:e,windowsHide:!0})]),r=n.trim(),s=[],l=new Set;for(let c of t.split(`
679
- `)){if(!c.trim())continue;let d=Of(c);if(!d)continue;let u=so.resolve(r,d),f=so.relative(e,u).split(so.sep).join("/");if(!(!f||f.startsWith("..")||l.has(f))&&(l.add(f),s.push(f),s.length>=o))break}return s}catch{return[]}}a(ja,"getRecentWorkingSetFiles");function ao(e){let o=e.lastIndexOf("/");if(o===-1)return-1;for(;o>0&&!/\s/.test(e[o-1]??"");)if(o=e.lastIndexOf("/",o-1),o===-1)return-1;return o}a(ao,"findCommandSlashIndex");var hr=class{static{a(this,"FileCompleter")}cwdSource;cache=new Map;cacheTimeout=5e3;recentCache=new Map;recentFilesProvider;constructor(o,n=ja){this.cwdSource=o,this.recentFilesProvider=n}canComplete(o,n){let t=o.slice(0,n),r=t.lastIndexOf("@");return!(r===-1||r>0&&!/\s/.test(t[r-1]??"")||t.slice(r+1).includes(" "))}async getCompletions(o,n){let t=o.slice(0,n),r=t.lastIndexOf("@");if(r===-1)return[];let s=t.slice(r+1),l=[],c=this.resolveCwd(),d=s.lastIndexOf("/"),u=d===-1?c:jo.join(c,s.slice(0,d)),f=d===-1?s:s.slice(d+1);try{let k=(await this.readdir(u)).filter(b=>b.toLowerCase().startsWith(f.toLowerCase()));for(let b of k){let A=jo.join(u,b),R=await this.isDirectory(A),v=d===-1?b:s.slice(0,d+1)+b;l.push({text:"@"+v+(R?"/":""),display:b+(R?"/":""),description:R?"directory":"file",type:"file"})}}catch{}if(d===-1){let p=await this.getRecentFiles(c),k=new Set(l.map(R=>R.text)),b=f.toLowerCase(),A=[];for(let R of p){if(f&&!jo.basename(R).toLowerCase().startsWith(b))continue;let v="@"+R;k.has(v)||(k.add(v),A.push({text:v,display:R,description:"recent",type:"file"}))}l.unshift(...A)}return l}async getRecentFiles(o){let n=Date.now(),t=this.recentCache.get(o);if(t&&t.expiresAt>n)return t.files;let r=await this.recentFilesProvider(o);return this.recentCache.set(o,{files:r,expiresAt:Date.now()+this.cacheTimeout}),r}resolveCwd(){return typeof this.cwdSource=="function"?this.cwdSource():this.cwdSource??process.cwd()}async readdir(o){let n=Date.now(),t=this.cache.get(o);return t&&t.expiresAt>n?t.entries:(t&&this.cache.delete(o),new Promise(r=>{Dn.readdir(o,(s,l)=>{s?r([]):(this.cache.set(o,{entries:l,expiresAt:Date.now()+this.cacheTimeout}),r(l))})}))}async isDirectory(o){return new Promise(n=>{Dn.stat(o,(t,r)=>{n(!t&&r.isDirectory())})})}},yr=class{static{a(this,"CommandCompleter")}commands;constructor(){this.commands=new Map,this.loadCommands()}loadCommands(){for(let n of Do().getAll())n.userInvocable!==!1&&this.commands.set(n.name,{description:n.description,aliases:n.aliases??[]});let o=se();for(let n of o?.listCommands()??[])n.metadata?.userInvocable!==!1&&this.commands.set(n.name,{description:n.description,aliases:n.aliases??[]})}canComplete(o,n){let t=o.slice(0,n),r=ao(t);return r===-1?!1:!t.slice(r).includes(" ")}async getCompletions(o,n){let t=o.slice(0,n),r=ao(t);if(r===-1)return[];this.commands.clear(),this.loadCommands();let s=t.slice(r+1).toLowerCase(),l=[];for(let[c,d]of this.commands){this.fuzzyMatch(s,c)&&l.push({text:"/"+c,display:"/"+c,description:d.description,type:"command"});for(let u of d.aliases)u!==c&&this.fuzzyMatch(s,u)&&l.push({text:"/"+u,display:"/"+u,description:`Alias for /${c}: ${d.description}`,type:"command"})}return l}fuzzyMatch(o,n){if(!o)return!0;let t=o.toLowerCase(),r=n.toLowerCase(),s=0;for(let l=0;l<r.length&&s<t.length;l++)r[l]===t[s]&&s++;return s===t.length}};function _v(e){let o=new hr(e),n=new Nn,t=new yr;return async r=>{let s=r.includes("@"),l=r.includes("/");if(!s&&!l)return[[],r];let c=[];if(l){let u=await Nf(r,r.length);c.push(...u)}if(l&&n.canComplete(r,r.length)){let u=await n.getCompletions(r,r.length);c.push(...u)}if(l&&t.canComplete(r,r.length)){let u=await t.getCompletions(r,r.length);c.push(...u)}if(s&&o.canComplete(r,r.length)){let u=await o.getCompletions(r,r.length);c.push(...u)}return[c.map(u=>Df(r,u)),r]}}a(_v,"createCompleter");async function Nf(e,o){let{ArgumentCompleter:n}=await import("./argument-completer-SRCHPEMA.js"),t=new n;return t.canComplete(e,o)?t.getCompletions(e,o):[]}a(Nf,"getArgumentCompletions");function Df(e,o){if(o.type!=="argument")return o.text;let n=ao(e);if(n!==-1&&!/\s/.test(e.slice(n)))return`${e} ${o.text}`;let r=e.match(/\S+$/)?.[0]??"";return`${r?e.slice(0,e.length-r.length):e}${o.text}`}a(Df,"formatReadlineCompletion");import{existsSync as jn,readdirSync as Ka,readFileSync as Ba}from"node:fs";import{join as Un}from"node:path";var jf=[{name:"plan",description:"Read-only planning mode - blocks all modifications",type:"enum"},{name:"accept-edits",description:"File edits auto-approved, bash requires confirmation",type:"enum"},{name:"auto",description:"Use auto-mode classifier for tool permissions",type:"enum"}],lo=[{name:"none",description:"Disable reasoning when the model supports it",type:"enum"},{name:"auto",description:"Clear the explicit effort override",type:"enum"},{name:"low",description:"Use low reasoning effort",type:"enum"},{name:"medium",description:"Use medium reasoning effort",type:"enum"},{name:"high",description:"Use high reasoning effort",type:"enum"},{name:"xhigh",description:"Use extra-high reasoning effort",type:"enum"},{name:"max",description:"Use maximum reasoning effort",type:"enum"}];function Uf(e){if(e&&e.includes("/")){let o=e.indexOf("/"),n=e.slice(0,o),t=e.slice(o+1);if(Ne(n))try{return Be(n).filter(s=>!t||s.toLowerCase().includes(t.toLowerCase())).map(s=>({name:`${n}/${s}`,description:s,type:"enum"}))}catch{}return[]}return De().map(o=>({name:o,description:`Switch to ${o} provider`,type:"enum"}))}a(Uf,"getModelArgs");var vr=[{name:"workspace",description:"Inspect current workspace/runtime truth in more detail",type:"enum"},{name:"runtime",description:"Alias for workspace runtime inspection",type:"enum"},{name:"worktree",description:"Alias for workspace runtime inspection",type:"enum"}],kr=[{name:"all",description:"Delete ALL sessions",type:"enum"}],Ff=[{name:"status",description:"Show MCP server status",type:"enum"},{name:"refresh",description:"Refresh MCP server catalogs",type:"enum"}],Hf=[{name:"status",description:"Show child-task fallback order",type:"enum"},{name:"off",description:"Disable child-task fallback providers",type:"enum"}],Kf=[{name:"llm",description:"Use LLM classifier for auto mode",type:"enum"},{name:"rules",description:"Use rules-only auto mode",type:"enum"}],Ua=[{name:"ama",description:"Use AMA agent mode",type:"enum"},{name:"sa",description:"Use single-agent mode",type:"enum"},{name:"toggle",description:"Cycle to the next agent mode",type:"enum"}],Fa=[{name:"on",description:"Enable logging",type:"enum"},{name:"off",description:"Disable logging",type:"enum"}],Bf=[{name:"list",description:"Summarize accepted Memory",type:"enum"},{name:"remember",description:"Remember one explicit keyed claim now",type:"enum"},{name:"forget",description:"Forget one exact accepted Memory",type:"enum"},{name:"decisions",description:"List exceptional changes that need you",type:"enum"},{name:"show",description:"Show one accepted Memory or decision",type:"enum"},{name:"approve",description:"Approve one reviewed decision",type:"enum"},{name:"reject",description:"Reject one reviewed decision",type:"enum"},{name:"doctor",description:"Diagnose the Memory pipeline",type:"enum"},{name:"open",description:"Open Memory in an external editor",type:"enum"},{name:"help",description:"Show memory help",type:"enum"}],qf=[{name:"list",description:"List learned capabilities",type:"enum"},{name:"ready",description:"List capabilities ready for review/control",type:"enum"},{name:"pending",description:"Compatibility alias for ready capabilities",type:"enum"},{name:"show",description:"Inspect one exact learned capability",type:"enum"},{name:"review",description:"Start or restart bounded canary review",type:"enum"},{name:"trust",description:"Explicitly trust a reviewed revision",type:"enum"},{name:"reject",description:"Reject a learned capability",type:"enum"},{name:"disable",description:"Disable an active learned capability",type:"enum"},{name:"rollback",description:"Restore the previous good revision",type:"enum"},{name:"promote",description:"Promote an exact revision to the user Skill catalog",type:"enum"},{name:"help",description:"Show Learning Center help",type:"enum"}];function Gf(e){let[o=""]=e,n=o.toLowerCase(),t=e.length===1&&e[0]===""?0:e.length;return t<=1?qf:n==="help"&&t<=2?[{name:"promote",description:"Show dedicated promotion help",type:"enum"}]:n!=="promote"?[]:t<=2?[{name:"--help",description:"Show dedicated promotion help",type:"enum"}]:t<=3?[{name:"--scope",description:"Choose the formal user Skill scope",type:"enum"}]:e[2]?.toLowerCase()==="--scope"&&t<=4?[{name:"user",description:"Promote to the formal user Skill catalog",type:"enum"}]:[]}a(Gf,"getLearnArgs");var zf=[{name:"status",description:"Show current persistent goal",type:"enum"},{name:"pause",description:"Pause the active goal",type:"enum"},{name:"resume",description:"Resume a paused goal",type:"enum"},{name:"clear",description:"Clear the current goal",type:"enum"},{name:"help",description:"Show goal help",type:"enum"},{name:"--tokens",description:"Set an optional goal token budget",type:"enum"}],Xf=[{name:"show",description:"Show a captured paste by id",type:"enum"},{name:"list",description:"List captured pastes",type:"enum"}],Vf=[{name:"--lean",description:"Add a minimal-diff/YAGNI review pass",type:"enum"},{name:"--workflow",description:"Review through a dynamic workflow",type:"enum"},{name:"base",description:"Review changes against the detected base branch",type:"enum"},{name:"sha",description:"Review a specific commit",type:"enum"},{name:"help",description:"Show review help",type:"enum"}],Yf=[{name:"init",description:"Create AGENTS.md in the target project if absent",type:"enum"},{name:"lean",description:"Initialize or LLM-review AGENTS.md for Lean Mode guidance",type:"enum"},{name:"help",description:"Show agents help",type:"enum"}],Jf=[{name:"status",description:"Inspect the current repo-intelligence runtime state",type:"enum"},{name:"mode",description:"Switch repo-intelligence runtime mode",type:"enum"},{name:"trace",description:"Toggle repo-intelligence trace output",type:"enum"}],Zf=[{name:"auto",description:"Let KodaX pick the best repo-intelligence engine",type:"enum"},{name:"full",description:"Prefer the full repo-intelligence engine",type:"enum"},{name:"light",description:"Use the light repo-intelligence engine",type:"enum"},{name:"off",description:"Disable repo-intelligence injection",type:"enum"}],Qf=[{name:"on",description:"Enable repo-intelligence trace output",type:"enum"},{name:"off",description:"Disable repo-intelligence trace output",type:"enum"},{name:"toggle",description:"Toggle repo-intelligence trace output",type:"enum"}],em=[{name:"status",description:"Deprecated alias for /repo-intel status",type:"enum"}],om=[{name:"list",description:"List built-in and saved workflows",type:"enum"},{name:"create",description:"Generate and run a workflow from a request",type:"enum"},{name:"runs",description:"List active and recent workflow runs",type:"enum"},{name:"show",description:"Show latest run or a specific workflow run",type:"enum"},{name:"pause",description:"Pause future child launches for a run",type:"enum"},{name:"resume",description:"Resume a paused run",type:"enum"},{name:"stop",description:"Stop an active workflow run",type:"enum"},{name:"delete",description:"Delete one persisted workflow run or generated saved capsule",type:"enum"},{name:"prune",description:"Preview or delete old terminal workflow runs",type:"enum"},{name:"rerun",description:"Rerun a run id or saved workflow name",type:"enum"},{name:"save",description:"Save a generated run as a workflow capsule",type:"enum"},{name:"rename",description:"Rename a run display name or saved workflow capsule",type:"enum"},{name:"revise",description:"Generate a revised workflow capsule",type:"enum"},{name:"help",description:"Show workflow help",type:"enum"}],nm=new Set(["show","pause","resume","stop","delete","rerun","save","rename","revise"]),tm=new Set(["show","delete","rerun","save","rename","revise"]),rm=[{name:"--all",description:"Show all persisted workflow runs",type:"enum"},{name:"--limit",description:"Show at most N persisted workflow runs",type:"enum"}],im=[{name:"--dry-run",description:"Preview cleanup without deleting runs",type:"enum"},{name:"--keep",description:"Keep the newest N terminal runs",type:"enum"},{name:"--older-than",description:"Delete terminal runs older than Nd or Nh",type:"enum"}],sm=[{name:"--force",description:"Delete stale non-terminal run records",type:"enum"},{name:"--run",description:"Treat the target as a workflow run record",type:"enum"},{name:"--saved",description:"Treat the target as a generated saved workflow capsule",type:"enum"}],am=[".workflow.json",".ts",".mjs",".js"];function lm(e,o){switch(e){case"pause":return o==="running";case"resume":return o==="paused";case"stop":return o==="running"||o==="paused";case"delete":return o!=="running"&&o!=="paused";default:return!0}}a(lm,"workflowRunMatchesSubcommand");function Fn(e){return/^[a-zA-Z0-9._-]{1,120}$/.test(e)&&!e.startsWith(".")&&!e.includes("..")}a(Fn,"isWorkflowRunEntryName");function cm(e,o){let n=Un(e,"workflow-metadata.json");if(jn(n))try{let r=JSON.parse(Ba(n,"utf8"));if(typeof r=="object"&&r!==null){let s=r.displayName;if(typeof s=="string"&&Fn(s.trim()))return s.trim()}}catch{}let t=o.displayName;return typeof t=="string"&&Fn(t.trim())?t.trim():void 0}a(cm,"readWorkflowRunDisplayName");function dm(){let e=ye(process.cwd()).key,o=W("workflow-runs",e);if(!jn(o))return[];let n=[];for(let t of Ka(o)){if(!Fn(t))continue;let r=Un(o,t,"run.json");if(jn(r))try{let s=JSON.parse(Ba(r,"utf8")),l=typeof s.workflow=="string"?s.workflow:"?",c=typeof s.status=="string"?s.status:"?",d=typeof s.endedAt=="number"?s.endedAt:0;n.push({arg:{name:t,description:`${l} - ${c}`,type:"string"},endedAt:d});let u=cm(Un(o,t),s);u&&u!==t&&n.push({arg:{name:u,description:`${l} alias for ${t} - ${c}`,type:"string"},endedAt:d})}catch{}}return n.sort((t,r)=>r.endedAt-t.endedAt).map(t=>t.arg)}a(dm,"getPersistedWorkflowRunIdArgs");function Hn(e){let o=He().list().filter(r=>lm(e,r.status)).map(r=>({name:r.runId,description:`${r.workflow} - ${r.status}`,type:"string"})),n=tm.has(e)?dm():[],t=new Set;return[...o,...n].filter(r=>t.has(r.name)?!1:(t.add(r.name),!0))}a(Hn,"getWorkflowRunIdArgs");function um(e){for(let o of am)if(e.endsWith(o)){let n=e.slice(0,-o.length);return Fn(n)?n:void 0}}a(um,"savedWorkflowNameFromFile");function Uo(e={}){let o=[{path:W("workflows"),source:"personal"},{path:Un(process.cwd(),".kodax","workflows"),source:"project"}],n=new Map;for(let t of o)if(jn(t.path))try{for(let r of Ka(t.path)){if(e.generatedOnly===!0&&!r.endsWith(".workflow.json"))continue;let s=um(r);s&&n.set(s,{name:s,description:`${t.source} saved workflow`,type:"enum"})}}catch{}return[...n.values()].sort((t,r)=>t.name.localeCompare(r.name))}a(Uo,"getSavedWorkflowNameArgs");function fm(){let e=new Map;for(let o of Hn("rerun"))e.set(o.name,{...o,description:`recent run: ${o.description}`,type:"string"});for(let o of Uo()){let n=e.get(o.name);if(n){e.set(o.name,{...n,description:`${n.description}; also ${o.description}`});continue}e.set(o.name,{...o,description:o.description,type:"string"})}return[...e.values()]}a(fm,"getWorkflowRerunArgs");function br(e){let o=new Map;for(let n of Hn(e))o.set(n.name,{...n,description:`workflow run: ${n.description}`,type:"string"});for(let n of Uo({generatedOnly:e==="delete"})){let t=o.get(n.name);if(t){o.set(n.name,{...t,description:`${t.description}; also ${n.description}`});continue}o.set(n.name,{...n,description:n.description,type:"string"})}return[...o.values()]}a(br,"getWorkflowRunOrSavedNameArgs");function Ha(e){let o=new Set(e.slice(1).filter(n=>n.startsWith("--")));return o.has("--saved")?Uo({generatedOnly:!0}):o.has("--run")?Hn("delete"):br("delete")}a(Ha,"getWorkflowDeleteTargetArgs");function mm(e){let[o=""]=e,n=o.toLowerCase(),t=e.length===1&&e[0]===""?0:e.length;if(t<=1)return[...om,...Jo().map(r=>({name:r.name,description:r.description,type:"enum"})),...Uo()];if(n==="rerun"&&t<=2)return fm();if(n==="rename"&&t<=2)return br("rename");if(n==="delete"&&t<=2)return[...sm,...Ha(e)];if(n==="delete"&&t<=3&&e.slice(1).some(r=>r.startsWith("--")))return Ha(e);if(n==="revise"){if(t<=2)return[{name:"--replace",description:"Replace a saved workflow after confirmation",type:"enum"},...br("revise")];if(e[1]==="--replace"&&t<=3)return Uo()}return nm.has(n)&&t<=2?Hn(n):n==="runs"&&t<=2?rm:n==="prune"&&t<=2?im:[]}a(mm,"getWorkflowArgs");function pm(e){let[o=""]=e,n=o.toLowerCase(),t=e.length===1&&e[0]===""?0:e.length;return t<=1?Jf:t>2?[]:n==="mode"?Zf:n==="trace"?Qf:[]}a(pm,"getRepoIntelArgs");var gm=new Map([["mode",jf],["thinking",lo],["think",lo],["t",lo],["reasoning",lo],["reason",lo],["effort",lo],["status",vr],["info",vr],["ctx",vr],["mcp",Ff],["fallback",Hf],["auto-engine",Kf],["agent-mode",Ua],["am",Ua],["verifier-log",Fa],["stall-log",Fa],["memory",Bf],["goal",zf],["paste",Xf],["review",Vf],["agents",Yf],["delete",kr],["rm",kr],["del",kr]]),wm=new Set(["model","m","provider"]),hm=new Set(["repo-intel"]),ym=new Set(["repointel","ri"]),vm=new Set(["workflow"]),km=new Set(["learn"]);function $r(e,o,n=[]){let t=e.toLowerCase();return wm.has(t)?Uf(o):hm.has(t)?pm(n):ym.has(t)?n.length<=1?em:[]:vm.has(t)?mm(n):km.has(t)?Gf(n):gm.get(t)??[]}a($r,"getCommandArguments");var Sr=class{static{a(this,"ArgumentCompleter")}canComplete(o,n){let t=o.slice(0,n),r=ao(t);if(r===-1)return!1;let s=t.slice(r),l=s.split(/\s+/);if(l.length>=2&&l[0]!=="")return!0;let c=s.slice(1).toLowerCase();return $r(c).length>0}async getCompletions(o,n){let t=o.slice(0,n),r=ao(t);if(r===-1)return[];let s=t.slice(r),l=s.indexOf(" "),c=(l===-1?s.slice(1):s.slice(1,l)).toLowerCase(),d=l===-1?"":s.slice(l+1),u=d?d.split(/\s+/):[""],f=u.length-1,p=u[f]??"",k=p.toLowerCase(),b=$r(c,p,u);if(!b||b.length===0)return[];let A=new Set(u.slice(0,-1).map(v=>v.toLowerCase()));return b.filter(v=>!A.has(v.name.toLowerCase())).filter(v=>!k||v.name.includes("/")?!0:v.name.toLowerCase().includes(k)).map(v=>({text:v.name,display:v.name,description:v.description,type:"argument"})).sort((v,$)=>{if(!k)return 0;let I=v.display.toLowerCase().startsWith(k),M=$.display.toLowerCase().startsWith(k);return I&&!M?-1:!I&&M?1:v.display.length-$.display.length})}};function Gv(){return new Sr}a(Gv,"createArgumentCompleter");export{yt as a,B as b,mg as c,ms as d,pg as e,nn as f,Xa as g,Am as h,Va as i,Rm as j,tn as k,Ei as l,ko as m,$o as n,Ge as o,ze as p,Oi as q,Ni as r,Di as s,qi as t,Gi as u,lt as v,Xi as w,Il as x,Ml as y,Lp as z,Vp as A,_l as B,pt as C,Yp as D,Jp as E,as as F,rg as G,ig as H,fs as I,ae as J,ws as K,hs as L,kg as M,Yl as N,dc as O,bg as P,dn as Q,kt as R,$g as S,Cs as T,Sg as U,xg as V,Ag as W,Zg as X,Qg as Y,ew as Z,ow as _,Hs as $,Ct as aa,Ks as ba,ye as ca,wd as da,aw as ea,Eo as fa,_t as ga,Te as ha,Gd as ia,zd as ja,la as ka,_w as la,Lw as ma,su as na,Ph as oa,Th as pa,Mh as qa,Jh as ra,Zh as sa,Qh as ta,ey as ua,oy as va,ba as wa,ay as xa,ly as ya,Sa as za,cy as Aa,Ey as Ba,xa as Ca,Do as Da,yv as Ea,vv as Fa,Nn as Ga,Sr as Ha,Gv as Ia,ao as Ja,hr as Ka,yr as La,_v as Ma};
679
+ `)){if(!c.trim())continue;let d=Of(c);if(!d)continue;let u=so.resolve(r,d),f=so.relative(e,u).split(so.sep).join("/");if(!(!f||f.startsWith("..")||l.has(f))&&(l.add(f),s.push(f),s.length>=o))break}return s}catch{return[]}}a(ja,"getRecentWorkingSetFiles");function ao(e){let o=e.lastIndexOf("/");if(o===-1)return-1;for(;o>0&&!/\s/.test(e[o-1]??"");)if(o=e.lastIndexOf("/",o-1),o===-1)return-1;return o}a(ao,"findCommandSlashIndex");var hr=class{static{a(this,"FileCompleter")}cwdSource;cache=new Map;cacheTimeout=5e3;recentCache=new Map;recentFilesProvider;constructor(o,n=ja){this.cwdSource=o,this.recentFilesProvider=n}canComplete(o,n){let t=o.slice(0,n),r=t.lastIndexOf("@");return!(r===-1||r>0&&!/\s/.test(t[r-1]??"")||t.slice(r+1).includes(" "))}async getCompletions(o,n){let t=o.slice(0,n),r=t.lastIndexOf("@");if(r===-1)return[];let s=t.slice(r+1),l=[],c=this.resolveCwd(),d=s.lastIndexOf("/"),u=d===-1?c:jo.join(c,s.slice(0,d)),f=d===-1?s:s.slice(d+1);try{let k=(await this.readdir(u)).filter(b=>b.toLowerCase().startsWith(f.toLowerCase()));for(let b of k){let A=jo.join(u,b),R=await this.isDirectory(A),v=d===-1?b:s.slice(0,d+1)+b;l.push({text:"@"+v+(R?"/":""),display:b+(R?"/":""),description:R?"directory":"file",type:"file"})}}catch{}if(d===-1){let p=await this.getRecentFiles(c),k=new Set(l.map(R=>R.text)),b=f.toLowerCase(),A=[];for(let R of p){if(f&&!jo.basename(R).toLowerCase().startsWith(b))continue;let v="@"+R;k.has(v)||(k.add(v),A.push({text:v,display:R,description:"recent",type:"file"}))}l.unshift(...A)}return l}async getRecentFiles(o){let n=Date.now(),t=this.recentCache.get(o);if(t&&t.expiresAt>n)return t.files;let r=await this.recentFilesProvider(o);return this.recentCache.set(o,{files:r,expiresAt:Date.now()+this.cacheTimeout}),r}resolveCwd(){return typeof this.cwdSource=="function"?this.cwdSource():this.cwdSource??process.cwd()}async readdir(o){let n=Date.now(),t=this.cache.get(o);return t&&t.expiresAt>n?t.entries:(t&&this.cache.delete(o),new Promise(r=>{Dn.readdir(o,(s,l)=>{s?r([]):(this.cache.set(o,{entries:l,expiresAt:Date.now()+this.cacheTimeout}),r(l))})}))}async isDirectory(o){return new Promise(n=>{Dn.stat(o,(t,r)=>{n(!t&&r.isDirectory())})})}},yr=class{static{a(this,"CommandCompleter")}commands;constructor(){this.commands=new Map,this.loadCommands()}loadCommands(){for(let n of Do().getAll())n.userInvocable!==!1&&this.commands.set(n.name,{description:n.description,aliases:n.aliases??[]});let o=se();for(let n of o?.listCommands()??[])n.metadata?.userInvocable!==!1&&this.commands.set(n.name,{description:n.description,aliases:n.aliases??[]})}canComplete(o,n){let t=o.slice(0,n),r=ao(t);return r===-1?!1:!t.slice(r).includes(" ")}async getCompletions(o,n){let t=o.slice(0,n),r=ao(t);if(r===-1)return[];this.commands.clear(),this.loadCommands();let s=t.slice(r+1).toLowerCase(),l=[];for(let[c,d]of this.commands){this.fuzzyMatch(s,c)&&l.push({text:"/"+c,display:"/"+c,description:d.description,type:"command"});for(let u of d.aliases)u!==c&&this.fuzzyMatch(s,u)&&l.push({text:"/"+u,display:"/"+u,description:`Alias for /${c}: ${d.description}`,type:"command"})}return l}fuzzyMatch(o,n){if(!o)return!0;let t=o.toLowerCase(),r=n.toLowerCase(),s=0;for(let l=0;l<r.length&&s<t.length;l++)r[l]===t[s]&&s++;return s===t.length}};function _v(e){let o=new hr(e),n=new Nn,t=new yr;return async r=>{let s=r.includes("@"),l=r.includes("/");if(!s&&!l)return[[],r];let c=[];if(l){let u=await Nf(r,r.length);c.push(...u)}if(l&&n.canComplete(r,r.length)){let u=await n.getCompletions(r,r.length);c.push(...u)}if(l&&t.canComplete(r,r.length)){let u=await t.getCompletions(r,r.length);c.push(...u)}if(s&&o.canComplete(r,r.length)){let u=await o.getCompletions(r,r.length);c.push(...u)}return[c.map(u=>Df(r,u)),r]}}a(_v,"createCompleter");async function Nf(e,o){let{ArgumentCompleter:n}=await import("./argument-completer-6ZTRBNZM.js"),t=new n;return t.canComplete(e,o)?t.getCompletions(e,o):[]}a(Nf,"getArgumentCompletions");function Df(e,o){if(o.type!=="argument")return o.text;let n=ao(e);if(n!==-1&&!/\s/.test(e.slice(n)))return`${e} ${o.text}`;let r=e.match(/\S+$/)?.[0]??"";return`${r?e.slice(0,e.length-r.length):e}${o.text}`}a(Df,"formatReadlineCompletion");import{existsSync as jn,readdirSync as Ka,readFileSync as Ba}from"node:fs";import{join as Un}from"node:path";var jf=[{name:"plan",description:"Read-only planning mode - blocks all modifications",type:"enum"},{name:"accept-edits",description:"File edits auto-approved, bash requires confirmation",type:"enum"},{name:"auto",description:"Use auto-mode classifier for tool permissions",type:"enum"}],lo=[{name:"none",description:"Disable reasoning when the model supports it",type:"enum"},{name:"auto",description:"Clear the explicit effort override",type:"enum"},{name:"low",description:"Use low reasoning effort",type:"enum"},{name:"medium",description:"Use medium reasoning effort",type:"enum"},{name:"high",description:"Use high reasoning effort",type:"enum"},{name:"xhigh",description:"Use extra-high reasoning effort",type:"enum"},{name:"max",description:"Use maximum reasoning effort",type:"enum"}];function Uf(e){if(e&&e.includes("/")){let o=e.indexOf("/"),n=e.slice(0,o),t=e.slice(o+1);if(Ne(n))try{return Be(n).filter(s=>!t||s.toLowerCase().includes(t.toLowerCase())).map(s=>({name:`${n}/${s}`,description:s,type:"enum"}))}catch{}return[]}return De().map(o=>({name:o,description:`Switch to ${o} provider`,type:"enum"}))}a(Uf,"getModelArgs");var vr=[{name:"workspace",description:"Inspect current workspace/runtime truth in more detail",type:"enum"},{name:"runtime",description:"Alias for workspace runtime inspection",type:"enum"},{name:"worktree",description:"Alias for workspace runtime inspection",type:"enum"}],kr=[{name:"all",description:"Delete ALL sessions",type:"enum"}],Ff=[{name:"status",description:"Show MCP server status",type:"enum"},{name:"refresh",description:"Refresh MCP server catalogs",type:"enum"}],Hf=[{name:"status",description:"Show child-task fallback order",type:"enum"},{name:"off",description:"Disable child-task fallback providers",type:"enum"}],Kf=[{name:"llm",description:"Use LLM classifier for auto mode",type:"enum"},{name:"rules",description:"Use rules-only auto mode",type:"enum"}],Ua=[{name:"ama",description:"Use AMA agent mode",type:"enum"},{name:"sa",description:"Use single-agent mode",type:"enum"},{name:"toggle",description:"Cycle to the next agent mode",type:"enum"}],Fa=[{name:"on",description:"Enable logging",type:"enum"},{name:"off",description:"Disable logging",type:"enum"}],Bf=[{name:"list",description:"Summarize accepted Memory",type:"enum"},{name:"remember",description:"Remember one explicit keyed claim now",type:"enum"},{name:"forget",description:"Forget one exact accepted Memory",type:"enum"},{name:"decisions",description:"List exceptional changes that need you",type:"enum"},{name:"show",description:"Show one accepted Memory or decision",type:"enum"},{name:"approve",description:"Approve one reviewed decision",type:"enum"},{name:"reject",description:"Reject one reviewed decision",type:"enum"},{name:"doctor",description:"Diagnose the Memory pipeline",type:"enum"},{name:"open",description:"Open Memory in an external editor",type:"enum"},{name:"help",description:"Show memory help",type:"enum"}],qf=[{name:"list",description:"List learned capabilities",type:"enum"},{name:"ready",description:"List capabilities ready for review/control",type:"enum"},{name:"pending",description:"Compatibility alias for ready capabilities",type:"enum"},{name:"show",description:"Inspect one exact learned capability",type:"enum"},{name:"review",description:"Start or restart bounded canary review",type:"enum"},{name:"trust",description:"Explicitly trust a reviewed revision",type:"enum"},{name:"reject",description:"Reject a learned capability",type:"enum"},{name:"disable",description:"Disable an active learned capability",type:"enum"},{name:"rollback",description:"Restore the previous good revision",type:"enum"},{name:"promote",description:"Promote an exact revision to the user Skill catalog",type:"enum"},{name:"help",description:"Show Learning Center help",type:"enum"}];function Gf(e){let[o=""]=e,n=o.toLowerCase(),t=e.length===1&&e[0]===""?0:e.length;return t<=1?qf:n==="help"&&t<=2?[{name:"promote",description:"Show dedicated promotion help",type:"enum"}]:n!=="promote"?[]:t<=2?[{name:"--help",description:"Show dedicated promotion help",type:"enum"}]:t<=3?[{name:"--scope",description:"Choose the formal user Skill scope",type:"enum"}]:e[2]?.toLowerCase()==="--scope"&&t<=4?[{name:"user",description:"Promote to the formal user Skill catalog",type:"enum"}]:[]}a(Gf,"getLearnArgs");var zf=[{name:"status",description:"Show current persistent goal",type:"enum"},{name:"pause",description:"Pause the active goal",type:"enum"},{name:"resume",description:"Resume a paused goal",type:"enum"},{name:"clear",description:"Clear the current goal",type:"enum"},{name:"help",description:"Show goal help",type:"enum"},{name:"--tokens",description:"Set an optional goal token budget",type:"enum"}],Xf=[{name:"show",description:"Show a captured paste by id",type:"enum"},{name:"list",description:"List captured pastes",type:"enum"}],Vf=[{name:"--lean",description:"Add a minimal-diff/YAGNI review pass",type:"enum"},{name:"--workflow",description:"Review through a dynamic workflow",type:"enum"},{name:"base",description:"Review changes against the detected base branch",type:"enum"},{name:"sha",description:"Review a specific commit",type:"enum"},{name:"help",description:"Show review help",type:"enum"}],Yf=[{name:"init",description:"Create AGENTS.md in the target project if absent",type:"enum"},{name:"lean",description:"Initialize or LLM-review AGENTS.md for Lean Mode guidance",type:"enum"},{name:"help",description:"Show agents help",type:"enum"}],Jf=[{name:"status",description:"Inspect the current repo-intelligence runtime state",type:"enum"},{name:"mode",description:"Switch repo-intelligence runtime mode",type:"enum"},{name:"trace",description:"Toggle repo-intelligence trace output",type:"enum"}],Zf=[{name:"auto",description:"Let KodaX pick the best repo-intelligence engine",type:"enum"},{name:"full",description:"Prefer the full repo-intelligence engine",type:"enum"},{name:"light",description:"Use the light repo-intelligence engine",type:"enum"},{name:"off",description:"Disable repo-intelligence injection",type:"enum"}],Qf=[{name:"on",description:"Enable repo-intelligence trace output",type:"enum"},{name:"off",description:"Disable repo-intelligence trace output",type:"enum"},{name:"toggle",description:"Toggle repo-intelligence trace output",type:"enum"}],em=[{name:"status",description:"Deprecated alias for /repo-intel status",type:"enum"}],om=[{name:"list",description:"List built-in and saved workflows",type:"enum"},{name:"create",description:"Generate and run a workflow from a request",type:"enum"},{name:"runs",description:"List active and recent workflow runs",type:"enum"},{name:"show",description:"Show latest run or a specific workflow run",type:"enum"},{name:"pause",description:"Pause future child launches for a run",type:"enum"},{name:"resume",description:"Resume a paused run",type:"enum"},{name:"stop",description:"Stop an active workflow run",type:"enum"},{name:"delete",description:"Delete one persisted workflow run or generated saved capsule",type:"enum"},{name:"prune",description:"Preview or delete old terminal workflow runs",type:"enum"},{name:"rerun",description:"Rerun a run id or saved workflow name",type:"enum"},{name:"save",description:"Save a generated run as a workflow capsule",type:"enum"},{name:"rename",description:"Rename a run display name or saved workflow capsule",type:"enum"},{name:"revise",description:"Generate a revised workflow capsule",type:"enum"},{name:"help",description:"Show workflow help",type:"enum"}],nm=new Set(["show","pause","resume","stop","delete","rerun","save","rename","revise"]),tm=new Set(["show","delete","rerun","save","rename","revise"]),rm=[{name:"--all",description:"Show all persisted workflow runs",type:"enum"},{name:"--limit",description:"Show at most N persisted workflow runs",type:"enum"}],im=[{name:"--dry-run",description:"Preview cleanup without deleting runs",type:"enum"},{name:"--keep",description:"Keep the newest N terminal runs",type:"enum"},{name:"--older-than",description:"Delete terminal runs older than Nd or Nh",type:"enum"}],sm=[{name:"--force",description:"Delete stale non-terminal run records",type:"enum"},{name:"--run",description:"Treat the target as a workflow run record",type:"enum"},{name:"--saved",description:"Treat the target as a generated saved workflow capsule",type:"enum"}],am=[".workflow.json",".ts",".mjs",".js"];function lm(e,o){switch(e){case"pause":return o==="running";case"resume":return o==="paused";case"stop":return o==="running"||o==="paused";case"delete":return o!=="running"&&o!=="paused";default:return!0}}a(lm,"workflowRunMatchesSubcommand");function Fn(e){return/^[a-zA-Z0-9._-]{1,120}$/.test(e)&&!e.startsWith(".")&&!e.includes("..")}a(Fn,"isWorkflowRunEntryName");function cm(e,o){let n=Un(e,"workflow-metadata.json");if(jn(n))try{let r=JSON.parse(Ba(n,"utf8"));if(typeof r=="object"&&r!==null){let s=r.displayName;if(typeof s=="string"&&Fn(s.trim()))return s.trim()}}catch{}let t=o.displayName;return typeof t=="string"&&Fn(t.trim())?t.trim():void 0}a(cm,"readWorkflowRunDisplayName");function dm(){let e=ye(process.cwd()).key,o=W("workflow-runs",e);if(!jn(o))return[];let n=[];for(let t of Ka(o)){if(!Fn(t))continue;let r=Un(o,t,"run.json");if(jn(r))try{let s=JSON.parse(Ba(r,"utf8")),l=typeof s.workflow=="string"?s.workflow:"?",c=typeof s.status=="string"?s.status:"?",d=typeof s.endedAt=="number"?s.endedAt:0;n.push({arg:{name:t,description:`${l} - ${c}`,type:"string"},endedAt:d});let u=cm(Un(o,t),s);u&&u!==t&&n.push({arg:{name:u,description:`${l} alias for ${t} - ${c}`,type:"string"},endedAt:d})}catch{}}return n.sort((t,r)=>r.endedAt-t.endedAt).map(t=>t.arg)}a(dm,"getPersistedWorkflowRunIdArgs");function Hn(e){let o=He().list().filter(r=>lm(e,r.status)).map(r=>({name:r.runId,description:`${r.workflow} - ${r.status}`,type:"string"})),n=tm.has(e)?dm():[],t=new Set;return[...o,...n].filter(r=>t.has(r.name)?!1:(t.add(r.name),!0))}a(Hn,"getWorkflowRunIdArgs");function um(e){for(let o of am)if(e.endsWith(o)){let n=e.slice(0,-o.length);return Fn(n)?n:void 0}}a(um,"savedWorkflowNameFromFile");function Uo(e={}){let o=[{path:W("workflows"),source:"personal"},{path:Un(process.cwd(),".kodax","workflows"),source:"project"}],n=new Map;for(let t of o)if(jn(t.path))try{for(let r of Ka(t.path)){if(e.generatedOnly===!0&&!r.endsWith(".workflow.json"))continue;let s=um(r);s&&n.set(s,{name:s,description:`${t.source} saved workflow`,type:"enum"})}}catch{}return[...n.values()].sort((t,r)=>t.name.localeCompare(r.name))}a(Uo,"getSavedWorkflowNameArgs");function fm(){let e=new Map;for(let o of Hn("rerun"))e.set(o.name,{...o,description:`recent run: ${o.description}`,type:"string"});for(let o of Uo()){let n=e.get(o.name);if(n){e.set(o.name,{...n,description:`${n.description}; also ${o.description}`});continue}e.set(o.name,{...o,description:o.description,type:"string"})}return[...e.values()]}a(fm,"getWorkflowRerunArgs");function br(e){let o=new Map;for(let n of Hn(e))o.set(n.name,{...n,description:`workflow run: ${n.description}`,type:"string"});for(let n of Uo({generatedOnly:e==="delete"})){let t=o.get(n.name);if(t){o.set(n.name,{...t,description:`${t.description}; also ${n.description}`});continue}o.set(n.name,{...n,description:n.description,type:"string"})}return[...o.values()]}a(br,"getWorkflowRunOrSavedNameArgs");function Ha(e){let o=new Set(e.slice(1).filter(n=>n.startsWith("--")));return o.has("--saved")?Uo({generatedOnly:!0}):o.has("--run")?Hn("delete"):br("delete")}a(Ha,"getWorkflowDeleteTargetArgs");function mm(e){let[o=""]=e,n=o.toLowerCase(),t=e.length===1&&e[0]===""?0:e.length;if(t<=1)return[...om,...Jo().map(r=>({name:r.name,description:r.description,type:"enum"})),...Uo()];if(n==="rerun"&&t<=2)return fm();if(n==="rename"&&t<=2)return br("rename");if(n==="delete"&&t<=2)return[...sm,...Ha(e)];if(n==="delete"&&t<=3&&e.slice(1).some(r=>r.startsWith("--")))return Ha(e);if(n==="revise"){if(t<=2)return[{name:"--replace",description:"Replace a saved workflow after confirmation",type:"enum"},...br("revise")];if(e[1]==="--replace"&&t<=3)return Uo()}return nm.has(n)&&t<=2?Hn(n):n==="runs"&&t<=2?rm:n==="prune"&&t<=2?im:[]}a(mm,"getWorkflowArgs");function pm(e){let[o=""]=e,n=o.toLowerCase(),t=e.length===1&&e[0]===""?0:e.length;return t<=1?Jf:t>2?[]:n==="mode"?Zf:n==="trace"?Qf:[]}a(pm,"getRepoIntelArgs");var gm=new Map([["mode",jf],["thinking",lo],["think",lo],["t",lo],["reasoning",lo],["reason",lo],["effort",lo],["status",vr],["info",vr],["ctx",vr],["mcp",Ff],["fallback",Hf],["auto-engine",Kf],["agent-mode",Ua],["am",Ua],["verifier-log",Fa],["stall-log",Fa],["memory",Bf],["goal",zf],["paste",Xf],["review",Vf],["agents",Yf],["delete",kr],["rm",kr],["del",kr]]),wm=new Set(["model","m","provider"]),hm=new Set(["repo-intel"]),ym=new Set(["repointel","ri"]),vm=new Set(["workflow"]),km=new Set(["learn"]);function $r(e,o,n=[]){let t=e.toLowerCase();return wm.has(t)?Uf(o):hm.has(t)?pm(n):ym.has(t)?n.length<=1?em:[]:vm.has(t)?mm(n):km.has(t)?Gf(n):gm.get(t)??[]}a($r,"getCommandArguments");var Sr=class{static{a(this,"ArgumentCompleter")}canComplete(o,n){let t=o.slice(0,n),r=ao(t);if(r===-1)return!1;let s=t.slice(r),l=s.split(/\s+/);if(l.length>=2&&l[0]!=="")return!0;let c=s.slice(1).toLowerCase();return $r(c).length>0}async getCompletions(o,n){let t=o.slice(0,n),r=ao(t);if(r===-1)return[];let s=t.slice(r),l=s.indexOf(" "),c=(l===-1?s.slice(1):s.slice(1,l)).toLowerCase(),d=l===-1?"":s.slice(l+1),u=d?d.split(/\s+/):[""],f=u.length-1,p=u[f]??"",k=p.toLowerCase(),b=$r(c,p,u);if(!b||b.length===0)return[];let A=new Set(u.slice(0,-1).map(v=>v.toLowerCase()));return b.filter(v=>!A.has(v.name.toLowerCase())).filter(v=>!k||v.name.includes("/")?!0:v.name.toLowerCase().includes(k)).map(v=>({text:v.name,display:v.name,description:v.description,type:"argument"})).sort((v,$)=>{if(!k)return 0;let I=v.display.toLowerCase().startsWith(k),M=$.display.toLowerCase().startsWith(k);return I&&!M?-1:!I&&M?1:v.display.length-$.display.length})}};function Gv(){return new Sr}a(Gv,"createArgumentCompleter");export{yt as a,B as b,mg as c,ms as d,pg as e,nn as f,Xa as g,Am as h,Va as i,Rm as j,tn as k,Ei as l,ko as m,$o as n,Ge as o,ze as p,Oi as q,Ni as r,Di as s,qi as t,Gi as u,lt as v,Xi as w,Il as x,Ml as y,Lp as z,Vp as A,_l as B,pt as C,Yp as D,Jp as E,as as F,rg as G,ig as H,fs as I,ae as J,ws as K,hs as L,kg as M,Yl as N,dc as O,bg as P,dn as Q,kt as R,$g as S,Cs as T,Sg as U,xg as V,Ag as W,Zg as X,Qg as Y,ew as Z,ow as _,Hs as $,Ct as aa,Ks as ba,ye as ca,wd as da,aw as ea,Eo as fa,_t as ga,Te as ha,Gd as ia,zd as ja,la as ka,_w as la,Lw as ma,su as na,Ph as oa,Th as pa,Mh as qa,Jh as ra,Zh as sa,Qh as ta,ey as ua,oy as va,ba as wa,ay as xa,ly as ya,Sa as za,cy as Aa,Ey as Ba,xa as Ca,Do as Da,yv as Ea,vv as Fa,Nn as Ga,Sr as Ha,Gv as Ia,ao as Ja,hr as Ka,yr as La,_v as Ma};
@@ -2,7 +2,7 @@
2
2
  import{a as n}from"./chunk-ONUPGMER.js";var M={user:0,background:1};function xt(e,t){return M[e]<=M[t]}n(xt,"priorityWithinMax");function me(e,t){return!(e.agentId!==t.agentId||!xt(e.priority,t.maxPriority)||t.mode!==void 0&&e.mode!==t.mode||t.id!==void 0&&e.id!==t.id||t.predicate&&!t.predicate(e))}n(me,"matchesFilter");var U=class{static{n(this,"MessageQueue")}messages=[];nextSeq=1;listeners=new Set;snapshotRef=Object.freeze([]);notify(t){this.snapshotRef=Object.freeze([...this.messages]);for(let o of this.listeners)try{o(t)}catch{}}subscribe=n(t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}),"subscribe");getSnapshot=n(()=>this.snapshotRef,"getSnapshot");enqueue(t){let o=`msg-${this.nextSeq++}`,r={id:o,priority:t.priority,mode:t.mode,content:t.content,agentId:t.agentId,inputArtifacts:t.inputArtifacts,taskResult:t.taskResult,enqueuedAt:Date.now()};return this.messages=[...this.messages,r],this.notify({kind:"enqueued",message:r}),o}dequeue(t){let o=[];for(let d=0;d<this.messages.length;d++){let l=this.messages[d];l&&me(l,t)&&o.push({originalIndex:d,message:l})}o.sort((d,l)=>{let y=M[d.message.priority]-M[l.message.priority];return y!==0?y:d.originalIndex-l.originalIndex});let r=t.limit,i=typeof r=="number"&&o.length>r?o.slice(0,r):o;if(i.length===0)return[];let s=new Set(i.map(d=>d.originalIndex));this.messages=this.messages.filter((d,l)=>!s.has(l));let a=i.map(d=>d.message);return this.notify({kind:"dequeued",messages:a}),a}peek(t){let o=[];for(let s=0;s<this.messages.length;s++){let a=this.messages[s];a&&me(a,t)&&o.push({originalIndex:s,message:a})}o.sort((s,a)=>{let d=M[s.message.priority]-M[a.message.priority];return d!==0?d:s.originalIndex-a.originalIndex});let r=t.limit;return(typeof r=="number"&&o.length>r?o.slice(0,r):o).map(s=>s.message)}size(){return this.messages.length}count(t){return this.peek(t).length}has(t){return this.count(t)>0}clear(){if(this.messages.length===0)return;let t=this.messages;this.messages=[],this.notify({kind:"cleared",messages:t})}},j;function I(){return j||(j=new U),j}n(I,"getMessageQueue");function wt(){j=void 0}n(wt,"_resetMessageQueueForTests");function J(e,t){return e?`actor:${e}:${t}`:t==="/root"?void 0:t}n(J,"actorQueueId");var k=new Map;function Mt(e){k.set(e,(k.get(e)??0)+1);let t=!1;return()=>{if(t)return;t=!0;let o=k.get(e);o===void 0||o<=1?k.delete(e):k.set(e,o-1)}}n(Mt,"registerActiveRootQueueRoute");function Y(){if(k.size!==0){if(k.size===1)return k.keys().next().value;throw new Error("Cannot infer queued follow-up target: multiple Actor root sessions are active. Pass sessionId or agentId explicitly.")}}n(Y,"resolveActiveRootQueueRoute");function St(){k.clear()}n(St,"_resetActiveRootQueueRoutesForTests");var he=new Set(["wait_agent"]);function ye(e){return e.some(o=>he.has(o))?"background":"user"}n(ye,"midTurnDrainPriority");function _t(e){let t=ye(e.lastTurnToolNames);return I().dequeue({agentId:e.agentId,maxPriority:t,limit:e.limit})}n(_t,"maybeDrainMidTurn");var m=class extends Error{static{n(this,"KodaXMediaError")}code;detail;cause;constructor(t,o,r={}){super(o),this.name="KodaXMediaError",this.code=t,this.detail=r.detail,this.cause=r.cause}},x=class extends m{static{n(this,"ImageResizeError")}constructor(t,o={}){super(o.code??"IMAGE_TOO_LARGE",t,o),this.name="ImageResizeError"}};import be from"node:path";var At={".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".webp":"image/webp"},Kt={".3gp":"video/3gpp",".3gpp":"video/3gpp",".avi":"video/x-msvideo",".flv":"video/x-flv",".mov":"video/quicktime",".mp4":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".webm":"video/webm",".wmv":"video/x-ms-wmv"};function ve(e){return At[be.extname(e).toLowerCase()]}n(ve,"inferImageMediaType");function ke(e){return Kt[be.extname(e).toLowerCase()]}n(ke,"inferVideoMediaType");function Xt(e,t={}){let o=t.mediaType??ve(e);return{kind:"image",path:e,...o?{mediaType:o}:{},...t.source?{source:t.source}:{},...t.description?{description:t.description}:{}}}n(Xt,"createImageArtifactFromPath");function It(e,t={}){if(t.mediaType!==void 0&&t.mimeType!==void 0&&t.mediaType!==t.mimeType)throw new m("UNSUPPORTED_MEDIA_TYPE",`File artifact mediaType and mimeType disagree: ${t.mediaType} != ${t.mimeType}.`);return{kind:"file",path:e,...t.mediaType?{mediaType:t.mediaType}:{},...t.mimeType?{mimeType:t.mimeType}:{},...t.name?{name:t.name}:{},...t.source?{source:t.source}:{},...t.description?{description:t.description}:{}}}n(It,"createFileArtifactFromPath");function Ot(e,t={}){let o=t.mediaType??ke(e);if(!o)throw new m("UNSUPPORTED_MEDIA_TYPE",`Cannot infer video media type from path: ${e}.`);return{kind:"video",path:e,mediaType:o,...t.name?{name:t.name}:{},...t.source?{source:t.source}:{},...t.description?{description:t.description}:{}}}n(Ot,"createVideoArtifactFromPath");var Ce=2e3,Pe=Math.floor(3.75*1024*1024),Dt=[80,60,40];async function Q(e,t={}){let o=t.maxDimension??Ce,r=t.targetBytes??Pe;if(e.length===0)throw new x("Empty image buffer.",{code:"IMAGE_DECODE_FAILED"});let i;try{let{Jimp:u}=await import("jimp");i=await u.read(e)}catch(u){let v=u instanceof Error?u.message:String(u);throw new x(`Failed to decode image: ${v}`,{code:"IMAGE_DECODE_FAILED",cause:u})}let{width:s,height:a}=i.bitmap,d=Math.max(s,a);if(d>o){let u=o/d;i.resize({w:Math.max(1,Math.round(s*u)),h:Math.max(1,Math.round(a*u))})}let l=i.bitmap.width,y=i.bitmap.height;if(t.preferMediaType!=="image/jpeg"){let u=await i.getBuffer("image/png");if(u.length<=r)return{buffer:Buffer.from(u),mediaType:"image/png",width:l,height:y}}for(let u of Dt){let v=await i.getBuffer("image/jpeg",{quality:u});if(v.length<=r)return{buffer:Buffer.from(v),mediaType:"image/jpeg",width:l,height:y}}if(t.preferMediaType==="image/jpeg"){let u=await i.getBuffer("image/png");if(u.length<=r)return{buffer:Buffer.from(u),mediaType:"image/png",width:l,height:y}}throw new x(`Image still exceeds budget (${r} bytes raw) after PNG and JPEG q40 compression. Try a smaller image or take a fresh screenshot of a smaller region.`,{code:"IMAGE_TOO_LARGE"})}n(Q,"normalizePastedImage");import{spawn as Ee}from"node:child_process";import{mkdtemp as Nt,readFile as Bt,rm as Lt}from"node:fs/promises";import{tmpdir as Ft}from"node:os";import Te from"node:path";var xe=5e3;async function we(){switch(process.platform){case"darwin":return jt();case"win32":return Ut();case"linux":return Wt();default:throw new m("UNSUPPORTED_PLATFORM",`Clipboard image fallback is not supported on platform "${process.platform}".`)}}n(we,"readClipboardImage");async function $t(e={}){let t=await we();return t?Q(t,e):null}n($t,"readAndNormalizeClipboardImage");async function Me(e){let t=await Nt(Te.join(Ft(),"kodax-clip-")),o=Te.join(t,"clip.png");try{return await e(o)}finally{await Lt(t,{recursive:!0,force:!0}).catch(r=>{})}}n(Me,"runWithTempPng");async function jt(){return Me(async e=>{let t=`set png_data to (the clipboard as \xABclass PNGf\xBB)
3
3
  set fh to open for access POSIX file "${e.replace(/"/g,'\\"')}" with write permission
4
4
  write png_data to fh
5
- close access fh`;return await _e("osascript",["-e",t])?Se(e):null})}n(jt,"readMacClipboard");async function Ut(){return Me(async e=>{let t=["Add-Type -AssemblyName System.Drawing | Out-Null","$img = Get-Clipboard -Format Image","if ($null -eq $img) { exit 1 }",`$img.Save('${e.replace(/'/g,"''")}', [System.Drawing.Imaging.ImageFormat]::Png)`].join("; ");return await _e("powershell",["-NoProfile","-Command",t])?Se(e):null})}n(Ut,"readWinClipboard");async function Wt(){return await Re("wl-paste",["--type","image/png"])??Re("xclip",["-selection","clipboard","-t","image/png","-o"])}n(Wt,"readLinuxClipboard");async function Se(e){try{let t=await Bt(e);return t.length>0?t:null}catch(t){return null}}n(Se,"readNonEmptyFile");function _e(e,t){return new Promise(o=>{let r=!1,i=Ee(e,[...t],{stdio:"ignore",windowsHide:!0}),s=setTimeout(()=>{r||(r=!0,i.kill(),o(!1))},xe);i.once("error",()=>{r||(r=!0,clearTimeout(s),o(!1))}),i.once("exit",a=>{r||(r=!0,clearTimeout(s),o(a===0))})})}n(_e,"runCommand");function Re(e,t){return new Promise(o=>{let r=!1,i=[],s=Ee(e,[...t],{stdio:["ignore","pipe","ignore"],windowsHide:!0}),a=setTimeout(()=>{r||(r=!0,s.kill(),o(null))},xe);s.stdout?.on("data",d=>i.push(d)),s.once("error",()=>{r||(r=!0,clearTimeout(a),o(null))}),s.once("exit",d=>{if(r)return;if(r=!0,clearTimeout(a),d!==0){o(null);return}let l=Buffer.concat(i);o(l.length>0?l:null)})})}n(Re,"collectStdoutBytes");import{createHash as zt}from"node:crypto";import{mkdir as Vt,readdir as Gt,stat as qt,unlink as Ht,writeFile as Jt}from"node:fs/promises";import{tmpdir as Yt}from"node:os";import Z from"node:path";var Ae="KODAX_PASTE_TMP_DIR",Ke=1440*60*1e3;function Xe(){return process.env[Ae]??Z.join(Yt(),"kodax-paste")}n(Xe,"resolvePasteTmpDir");function Qt(e){let t=e?.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");return t&&t.length>0?t:"paste"}n(Qt,"sanitizeFileNamePrefix");async function Zt(e,t={}){let o=t.directory??Xe();await Vt(o,{recursive:!0});let r=e.mediaType==="image/jpeg"?".jpg":".png",i=zt("sha256").update(e.buffer).digest("hex").slice(0,16),s=`${Qt(t.fileNamePrefix)}-${i}${r}`,a=Z.join(o,s);return await Jt(a,e.buffer),{type:"image",path:a,mediaType:e.mediaType}}n(Zt,"persistImageAsBlock");async function en(e=Date.now()){let t=Xe(),o;try{o=await Gt(t)}catch(s){return 0}let r=e-Ke,i=0;return await Promise.all(o.filter(s=>/-[0-9a-f]{16}\.(?:png|jpg)$/.test(s)).map(async s=>{let a=Z.join(t,s);try{(await qt(a)).mtimeMs<r&&(await Ht(a),i+=1)}catch(d){}})),i}n(en,"prunePasteTmpDir");import{AsyncLocalStorage as tn}from"node:async_hooks";var nn=new tn;function on(e){let t=nn.getStore()?.credential;return t?O(e,t,new WeakMap):e}n(on,"redactScopedProviderCredential");function O(e,t,o){if(typeof e=="string")return e.split(t).join("[REDACTED_CREDENTIAL]");if(e===null||typeof e!="object")return e;let r=o.get(e);if(r!==void 0)return r;if(e instanceof Error){let s=new Error(O(e.message,t,o));return o.set(e,s),s.name=e.name,e.stack!==void 0&&(s.stack=O(e.stack,t,o)),s}if(Array.isArray(e)){let s=[];o.set(e,s);for(let a of e)s.push(O(a,t,o));return s}let i={};o.set(e,i);for(let[s,a]of Object.entries(Object.getOwnPropertyDescriptors(e))){if(!a.enumerable||!("value"in a))continue;let d=s.split(t).join("[REDACTED_CREDENTIAL]");i[d]=O(a.value,t,o)}return i}n(O,"redactCredentialValue");function W(e,t){return`${e}/${t??""}`}n(W,"capabilityCacheKey");function rn(e,t,o){return e[W(t,o)]?.rejected??[]}n(rn,"getRejectedEfforts");function sn(e,t,o,r,i,s){let a=W(t,o),d=e[a],l=d?.rejected.includes(r)?d.rejected:[...d?.rejected??[],r];return{...e,[a]:{rejected:l,source:i,updatedAt:s}}}n(sn,"addRejectedEffort");function an(e,t,o){if(!t)return{};let r={...e};return delete r[W(t,o)],r}n(an,"removeCacheEntry");function dn(e){if(!e||typeof e!="object")return{};let t={};for(let[o,r]of Object.entries(e)){if(!r||typeof r!="object")continue;let i=r,s=Array.isArray(i.rejected)?i.rejected.filter(l=>typeof l=="string"):[],a=i.source==="probed"?"probed":"observed",d=typeof i.updatedAt=="string"?i.updatedAt:"";t[o]={rejected:s,source:a,updatedAt:d}}return t}n(dn,"sanitizeCapabilityCache");import{AsyncLocalStorage as ln}from"node:async_hooks";var un=new ln,Ie=8,Oe=32;function cn(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0?t:void 0}n(cn,"parsePositiveInt");function fn(){let e=ee()?.workflow?.maxConcurrency,t=typeof e=="number"&&Number.isInteger(e)&&e>0?e:cn(process.env.KODAX_WORKFLOW_MAX_CONCURRENCY)??Ie;return Math.max(1,Math.min(Oe,t))}n(fn,"resolveWorkflowMaxConcurrency");function ee(){return un.getStore()}n(ee,"getRunScopedConfig");var D={transport:"native-api",conversationSemantics:"full-history",mcpSupport:"none",contextFidelity:"full",toolCallingFidelity:"full",sessionSupport:"full",longRunningSupport:"full",multimodalSupport:"none",evidenceSupport:"full"},De={...D,multimodalSupport:"image-input"},z={transport:"cli-bridge",conversationSemantics:"last-user-message",mcpSupport:"none",contextFidelity:"lossy",toolCallingFidelity:"limited",sessionSupport:"stateless",longRunningSupport:"limited",multimodalSupport:"none",evidenceSupport:"limited"},Ne={...z,multimodalSupport:"image-input"};function N(e){return{transport:e.transport,conversationSemantics:e.conversationSemantics,mcpSupport:e.mcpSupport,contextFidelity:e.contextFidelity??"full",toolCallingFidelity:e.toolCallingFidelity??"full",sessionSupport:e.sessionSupport??"full",longRunningSupport:e.longRunningSupport??"full",multimodalSupport:e.multimodalSupport??"none",evidenceSupport:e.evidenceSupport??"full"}}n(N,"normalizeCapabilityProfile");import{createRequire as Mn}from"node:module";import{parse as li}from"partial-json";var Ki=Mn(import.meta.url);import{createRequire as An}from"node:module";var qi=An(import.meta.url);var Yi=Object.freeze({status:"terminated"}),Qi=Object.freeze({status:"already-exited"}),Zi=Object.freeze({status:"unknown"}),es=String.raw`
5
+ close access fh`;return await _e("osascript",["-e",t])?Se(e):null})}n(jt,"readMacClipboard");async function Ut(){return Me(async e=>{let t=["Add-Type -AssemblyName System.Drawing | Out-Null","$img = Get-Clipboard -Format Image","if ($null -eq $img) { exit 1 }",`$img.Save('${e.replace(/'/g,"''")}', [System.Drawing.Imaging.ImageFormat]::Png)`].join("; ");return await _e("powershell",["-NoProfile","-Command",t])?Se(e):null})}n(Ut,"readWinClipboard");async function Wt(){return await Re("wl-paste",["--type","image/png"])??Re("xclip",["-selection","clipboard","-t","image/png","-o"])}n(Wt,"readLinuxClipboard");async function Se(e){try{let t=await Bt(e);return t.length>0?t:null}catch(t){return null}}n(Se,"readNonEmptyFile");function _e(e,t){return new Promise(o=>{let r=!1,i=Ee(e,[...t],{stdio:"ignore",windowsHide:!0}),s=setTimeout(()=>{r||(r=!0,i.kill(),o(!1))},xe);i.once("error",()=>{r||(r=!0,clearTimeout(s),o(!1))}),i.once("exit",a=>{r||(r=!0,clearTimeout(s),o(a===0))})})}n(_e,"runCommand");function Re(e,t){return new Promise(o=>{let r=!1,i=[],s=Ee(e,[...t],{stdio:["ignore","pipe","ignore"],windowsHide:!0}),a=setTimeout(()=>{r||(r=!0,s.kill(),o(null))},xe);s.stdout?.on("data",d=>i.push(d)),s.once("error",()=>{r||(r=!0,clearTimeout(a),o(null))}),s.once("exit",d=>{if(r)return;if(r=!0,clearTimeout(a),d!==0){o(null);return}let l=Buffer.concat(i);o(l.length>0?l:null)})})}n(Re,"collectStdoutBytes");import{createHash as zt}from"node:crypto";import{mkdir as Vt,readdir as Gt,stat as qt,unlink as Ht,writeFile as Jt}from"node:fs/promises";import{tmpdir as Yt}from"node:os";import Z from"node:path";var Ae="KODAX_PASTE_TMP_DIR",Ke=1440*60*1e3;function Xe(){return process.env[Ae]??Z.join(Yt(),"kodax-paste")}n(Xe,"resolvePasteTmpDir");function Qt(e){let t=e?.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");return t&&t.length>0?t:"paste"}n(Qt,"sanitizeFileNamePrefix");async function Zt(e,t={}){let o=t.directory??Xe();await Vt(o,{recursive:!0});let r=e.mediaType==="image/jpeg"?".jpg":".png",i=zt("sha256").update(e.buffer).digest("hex").slice(0,16),s=`${Qt(t.fileNamePrefix)}-${i}${r}`,a=Z.join(o,s);return await Jt(a,e.buffer),{type:"image",path:a,mediaType:e.mediaType}}n(Zt,"persistImageAsBlock");async function en(e=Date.now()){let t=Xe(),o;try{o=await Gt(t)}catch(s){return 0}let r=e-Ke,i=0;return await Promise.all(o.filter(s=>/-[0-9a-f]{16}\.(?:png|jpg)$/.test(s)).map(async s=>{let a=Z.join(t,s);try{(await qt(a)).mtimeMs<r&&(await Ht(a),i+=1)}catch(d){}})),i}n(en,"prunePasteTmpDir");import{AsyncLocalStorage as tn}from"node:async_hooks";var nn=new tn;function on(e){let t=nn.getStore()?.credential;return t?O(e,t,new WeakMap):e}n(on,"redactScopedProviderCredential");function O(e,t,o){if(typeof e=="string")return e.split(t).join("[REDACTED_CREDENTIAL]");if(e===null||typeof e!="object")return e;let r=o.get(e);if(r!==void 0)return r;if(e instanceof Error){let s=new Error(O(e.message,t,o));return o.set(e,s),s.name=e.name,e.stack!==void 0&&(s.stack=O(e.stack,t,o)),s}if(Array.isArray(e)){let s=[];o.set(e,s);for(let a of e)s.push(O(a,t,o));return s}let i={};o.set(e,i);for(let[s,a]of Object.entries(Object.getOwnPropertyDescriptors(e))){if(!a.enumerable||!("value"in a))continue;let d=s.split(t).join("[REDACTED_CREDENTIAL]");i[d]=O(a.value,t,o)}return i}n(O,"redactCredentialValue");function W(e,t){return`${e}/${t??""}`}n(W,"capabilityCacheKey");function rn(e,t,o){return e[W(t,o)]?.rejected??[]}n(rn,"getRejectedEfforts");function sn(e,t,o,r,i,s){let a=W(t,o),d=e[a],l=d?.rejected.includes(r)?d.rejected:[...d?.rejected??[],r];return{...e,[a]:{rejected:l,source:i,updatedAt:s}}}n(sn,"addRejectedEffort");function an(e,t,o){if(!t)return{};let r={...e};return delete r[W(t,o)],r}n(an,"removeCacheEntry");function dn(e){if(!e||typeof e!="object")return{};let t={};for(let[o,r]of Object.entries(e)){if(!r||typeof r!="object")continue;let i=r,s=Array.isArray(i.rejected)?i.rejected.filter(l=>typeof l=="string"):[],a=i.source==="probed"?"probed":"observed",d=typeof i.updatedAt=="string"?i.updatedAt:"";t[o]={rejected:s,source:a,updatedAt:d}}return t}n(dn,"sanitizeCapabilityCache");import{AsyncLocalStorage as ln}from"node:async_hooks";var un=new ln,Ie=8,Oe=32;function cn(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0?t:void 0}n(cn,"parsePositiveInt");function fn(){let e=ee()?.workflow?.maxConcurrency,t=typeof e=="number"&&Number.isInteger(e)&&e>0?e:cn(process.env.KODAX_WORKFLOW_MAX_CONCURRENCY)??Ie;return Math.max(1,Math.min(Oe,t))}n(fn,"resolveWorkflowMaxConcurrency");function ee(){return un.getStore()}n(ee,"getRunScopedConfig");var D={transport:"native-api",conversationSemantics:"full-history",mcpSupport:"none",contextFidelity:"full",toolCallingFidelity:"full",sessionSupport:"full",longRunningSupport:"full",multimodalSupport:"none",evidenceSupport:"full"},De={...D,multimodalSupport:"image-input"},z={transport:"cli-bridge",conversationSemantics:"last-user-message",mcpSupport:"none",contextFidelity:"lossy",toolCallingFidelity:"limited",sessionSupport:"stateless",longRunningSupport:"limited",multimodalSupport:"none",evidenceSupport:"limited"},Ne={...z,multimodalSupport:"image-input"};function N(e){return{transport:e.transport,conversationSemantics:e.conversationSemantics,mcpSupport:e.mcpSupport,contextFidelity:e.contextFidelity??"full",toolCallingFidelity:e.toolCallingFidelity??"full",sessionSupport:e.sessionSupport??"full",longRunningSupport:e.longRunningSupport??"full",multimodalSupport:e.multimodalSupport??"none",evidenceSupport:e.evidenceSupport??"full"}}n(N,"normalizeCapabilityProfile");import{parse as ai}from"partial-json";var zi=Object.freeze({status:"terminated"}),Vi=Object.freeze({status:"already-exited"}),Gi=Object.freeze({status:"unknown"}),qi=String.raw`
6
6
  using System;
7
7
  using System.Runtime.InteropServices;
8
8
  using System.Text;
@@ -89,4 +89,4 @@ public static class KodaXNativeProcessSnapshot {
89
89
  CloseHandle(snapshot);
90
90
  }
91
91
  }
92
- }`;import We from"node:fs";import ze from"node:os";import Ve from"node:path";var Dn="gpt-5.4",Nn="auto-gemini-3",Bn=["gpt-5.4","gpt-5.3-codex","gpt-5.3-codex-spark"],Ln=["auto-gemini-3","gemini-3.1-pro-preview","gemini-3-flash-preview","gemini-2.5-pro","gemini-2.5-flash"];function Ge(e){let t=new Set,o=[];for(let r of e){let i=r.trim();if(!i)continue;let s=i.toLowerCase();t.has(s)||(t.add(s),o.push(i))}return o}n(Ge,"dedupePreserveOrder");function Fn(){let e=Ve.join(ze.homedir(),".codex","config.toml");try{return We.readFileSync(e,"utf8").match(/^\s*model\s*=\s*"([^"]+)"/m)?.[1]?.trim()||null}catch{return null}}n(Fn,"readCodexConfiguredModel");function $n(){let e=Ve.join(ze.homedir(),".gemini","settings.json");try{let t=JSON.parse(We.readFileSync(e,"utf8")),o=typeof t.model=="string"?t.model.trim():"";return o||(typeof t.general?.model=="string"?t.general.model.trim():"")||null}catch{return null}}n($n,"readGeminiConfiguredModel");function S(){return Fn()||Dn}n(S,"getCodexCliDefaultModel");function _(){return $n()||Nn}n(_,"getGeminiCliDefaultModel");function B(){return Ge([S(),...Bn])}n(B,"getCodexCliKnownModels");function L(){return Ge([_(),...Ln])}n(L,"getGeminiCliKnownModels");var Ds=_(),Ns=L();var Hs=S(),Js=B();import{existsSync as Qn,readFileSync as Zn}from"node:fs";import K from"node:path";import{fileURLToPath as eo}from"node:url";var qe=["none","prompt-only","native-effort","native-budget","native-toggle","native-adaptive","unknown"],He=["openai-responses-effort","openai-chat-effort","codex-cli-config","anthropic-output-effort","anthropic-reasoning-effort","provider-budget","provider-toggle","prompt-only","none"],Je=["anthropic-adaptive","anthropic-budget","provider-budget","provider-toggle","none"],Ye=["zai-glm-5.3","zai-glm-5.2","zai-glm-toggle","deepseek-v4-flash-openai","deepseek-v4-pro-openai","deepseek-v4-openai","deepseek-v4-anthropic","deepseek-toggle","kimi-k3","kimi-k2.7-code","kimi-hybrid-toggle","minimax-m3","minimax-m2-always","mimo-v2.5-toggle","qwen-hybrid-thinking","openai-chat-reasoning","openai-responses-reasoning","codex-cli-effort","claude-adaptive-xhigh","claude-adaptive-max","anthropic-budget","generic-thinking-toggle","none"],Qe=["max_tokens","max_completion_tokens"],Ze=["native","image-input-native","cli-bridge","image-input-cli-bridge"],et=["count-tokens","models-list","minimal-message","unsupported"];function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(C,"isPlainObject");function w(e,t){if(typeof e!="string"||e.length===0)throw new Error(`provider-capabilities.json: ${t} must be a non-empty string`);return e}n(w,"requireString");function A(e,t){if(e!==void 0)return w(e,t)}n(A,"optionalString");function ot(e,t){if(e!==void 0){if(typeof e!="string"||!Qe.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Qe.join(", ")}, got ${JSON.stringify(e)}`);return e}}n(ot,"optionalMaxOutputTokensField");function E(e,t){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error(`provider-capabilities.json: ${t} must be a non-negative finite number`);return e}}n(E,"optionalNumber");function h(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`provider-capabilities.json: ${t} must be a boolean`);return e}}n(h,"optionalBoolean");function tt(e,t){if(e!==void 0){if(!Array.isArray(e))throw new Error(`provider-capabilities.json: ${t} must be an array`);return e.map((o,r)=>w(o,`${t}[${r}]`))}}n(tt,"optionalStringArray");function Un(e,t){if(e===void 0)return;if(!C(e))throw new Error(`provider-capabilities.json: ${t} must be an object`);let o={};for(let[r,i]of Object.entries(e))o[r]=w(i,`${t}.${r}`);return o}n(Un,"optionalStringMap");function Wn(e,t){if(e!==void 0){if(typeof e!="string"||!Ye.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Ye.join(", ")}, got ${JSON.stringify(e)}`);return e}}n(Wn,"optionalReasoningPreset");function oe(e,t){if(typeof e!="string"||!qe.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${qe.join(", ")}, got ${JSON.stringify(e)}`);return e}n(oe,"requireReasoningCapability");function zn(e,t){if(typeof e!="string"||!He.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${He.join(", ")}, got ${JSON.stringify(e)}`);return e}n(zn,"requireEffortStrategy");function Vn(e,t){if(e!==void 0){if(typeof e!="string"||!Je.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Je.join(", ")}, got ${JSON.stringify(e)}`);return e}}n(Vn,"optionalThinkingStrategy");function nt(e,t){if(e===void 0)return;if(!C(e))throw new Error(`provider-capabilities.json: ${t} must be an object`);let o=zn(e.effortStrategy,`${t}.effortStrategy`),r=Wn(e.reasoningPreset,`${t}.reasoningPreset`),i=Vn(e.thinkingStrategy,`${t}.thinkingStrategy`),s=A(e.defaultEffort,`${t}.defaultEffort`),a=Un(e.effortAliases,`${t}.effortAliases`),d=tt(e.disabledEfforts,`${t}.disabledEfforts`),l=tt(e.localRejectEfforts,`${t}.localRejectEfforts`),y=h(e.allowCustomEffort,`${t}.allowCustomEffort`),u=h(e.supportsReasoningEffort,`${t}.supportsReasoningEffort`),v=h(e.supportsReasoningSummary,`${t}.supportsReasoningSummary`),P=h(e.supportsEncryptedReasoningReplay,`${t}.supportsEncryptedReasoningReplay`),T=h(e.supportsAdaptiveThinking,`${t}.supportsAdaptiveThinking`),c=h(e.supportsManualThinkingBudget,`${t}.supportsManualThinkingBudget`),R=h(e.supportsDisabledThinking,`${t}.supportsDisabledThinking`),b=h(e.requiresEffortBetaHeader,`${t}.requiresEffortBetaHeader`),f={effortStrategy:o};if(r!==void 0&&(f.reasoningPreset=r),i!==void 0&&(f.thinkingStrategy=i),s!==void 0&&(f.defaultEffort=s),a!==void 0&&(f.effortAliases=a),d!==void 0&&(f.disabledEfforts=d),l!==void 0&&(f.localRejectEfforts=l),e.supportedEfforts!==void 0){if(!Array.isArray(e.supportedEfforts))throw new Error(`provider-capabilities.json: ${t}.supportedEfforts must be an array`);f.supportedEfforts=e.supportedEfforts.map((p,g)=>{if(!C(p))throw new Error(`provider-capabilities.json: ${t}.supportedEfforts[${g}] must be an object`);return{value:w(p.value,`${t}.supportedEfforts[${g}].value`),...A(p.description,`${t}.supportedEfforts[${g}].description`)!==void 0?{description:A(p.description,`${t}.supportedEfforts[${g}].description`)}:{},...h(p.isDefault,`${t}.supportedEfforts[${g}].isDefault`)!==void 0?{isDefault:h(p.isDefault,`${t}.supportedEfforts[${g}].isDefault`)}:{},...h(p.isUserVisible,`${t}.supportedEfforts[${g}].isUserVisible`)!==void 0?{isUserVisible:h(p.isUserVisible,`${t}.supportedEfforts[${g}].isUserVisible`)}:{}}})}if(e.budgetByEffort!==void 0){if(!C(e.budgetByEffort))throw new Error(`provider-capabilities.json: ${t}.budgetByEffort must be an object`);let p={};for(let[g,ge]of Object.entries(e.budgetByEffort))p[g]=E(ge,`${t}.budgetByEffort.${g}`)??0;f.budgetByEffort=p}return y!==void 0&&(f.allowCustomEffort=y),u!==void 0&&(f.supportsReasoningEffort=u),v!==void 0&&(f.supportsReasoningSummary=v),P!==void 0&&(f.supportsEncryptedReasoningReplay=P),T!==void 0&&(f.supportsAdaptiveThinking=T),c!==void 0&&(f.supportsManualThinkingBudget=c),R!==void 0&&(f.supportsDisabledThinking=R),b!==void 0&&(f.requiresEffortBetaHeader=b),f}n(nt,"validateReasoningProfile");function rt(e,t){let o=e.reasoningProfile,r=e.reasoningCapabilityV2;if(o!==void 0&&r!==void 0)throw new Error(`provider-capabilities.json: ${t} must not define both reasoningProfile and deprecated reasoningCapabilityV2`);return o!==void 0?nt(o,`${t}.reasoningProfile`):nt(r,`${t}.reasoningCapabilityV2`)}n(rt,"validateReasoningProfileField");function Gn(e,t){if(typeof e!="string"||!Ze.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Ze.join(", ")}, got ${JSON.stringify(e)}`);return e}n(Gn,"requireProfileName");function qn(e,t){if(typeof e!="string"||!et.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${et.join(", ")}, got ${JSON.stringify(e)}`);return e}n(qn,"requireVerifyStrategy");function Hn(e,t){if(!C(e))throw new Error(`provider-capabilities.json: ${t} must be an object`);let o=w(e.id,`${t}.id`),r=A(e.wireModel,`${t}.wireModel`),i=A(e.displayName,`${t}.displayName`),s=E(e.contextWindow,`${t}.contextWindow`),a=E(e.maxOutputTokens,`${t}.maxOutputTokens`),d=ot(e.maxOutputTokensField,`${t}.maxOutputTokensField`),l=E(e.thinkingBudgetCap,`${t}.thinkingBudgetCap`),y=h(e.replayReasoningContent,`${t}.replayReasoningContent`),u=h(e.strictThinkingSignature,`${t}.strictThinkingSignature`),v=E(e.streamMaxDurationMs,`${t}.streamMaxDurationMs`),P=e.reasoningCapability===void 0?void 0:oe(e.reasoningCapability,`${t}.reasoningCapability`),T=rt(e,t),c={id:o};return r!==void 0&&(c.wireModel=r),i!==void 0&&(c.displayName=i),s!==void 0&&(c.contextWindow=s),a!==void 0&&(c.maxOutputTokens=a),d!==void 0&&(c.maxOutputTokensField=d),l!==void 0&&(c.thinkingBudgetCap=l),P!==void 0&&(c.reasoningCapability=P),T!==void 0&&(c.reasoningProfile=T),y!==void 0&&(c.replayReasoningContent=y),u!==void 0&&(c.strictThinkingSignature=u),v!==void 0&&(c.streamMaxDurationMs=v),c}n(Hn,"validateModelDescriptor");function Jn(e,t){if(e===void 0)return;if(!C(e))throw new Error(`provider-capabilities.json: ${t} must be an object`);let o={};for(let[r,i]of Object.entries(e))o[r]=oe(i,`${t}.${r}`);return o}n(Jn,"validateModelReasoningCapabilities");function Yn(e,t){if(!C(e))throw new Error(`provider-capabilities.json: providers.${t} must be an object`);let o=h(e.cliBridge,`providers.${t}.cliBridge`),r=w(e.apiKeyEnv,`providers.${t}.apiKeyEnv`),i=oe(e.reasoningCapability,`providers.${t}.reasoningCapability`),s=rt(e,`providers.${t}`),a=Gn(e.capabilityProfile,`providers.${t}.capabilityProfile`),d=qn(e.verifyStrategy,`providers.${t}.verifyStrategy`);if(o&&d!=="unsupported")throw new Error(`provider-capabilities.json: providers.${t} is a cliBridge entry but verifyStrategy="${d}" \u2014 must be "unsupported" (CLI binary owns credentials)`);let l=E(e.contextWindow,`providers.${t}.contextWindow`),y=E(e.maxOutputTokens,`providers.${t}.maxOutputTokens`),u=ot(e.maxOutputTokensField,`providers.${t}.maxOutputTokensField`),v=E(e.thinkingBudgetCap,`providers.${t}.thinkingBudgetCap`),P=h(e.supportsThinking,`providers.${t}.supportsThinking`),T=Jn(e.modelReasoningCapabilities,`providers.${t}.modelReasoningCapabilities`),c=A(e.model,`providers.${t}.model`);if(o&&(c!==void 0||e.models!==void 0))throw new Error(`provider-capabilities.json: providers.${t} is a cliBridge entry but defines model/models \u2014 must be omitted (filled at load time)`);if(!o&&c===void 0)throw new Error(`provider-capabilities.json: providers.${t}.model is required (only cliBridge entries may omit)`);let R;if(e.models!==void 0){if(!Array.isArray(e.models))throw new Error(`provider-capabilities.json: providers.${t}.models must be an array`);R=e.models.map((p,g)=>Hn(p,`providers.${t}.models[${g}]`));let f=new Set([...c===void 0?[]:[c],...R.map(p=>p.id)]);for(let[p,g]of R.entries())if(g.wireModel!==void 0&&!f.has(g.wireModel))throw new Error(`provider-capabilities.json: providers.${t}.models[${p}].wireModel must reference a declared model, got ${JSON.stringify(g.wireModel)}`)}let b={apiKeyEnv:r,reasoningCapability:i,capabilityProfile:a,verifyStrategy:d};return s!==void 0&&(b.reasoningProfile=s),c!==void 0&&(b.model=c),R!==void 0&&(b.models=R),l!==void 0&&(b.contextWindow=l),y!==void 0&&(b.maxOutputTokens=y),u!==void 0&&(b.maxOutputTokensField=u),v!==void 0&&(b.thinkingBudgetCap=v),P!==void 0&&(b.supportsThinking=P),T!==void 0&&(b.modelReasoningCapabilities=T),o&&(b.cliBridge=!0),b}n(Yn,"validateProviderEntry");function it(e){if(!C(e))throw new Error("provider-capabilities.json: root must be an object");if(e.version!==1)throw new Error(`provider-capabilities.json: version must be 1, got ${JSON.stringify(e.version)}`);let t=w(e.updatedAt,"updatedAt");if(!C(e.providers))throw new Error("provider-capabilities.json: providers must be an object");let o={};for(let[r,i]of Object.entries(e.providers))o[r]=Yn(i,r);return{version:1,updatedAt:t,providers:o}}n(it,"validateProviderCapabilitiesJson");var to=Object.freeze({native:D,"image-input-native":De,"cli-bridge":z,"image-input-cli-bridge":Ne}),H=null;function no(){if(process.env.KODAX_BUNDLED==="true")return K.join(K.dirname(process.execPath),"provider-capabilities.json");let e=K.dirname(eo(import.meta.url)),t=[K.join(e,"provider-capabilities.json"),K.join(K.dirname(e),"provider-capabilities.json")];for(let o of t)if(Qn(o))return o;return t[0]}n(no,"resolveJsonPath");function oo(e){if(e.models){for(let t of e.models)t.reasoningProfile&&st(t.reasoningProfile);for(let t of e.models)Object.freeze(t);Object.freeze(e.models)}return e.reasoningProfile&&st(e.reasoningProfile),e.modelReasoningCapabilities&&Object.freeze(e.modelReasoningCapabilities),Object.freeze(e)}n(oo,"deepFreezeSnapshot");function st(e){if(e.supportedEfforts){for(let t of e.supportedEfforts)Object.freeze(t);Object.freeze(e.supportedEfforts)}e.budgetByEffort&&Object.freeze(e.budgetByEffort),e.effortAliases&&Object.freeze(e.effortAliases),e.disabledEfforts&&Object.freeze(e.disabledEfforts),e.localRejectEfforts&&Object.freeze(e.localRejectEfforts),Object.freeze(e)}n(st,"freezeReasoningProfile");function ro(e){if(e==="gemini-cli"){let t=_();return{model:t,models:L().filter(o=>o!==t).map(o=>({id:o}))}}if(e==="codex-cli"){let t=S();return{model:t,models:B().filter(o=>o!==t).map(o=>({id:o}))}}throw new Error(`provider-capabilities loader: unknown cliBridge provider '${e}'`)}n(ro,"resolveCliBridgeModels");function io(e,t){let o=to[t.capabilityProfile];if(!o)throw new Error(`provider-capabilities loader: unknown capabilityProfile '${t.capabilityProfile}' for provider '${e}'`);if(t.cliBridge){let i=ro(e),s={model:i.model,models:i.models,apiKeyEnv:t.apiKeyEnv,reasoningCapability:t.reasoningCapability,capabilityProfile:o,verifyStrategy:t.verifyStrategy};return t.reasoningProfile!==void 0&&(s.reasoningProfile=t.reasoningProfile),t.supportsThinking!==void 0&&(s.supportsThinking=t.supportsThinking),s}let r={model:t.model,apiKeyEnv:t.apiKeyEnv,reasoningCapability:t.reasoningCapability,capabilityProfile:o,verifyStrategy:t.verifyStrategy};return t.reasoningProfile!==void 0&&(r.reasoningProfile=t.reasoningProfile),t.models!==void 0&&(r.models=t.models),t.modelReasoningCapabilities!==void 0&&(r.modelReasoningCapabilities=t.modelReasoningCapabilities),t.contextWindow!==void 0&&(r.contextWindow=t.contextWindow),t.maxOutputTokens!==void 0&&(r.maxOutputTokens=t.maxOutputTokens),t.maxOutputTokensField!==void 0&&(r.maxOutputTokensField=t.maxOutputTokensField),t.thinkingBudgetCap!==void 0&&(r.thinkingBudgetCap=t.thinkingBudgetCap),t.supportsThinking!==void 0&&(r.supportsThinking=t.supportsThinking),r}n(io,"buildSnapshot");function at(){if(H)return H;let e=no(),t;try{let i=Zn(e,"utf8");t=JSON.parse(i)}catch(i){let s=i instanceof Error?i.message:String(i);throw new Error(`provider-capabilities loader: failed to read ${e}: ${s}`)}let o=it(t),r={};for(let[i,s]of Object.entries(o.providers))r[i]=oo(io(i,s));return H=Object.freeze(r),H}n(at,"getProviderSnapshots");var X=at();var dt=process.env.KODAX_PROVIDER??"zhipu-coding";var F=["image/png","image/jpeg","image/webp","image/gif"],$=["video/mp4","video/mpeg","video/quicktime","video/x-msvideo","video/x-flv","video/webm","video/x-ms-wmv","video/3gpp"],Xo=[],Io=new Set(["anthropic","openai"]),Oo=new Set(["ark-coding/doubao-seed-2.0-code","ark-coding/doubao-seed-2.0-pro","ark-coding/kimi-k2.6","ark-coding/kimi-k2.7-code","ark-coding/minimax-m3","kimi-code/k3-256k","qwen-token-plan/qwen3.8-max","qwen-token-plan/qwen3.8-max-preview","qwen-token-plan/qwen3.7-plus","qwen-token-plan/qwen3.6-flash"]),Do=new Set(["kimi-code/kimi-for-coding","kimi-code/kimi-for-coding-highspeed","kimi-code/k3","kimi/kimi-k3","kimi/kimi-k2.5","kimi/kimi-k2.6","kimi/kimi-k2.7-code","kimi/kimi-k2.7-code-highspeed","minimax-coding/minimax-m3","minimax/minimax-m3","mimo-coding/mimo-v2.5","mimo/mimo-v2.5"]);function le(e){return{nativeSupported:!1,sdkSupported:!1,status:"unsupported",mediaTypes:[],maxCount:0,reason:e}}n(le,"unsupported");function No(e){return{nativeSupported:!0,sdkSupported:!0,status:"supported",mediaTypes:F,nativeMediaTypes:F,reason:e}}n(No,"supportedImage");function Bo(e){return{nativeSupported:!0,sdkSupported:!1,status:"provider-native-unwired",mediaTypes:[],nativeMediaTypes:$,maxCount:0,reason:e}}n(Bo,"nativeVideoUnwired");function Lo(e){return e.trim().toLowerCase()}n(Lo,"normalizeProvider");function Fo(e){return X[e]?.model}n(Fo,"resolveProviderDefaultModel");function Et(e,t){if(!t)return;let o=t.trim().toLowerCase();if(e==="kimi"){if(o==="k2.5")return"kimi-k2.5";if(o==="k2.6")return"kimi-k2.6";if(o==="k2.7-code")return"kimi-k2.7-code";if(o==="k2.7-code-highspeed")return"kimi-k2.7-code-highspeed"}return(e==="minimax-coding"||e==="minimax")&&o==="minimax-m3"?"minimax-m3":o}n(Et,"normalizeModel");function $o(e){if(!Io.has(e))return!1;let t=X[e];return t?N(t.capabilityProfile).multimodalSupport!=="none":!1}n($o,"hasOfficialImageSupport");function jo(e,t){let o=Et(e,t);if(!o)return!1;let r=`${e}/${o}`;return Do.has(r)}n(jo,"hasSourceBackedNativeMedia");function Uo(e,t){let o=Et(e,t);return o?Oo.has(`${e}/${o}`):!1}n(Uo,"hasSourceBackedImage");function Wo(e,t,o){if(o)return"source-backed";if(t){if(e==="openai")return"openai-official";if(e==="anthropic")return"anthropic-official"}}n(Wo,"resolveImageCapabilityRoute");function zo(e){switch(e){case"openai-official":return"Model route supports KodaX image input. Direct-path image/gif is sent as image/gif, but OpenAI requires non-animated GIF semantics.";case"anthropic-official":return"Model route supports KodaX image input. Direct-path image/gif is sent as image/gif, but Anthropic uses only the first frame of animated GIFs.";case"source-backed":return"Model route supports KodaX image input. Direct-path image/gif is sent as image/gif; animated-GIF interpretation is provider-owned."}}n(zo,"imageCapabilityReason");function ue(e){let t=Lo(e.provider),o=e.model?.trim()||Fo(t),r=$o(t),i=jo(t,o),s=i||Uo(t,o),a=Wo(t,r,s),d=a!==void 0,l=i;return{text:!0,image:d?No(zo(a)):le("No verified KodaX image-input route for this provider/model."),video:l?Bo("Model route is native-video capable, but KodaX SDK video sending is not wired yet. Reject or downgrade before send."):le("No verified native video route for this provider/model."),file:le("File artifact contract is stable, but KodaX SDK file sending/extraction is not wired yet. Reject or downgrade before send.")}}n(ue,"getModelInputCapabilities");function Vo(e){return F.includes(e)}n(Vo,"isKnownImageMediaType");function Go(e){return $.includes(e)}n(Go,"isKnownVideoMediaType");function ce(e){return`${e.provider}${e.model?`/${e.model}`:""}`}n(ce,"routeLabel");function fe(e){return e.reason?`${e.status}: ${e.reason}`:e.status}n(fe,"capabilityDetail");function pe(e,t){if(e.length===0)return;let o=ue(t);for(let r of e){let i=r;if(i.kind==="image"){if(!o.image.nativeSupported||!o.image.sdkSupported)throw new m("MODEL_INPUT_UNSUPPORTED",`Provider/model cannot consume image artifacts: ${ce(t)}.`,{detail:fe(o.image)});if(typeof i.mediaType=="string"&&!Vo(i.mediaType))throw new m("UNSUPPORTED_MEDIA_TYPE",`Unsupported image media type: ${i.mediaType}.`);continue}throw i.kind==="video"?typeof i.mediaType!="string"||!Go(i.mediaType)?new m("UNSUPPORTED_MEDIA_TYPE",`Unsupported video media type: ${String(i.mediaType)}.`,{detail:`Supported video media types: ${$.join(", ")}`}):new m("MODEL_INPUT_UNSUPPORTED",`Provider/model cannot consume video artifacts through this SDK runtime: ${ce(t)}.`,{detail:fe(o.video)}):i.kind==="file"?typeof i.mediaType=="string"&&typeof i.mimeType=="string"&&i.mediaType!==i.mimeType?new m("UNSUPPORTED_MEDIA_TYPE",`File artifact mediaType and mimeType disagree: ${i.mediaType} != ${i.mimeType}.`):new m("MODEL_INPUT_UNSUPPORTED",`Provider/model cannot consume file artifacts through this SDK runtime: ${ce(t)}.`,{detail:fe(o.file)}):new m("MODEL_INPUT_UNSUPPORTED",`Unsupported input artifact kind: ${String(i.kind)}.`)}}n(pe,"validateInputArtifactsForModel");function qo(e){if(pe(e.inputArtifacts??[],e),e.agentId!==void 0&&e.sessionId!==void 0)throw new Error("enqueueWithArtifacts accepts either agentId or sessionId, not both.");if(e.sessionId!==void 0&&e.sessionId.trim().length===0)throw new Error("enqueueWithArtifacts sessionId must not be empty.");let t=e.agentId??(e.sessionId!==void 0?J(e.sessionId,"/root"):Y());return I().enqueue({priority:e.priority??"user",mode:"prompt",content:e.content,agentId:t,inputArtifacts:e.inputArtifacts})}n(qo,"enqueueWithArtifacts");export{on as a,rn as b,sn as c,an as d,dn as e,fn as f,U as g,I as h,wt as i,J as j,Mt as k,Y as l,St as m,he as n,ye as o,_t as p,m as q,x as r,ve as s,ke as t,Xt as u,It as v,Ot as w,Ce as x,Pe as y,Q as z,we as A,$t as B,Ae as C,Ke as D,Zt as E,en as F,F as G,$ as H,Xo as I,ue as J,pe as K,qo as L};
92
+ }`;import We from"node:fs";import ze from"node:os";import Ve from"node:path";var In="gpt-5.4",On="auto-gemini-3",Dn=["gpt-5.4","gpt-5.3-codex","gpt-5.3-codex-spark"],Nn=["auto-gemini-3","gemini-3.1-pro-preview","gemini-3-flash-preview","gemini-2.5-pro","gemini-2.5-flash"];function Ge(e){let t=new Set,o=[];for(let r of e){let i=r.trim();if(!i)continue;let s=i.toLowerCase();t.has(s)||(t.add(s),o.push(i))}return o}n(Ge,"dedupePreserveOrder");function Bn(){let e=Ve.join(ze.homedir(),".codex","config.toml");try{return We.readFileSync(e,"utf8").match(/^\s*model\s*=\s*"([^"]+)"/m)?.[1]?.trim()||null}catch{return null}}n(Bn,"readCodexConfiguredModel");function Ln(){let e=Ve.join(ze.homedir(),".gemini","settings.json");try{let t=JSON.parse(We.readFileSync(e,"utf8")),o=typeof t.model=="string"?t.model.trim():"";return o||(typeof t.general?.model=="string"?t.general.model.trim():"")||null}catch{return null}}n(Ln,"readGeminiConfiguredModel");function S(){return Bn()||In}n(S,"getCodexCliDefaultModel");function _(){return Ln()||On}n(_,"getGeminiCliDefaultModel");function B(){return Ge([S(),...Dn])}n(B,"getCodexCliKnownModels");function L(){return Ge([_(),...Nn])}n(L,"getGeminiCliKnownModels");var _s=_(),As=L();var Us=S(),Ws=B();import{existsSync as Jn,readFileSync as Yn}from"node:fs";import K from"node:path";import{fileURLToPath as Qn}from"node:url";var qe=["none","prompt-only","native-effort","native-budget","native-toggle","native-adaptive","unknown"],He=["openai-responses-effort","openai-chat-effort","codex-cli-config","anthropic-output-effort","anthropic-reasoning-effort","provider-budget","provider-toggle","prompt-only","none"],Je=["anthropic-adaptive","anthropic-budget","provider-budget","provider-toggle","none"],Ye=["zai-glm-5.3","zai-glm-5.2","zai-glm-toggle","deepseek-v4-flash-openai","deepseek-v4-pro-openai","deepseek-v4-openai","deepseek-v4-anthropic","deepseek-toggle","kimi-k3","kimi-k2.7-code","kimi-hybrid-toggle","minimax-m3","minimax-m2-always","mimo-v2.5-toggle","qwen-hybrid-thinking","openai-chat-reasoning","openai-responses-reasoning","codex-cli-effort","claude-adaptive-xhigh","claude-adaptive-max","anthropic-budget","generic-thinking-toggle","none"],Qe=["max_tokens","max_completion_tokens"],Ze=["native","image-input-native","cli-bridge","image-input-cli-bridge"],et=["count-tokens","models-list","minimal-message","unsupported"];function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(C,"isPlainObject");function w(e,t){if(typeof e!="string"||e.length===0)throw new Error(`provider-capabilities.json: ${t} must be a non-empty string`);return e}n(w,"requireString");function A(e,t){if(e!==void 0)return w(e,t)}n(A,"optionalString");function ot(e,t){if(e!==void 0){if(typeof e!="string"||!Qe.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Qe.join(", ")}, got ${JSON.stringify(e)}`);return e}}n(ot,"optionalMaxOutputTokensField");function E(e,t){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error(`provider-capabilities.json: ${t} must be a non-negative finite number`);return e}}n(E,"optionalNumber");function h(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`provider-capabilities.json: ${t} must be a boolean`);return e}}n(h,"optionalBoolean");function tt(e,t){if(e!==void 0){if(!Array.isArray(e))throw new Error(`provider-capabilities.json: ${t} must be an array`);return e.map((o,r)=>w(o,`${t}[${r}]`))}}n(tt,"optionalStringArray");function $n(e,t){if(e===void 0)return;if(!C(e))throw new Error(`provider-capabilities.json: ${t} must be an object`);let o={};for(let[r,i]of Object.entries(e))o[r]=w(i,`${t}.${r}`);return o}n($n,"optionalStringMap");function jn(e,t){if(e!==void 0){if(typeof e!="string"||!Ye.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Ye.join(", ")}, got ${JSON.stringify(e)}`);return e}}n(jn,"optionalReasoningPreset");function oe(e,t){if(typeof e!="string"||!qe.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${qe.join(", ")}, got ${JSON.stringify(e)}`);return e}n(oe,"requireReasoningCapability");function Un(e,t){if(typeof e!="string"||!He.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${He.join(", ")}, got ${JSON.stringify(e)}`);return e}n(Un,"requireEffortStrategy");function Wn(e,t){if(e!==void 0){if(typeof e!="string"||!Je.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Je.join(", ")}, got ${JSON.stringify(e)}`);return e}}n(Wn,"optionalThinkingStrategy");function nt(e,t){if(e===void 0)return;if(!C(e))throw new Error(`provider-capabilities.json: ${t} must be an object`);let o=Un(e.effortStrategy,`${t}.effortStrategy`),r=jn(e.reasoningPreset,`${t}.reasoningPreset`),i=Wn(e.thinkingStrategy,`${t}.thinkingStrategy`),s=A(e.defaultEffort,`${t}.defaultEffort`),a=$n(e.effortAliases,`${t}.effortAliases`),d=tt(e.disabledEfforts,`${t}.disabledEfforts`),l=tt(e.localRejectEfforts,`${t}.localRejectEfforts`),y=h(e.allowCustomEffort,`${t}.allowCustomEffort`),u=h(e.supportsReasoningEffort,`${t}.supportsReasoningEffort`),v=h(e.supportsReasoningSummary,`${t}.supportsReasoningSummary`),P=h(e.supportsEncryptedReasoningReplay,`${t}.supportsEncryptedReasoningReplay`),T=h(e.supportsAdaptiveThinking,`${t}.supportsAdaptiveThinking`),c=h(e.supportsManualThinkingBudget,`${t}.supportsManualThinkingBudget`),R=h(e.supportsDisabledThinking,`${t}.supportsDisabledThinking`),b=h(e.requiresEffortBetaHeader,`${t}.requiresEffortBetaHeader`),f={effortStrategy:o};if(r!==void 0&&(f.reasoningPreset=r),i!==void 0&&(f.thinkingStrategy=i),s!==void 0&&(f.defaultEffort=s),a!==void 0&&(f.effortAliases=a),d!==void 0&&(f.disabledEfforts=d),l!==void 0&&(f.localRejectEfforts=l),e.supportedEfforts!==void 0){if(!Array.isArray(e.supportedEfforts))throw new Error(`provider-capabilities.json: ${t}.supportedEfforts must be an array`);f.supportedEfforts=e.supportedEfforts.map((p,g)=>{if(!C(p))throw new Error(`provider-capabilities.json: ${t}.supportedEfforts[${g}] must be an object`);return{value:w(p.value,`${t}.supportedEfforts[${g}].value`),...A(p.description,`${t}.supportedEfforts[${g}].description`)!==void 0?{description:A(p.description,`${t}.supportedEfforts[${g}].description`)}:{},...h(p.isDefault,`${t}.supportedEfforts[${g}].isDefault`)!==void 0?{isDefault:h(p.isDefault,`${t}.supportedEfforts[${g}].isDefault`)}:{},...h(p.isUserVisible,`${t}.supportedEfforts[${g}].isUserVisible`)!==void 0?{isUserVisible:h(p.isUserVisible,`${t}.supportedEfforts[${g}].isUserVisible`)}:{}}})}if(e.budgetByEffort!==void 0){if(!C(e.budgetByEffort))throw new Error(`provider-capabilities.json: ${t}.budgetByEffort must be an object`);let p={};for(let[g,ge]of Object.entries(e.budgetByEffort))p[g]=E(ge,`${t}.budgetByEffort.${g}`)??0;f.budgetByEffort=p}return y!==void 0&&(f.allowCustomEffort=y),u!==void 0&&(f.supportsReasoningEffort=u),v!==void 0&&(f.supportsReasoningSummary=v),P!==void 0&&(f.supportsEncryptedReasoningReplay=P),T!==void 0&&(f.supportsAdaptiveThinking=T),c!==void 0&&(f.supportsManualThinkingBudget=c),R!==void 0&&(f.supportsDisabledThinking=R),b!==void 0&&(f.requiresEffortBetaHeader=b),f}n(nt,"validateReasoningProfile");function rt(e,t){let o=e.reasoningProfile,r=e.reasoningCapabilityV2;if(o!==void 0&&r!==void 0)throw new Error(`provider-capabilities.json: ${t} must not define both reasoningProfile and deprecated reasoningCapabilityV2`);return o!==void 0?nt(o,`${t}.reasoningProfile`):nt(r,`${t}.reasoningCapabilityV2`)}n(rt,"validateReasoningProfileField");function zn(e,t){if(typeof e!="string"||!Ze.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Ze.join(", ")}, got ${JSON.stringify(e)}`);return e}n(zn,"requireProfileName");function Vn(e,t){if(typeof e!="string"||!et.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${et.join(", ")}, got ${JSON.stringify(e)}`);return e}n(Vn,"requireVerifyStrategy");function Gn(e,t){if(!C(e))throw new Error(`provider-capabilities.json: ${t} must be an object`);let o=w(e.id,`${t}.id`),r=A(e.wireModel,`${t}.wireModel`),i=A(e.displayName,`${t}.displayName`),s=E(e.contextWindow,`${t}.contextWindow`),a=E(e.maxOutputTokens,`${t}.maxOutputTokens`),d=ot(e.maxOutputTokensField,`${t}.maxOutputTokensField`),l=E(e.thinkingBudgetCap,`${t}.thinkingBudgetCap`),y=h(e.replayReasoningContent,`${t}.replayReasoningContent`),u=h(e.strictThinkingSignature,`${t}.strictThinkingSignature`),v=E(e.streamMaxDurationMs,`${t}.streamMaxDurationMs`),P=e.reasoningCapability===void 0?void 0:oe(e.reasoningCapability,`${t}.reasoningCapability`),T=rt(e,t),c={id:o};return r!==void 0&&(c.wireModel=r),i!==void 0&&(c.displayName=i),s!==void 0&&(c.contextWindow=s),a!==void 0&&(c.maxOutputTokens=a),d!==void 0&&(c.maxOutputTokensField=d),l!==void 0&&(c.thinkingBudgetCap=l),P!==void 0&&(c.reasoningCapability=P),T!==void 0&&(c.reasoningProfile=T),y!==void 0&&(c.replayReasoningContent=y),u!==void 0&&(c.strictThinkingSignature=u),v!==void 0&&(c.streamMaxDurationMs=v),c}n(Gn,"validateModelDescriptor");function qn(e,t){if(e===void 0)return;if(!C(e))throw new Error(`provider-capabilities.json: ${t} must be an object`);let o={};for(let[r,i]of Object.entries(e))o[r]=oe(i,`${t}.${r}`);return o}n(qn,"validateModelReasoningCapabilities");function Hn(e,t){if(!C(e))throw new Error(`provider-capabilities.json: providers.${t} must be an object`);let o=h(e.cliBridge,`providers.${t}.cliBridge`),r=w(e.apiKeyEnv,`providers.${t}.apiKeyEnv`),i=oe(e.reasoningCapability,`providers.${t}.reasoningCapability`),s=rt(e,`providers.${t}`),a=zn(e.capabilityProfile,`providers.${t}.capabilityProfile`),d=Vn(e.verifyStrategy,`providers.${t}.verifyStrategy`);if(o&&d!=="unsupported")throw new Error(`provider-capabilities.json: providers.${t} is a cliBridge entry but verifyStrategy="${d}" \u2014 must be "unsupported" (CLI binary owns credentials)`);let l=E(e.contextWindow,`providers.${t}.contextWindow`),y=E(e.maxOutputTokens,`providers.${t}.maxOutputTokens`),u=ot(e.maxOutputTokensField,`providers.${t}.maxOutputTokensField`),v=E(e.thinkingBudgetCap,`providers.${t}.thinkingBudgetCap`),P=h(e.supportsThinking,`providers.${t}.supportsThinking`),T=qn(e.modelReasoningCapabilities,`providers.${t}.modelReasoningCapabilities`),c=A(e.model,`providers.${t}.model`);if(o&&(c!==void 0||e.models!==void 0))throw new Error(`provider-capabilities.json: providers.${t} is a cliBridge entry but defines model/models \u2014 must be omitted (filled at load time)`);if(!o&&c===void 0)throw new Error(`provider-capabilities.json: providers.${t}.model is required (only cliBridge entries may omit)`);let R;if(e.models!==void 0){if(!Array.isArray(e.models))throw new Error(`provider-capabilities.json: providers.${t}.models must be an array`);R=e.models.map((p,g)=>Gn(p,`providers.${t}.models[${g}]`));let f=new Set([...c===void 0?[]:[c],...R.map(p=>p.id)]);for(let[p,g]of R.entries())if(g.wireModel!==void 0&&!f.has(g.wireModel))throw new Error(`provider-capabilities.json: providers.${t}.models[${p}].wireModel must reference a declared model, got ${JSON.stringify(g.wireModel)}`)}let b={apiKeyEnv:r,reasoningCapability:i,capabilityProfile:a,verifyStrategy:d};return s!==void 0&&(b.reasoningProfile=s),c!==void 0&&(b.model=c),R!==void 0&&(b.models=R),l!==void 0&&(b.contextWindow=l),y!==void 0&&(b.maxOutputTokens=y),u!==void 0&&(b.maxOutputTokensField=u),v!==void 0&&(b.thinkingBudgetCap=v),P!==void 0&&(b.supportsThinking=P),T!==void 0&&(b.modelReasoningCapabilities=T),o&&(b.cliBridge=!0),b}n(Hn,"validateProviderEntry");function it(e){if(!C(e))throw new Error("provider-capabilities.json: root must be an object");if(e.version!==1)throw new Error(`provider-capabilities.json: version must be 1, got ${JSON.stringify(e.version)}`);let t=w(e.updatedAt,"updatedAt");if(!C(e.providers))throw new Error("provider-capabilities.json: providers must be an object");let o={};for(let[r,i]of Object.entries(e.providers))o[r]=Hn(i,r);return{version:1,updatedAt:t,providers:o}}n(it,"validateProviderCapabilitiesJson");var Zn=Object.freeze({native:D,"image-input-native":De,"cli-bridge":z,"image-input-cli-bridge":Ne}),H=null;function eo(){if(process.env.KODAX_BUNDLED==="true")return K.join(K.dirname(process.execPath),"provider-capabilities.json");let e=K.dirname(Qn(import.meta.url)),t=[K.join(e,"provider-capabilities.json"),K.join(K.dirname(e),"provider-capabilities.json")];for(let o of t)if(Jn(o))return o;return t[0]}n(eo,"resolveJsonPath");function to(e){if(e.models){for(let t of e.models)t.reasoningProfile&&st(t.reasoningProfile);for(let t of e.models)Object.freeze(t);Object.freeze(e.models)}return e.reasoningProfile&&st(e.reasoningProfile),e.modelReasoningCapabilities&&Object.freeze(e.modelReasoningCapabilities),Object.freeze(e)}n(to,"deepFreezeSnapshot");function st(e){if(e.supportedEfforts){for(let t of e.supportedEfforts)Object.freeze(t);Object.freeze(e.supportedEfforts)}e.budgetByEffort&&Object.freeze(e.budgetByEffort),e.effortAliases&&Object.freeze(e.effortAliases),e.disabledEfforts&&Object.freeze(e.disabledEfforts),e.localRejectEfforts&&Object.freeze(e.localRejectEfforts),Object.freeze(e)}n(st,"freezeReasoningProfile");function no(e){if(e==="gemini-cli"){let t=_();return{model:t,models:L().filter(o=>o!==t).map(o=>({id:o}))}}if(e==="codex-cli"){let t=S();return{model:t,models:B().filter(o=>o!==t).map(o=>({id:o}))}}throw new Error(`provider-capabilities loader: unknown cliBridge provider '${e}'`)}n(no,"resolveCliBridgeModels");function oo(e,t){let o=Zn[t.capabilityProfile];if(!o)throw new Error(`provider-capabilities loader: unknown capabilityProfile '${t.capabilityProfile}' for provider '${e}'`);if(t.cliBridge){let i=no(e),s={model:i.model,models:i.models,apiKeyEnv:t.apiKeyEnv,reasoningCapability:t.reasoningCapability,capabilityProfile:o,verifyStrategy:t.verifyStrategy};return t.reasoningProfile!==void 0&&(s.reasoningProfile=t.reasoningProfile),t.supportsThinking!==void 0&&(s.supportsThinking=t.supportsThinking),s}let r={model:t.model,apiKeyEnv:t.apiKeyEnv,reasoningCapability:t.reasoningCapability,capabilityProfile:o,verifyStrategy:t.verifyStrategy};return t.reasoningProfile!==void 0&&(r.reasoningProfile=t.reasoningProfile),t.models!==void 0&&(r.models=t.models),t.modelReasoningCapabilities!==void 0&&(r.modelReasoningCapabilities=t.modelReasoningCapabilities),t.contextWindow!==void 0&&(r.contextWindow=t.contextWindow),t.maxOutputTokens!==void 0&&(r.maxOutputTokens=t.maxOutputTokens),t.maxOutputTokensField!==void 0&&(r.maxOutputTokensField=t.maxOutputTokensField),t.thinkingBudgetCap!==void 0&&(r.thinkingBudgetCap=t.thinkingBudgetCap),t.supportsThinking!==void 0&&(r.supportsThinking=t.supportsThinking),r}n(oo,"buildSnapshot");function at(){if(H)return H;let e=eo(),t;try{let i=Yn(e,"utf8");t=JSON.parse(i)}catch(i){let s=i instanceof Error?i.message:String(i);throw new Error(`provider-capabilities loader: failed to read ${e}: ${s}`)}let o=it(t),r={};for(let[i,s]of Object.entries(o.providers))r[i]=to(oo(i,s));return H=Object.freeze(r),H}n(at,"getProviderSnapshots");var X=at();var dt=process.env.KODAX_PROVIDER??"zhipu-coding";var F=["image/png","image/jpeg","image/webp","image/gif"],$=["video/mp4","video/mpeg","video/quicktime","video/x-msvideo","video/x-flv","video/webm","video/x-ms-wmv","video/3gpp"],Ao=[],Ko=new Set(["anthropic","openai"]),Xo=new Set(["ark-coding/doubao-seed-2.0-code","ark-coding/doubao-seed-2.0-pro","ark-coding/kimi-k2.6","ark-coding/kimi-k2.7-code","ark-coding/minimax-m3","kimi-code/k3-256k","qwen-token-plan/qwen3.8-max","qwen-token-plan/qwen3.8-max-preview","qwen-token-plan/qwen3.7-plus","qwen-token-plan/qwen3.6-flash"]),Io=new Set(["kimi-code/kimi-for-coding","kimi-code/kimi-for-coding-highspeed","kimi-code/k3","kimi/kimi-k3","kimi/kimi-k2.5","kimi/kimi-k2.6","kimi/kimi-k2.7-code","kimi/kimi-k2.7-code-highspeed","minimax-coding/minimax-m3","minimax/minimax-m3","mimo-coding/mimo-v2.5","mimo/mimo-v2.5"]);function le(e){return{nativeSupported:!1,sdkSupported:!1,status:"unsupported",mediaTypes:[],maxCount:0,reason:e}}n(le,"unsupported");function Oo(e){return{nativeSupported:!0,sdkSupported:!0,status:"supported",mediaTypes:F,nativeMediaTypes:F,reason:e}}n(Oo,"supportedImage");function Do(e){return{nativeSupported:!0,sdkSupported:!1,status:"provider-native-unwired",mediaTypes:[],nativeMediaTypes:$,maxCount:0,reason:e}}n(Do,"nativeVideoUnwired");function No(e){return e.trim().toLowerCase()}n(No,"normalizeProvider");function Bo(e){return X[e]?.model}n(Bo,"resolveProviderDefaultModel");function Et(e,t){if(!t)return;let o=t.trim().toLowerCase();if(e==="kimi"){if(o==="k2.5")return"kimi-k2.5";if(o==="k2.6")return"kimi-k2.6";if(o==="k2.7-code")return"kimi-k2.7-code";if(o==="k2.7-code-highspeed")return"kimi-k2.7-code-highspeed"}return(e==="minimax-coding"||e==="minimax")&&o==="minimax-m3"?"minimax-m3":o}n(Et,"normalizeModel");function Lo(e){if(!Ko.has(e))return!1;let t=X[e];return t?N(t.capabilityProfile).multimodalSupport!=="none":!1}n(Lo,"hasOfficialImageSupport");function Fo(e,t){let o=Et(e,t);if(!o)return!1;let r=`${e}/${o}`;return Io.has(r)}n(Fo,"hasSourceBackedNativeMedia");function $o(e,t){let o=Et(e,t);return o?Xo.has(`${e}/${o}`):!1}n($o,"hasSourceBackedImage");function jo(e,t,o){if(o)return"source-backed";if(t){if(e==="openai")return"openai-official";if(e==="anthropic")return"anthropic-official"}}n(jo,"resolveImageCapabilityRoute");function Uo(e){switch(e){case"openai-official":return"Model route supports KodaX image input. Direct-path image/gif is sent as image/gif, but OpenAI requires non-animated GIF semantics.";case"anthropic-official":return"Model route supports KodaX image input. Direct-path image/gif is sent as image/gif, but Anthropic uses only the first frame of animated GIFs.";case"source-backed":return"Model route supports KodaX image input. Direct-path image/gif is sent as image/gif; animated-GIF interpretation is provider-owned."}}n(Uo,"imageCapabilityReason");function ue(e){let t=No(e.provider),o=e.model?.trim()||Bo(t),r=Lo(t),i=Fo(t,o),s=i||$o(t,o),a=jo(t,r,s),d=a!==void 0,l=i;return{text:!0,image:d?Oo(Uo(a)):le("No verified KodaX image-input route for this provider/model."),video:l?Do("Model route is native-video capable, but KodaX SDK video sending is not wired yet. Reject or downgrade before send."):le("No verified native video route for this provider/model."),file:le("File artifact contract is stable, but KodaX SDK file sending/extraction is not wired yet. Reject or downgrade before send.")}}n(ue,"getModelInputCapabilities");function Wo(e){return F.includes(e)}n(Wo,"isKnownImageMediaType");function zo(e){return $.includes(e)}n(zo,"isKnownVideoMediaType");function ce(e){return`${e.provider}${e.model?`/${e.model}`:""}`}n(ce,"routeLabel");function fe(e){return e.reason?`${e.status}: ${e.reason}`:e.status}n(fe,"capabilityDetail");function pe(e,t){if(e.length===0)return;let o=ue(t);for(let r of e){let i=r;if(i.kind==="image"){if(!o.image.nativeSupported||!o.image.sdkSupported)throw new m("MODEL_INPUT_UNSUPPORTED",`Provider/model cannot consume image artifacts: ${ce(t)}.`,{detail:fe(o.image)});if(typeof i.mediaType=="string"&&!Wo(i.mediaType))throw new m("UNSUPPORTED_MEDIA_TYPE",`Unsupported image media type: ${i.mediaType}.`);continue}throw i.kind==="video"?typeof i.mediaType!="string"||!zo(i.mediaType)?new m("UNSUPPORTED_MEDIA_TYPE",`Unsupported video media type: ${String(i.mediaType)}.`,{detail:`Supported video media types: ${$.join(", ")}`}):new m("MODEL_INPUT_UNSUPPORTED",`Provider/model cannot consume video artifacts through this SDK runtime: ${ce(t)}.`,{detail:fe(o.video)}):i.kind==="file"?typeof i.mediaType=="string"&&typeof i.mimeType=="string"&&i.mediaType!==i.mimeType?new m("UNSUPPORTED_MEDIA_TYPE",`File artifact mediaType and mimeType disagree: ${i.mediaType} != ${i.mimeType}.`):new m("MODEL_INPUT_UNSUPPORTED",`Provider/model cannot consume file artifacts through this SDK runtime: ${ce(t)}.`,{detail:fe(o.file)}):new m("MODEL_INPUT_UNSUPPORTED",`Unsupported input artifact kind: ${String(i.kind)}.`)}}n(pe,"validateInputArtifactsForModel");function Vo(e){if(pe(e.inputArtifacts??[],e),e.agentId!==void 0&&e.sessionId!==void 0)throw new Error("enqueueWithArtifacts accepts either agentId or sessionId, not both.");if(e.sessionId!==void 0&&e.sessionId.trim().length===0)throw new Error("enqueueWithArtifacts sessionId must not be empty.");let t=e.agentId??(e.sessionId!==void 0?J(e.sessionId,"/root"):Y());return I().enqueue({priority:e.priority??"user",mode:"prompt",content:e.content,agentId:t,inputArtifacts:e.inputArtifacts})}n(Vo,"enqueueWithArtifacts");export{on as a,rn as b,sn as c,an as d,dn as e,fn as f,U as g,I as h,wt as i,J as j,Mt as k,Y as l,St as m,he as n,ye as o,_t as p,m as q,x as r,ve as s,ke as t,Xt as u,It as v,Ot as w,Ce as x,Pe as y,Q as z,we as A,$t as B,Ae as C,Ke as D,Zt as E,en as F,F as G,$ as H,Ao as I,ue as J,pe as K,Vo as L};