@kodax-ai/kodax 0.7.92 → 0.7.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +9 -0
  3. package/README_CN.md +9 -0
  4. package/dist/chunks/{agent-YHHFIH7N.js → agent-R7HVNARP.js} +1 -1
  5. package/dist/chunks/argument-completer-JHXUJWHC.js +2 -0
  6. package/dist/chunks/{chunk-PKPBII4F.js → chunk-3YOZIFSJ.js} +2 -2
  7. package/dist/chunks/{chunk-OSQIYUGD.js → chunk-4BY53JTF.js} +2 -2
  8. package/dist/chunks/{chunk-X75UGXP3.js → chunk-7QBWHCIZ.js} +1 -1
  9. package/dist/chunks/chunk-A3ZQE2BX.js +519 -0
  10. package/dist/chunks/{chunk-FBL7IVMK.js → chunk-BHE66SP3.js} +14 -14
  11. package/dist/chunks/chunk-D27EY4XC.js +383 -0
  12. package/dist/chunks/{chunk-5CIKWSCA.js → chunk-HLZWPB32.js} +2 -2
  13. package/dist/chunks/{chunk-RJIYXB62.js → chunk-JJ2YDBSN.js} +2 -2
  14. package/dist/chunks/{chunk-AGZNXFHZ.js → chunk-JTZKC4TV.js} +4 -4
  15. package/dist/chunks/{chunk-QPBN3J4E.js → chunk-PRASABCC.js} +2 -2
  16. package/dist/chunks/{chunk-QKLS4BYA.js → chunk-SMVC3Q3U.js} +4 -4
  17. package/dist/chunks/{chunk-THZVJ6R7.js → chunk-XTWIGVUL.js} +1 -1
  18. package/dist/chunks/{construction-bootstrap-QVLJPFTL.js → construction-bootstrap-474QPSYB.js} +1 -1
  19. package/dist/chunks/{dist-XC5M7UYX.js → dist-H4PT2QAV.js} +1 -1
  20. package/dist/chunks/{dist-WNMK42WE.js → dist-ITTXQHRJ.js} +1 -1
  21. package/dist/chunks/{host-B3TK2U43.js → host-OR3IO2A4.js} +1 -1
  22. package/dist/chunks/{run-manager-5AV3MR4W.js → run-manager-MNOTWIFX.js} +1 -1
  23. package/dist/chunks/{utils-HPVZCR2J.js → utils-5J4BHNBV.js} +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/kodax_bootstrap.js +1 -1
  26. package/dist/kodax_cli.js +1035 -1035
  27. package/dist/runtime-worker.js +1007 -1007
  28. package/dist/sandbox-workspace-session.js +1 -1
  29. package/dist/sdk-a2a.js +1 -1
  30. package/dist/sdk-coding.js +1 -1
  31. package/dist/sdk-llm.js +1 -1
  32. package/dist/sdk-repl.js +1 -1
  33. package/dist/sdk-runtime.js +1 -1
  34. package/dist/sdk-sandbox.js +1 -1
  35. package/dist/sdk-session.js +1 -1
  36. package/package.json +1 -1
  37. package/dist/chunks/argument-completer-6ZTRBNZM.js +0 -2
  38. package/dist/chunks/chunk-A6GNPNGB.js +0 -383
  39. package/dist/chunks/chunk-BV3SVH36.js +0 -519
package/CHANGELOG.md CHANGED
@@ -8,6 +8,33 @@ All notable changes to this project will be documented in this file.
8
8
 
9
9
  ---
10
10
 
11
+ ## [0.7.93] - 2026-08-19
12
+
13
+ ### Fixed
14
+
15
+ - Runtime exit settlement no longer spends the 170-second orderly Windows
16
+ daemon-exit window after the exact owner has already persisted a terminal
17
+ `failed` shutdown outcome. Settlement observes that durable evidence while
18
+ waiting for process exit and enters the existing exact PID/start-identity,
19
+ Job-containment, and ACL-recovery path immediately. Slow cleanup without a
20
+ terminal failure still keeps the full budget; POSIX behavior is unchanged.
21
+ - Runtime exit settlement now recovers Windows sandbox ACL markers from multiple
22
+ owners only after a changed boot identity and a machine-lock recheck prove
23
+ that every marker has a canonical non-current boot identity. Recovery is
24
+ durably recorded with the recovery boot before marker removal. A further
25
+ reboot repeats native recovery before clear; same-boot, mixed, unreadable, or
26
+ identity-free markers remain fail-closed, and the path never enters sandbox
27
+ provisioning or elevation.
28
+ - Anthropic and OpenAI SDK abort wrappers whose runtime `name` remains `Error`
29
+ are now recognized by their lazily loaded `APIUserAbortError` class identity
30
+ when the request signal is already aborted. Each SDK load is isolated, so a
31
+ missing or broken sibling package cannot replace the original error.
32
+ Managed Runtime Stop therefore retains its trusted interrupted terminal
33
+ cause before run-scoped credential redaction, without reclassifying
34
+ independent same-message Provider failures.
35
+
36
+ ---
37
+
11
38
  ## [0.7.92] - 2026-08-18
12
39
 
13
40
  ### Fixed
package/README.md CHANGED
@@ -726,6 +726,15 @@ permission UI, and recovers stale prepared Session tails through an
726
726
  authoritative merge. Background persistence failures are surfaced as
727
727
  diagnostics rather than hidden.
728
728
 
729
+ **v0.7.93 release:** Runtime exit settlement no longer spends the 170-second
730
+ Windows orderly-exit window after a durable `failed` shutdown outcome, can
731
+ recover previous-boot shared ACL markers after a verified boot change, and
732
+ keeps managed Stop interrupted when an Anthropic or OpenAI abort wrapper
733
+ does not carry the `APIUserAbortError` runtime name. Capability versions are
734
+ unchanged. Issue 256 remains open. See the
735
+ [v0.7.93 release checklist](docs/release.md#v0793-release-preparation)
736
+ and [SDK Embedder Guide](public_docs/sdk/embedder-guide.md).
737
+
729
738
  **v0.7.92 release:** the filesystem-effect coordinator now gives each
730
739
  queue attempt an exact token and heartbeat. It can reclaim a stale same-daemon
731
740
  ticket only when that token no longer owns the coordinator lock, and durable
package/README_CN.md CHANGED
@@ -266,6 +266,15 @@ SDK 系统代码契约更新,但没有放宽 shell/sandbox 的 fail-closed 边
266
266
  `handleRuntimePermissionRequest()` 管理 SDK 权限 UI,并在 prepared Session 尾部遇到
267
267
  `data_changed` 时通过权威 delta 合并恢复;后台持久化失败会显示为诊断,不再静默丢失。
268
268
 
269
+ **v0.7.93 发布**:Windows 退出结算在精确 owner 已写入 durable `failed`
270
+ shutdown outcome 后不再空等 170 秒有序窗口,改为立即进入既有精确恢复路径。
271
+ 验证 boot 变化后,可在 machine lock 下回收上一启动留下的共享 ACL marker,
272
+ 并在记录 recovery 之后才清除。Anthropic/OpenAI 的 abort 包装在请求 signal
273
+ 已中止时按隔离加载的 SDK class identity 识别,managed Stop 在凭据脱敏前
274
+ 仍保持 interrupted。能力版本不变。Issue 256 仍保持 Open。
275
+ 详见 [v0.7.93 发布清单](docs/release.md#v0793-release-preparation) 与
276
+ [SDK Embedder Guide](public_docs/sdk/embedder-guide.md)。
277
+
269
278
  **v0.7.92 发布**:文件系统效应协调器为每次排队使用精确 token 并 heartbeat。
270
279
  只有当该 token 不再持有 coordinator lock 时,才会回收同一长期 daemon PID 上的过期票;
271
280
  durable release marker 允许后续调用退役已结算的 effect owner。精确仍持有的 lock、
@@ -1,2 +1,2 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Ka as g,Ma as h,Za as i,_a as j,a as c,sa as d,ta as e,ua as f,yc as k}from"./chunk-RJIYXB62.js";import"./chunk-X75UGXP3.js";import"./chunk-AGZNXFHZ.js";import"./chunk-GH3KBC2H.js";import"./chunk-YVG6OKN7.js";import"./chunk-FBL7IVMK.js";import{Jb as a,Kb as b}from"./chunk-7XSZVOG7.js";import"./chunk-QFV6YCIH.js";import"./chunk-ONUPGMER.js";export{e as bucketProviderPayloadSize,g as buildAutoRepoIntelligenceContext,f as checkPromiseSignal,b as cleanupIncompleteToolCalls,h as describeTransientProviderRetry,c as emitResilienceDebug,d as estimateProviderPayloadBytes,k as runKodaX,j as saveRequiredSessionSnapshot,i as saveSessionSnapshot,a as validateAndFixToolHistory};
2
+ import{Ka as g,Ma as h,Za as i,_a as j,a as c,sa as d,ta as e,ua as f,yc as k}from"./chunk-JJ2YDBSN.js";import"./chunk-7QBWHCIZ.js";import"./chunk-JTZKC4TV.js";import"./chunk-GH3KBC2H.js";import"./chunk-YVG6OKN7.js";import"./chunk-BHE66SP3.js";import{Jb as a,Kb as b}from"./chunk-7XSZVOG7.js";import"./chunk-QFV6YCIH.js";import"./chunk-ONUPGMER.js";export{e as bucketProviderPayloadSize,g as buildAutoRepoIntelligenceContext,f as checkPromiseSignal,b as cleanupIncompleteToolCalls,h as describeTransientProviderRetry,c as emitResilienceDebug,d as estimateProviderPayloadBytes,k as runKodaX,j as saveRequiredSessionSnapshot,i as saveSessionSnapshot,a as validateAndFixToolHistory};
@@ -0,0 +1,2 @@
1
+ // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
+ import{Ha as a,Ia as b}from"./chunk-3YOZIFSJ.js";import"./chunk-HLZWPB32.js";import"./chunk-GRWUC6H7.js";import"./chunk-4BY53JTF.js";import"./chunk-XTWIGVUL.js";import"./chunk-JJ2YDBSN.js";import"./chunk-7QBWHCIZ.js";import"./chunk-PRASABCC.js";import"./chunk-JTZKC4TV.js";import"./chunk-GH3KBC2H.js";import"./chunk-YVG6OKN7.js";import"./chunk-BHE66SP3.js";import"./chunk-7XSZVOG7.js";import"./chunk-QFV6YCIH.js";import"./chunk-ONUPGMER.js";export{a as ArgumentCompleter,b as createArgumentCompleter};
@@ -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-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)}
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-HLZWPB32.js";import{a as Ri}from"./chunk-GRWUC6H7.js";import{ha as ai,ia as li,ma as ci,oa as di}from"./chunk-4BY53JTF.js";import{i as Vo}from"./chunk-XTWIGVUL.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-JJ2YDBSN.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-PRASABCC.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-JTZKC4TV.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-BHE66SP3.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-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};
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-JHXUJWHC.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};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{$ as xo,$a as sc,Aa as Qt,Ba as Ma,Ca as Oa,D as Fn,Da as Pa,E as Bn,Ea as Da,F as ua,Fa as bt,G as To,Ga as Na,H as la,Ha as $a,Ia as La,Ja as Ka,K as fa,Ka as Xa,L as ma,La as za,M as pa,Ma as Ya,N as Yt,Na as qn,O as vo,Oa as Ja,Pa as Qa,Qa as Za,R as yo,Ra as ec,S as ko,Sa as tc,T as Ro,Ta as Gn,U as wo,Ua as No,V as ka,Va as $o,W as Ra,Wa as nc,Xa as rc,Y as bo,Ya as oc,Z as Eo,Za as Lo,_a as ic,a as me,ab as ac,ba as So,ca as wa,da as ba,ea as Un,f as $r,fa as _o,h as Ls,i as Lr,ja as Jt,k as jr,l as bn,la as Ea,ma as xa,na as Co,o as Gt,pa as Io,ra as Ao,sa as Sa,ta as _a,va as Mo,wa as Ca,xa as Oo,xc as cc,ya as Ia,yc as Ue,z as ho,za as Aa}from"./chunk-RJIYXB62.js";import{a as Po}from"./chunk-X75UGXP3.js";import{A as Do,o as Ua,t as Wa,u as qa,v as Ga,y as Ha}from"./chunk-QPBN3J4E.js";import{$b as Xt,$d as ya,Ba as _n,D as Gs,F as Wr,G as qr,Gd as He,Ha as Kt,Hd as po,I as Gr,Ia as Qr,Ka as Zr,Kb as ra,La as eo,Lb as oa,Mb as ia,Na as to,Oa as no,Od as go,Pb as An,Rb as Mn,S as Vs,Sa as ro,Sb as On,T as Ks,Td as da,V as Xs,Va as oo,Vb as Pn,Vd as ga,W as zs,Wb as Dn,Wd as ha,X as Hr,Xd as Ta,Y as Ys,Yb as co,Yd as va,Za as Cn,Zb as Ge,_a as In,a as wn,ac as uo,b as $s,bb as io,bc as Nn,bd as fo,cc as $n,da as xn,dc as Ln,eb as so,ec as lo,fa as Vr,fb as ao,fc as sa,ga as Kr,gb as na,ha as Sn,ia as Js,ja as Xr,ka as zr,l as Fr,la as Qs,ma as st,me as ja,nd as aa,o as js,oa as Zs,od as ca,p as Br,q as Fs,s as Bs,sd as jn,se as Fa,t as Us,td as zt,te as Wn,u as En,ua as Yr,ue as Ba,v as Ws,va as Jr,w as Ht,wa as ea,we as Va,x as qs,xa as ta,xd as mo,z as Ur,za as Vt,zb as De}from"./chunk-AGZNXFHZ.js";import{h as Hs}from"./chunk-GH3KBC2H.js";import{D as nt,Pa as Ee,R as Qi,T as gn,ab as xr,bb as hn,cb as Sr,db as _r,e as Er,fb as Cr,gb as Zi,k as pn,na as rt,ua as ot}from"./chunk-FBL7IVMK.js";import{$f as As,Aa as Ar,Ab as gs,B as ts,Db as hs,Eb as Ts,Ga as as,Gb as vs,Ia as Mr,Jb as Or,Kb as Pr,L as ns,Me as Rn,Nb as Rt,O as rs,Ob as ys,Vd as ks,Zd as Rs,_d as ws,_f as wt,fb as cs,g as Tn,gf as bs,ha as Ir,ib as ds,k as re,kg as Ms,l as qe,o as qt,og as Os,pf as Dr,pg as Ps,q as vn,qb as Pe,qf as Es,r as es,rf as xs,rg as Ds,sb as us,t as it,ta as kt,tf as Ss,ua as os,uf as _s,vb as ps,vf as Cs,wa as is,wf as Is,xf as Nr,xg as Ns,za as ss}from"./chunk-7XSZVOG7.js";import{K as ms,h as yn,j as kn,k as ls,p as fs}from"./chunk-QFV6YCIH.js";import{a as o}from"./chunk-ONUPGMER.js";function Xl(){return{retained:[]}}o(Xl,"createOutputSegmentProjection");function zl(e,t){if(t.type==="segment.started"){if(e.active?.responseId===t.responseId&&e.active.providerRequestId===t.providerRequestId&&e.active.mode===t.mode)return{state:e,accepted:!0};let n=e.active?.responseId??e.retained[e.retained.length-1]?.responseId,r=n===void 0||n===t.responseId,i=t.mode==="append"?e.active:void 0;return{accepted:!0,state:{retained:r?i?[...e.retained,i]:e.retained:[],active:{responseId:t.responseId,providerRequestId:t.providerRequestId,mode:t.mode,...t.startedAtSeq!==void 0?{startedAtSeq:t.startedAtSeq}:{},assistantText:"",thinkingText:""}}}}return e.active?.providerRequestId!==t.providerRequestId?{state:e,accepted:!1}:{accepted:!0,state:{...e,active:{...e.active,...t.type==="assistant.delta"?{assistantText:e.active.assistantText+t.text}:{thinkingText:e.active.thinkingText+t.text}}}}}o(zl,"reduceOutputSegmentProjection");function Yl(e,t){let n=t==="assistant"?"assistantText":"thinkingText";return e.retained.map(r=>r[n]).join("")+(e.active?.[n]??"")}o(Yl,"effectiveOutputSegmentText");var Zt=class extends Error{static{o(this,"KodaXError")}code;constructor(t,n="KODAX_ERROR"){super(t),this.code=n,this.name="KodaXError"}};var jo=class extends Zt{static{o(this,"KodaXToolError")}toolName;toolId;constructor(t,n,r){super(t,"TOOL_ERROR"),this.toolName=n,this.toolId=r,this.name="KodaXToolError"}};var Fo=class extends Zt{static{o(this,"KodaXSessionError")}sessionId;constructor(t,n){super(t,"SESSION_ERROR"),this.sessionId=n,this.name="KodaXSessionError"}},Bo=class extends Zt{static{o(this,"KodaXTerminalError")}suggestions;constructor(t,n=[]){super(t,"TERMINAL_ERROR"),this.name="KodaXTerminalError",this.suggestions=n}};function Jl(){return new Hn}o(Jl,"createSessionControl");function Uo(e,t){let n=new AbortController,r=!1,i=o(p=>{r||(r=!0,n.abort(p))},"markAborted");e.abortSignal&&(e.abortSignal.aborted?i(e.abortSignal.reason):e.abortSignal.addEventListener("abort",()=>i(e.abortSignal.reason),{once:!0}));let s=new Hn;s.seed({provider:e.provider,model:e.modelOverride??e.model,reasoning:e.reasoningMode});let a=e.session?.id,c=a!=null,d=a??Ql(),f=!c&&e.session?.autoResume!==!0&&e.session?.resume!==!0?oc({...e.session??{},id:d}):e.session,u={...e,...e.agentMode!==void 0?{agentMode:Gt(e.agentMode)}:{},...f!==void 0?{session:f}:{},abortSignal:n.signal,sessionControl:s},h=Ue(u,t);return{id:d,get currentProvider(){return s.getProvider()},get currentModel(){return s.getModel()},get currentReasoning(){return s.getReasoning()},get aborted(){return r},get attached(){return s.isAttached()},setProvider:o(p=>s.setProvider(p),"setProvider"),setModel:o(p=>s.setModel(p),"setModel"),setReasoning:o(p=>s.setReasoning(p),"setReasoning"),abort:o(p=>i(p),"abort"),result:h}}o(Uo,"startKodaX");function Ql(){return`sess_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}o(Ql,"generateSessionId");var Hn=class{static{o(this,"SessionControlImpl")}mutators=null;providerValue;modelValue;reasoningValue;hasPendingProvider=!1;hasPendingModel=!1;hasPendingReasoning=!1;seed(t){this.providerValue=t.provider,this.modelValue=t.model,this.reasoningValue=t.reasoning}setProvider(t){this.providerValue=t,this.mutators?this.mutators.setProvider(t):this.hasPendingProvider=!0}setModel(t){this.modelValue=t,this.mutators?this.mutators.setModel(t):this.hasPendingModel=!0}setReasoning(t){this.reasoningValue=t,this.mutators?this.mutators.setReasoning(t):this.hasPendingReasoning=!0}getProvider(){return this.providerValue??""}getModel(){return this.modelValue}getReasoning(){return this.reasoningValue}isAttached(){return this.mutators!==null}_attach(t){this.mutators,this.mutators=t,this.hasPendingProvider&&this.providerValue!==void 0&&t.setProvider(this.providerValue),this.hasPendingModel&&t.setModel(this.modelValue),this.hasPendingReasoning&&t.setReasoning(this.reasoningValue),this.hasPendingProvider=!1,this.hasPendingModel=!1,this.hasPendingReasoning=!1}};function Zl(e,t){return e.kind!=="revise_count"?{ok:!0}:e.count<=3?{ok:!0}:{ok:!1,severity:"warn",reason:`boundedRevise: revise_count for harness="${e.harness}" reached ${e.count}, exceeding soft threshold 3`}}o(Zl,"observe");var Wo={id:"boundedRevise",description:"Per-harness revise count must stay within the soft threshold; crossings emit a warn signal for dispatch-eval (hard cap enforced by the budget controller).",observe:Zl};function ef(e,t){return typeof e.maxBudget!="number"?{ok:!0}:e.maxBudget<=t.systemCap.maxBudget?{ok:!0}:{ok:!1,severity:"clamp",reason:`budgetCeiling: manifest.maxBudget=${e.maxBudget} exceeds systemCap.maxBudget=${t.systemCap.maxBudget}`,patch:{clampMaxBudget:t.systemCap.maxBudget}}}o(ef,"admit");var qo={id:"budgetCeiling",description:"manifest.maxBudget must be \u2264 systemCap.maxBudget; over-cap declarations are clamped down to the cap.",admit:ef};function tf(e,t){return{ok:!0}}o(tf,"observe");var dc={id:"harnessSelectionTiming",description:"FEATURE_193 V2 no-op shell \u2014 predicate always admits since V1 Scout retired. Kept registered for admission-framework / audit-array compat.",observe:tf};function nf(e,t){if(e.kind!=="mutation_recorded")return{ok:!0};let n=t.recorder;return typeof n.todoUpdateCount!="number"?{ok:!0}:n.todoUpdateCount>0?{ok:!0}:n.workerTrivialDeclaration===!0?{ok:!0}:{ok:!1,severity:"warn",reason:`planBeforeMutate: Worker mutated ${e.file} without a prior todo_update plan commit and without a trivial declaration`}}o(nf,"observe");var uc={id:"planBeforeMutate",description:"Worker mutations should be preceded by a todo_update plan commit (or an explicit trivial declaration). Missing plan is a warn-only signal in v0.7.36.",observe:nf};function Go(e){switch(e){case"read":case"glob":case"grep":case"code_search":case"semantic_lookup":case"lsp_definition":case"lsp_hover":case"lsp_references":case"lsp_document_symbols":case"lsp_workspace_symbols":case"lsp_implementation":case"lsp_prepare_call_hierarchy":case"lsp_incoming_calls":case"lsp_outgoing_calls":case"repo_overview":case"changed_scope":case"changed_diff":case"changed_diff_bundle":case"module_context":case"symbol_context":case"process_context":case"impact_estimate":case"relationship_scan":case"cyclic_dependencies":case"ask_user_question":case"exit_plan_mode":return"read";case"write":case"edit":case"multi_edit":case"insert_after_anchor":case"undo":return"edit";case"bash":return"bash:mutating";case"web_search":case"web_fetch":case"mcp_search":case"mcp_describe":case"mcp_call":case"mcp_read_resource":case"mcp_get_prompt":return"bash:network";case"spawn_agent":case"send_message":case"followup_task":case"wait_agent":case"interrupt_agent":case"list_agents":case"agent_output":case"emit_verdict":case"scaffold_tool":case"validate_tool":case"stage_construction":case"test_tool":case"activate_tool":case"scaffold_agent":case"validate_agent":case"stage_agent_construction":case"test_agent":case"activate_agent":case"worktree_create":case"worktree_remove":return"subagent";default:return"subagent"}}o(Go,"resolveToolCapability");function rf(e){if(typeof e=="object"&&e!==null&&"name"in e){let t=e.name;if(typeof t=="string"&&t.length>0)return t}}o(rf,"getToolName");function of(e,t){if(!e.tools||e.tools.length===0)return{ok:!0};let n=new Set(t.systemCap.allowedToolCapabilities),r=[];for(let a of e.tools){let c=rf(a);if(!c)continue;let d=Go(c);n.has(d)||r.push({name:c,capability:d})}if(r.length===0)return{ok:!0};let i=r.map(a=>a.name);return{ok:!1,severity:"clamp",reason:`toolPermission: tools requiring disallowed capabilities \u2014 ${r.map(a=>`${a.name}=${a.capability}`).join(", ")}`,patch:{removeTools:i}}}o(of,"admit");var Ho={id:"toolPermission",description:"Every tool in manifest.tools must resolve to a capability tier that systemCap.allowedToolCapabilities permits; offending tools are clamped via removeTools.",admit:of};var lc=[qo,Ho,Wo,dc,uc];function sf(){as();for(let e of lc)rs(e)}o(sf,"registerCodingInvariants");var Vn=class{static{o(this,"KodaXClient")}options;sessionId;messages=[];contextTokenSnapshot;constructor(t){this.options=t,this.sessionId=t.session?.id??"",this.messages=t.session?.initialMessages?[...t.session.initialMessages]:[],this.contextTokenSnapshot=t.context?.contextTokenSnapshot}async send(t){let n=this.messages.length>0?this.messages:this.options.session?.initialMessages,r=await Ue({...this.options,session:{...this.options.session,id:this.sessionId||void 0,initialMessages:n},context:{...this.options.context,contextTokenSnapshot:this.contextTokenSnapshot}},t);return this.sessionId=r.sessionId,this.messages=r.messages,this.contextTokenSnapshot=r.contextTokenSnapshot,r}getSessionId(){return this.sessionId}getMessages(){return[...this.messages]}clear(){this.messages=[],this.sessionId="",this.contextTokenSnapshot=void 0}};function fc(e){return/\bworkflows?\b|工作流(?!程)|ワークフロー|워크플로우/iu.test(e)}o(fc,"hasExplicitNaturalLanguageWorkflowIntent");function Jv(e){return{action:e.source==="command"?"suggest":"none"}}o(Jv,"decideWorkflowInvocation");function Qv(e){return e.outcome==="started"||e.outcome==="cancelled"}o(Qv,"workflowStartOutcomeConsumesTurn");var af="KODAX_VERIFIER_PROVIDER",cf="KODAX_VERIFIER_MODEL";function df(e){if(ot(e))try{return rt(e)}catch{return}}o(df,"tryGetProvider");function Kn(e){let t=e.env??process.env,n=t[af],r=t[cf];if(n&&r){let i=df(n);if(i)return{provider:i,model:r,providerName:n,source:"explicit-env"}}return{provider:e.mainProvider,model:e.mainModel,providerName:e.mainProviderName,source:"inherit-main"}}o(Kn,"resolveVerifierProvider");function Vo(e){let t=e.context?.agentProfile;if(!t)return;let n=t.verification,r=e.context?.taskVerification;if(!n&&!r)return;let i={...n,...r};return Array.isArray(r?.criteria)&&r.criteria.length===0&&Array.isArray(n?.criteria)&&n.criteria.length>0?{...i,criteria:n.criteria}:i}o(Vo,"resolveEffectiveVerification");function uf(e){let t=e.provider??"anthropic";if(ot(t))try{let n=Kn({mainProvider:rt(t),mainProviderName:t,mainModel:e.modelOverride??e.model});return{provider:n.providerName,...n.model!==void 0?{model:n.model}:{}}}catch{return}}o(uf,"resolveVerifierAttribution");function Ko(e,t){let n=e.events?.onEffectiveConfig;if(!n)return;let r=t.verifier??uf(e),i={agentMode:t.agentMode,agentProfile:e.context?.agentProfile,toolScope:t.toolScope,verification:Vo(e),...r?{verifier:r}:{}};try{n(i)}catch{}}o(Ko,"emitEffectiveTaskConfig");var mc="kodax-review-findings",pc="kodax-investigation-shards",gc="kodax-lookup-shards",hc="kodax-child-result";var Tc="kodax-budget-request";function at(e,t=!1){return{globalWorkBudget:e?.totalBudget,budgetUsage:e?.spentBudget,budgetApprovalRequired:t}}o(at,"buildManagedStatusBudgetFields");function en(e,t=1){e.spentBudget=Math.max(0,e.spentBudget+t)}o(en,"incrementManagedBudgetUsage");function ff(e,t=200){e.totalBudget+=t}o(ff,"extendManagedWorkBudget");function zn(e,t,n=!1){if(!e?.askUser)return!1;if(!n){let r=Math.ceil(t.totalBudget*.9);if(t.spentBudget<r)return!1}return t.lastApprovalBudgetTotal!==t.totalBudget}o(zn,"canRequestAdditionalWorkBudget");async function Xo(e,t,n){let r=e?.askUser;if(!r||!zn(e,t,n.force))return"skipped";let i=n.additionalUnits??200,s=Math.min(100,Math.round(t.spentBudget/Math.max(1,t.totalBudget)*100)),a=/[\u4e00-\u9fff]/.test(n.originalTask??n.summary),c=Pe(await r({question:a?`\u5F53\u524D AMA \u8FD0\u884C\u5DF2\u4F7F\u7528 ${t.spentBudget}/${t.totalBudget} \u5DE5\u4F5C\u5355\u5143\uFF08${s}%\uFF09\uFF0C\u9700\u8981\u66F4\u591A\u5DE5\u4F5C\u91CF\u3002\u662F\u5426\u8FFD\u52A0 ${i} \u5355\u5143\uFF1F`:`This AMA run has used ${t.spentBudget}/${t.totalBudget} work units (${s}%) and needs more work. Add ${i} more work units?`,allowCustomInput:!1,options:[{label:a?`\u7EE7\u7EED (+${i})`:`Continue (+${i})`,value:"continue",description:a?`\u8FFD\u52A0 ${i} \u5DE5\u4F5C\u5355\u5143\uFF0C\u4ECE\u7B2C ${n.currentRound}/${n.maxRounds} \u8F6E\u7EE7\u7EED\u3002`:`Grant ${i} more work units and continue from round ${n.currentRound}/${n.maxRounds}.`},{label:a?"\u505C\u6B62":"Stop here",value:"stop",description:a?`\u4F7F\u7528\u5F53\u524D\u6700\u4F73\u7ED3\u679C\u3002\u6700\u65B0\u8FDB\u5C55\uFF1A${To(n.summary,80)}`:`Finish now with the current best result. Latest note: ${To(n.summary,80)}`}],default:"continue"})),d=t.totalBudget;return c==="continue"?(t.lastApprovalBudgetTotal=d,ff(t,i),"approved"):(t.lastApprovalBudgetTotal=d,"denied")}o(Xo,"maybeRequestAdditionalWorkBudget");import{readdir as hf,readFile as yc,stat as Tf}from"node:fs/promises";import{execFile as vf}from"node:child_process";import{promisify as yf}from"node:util";import Et from"node:path";import zo from"node:path";import{mkdir as mf,unlink as pf,writeFile as gf}from"node:fs/promises";function Ve(e){return e.context?.taskSurface??"cli"}o(Ve,"getManagedTaskSurface");function Ke(e,t){if(e.context?.managedTaskWorkspaceDir?.trim())return zo.resolve(e.context.managedTaskWorkspaceDir);let n=e.context?.executionCwd??e.context?.gitRoot??process.cwd();return zo.resolve(n,".agent","managed-tasks")}o(Ke,"getManagedTaskWorkspaceRoot");async function Z(e,t,n="utf8"){await Fr(e,async()=>{await mf(zo.dirname(e),{recursive:!0}),await gf(e,t,"utf8")})}o(Z,"writeManagedTaskFile");async function vc(e){await Fr(e,async()=>{try{await pf(e)}catch(t){if(t.code!=="ENOENT")throw t}})}o(vc,"deleteManagedTaskFile");var kf=yf(vf),kc=3600*1e3,Yn="checkpoint.json";function Yo(e){let t=e.session?.id?.trim();return t||void 0}o(Yo,"getCheckpointSessionId");function Rf(e,t){return t?e.sessionId===t:!1}o(Rf,"checkpointBelongsToSession");async function Jn(e){let t=Et.resolve(e?.trim()||process.cwd());try{let{stdout:n}=await kf("git",["rev-parse","--short","HEAD"],{cwd:t,windowsHide:!0});return n.trim()||void 0}catch{return}}o(Jn,"getGitHeadCommit");async function Jo(e,t){await Z(Et.join(e,Yn),`${JSON.stringify(t,null,2)}
2
+ import{$ as xo,$a as sc,Aa as Qt,Ba as Ma,Ca as Oa,D as Fn,Da as Pa,E as Bn,Ea as Da,F as ua,Fa as bt,G as To,Ga as Na,H as la,Ha as $a,Ia as La,Ja as Ka,K as fa,Ka as Xa,L as ma,La as za,M as pa,Ma as Ya,N as Yt,Na as qn,O as vo,Oa as Ja,Pa as Qa,Qa as Za,R as yo,Ra as ec,S as ko,Sa as tc,T as Ro,Ta as Gn,U as wo,Ua as No,V as ka,Va as $o,W as Ra,Wa as nc,Xa as rc,Y as bo,Ya as oc,Z as Eo,Za as Lo,_a as ic,a as me,ab as ac,ba as So,ca as wa,da as ba,ea as Un,f as $r,fa as _o,h as Ls,i as Lr,ja as Jt,k as jr,l as bn,la as Ea,ma as xa,na as Co,o as Gt,pa as Io,ra as Ao,sa as Sa,ta as _a,va as Mo,wa as Ca,xa as Oo,xc as cc,ya as Ia,yc as Ue,z as ho,za as Aa}from"./chunk-JJ2YDBSN.js";import{a as Po}from"./chunk-7QBWHCIZ.js";import{A as Do,o as Ua,t as Wa,u as qa,v as Ga,y as Ha}from"./chunk-PRASABCC.js";import{$b as Xt,$d as ya,Ba as _n,D as Gs,F as Wr,G as qr,Gd as He,Ha as Kt,Hd as po,I as Gr,Ia as Qr,Ka as Zr,Kb as ra,La as eo,Lb as oa,Mb as ia,Na as to,Oa as no,Od as go,Pb as An,Rb as Mn,S as Vs,Sa as ro,Sb as On,T as Ks,Td as da,V as Xs,Va as oo,Vb as Pn,Vd as ga,W as zs,Wb as Dn,Wd as ha,X as Hr,Xd as Ta,Y as Ys,Yb as co,Yd as va,Za as Cn,Zb as Ge,_a as In,a as wn,ac as uo,b as $s,bb as io,bc as Nn,bd as fo,cc as $n,da as xn,dc as Ln,eb as so,ec as lo,fa as Vr,fb as ao,fc as sa,ga as Kr,gb as na,ha as Sn,ia as Js,ja as Xr,ka as zr,l as Fr,la as Qs,ma as st,me as ja,nd as aa,o as js,oa as Zs,od as ca,p as Br,q as Fs,s as Bs,sd as jn,se as Fa,t as Us,td as zt,te as Wn,u as En,ua as Yr,ue as Ba,v as Ws,va as Jr,w as Ht,wa as ea,we as Va,x as qs,xa as ta,xd as mo,z as Ur,za as Vt,zb as De}from"./chunk-JTZKC4TV.js";import{h as Hs}from"./chunk-GH3KBC2H.js";import{D as nt,Pa as Ee,R as Qi,T as gn,ab as xr,bb as hn,cb as Sr,db as _r,e as Er,fb as Cr,gb as Zi,k as pn,na as rt,ua as ot}from"./chunk-BHE66SP3.js";import{$f as As,Aa as Ar,Ab as gs,B as ts,Db as hs,Eb as Ts,Ga as as,Gb as vs,Ia as Mr,Jb as Or,Kb as Pr,L as ns,Me as Rn,Nb as Rt,O as rs,Ob as ys,Vd as ks,Zd as Rs,_d as ws,_f as wt,fb as cs,g as Tn,gf as bs,ha as Ir,ib as ds,k as re,kg as Ms,l as qe,o as qt,og as Os,pf as Dr,pg as Ps,q as vn,qb as Pe,qf as Es,r as es,rf as xs,rg as Ds,sb as us,t as it,ta as kt,tf as Ss,ua as os,uf as _s,vb as ps,vf as Cs,wa as is,wf as Is,xf as Nr,xg as Ns,za as ss}from"./chunk-7XSZVOG7.js";import{K as ms,h as yn,j as kn,k as ls,p as fs}from"./chunk-QFV6YCIH.js";import{a as o}from"./chunk-ONUPGMER.js";function Xl(){return{retained:[]}}o(Xl,"createOutputSegmentProjection");function zl(e,t){if(t.type==="segment.started"){if(e.active?.responseId===t.responseId&&e.active.providerRequestId===t.providerRequestId&&e.active.mode===t.mode)return{state:e,accepted:!0};let n=e.active?.responseId??e.retained[e.retained.length-1]?.responseId,r=n===void 0||n===t.responseId,i=t.mode==="append"?e.active:void 0;return{accepted:!0,state:{retained:r?i?[...e.retained,i]:e.retained:[],active:{responseId:t.responseId,providerRequestId:t.providerRequestId,mode:t.mode,...t.startedAtSeq!==void 0?{startedAtSeq:t.startedAtSeq}:{},assistantText:"",thinkingText:""}}}}return e.active?.providerRequestId!==t.providerRequestId?{state:e,accepted:!1}:{accepted:!0,state:{...e,active:{...e.active,...t.type==="assistant.delta"?{assistantText:e.active.assistantText+t.text}:{thinkingText:e.active.thinkingText+t.text}}}}}o(zl,"reduceOutputSegmentProjection");function Yl(e,t){let n=t==="assistant"?"assistantText":"thinkingText";return e.retained.map(r=>r[n]).join("")+(e.active?.[n]??"")}o(Yl,"effectiveOutputSegmentText");var Zt=class extends Error{static{o(this,"KodaXError")}code;constructor(t,n="KODAX_ERROR"){super(t),this.code=n,this.name="KodaXError"}};var jo=class extends Zt{static{o(this,"KodaXToolError")}toolName;toolId;constructor(t,n,r){super(t,"TOOL_ERROR"),this.toolName=n,this.toolId=r,this.name="KodaXToolError"}};var Fo=class extends Zt{static{o(this,"KodaXSessionError")}sessionId;constructor(t,n){super(t,"SESSION_ERROR"),this.sessionId=n,this.name="KodaXSessionError"}},Bo=class extends Zt{static{o(this,"KodaXTerminalError")}suggestions;constructor(t,n=[]){super(t,"TERMINAL_ERROR"),this.name="KodaXTerminalError",this.suggestions=n}};function Jl(){return new Hn}o(Jl,"createSessionControl");function Uo(e,t){let n=new AbortController,r=!1,i=o(p=>{r||(r=!0,n.abort(p))},"markAborted");e.abortSignal&&(e.abortSignal.aborted?i(e.abortSignal.reason):e.abortSignal.addEventListener("abort",()=>i(e.abortSignal.reason),{once:!0}));let s=new Hn;s.seed({provider:e.provider,model:e.modelOverride??e.model,reasoning:e.reasoningMode});let a=e.session?.id,c=a!=null,d=a??Ql(),f=!c&&e.session?.autoResume!==!0&&e.session?.resume!==!0?oc({...e.session??{},id:d}):e.session,u={...e,...e.agentMode!==void 0?{agentMode:Gt(e.agentMode)}:{},...f!==void 0?{session:f}:{},abortSignal:n.signal,sessionControl:s},h=Ue(u,t);return{id:d,get currentProvider(){return s.getProvider()},get currentModel(){return s.getModel()},get currentReasoning(){return s.getReasoning()},get aborted(){return r},get attached(){return s.isAttached()},setProvider:o(p=>s.setProvider(p),"setProvider"),setModel:o(p=>s.setModel(p),"setModel"),setReasoning:o(p=>s.setReasoning(p),"setReasoning"),abort:o(p=>i(p),"abort"),result:h}}o(Uo,"startKodaX");function Ql(){return`sess_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}o(Ql,"generateSessionId");var Hn=class{static{o(this,"SessionControlImpl")}mutators=null;providerValue;modelValue;reasoningValue;hasPendingProvider=!1;hasPendingModel=!1;hasPendingReasoning=!1;seed(t){this.providerValue=t.provider,this.modelValue=t.model,this.reasoningValue=t.reasoning}setProvider(t){this.providerValue=t,this.mutators?this.mutators.setProvider(t):this.hasPendingProvider=!0}setModel(t){this.modelValue=t,this.mutators?this.mutators.setModel(t):this.hasPendingModel=!0}setReasoning(t){this.reasoningValue=t,this.mutators?this.mutators.setReasoning(t):this.hasPendingReasoning=!0}getProvider(){return this.providerValue??""}getModel(){return this.modelValue}getReasoning(){return this.reasoningValue}isAttached(){return this.mutators!==null}_attach(t){this.mutators,this.mutators=t,this.hasPendingProvider&&this.providerValue!==void 0&&t.setProvider(this.providerValue),this.hasPendingModel&&t.setModel(this.modelValue),this.hasPendingReasoning&&t.setReasoning(this.reasoningValue),this.hasPendingProvider=!1,this.hasPendingModel=!1,this.hasPendingReasoning=!1}};function Zl(e,t){return e.kind!=="revise_count"?{ok:!0}:e.count<=3?{ok:!0}:{ok:!1,severity:"warn",reason:`boundedRevise: revise_count for harness="${e.harness}" reached ${e.count}, exceeding soft threshold 3`}}o(Zl,"observe");var Wo={id:"boundedRevise",description:"Per-harness revise count must stay within the soft threshold; crossings emit a warn signal for dispatch-eval (hard cap enforced by the budget controller).",observe:Zl};function ef(e,t){return typeof e.maxBudget!="number"?{ok:!0}:e.maxBudget<=t.systemCap.maxBudget?{ok:!0}:{ok:!1,severity:"clamp",reason:`budgetCeiling: manifest.maxBudget=${e.maxBudget} exceeds systemCap.maxBudget=${t.systemCap.maxBudget}`,patch:{clampMaxBudget:t.systemCap.maxBudget}}}o(ef,"admit");var qo={id:"budgetCeiling",description:"manifest.maxBudget must be \u2264 systemCap.maxBudget; over-cap declarations are clamped down to the cap.",admit:ef};function tf(e,t){return{ok:!0}}o(tf,"observe");var dc={id:"harnessSelectionTiming",description:"FEATURE_193 V2 no-op shell \u2014 predicate always admits since V1 Scout retired. Kept registered for admission-framework / audit-array compat.",observe:tf};function nf(e,t){if(e.kind!=="mutation_recorded")return{ok:!0};let n=t.recorder;return typeof n.todoUpdateCount!="number"?{ok:!0}:n.todoUpdateCount>0?{ok:!0}:n.workerTrivialDeclaration===!0?{ok:!0}:{ok:!1,severity:"warn",reason:`planBeforeMutate: Worker mutated ${e.file} without a prior todo_update plan commit and without a trivial declaration`}}o(nf,"observe");var uc={id:"planBeforeMutate",description:"Worker mutations should be preceded by a todo_update plan commit (or an explicit trivial declaration). Missing plan is a warn-only signal in v0.7.36.",observe:nf};function Go(e){switch(e){case"read":case"glob":case"grep":case"code_search":case"semantic_lookup":case"lsp_definition":case"lsp_hover":case"lsp_references":case"lsp_document_symbols":case"lsp_workspace_symbols":case"lsp_implementation":case"lsp_prepare_call_hierarchy":case"lsp_incoming_calls":case"lsp_outgoing_calls":case"repo_overview":case"changed_scope":case"changed_diff":case"changed_diff_bundle":case"module_context":case"symbol_context":case"process_context":case"impact_estimate":case"relationship_scan":case"cyclic_dependencies":case"ask_user_question":case"exit_plan_mode":return"read";case"write":case"edit":case"multi_edit":case"insert_after_anchor":case"undo":return"edit";case"bash":return"bash:mutating";case"web_search":case"web_fetch":case"mcp_search":case"mcp_describe":case"mcp_call":case"mcp_read_resource":case"mcp_get_prompt":return"bash:network";case"spawn_agent":case"send_message":case"followup_task":case"wait_agent":case"interrupt_agent":case"list_agents":case"agent_output":case"emit_verdict":case"scaffold_tool":case"validate_tool":case"stage_construction":case"test_tool":case"activate_tool":case"scaffold_agent":case"validate_agent":case"stage_agent_construction":case"test_agent":case"activate_agent":case"worktree_create":case"worktree_remove":return"subagent";default:return"subagent"}}o(Go,"resolveToolCapability");function rf(e){if(typeof e=="object"&&e!==null&&"name"in e){let t=e.name;if(typeof t=="string"&&t.length>0)return t}}o(rf,"getToolName");function of(e,t){if(!e.tools||e.tools.length===0)return{ok:!0};let n=new Set(t.systemCap.allowedToolCapabilities),r=[];for(let a of e.tools){let c=rf(a);if(!c)continue;let d=Go(c);n.has(d)||r.push({name:c,capability:d})}if(r.length===0)return{ok:!0};let i=r.map(a=>a.name);return{ok:!1,severity:"clamp",reason:`toolPermission: tools requiring disallowed capabilities \u2014 ${r.map(a=>`${a.name}=${a.capability}`).join(", ")}`,patch:{removeTools:i}}}o(of,"admit");var Ho={id:"toolPermission",description:"Every tool in manifest.tools must resolve to a capability tier that systemCap.allowedToolCapabilities permits; offending tools are clamped via removeTools.",admit:of};var lc=[qo,Ho,Wo,dc,uc];function sf(){as();for(let e of lc)rs(e)}o(sf,"registerCodingInvariants");var Vn=class{static{o(this,"KodaXClient")}options;sessionId;messages=[];contextTokenSnapshot;constructor(t){this.options=t,this.sessionId=t.session?.id??"",this.messages=t.session?.initialMessages?[...t.session.initialMessages]:[],this.contextTokenSnapshot=t.context?.contextTokenSnapshot}async send(t){let n=this.messages.length>0?this.messages:this.options.session?.initialMessages,r=await Ue({...this.options,session:{...this.options.session,id:this.sessionId||void 0,initialMessages:n},context:{...this.options.context,contextTokenSnapshot:this.contextTokenSnapshot}},t);return this.sessionId=r.sessionId,this.messages=r.messages,this.contextTokenSnapshot=r.contextTokenSnapshot,r}getSessionId(){return this.sessionId}getMessages(){return[...this.messages]}clear(){this.messages=[],this.sessionId="",this.contextTokenSnapshot=void 0}};function fc(e){return/\bworkflows?\b|工作流(?!程)|ワークフロー|워크플로우/iu.test(e)}o(fc,"hasExplicitNaturalLanguageWorkflowIntent");function Jv(e){return{action:e.source==="command"?"suggest":"none"}}o(Jv,"decideWorkflowInvocation");function Qv(e){return e.outcome==="started"||e.outcome==="cancelled"}o(Qv,"workflowStartOutcomeConsumesTurn");var af="KODAX_VERIFIER_PROVIDER",cf="KODAX_VERIFIER_MODEL";function df(e){if(ot(e))try{return rt(e)}catch{return}}o(df,"tryGetProvider");function Kn(e){let t=e.env??process.env,n=t[af],r=t[cf];if(n&&r){let i=df(n);if(i)return{provider:i,model:r,providerName:n,source:"explicit-env"}}return{provider:e.mainProvider,model:e.mainModel,providerName:e.mainProviderName,source:"inherit-main"}}o(Kn,"resolveVerifierProvider");function Vo(e){let t=e.context?.agentProfile;if(!t)return;let n=t.verification,r=e.context?.taskVerification;if(!n&&!r)return;let i={...n,...r};return Array.isArray(r?.criteria)&&r.criteria.length===0&&Array.isArray(n?.criteria)&&n.criteria.length>0?{...i,criteria:n.criteria}:i}o(Vo,"resolveEffectiveVerification");function uf(e){let t=e.provider??"anthropic";if(ot(t))try{let n=Kn({mainProvider:rt(t),mainProviderName:t,mainModel:e.modelOverride??e.model});return{provider:n.providerName,...n.model!==void 0?{model:n.model}:{}}}catch{return}}o(uf,"resolveVerifierAttribution");function Ko(e,t){let n=e.events?.onEffectiveConfig;if(!n)return;let r=t.verifier??uf(e),i={agentMode:t.agentMode,agentProfile:e.context?.agentProfile,toolScope:t.toolScope,verification:Vo(e),...r?{verifier:r}:{}};try{n(i)}catch{}}o(Ko,"emitEffectiveTaskConfig");var mc="kodax-review-findings",pc="kodax-investigation-shards",gc="kodax-lookup-shards",hc="kodax-child-result";var Tc="kodax-budget-request";function at(e,t=!1){return{globalWorkBudget:e?.totalBudget,budgetUsage:e?.spentBudget,budgetApprovalRequired:t}}o(at,"buildManagedStatusBudgetFields");function en(e,t=1){e.spentBudget=Math.max(0,e.spentBudget+t)}o(en,"incrementManagedBudgetUsage");function ff(e,t=200){e.totalBudget+=t}o(ff,"extendManagedWorkBudget");function zn(e,t,n=!1){if(!e?.askUser)return!1;if(!n){let r=Math.ceil(t.totalBudget*.9);if(t.spentBudget<r)return!1}return t.lastApprovalBudgetTotal!==t.totalBudget}o(zn,"canRequestAdditionalWorkBudget");async function Xo(e,t,n){let r=e?.askUser;if(!r||!zn(e,t,n.force))return"skipped";let i=n.additionalUnits??200,s=Math.min(100,Math.round(t.spentBudget/Math.max(1,t.totalBudget)*100)),a=/[\u4e00-\u9fff]/.test(n.originalTask??n.summary),c=Pe(await r({question:a?`\u5F53\u524D AMA \u8FD0\u884C\u5DF2\u4F7F\u7528 ${t.spentBudget}/${t.totalBudget} \u5DE5\u4F5C\u5355\u5143\uFF08${s}%\uFF09\uFF0C\u9700\u8981\u66F4\u591A\u5DE5\u4F5C\u91CF\u3002\u662F\u5426\u8FFD\u52A0 ${i} \u5355\u5143\uFF1F`:`This AMA run has used ${t.spentBudget}/${t.totalBudget} work units (${s}%) and needs more work. Add ${i} more work units?`,allowCustomInput:!1,options:[{label:a?`\u7EE7\u7EED (+${i})`:`Continue (+${i})`,value:"continue",description:a?`\u8FFD\u52A0 ${i} \u5DE5\u4F5C\u5355\u5143\uFF0C\u4ECE\u7B2C ${n.currentRound}/${n.maxRounds} \u8F6E\u7EE7\u7EED\u3002`:`Grant ${i} more work units and continue from round ${n.currentRound}/${n.maxRounds}.`},{label:a?"\u505C\u6B62":"Stop here",value:"stop",description:a?`\u4F7F\u7528\u5F53\u524D\u6700\u4F73\u7ED3\u679C\u3002\u6700\u65B0\u8FDB\u5C55\uFF1A${To(n.summary,80)}`:`Finish now with the current best result. Latest note: ${To(n.summary,80)}`}],default:"continue"})),d=t.totalBudget;return c==="continue"?(t.lastApprovalBudgetTotal=d,ff(t,i),"approved"):(t.lastApprovalBudgetTotal=d,"denied")}o(Xo,"maybeRequestAdditionalWorkBudget");import{readdir as hf,readFile as yc,stat as Tf}from"node:fs/promises";import{execFile as vf}from"node:child_process";import{promisify as yf}from"node:util";import Et from"node:path";import zo from"node:path";import{mkdir as mf,unlink as pf,writeFile as gf}from"node:fs/promises";function Ve(e){return e.context?.taskSurface??"cli"}o(Ve,"getManagedTaskSurface");function Ke(e,t){if(e.context?.managedTaskWorkspaceDir?.trim())return zo.resolve(e.context.managedTaskWorkspaceDir);let n=e.context?.executionCwd??e.context?.gitRoot??process.cwd();return zo.resolve(n,".agent","managed-tasks")}o(Ke,"getManagedTaskWorkspaceRoot");async function Z(e,t,n="utf8"){await Fr(e,async()=>{await mf(zo.dirname(e),{recursive:!0}),await gf(e,t,"utf8")})}o(Z,"writeManagedTaskFile");async function vc(e){await Fr(e,async()=>{try{await pf(e)}catch(t){if(t.code!=="ENOENT")throw t}})}o(vc,"deleteManagedTaskFile");var kf=yf(vf),kc=3600*1e3,Yn="checkpoint.json";function Yo(e){let t=e.session?.id?.trim();return t||void 0}o(Yo,"getCheckpointSessionId");function Rf(e,t){return t?e.sessionId===t:!1}o(Rf,"checkpointBelongsToSession");async function Jn(e){let t=Et.resolve(e?.trim()||process.cwd());try{let{stdout:n}=await kf("git",["rev-parse","--short","HEAD"],{cwd:t,windowsHide:!0});return n.trim()||void 0}catch{return}}o(Jn,"getGitHeadCommit");async function Jo(e,t){await Z(Et.join(e,Yn),`${JSON.stringify(t,null,2)}
3
3
  `,"utf8")}o(Jo,"writeCheckpoint");async function ct(e){await vc(Et.join(e,Yn))}o(ct,"deleteCheckpoint");async function Qo(e){let t=e.context?.gitRoot,n=Ve(e),r=Ke(e,n),i;try{i=await hf(r)}catch{return}let s=await Jn(t),a=Yo(e),c=Date.now();for(let d of i){let l=Et.join(r,d),f=Et.join(l,Yn);try{let u=await Tf(f);if(!u.isFile())continue;let h=await yc(f,"utf8"),p=JSON.parse(h);if(!p||typeof p!="object")continue;let m=p;if(m.version!==1||typeof m.taskId!="string"||typeof m.createdAt!="string"||typeof m.gitCommit!="string"||typeof m.harnessProfile!="string"||m.sessionId!==void 0&&typeof m.sessionId!="string")continue;if(m.processId!==void 0||m.pid!==void 0){let M=m.processId??m.pid;if(typeof M!="number"||!Number.isFinite(M))continue}let v=m.processId??m.pid,g={version:1,taskId:m.taskId,...typeof m.sessionId=="string"&&m.sessionId.trim()?{sessionId:m.sessionId}:{},...typeof v=="number"&&Number.isFinite(v)?{processId:v}:{},createdAt:m.createdAt,gitCommit:m.gitCommit,objective:typeof m.objective=="string"?m.objective:"",harnessProfile:m.harnessProfile,currentRound:typeof m.currentRound=="number"?m.currentRound:1,completedWorkerIds:Array.isArray(m.completedWorkerIds)?m.completedWorkerIds.filter(M=>typeof M=="string"):[],scoutCompleted:m.scoutCompleted===!0},y=new Date(g.createdAt).getTime();if(Number.isNaN(y))continue;let R=c-u.mtimeMs;if(R>kc||R<0){await ct(l);continue}if(!Rf(g,a))continue;if(s&&g.gitCommit&&g.gitCommit!==s){await ct(l);continue}let k=Et.join(l,"managed-task.json"),x=await yc(k,"utf8"),S=JSON.parse(x);if(!S||typeof S!="object")continue;let _=S;if(!_.contract?.taskId||!_.evidence?.workspaceDir)continue;return{checkpoint:g,workspaceDir:l,managedTask:_}}catch{continue}}}o(Qo,"findValidCheckpoint");import F from"node:path";function Zo(e){let t=e?.runtime;return t?`${["# Runtime Execution Guide","","Use this guide to drive live verification against the runtime under test.","",t.cwd?`- Working directory: ${t.cwd}`:void 0,t.startupCommand?`- Startup command: ${t.startupCommand}`:void 0,t.readySignal?`- Ready signal: ${t.readySignal}`:void 0,t.baseUrl?`- Base URL: ${t.baseUrl}`:void 0,t.env&&Object.keys(t.env).length>0?`- Environment keys: ${Object.keys(t.env).join(", ")}`:void 0,"","Execution protocol:",t.startupCommand?"1. Start or confirm the runtime using the declared startup command before accepting the task.":"1. Confirm the target runtime is available before accepting the task.",t.readySignal||t.baseUrl?"2. Wait until the runtime is ready, using the ready signal or base URL when available.":"2. Confirm runtime readiness using the strongest observable signal you have.",t.uiFlows?.length?["3. Execute the declared UI flows:",...t.uiFlows.map((r,i)=>` ${i+1}. ${r}`)].join(`
4
4
  `):"3. Execute the critical user-facing flow when browser verification is required.",t.apiChecks?.length?["4. Run the declared API checks:",...t.apiChecks.map((r,i)=>` ${i+1}. ${r}`)].join(`
5
5
  `):void 0,t.dbChecks?.length?["5. Run the declared DB checks:",...t.dbChecks.map((r,i)=>` ${i+1}. ${r}`)].join(`
@@ -134,7 +134,7 @@ ${n}`:n:[...r.content,{type:"text",text:n}];return[...e.slice(0,-1),{...r,conten
134
134
 
135
135
  `),_=y.slice(k),M=f?.(),w=m;m=[];let N=[];if(s&&d){let b=Gd(d,s);b&&w.push(b);let B=Wd(d,s,_);B&&w.push(B)}if(s&&a){if(pd(a,R.name)&&rr(a),ld(a,s)){let b=md(s,a.roundsSinceUpdate.current);w.push(b)}fd(a)}if(w.length>0){let b=[..._].reverse().find($=>$.turnId!==void 0||$.timestamp!==void 0),B={role:"user",content:w.join(`
136
136
 
137
- `),_synthetic:!0,_source:"managed-runtime-reminder",turnId:b?.turnId,timestamp:b?.timestamp??new Date().toISOString()},U=_.at(-1);U?.role==="user"&&U._synthetic!==!0&&(typeof U.content=="string"||U.content.some($=>$.type!=="tool_result"))?m=w:(N.push(B),_=[..._,B])}let H=(R.tools??[]).map(b=>({name:b.name,description:b.description,input_schema:b.input_schema})),C=wi(e,R);h.current+=1,e.events?.onIterationStart?.(h.current,p);let E;if(t)E=await t(_,H,S,M);else{let b=Ee(e.provider??"anthropic"),B=e.provider??b.name??"anthropic",U=typeof b.supportsEphemeralSuffix=="function"&&b.supportsEphemeralSuffix(),ye=U?M:void 0,$=o(X=>U?[...X]:_g(X,M),"lowerProviderMessages"),oe=e.context?.contextIdentitySessionId??e.session?.id,de=e.context?.currentAgentId,Ne=e.context?.parentAgentId,gt=oe===void 0?void 0:de===void 0?oe:`${oe}/agent/${encodeURIComponent(de)}`,$t={...gt!==void 0?{contextId:gt}:{},contextKind:de!==void 0?"child":"root",...oe!==void 0&&de!==void 0?{parentContextId:Ne===void 0||Ne==="/root"?oe:`${oe}/agent/${encodeURIComponent(Ne)}`}:{},...de!==void 0?{agentId:de}:{}},$e=gn(e.disablePromptCache)?void 0:Gn({logicalSessionId:oe,...de!==void 0?{agentId:de}:{}}),Qe=o(X=>{if(!(e.context?.contextDiagnostics!==!0||!e.events?.onContextBudgetSnapshot))try{let ne=Qa(S,X,b),fe=l?.contextWindow??b.getEffectiveContextWindow(g),ae=[...ne.messages].reverse().find(j=>j.turnId!==void 0)?.turnId,W=M?.content?[...ne.messages,{role:"user",content:M.content,_synthetic:!0,_source:"managed-run-context",...ae!==void 0?{turnId:ae}:{}}]:ne.messages,be=pa(W,{skillTexts:[l?.skillCatalogText,l?.selectedSkillText].filter(j=>j!==void 0),mcpTexts:l?.mcpCatalogText?[l.mcpCatalogText]:[]});e.events.onContextBudgetSnapshot(vo({sessionId:e.session?.id,turnId:ae,...$t,provider:B,model:g??b.getModel?.()??"unknown",contextWindow:fe,systemPrompt:ne.system,toolDefinitions:H,messageTokenBreakdown:be,reservedResponseTokens:b.getEffectiveMaxOutputTokens(g),profile:"report_only"}))}catch(ne){me("[context-diagnostics:budget-error]",{error:ne instanceof Error?ne.message:String(ne)})}},"emitContextBudgetSnapshot"),Se=o((X,ne,fe="stream")=>ec({events:e.events,enabled:e.context?.contextDiagnostics===!0,provider:b,providerName:B,...$t,model:g??b.getModel?.()??"unknown",reasoning:C,disablePromptCache:e.disablePromptCache,system:S,tools:H,messages:X,...M!==void 0?{ephemeralSuffix:M}:{},...$e!==void 0?{promptCacheKey:$e}:{},attempt:ne,transport:fe}),"beginPromptCacheDiagnostic"),Ze=o((X,ne)=>{tc(e.events,X,ne)},"completePromptCacheDiagnostic"),ke=bo(B,Po(e.timeouts)),Lt=ke.requestTimeoutMs,et=ke.streamIdleTimeoutMs,ue=new xo,un=typeof b.supportsNonStreamingFallback=="function"?b.supportsNonStreamingFallback():!1,Re=new So(ue,{...ke,enableNonStreamingFallback:ke.enableNonStreamingFallback&&un}),P=[..._];P=Pr(P),P=Or(P);let Q=0,G,ht=!1,we=0,he=[...P].reverse().find(X=>X.turnId!==void 0)?.turnId??`response_${xg().replace(/-/g,"")}`,Ie="append";for(;;){Pt(e.abortSignal,P),Q+=1;let X=$(P);ue.beginRequest(B,g??b.getModel?.()??"unknown",X,Q,!1);let ne=ue.snapshot();Un(ne);let fe={providerRequestId:ne.requestId};e.events?.onOutputSegmentStart?.({responseId:he,providerRequestId:ne.requestId,mode:Ie},fe);let ae=new AbortController,W=setTimeout(()=>{ae.abort(new Error("API Hard Timeout (10 minutes)"))},Lt),be=et>0,j;be&&(j=setTimeout(()=>{ae.abort(new Error(`Stream stalled or delayed response (${et}ms idle)`))},et));let je=o(()=>{be&&(j&&clearTimeout(j),ae.signal.aborted||(j=setTimeout(()=>{ae.abort(new Error(`Stream stalled or delayed response (${et}ms idle)`))},et)))},"resetIdleTimer"),z=e.abortSignal?AbortSignal.any([e.abortSignal,ae.signal]):ae.signal,We=Sa(P,S)+Buffer.byteLength(M?.content??"","utf8");me("[resilience:request]",{provider:B,attempt:Q,fallbackActive:!1,payloadBytes:We,payloadBucket:_a(We)});let Ae={promptCacheKey:$e,modelOverride:g,ephemeralSuffix:ye,onTextDelta:o(q=>{ue.markTextDelta(q),je();let Me=q.includes("```")||tn.some(vt=>q.includes(vt))?di(q):q;Me.length!==0&&e.events?.onTextDelta?.(Me,fe)},"onTextDelta"),onThinkingDelta:o(q=>{ue.markThinkingDelta(q),je(),e.events?.onThinkingDelta?.(q,fe)},"onThinkingDelta"),onThinkingEnd:o(q=>{e.events?.onThinkingEnd?.(q,fe)},"onThinkingEnd"),onToolInputDelta:e.events?.onToolInputDelta,onRateLimit:o((q,ce,Me)=>{je(),e.events&&bt(e.events,q,ce,Me)},"onRateLimit"),onRetryAfter:o(q=>{je(),v=hn(v,{provider:q.provider,waitMs:q.waitMs,reason:q.reason,source:q.source}),e.events?.onRetryAfter?.(q)},"onRetryAfter")};try{Qe(P);let q=Se(P,Q);if(G=await b.stream(X,[...H],S,C,Ae,z),Ze(q,G.usage),G.stopReason==="max_tokens"&&!ht&&!process.env.KODAX_MAX_OUTPUT_TOKENS&&b.getEffectiveMaxOutputTokens(g)<64e3){Pt(e.abortSignal,P),ht=!0,b.setMaxOutputTokensOverride(64e3),e.events?.onRetry?.(`Output budget reached, escalating to ${64e3} tokens and retrying the same turn`,1,1),W&&clearTimeout(W),j&&clearTimeout(j),W=void 0,j=void 0,Q-=1,Ie="replace";continue}if(vu(G)&&G.stopReason!=="max_tokens"&&we<En&&!e.abortSignal?.aborted){we+=1,e.events?.onRetry?.(`Provider returned an empty turn, retrying ${we}/${En}`,we,En),W&&clearTimeout(W),j&&clearTimeout(j),W=void 0,j=void 0,Q-=1,Ie="replace",await Ri(Ws*we,e.abortSignal,P);continue}break}catch(q){let ce=q instanceof Error?q:new Error(String(q));if(ce.name==="AbortError"&&ae.signal.aborted&&!e.abortSignal?.aborted){let Ce=ae.signal.reason?.message??"Stream stalled",{KodaXNetworkError:Fe}=await import("./dist-WNMK42WE.js");ce=new Fe(Ce,!0)}ki(e.abortSignal,ce,P);let Me=ue.inferFailureStage(),vt=Eo(ce,Me);wa(ce,vt);let Y=Re.decideRecoveryAction(ce,vt,Q);if(ba(Y,Q),e.events?.onProviderRecovery?.({stage:Y.failureStage,errorClass:Y.reasonCode,attempt:Q,maxAttempts:ke.maxRetries,delayMs:Y.delayMs,recoveryAction:Y.action,ladderStep:Y.ladderStep,fallbackUsed:Y.shouldUseNonStreaming,serverRetryAfterMs:Y.serverRetryAfterMs}),Y.reasonCode==="rate_limit"&&e.events&&bt(e.events,Q,ke.maxRetries,Y.delayMs),!e.events?.onProviderRecovery&&Y.action!=="manual_continue"&&e.events?.onRetry?.(`${Ya(ce)} \xB7 retry ${Q}/${ke.maxRetries} in ${Math.round(Y.delayMs/1e3)}s`,Q,ke.maxRetries),Y.shouldUseNonStreaming&&typeof b.complete=="function"){Pt(e.abortSignal,P);let Ce=new AbortController,Fe=e.abortSignal?AbortSignal.any([e.abortSignal,Ce.signal]):Ce.signal,vr=setTimeout(()=>{Ce.abort(new Error("API Hard Timeout (10 minutes)"))},Lt);try{j&&clearTimeout(j),W&&clearTimeout(W),W=void 0,j=void 0;let Be=$(P);ue.beginRequest(B,g??b.getModel?.()??"unknown",Be,Q,!0);let jt=ue.snapshot();Un(jt);let tt={providerRequestId:jt.requestId};e.events?.onOutputSegmentStart?.({responseId:he,providerRequestId:jt.requestId,mode:"replace"},tt),Qe(P);let Ft=Se(P,Q,"complete");G=await b.complete(Be,[...H],S,C,{promptCacheKey:$e,modelOverride:g,ephemeralSuffix:ye,onTextDelta:o(Te=>{ue.markTextDelta(Te),e.events?.onTextDelta?.(Te,tt)},"onTextDelta"),onThinkingDelta:o(Te=>{ue.markThinkingDelta(Te),e.events?.onThinkingDelta?.(Te,tt)},"onThinkingDelta"),onThinkingEnd:o(Te=>{e.events?.onThinkingEnd?.(Te,tt)},"onThinkingEnd"),signal:Fe},Fe),Ze(Ft,G.usage);break}catch(Be){ce=Be instanceof Error?Be:new Error(String(Be)),ki(e.abortSignal,ce,P)}finally{clearTimeout(vr)}}if(Y.action==="sanitize_thinking_and_retry"){let Ce=Re.executeRecovery(P,Y);_o(Y.action,Ce),P=Ce.messages,W&&clearTimeout(W),j&&clearTimeout(j),W=void 0,j=void 0,Q-=1,Ie="replace",await Ri(Y.delayMs,e.abortSignal,P);continue}if(Y.action==="manual_continue"||Q>=ke.maxRetries)throw kt(ce,P),ce;let yt=Re.executeRecovery(P,Y);_o(Y.action,yt),P=yt.messages,Ie="replace",W&&clearTimeout(W),j&&clearTimeout(j),W=void 0,j=void 0,await Ri(Y.delayMs,e.abortSignal,P);continue}finally{W&&clearTimeout(W),j&&clearTimeout(j)}}if(vu(G)){let X=new Er("Provider returned no user-visible text or tool calls after recovery attempts; refusing to commit an empty assistant turn.",B);throw kt(X,P),X}let Le=0,_e=(G.textBlocks??[]).map(X=>X.text).join(""),Tt=G.thinkingBlocks?[...G.thinkingBlocks]:void 0;for(;G.stopReason==="max_tokens"&&(G.toolBlocks?.length??0)===0&&_e.trim().length>0&&Le<3;){Pt(e.abortSignal,P),Le+=1;let X=[...Tt??[],{type:"text",text:_e}];P=[...P,{role:"assistant",content:X},{role:"user",content:[{type:"text",text:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."}]}],e.events?.onRetry?.(`max_tokens mid-text, appending continuation ${Le}/${3}`,Le,3);let ne=e.abortSignal??void 0,fe="";try{let W=$(P);ue.beginRequest(B,g??b.getModel?.()??"unknown",W,Q+Le,!1);let be=ue.snapshot();Un(be);let j={providerRequestId:be.requestId};e.events?.onOutputSegmentStart?.({responseId:he,providerRequestId:be.requestId,mode:"append"},j),Qe(P);let je=Se(P,Q+Le);G=await b.stream(W,[...H],S,C,{promptCacheKey:$e,modelOverride:g,ephemeralSuffix:ye,onTextDelta:o(z=>{let Ae=z.includes("```")||tn.some(q=>z.includes(q))?di(z):z;Ae.length!==0&&(fe+=Ae,ue.markTextDelta(z),e.events?.onTextDelta?.(Ae,j))},"onTextDelta"),onThinkingDelta:o(z=>{ue.markThinkingDelta(z),e.events?.onThinkingDelta?.(z,j)},"onThinkingDelta"),onThinkingEnd:o(z=>{e.events?.onThinkingEnd?.(z,j)},"onThinkingEnd"),onToolInputDelta:e.events?.onToolInputDelta,onRateLimit:o((z,We,Ae)=>{e.events&&bt(e.events,z,We,Ae)},"onRateLimit"),onRetryAfter:o(z=>{v=hn(v,{provider:z.provider,waitMs:z.waitMs,reason:z.reason,source:z.source}),e.events?.onRetryAfter?.(z)},"onRetryAfter")},ne),Ze(je,G.usage)}catch(W){ki(e.abortSignal,W instanceof Error?W:new Error(String(W)),P),_e+=fe;break}let ae=(G.textBlocks??[]).map(W=>W.text).join("");if(ae&&(_e+=ae),G.thinkingBlocks&&Tt&&Tt.push(...G.thinkingBlocks),(G.toolBlocks?.length??0)>0||G.stopReason!=="max_tokens")break}E={textBlocks:_e?[{text:_e}]:G.textBlocks,toolBlocks:G.toolBlocks,thinkingBlocks:Tt??G.thinkingBlocks,usage:G.usage}}if(n&&E.usage){let b=n.current;n.current={totalTokens:E.usage.totalTokens??b.totalTokens,lastUsage:E.usage,source:"api"}}if(E.usage){let b=e.provider??"anthropic";v=Sr(v,{provider:b,model:e.modelOverride??e.model??"unknown",inputTokens:E.usage.inputTokens,outputTokens:E.usage.outputTokens,cacheReadTokens:E.usage.cachedReadTokens,cacheWriteTokens:E.usage.cachedWriteTokens})}if(e.events&&Oa(e.events),e.events?.onIterationEnd){let b=E.usage,B=b?.totalTokens??b?.outputTokens??0;e.events.onIterationEnd({iter:h.current,maxIter:p,tokenCount:B,tokenSource:b?"api":"estimate",usage:b,scope:"worker"})}let K=(E.textBlocks??[]).map(b=>b.text).join(""),te=(E.toolBlocks??[]).map(b=>({id:b.id,name:b.name,input:b.input??{}})),se=E.thinkingBlocks,ge={text:K,toolCalls:te,thinkingBlocks:se,injectedInputMessages:N};if(i){let b=[...y,...N,Ir(ge)],B=E.usage?.totalTokens;if(typeof B=="number"&&Number.isFinite(B)&&B>=0)i.current={currentTokens:B,baselineEstimatedTokens:re(b),source:"api",usage:E.usage};else{let U=[..._,Ir(ge)];i.current={currentTokens:Sg(U,H,S,M),baselineEstimatedTokens:re(b),source:"estimate"}}}return ge}}o(ku,"buildRunnerLlmAdapter");import Ig from"node:path";function lr(e,t,n){return Math.max(t,Math.min(n,e))}o(lr,"clampNumber");function Ru(e,t){return e?.rubricFamily?e.rubricFamily:e?.capabilityHints?.some(n=>/agent-browser|playwright/i.test(n.name))?"frontend":t==="review"?"code-review":t==="bugfix"?"functionality":"code-quality"}o(Ru,"inferVerificationRubricFamily");function Cg(e,t){if(e?.criteria?.length)return e.criteria.map(s=>({...s,threshold:lr(s.threshold,0,100),weight:lr(s.weight,0,1)}));let n=Ru(e,t),r=e?.requiredEvidence??[],i=e?.requiredChecks??[];return n==="frontend"?[{id:"ui-flow",label:"UI flow verification",description:"Critical browser path completes without visible breakage.",threshold:75,weight:.4,requiredEvidence:r},{id:"console-clean",label:"Console and runtime health",description:"Browser or app runtime should not show blocking errors.",threshold:75,weight:.25,requiredEvidence:r},{id:"check-evidence",label:"Deterministic checks",description:"Required checks or tests must be explicitly reported.",threshold:70,weight:.35,requiredEvidence:[...r,...i]}]:n==="code-review"?[{id:"finding-accuracy",label:"Finding accuracy",description:"Reported issues should be grounded in concrete evidence.",threshold:80,weight:.45,requiredEvidence:r},{id:"verification",label:"Independent verification",description:"Claims should be independently verified before acceptance.",threshold:75,weight:.35,requiredEvidence:[...r,...i]},{id:"completeness",label:"Review completeness",description:"High-risk changes should not truncate before the critical findings are delivered.",threshold:70,weight:.2,requiredEvidence:r}]:[{id:"functionality",label:"Functional correctness",description:"The requested behavior is implemented and evidenced.",threshold:75,weight:.5,requiredEvidence:r},{id:"checks",label:"Check coverage",description:"Relevant checks and validation evidence are reported.",threshold:70,weight:.3,requiredEvidence:[...r,...i]},{id:"quality",label:"Quality and safety",description:"The result does not leave obvious correctness or safety gaps behind.",threshold:70,weight:.2,requiredEvidence:r}]}o(Cg,"resolveVerificationCriteria");function wu(e,t){let n=e.contract.verification;if(!n)return;let r=Cg(n,e.contract.primaryTask).map(c=>{let d=[...c.requiredEvidence??[],...e.evidence.entries.filter(u=>u.status==="completed"&&u.summary).map(u=>u.summary).slice(-2)],l=t?.status==="accept"?100:t?.status==="revise"?45:e.verdict.status==="completed"?90:e.verdict.status==="blocked"?35:55,f=lr(l,0,100);return{id:c.id,label:c.label,threshold:c.threshold,score:f,passed:f>=c.threshold,weight:c.weight,requiredEvidence:c.requiredEvidence,evidence:d,reason:t?.reason}}),i=r.reduce((c,d)=>c+d.weight,0)||1,s=lr(Math.round(r.reduce((c,d)=>c+d.score*d.weight,0)/i),0,100),a=r.every(c=>c.passed)?"accept":t?.status==="blocked"||e.verdict.status==="blocked"?"blocked":"revise";return{rubricFamily:Ru(n,e.contract.primaryTask),overallScore:s,verdict:a,criteria:r,trend:t?.status==="accept"?"improving":t?.status==="revise"?"flat":"regressing",summary:t?.reason??e.verdict.summary}}o(wu,"createVerificationScorecard");var Ag=50;function bi(e){let{prompt:t,options:n,recorder:r,rolesEmitted:i,baseCtx:s,signal:a,verdictStatus:c,userAnswer:d,budget:l,plan:f,entries:u,degradedContinue:h,taskId:p,extraArtifacts:m,rawRoutingDecision:v,routingOverrideReason:g,toolOutputTruncated:y,toolOutputTruncationNotes:R}=e,k=new Date().toISOString(),x=p??`runner-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,S=Ve(n),_=Ig.join(Ke(n,S),x),M=a==="BLOCKED"?"blocked":c==="accept"?"completed":"running",w=f?.decision,N={taskId:x,surface:S,objective:t,createdAt:k,updatedAt:k,status:M,primaryTask:w?.primaryTask??"conversation",workIntent:w?.workIntent??"new",complexity:w?.complexity??"simple",riskLevel:w?.riskLevel??"low",harnessProfile:"H0_DIRECT",recommendedMode:w?.recommendedMode??"conversation",requiresBrainstorm:w?.requiresBrainstorm??!1,reason:w?.reason??"Runner-driven AMA path",contractSummary:void 0,successCriteria:[],requiredEvidence:[],constraints:[],verification:n.context?.taskVerification},H=[];for(let U of i)H.includes(U)||H.push(U);let E=(H.length<=1?["direct"]:H).map(U=>({id:U,role:U,title:U.charAt(0).toUpperCase()+U.slice(1),dependsOn:[],status:M})),K="direct",te=d??r.verdict?.payload.verdict?.reason??"",se={contract:N,roleAssignments:E,workItems:[],evidence:{workspaceDir:_,artifacts:Zn(Ic(_),m),entries:u?[...u]:[],routingNotes:f?.decision.routingNotes?[...f.decision.routingNotes]:[]},verdict:{status:c==="blocked"?"blocked":c==="accept"?"completed":"running",decidedByAssignmentId:K,summary:te,signal:a},runtime:{globalWorkBudget:l?.totalBudget??Ag,budgetUsage:l?.spentBudget??i.length,harnessTransitions:[],routingAttempts:f?.decision.routingAttempts,routingSource:f?.decision.routingSource,currentHarness:"H0_DIRECT",upgradeCeiling:f?.decision.upgradeCeiling??"H0_DIRECT",qualityAssuranceMode:Mg(f),degradedContinue:h||void 0,completionContractStatus:mu(n.context?.taskVerification,c),rawRoutingDecision:v,finalRoutingDecision:f?.decision,routingOverrideReason:g,toolOutputTruncated:y||void 0,toolOutputTruncationNotes:R&&R.length>0?[...R]:void 0}},ge=r.verdict?.payload.verdict,b=ge?{status:ge.status,reason:ge.reason}:void 0,B=wu(se,b);return B&&se.runtime?{...se,runtime:{...se.runtime,scorecard:B}}:se}o(bi,"buildManagedTaskPayload");function Mg(e){let t=e?.decision;return t&&(t.assuranceIntent==="explicit-check"||t.needsIndependentQA===!0||t.riskLevel==="high"||t.primaryTask==="qa"||t.primaryTask==="plan"||t.recommendedMode==="pr-review"||t.recommendedMode==="strict-audit")?"required":"optional"}o(Mg,"deriveQualityAssuranceMode");import Og from"node:path";async function bu(e){let t;try{t=await Qo(e)}catch{return}if(!t)return;let n=o(async()=>{try{await ct(t.workspaceDir)}catch{}},"deleteSafely");if(!e.events?.askUser){await n();return}let r=/[一-鿿]/.test(t.managedTask.contract.objective??""),i=Pe(await e.events.askUser({question:r?"\u53D1\u73B0\u672A\u5B8C\u6210\u7684\u4EFB\u52A1":"Found incomplete task",allowCustomInput:!1,options:[{label:r?"\u7EE7\u7EED\u672A\u5B8C\u6210\u7684\u5DE5\u4F5C":"Resume",value:"resume",description:r?"\u5728\u5148\u524D Scout/\u6267\u884C\u7ED3\u679C\u7684\u57FA\u7840\u4E0A\u7EE7\u7EED\uFF08\u4E0A\u4E0B\u6587\u4FDD\u7559\uFF09":"Continue with preserved prior Scout / execution context"},{label:r?"\u91CD\u65B0\u5F00\u59CB":"Restart",value:"restart",description:r?"\u4E22\u5F03\u4E4B\u524D\u7684\u8FDB\u5EA6\uFF0C\u91CD\u65B0\u5F00\u59CB":"Discard previous progress and start fresh"},{label:r?"\u53D6\u6D88":"Cancel",value:"cancel",description:r?"\u4E2D\u6B62\u5F53\u524D\u8BF7\u6C42":"Abort the current request"}],default:"resume"}));if(i==="cancel")throw await n(),new Error("Runner-driven path: user cancelled due to pre-existing checkpoint");if(i==="resume")return{resumeFrom:t};await n()}o(bu,"handlePreRunCheckpoint");function Eu(e){let t=e.managedTask,n=["=== RESUMING INCOMPLETE TASK ===",`Checkpoint from: ${e.checkpoint.createdAt}`,`Original objective: ${t.contract.objective}`,`Roles already executed: ${e.checkpoint.completedWorkerIds.join(", ")||"none"}`],r=t.contract.contractSummary;if(r&&(n.push("","--- Contract (already produced) ---"),n.push(r),t.contract.successCriteria.length>0)){n.push("Success criteria:");for(let i of t.contract.successCriteria)n.push(` - ${i}`)}return t.verdict?.summary&&(n.push("","--- Last verdict ---"),n.push(`Status: ${t.verdict.status}`),n.push(`Summary: ${t.verdict.summary}`)),n.push("","Use this preserved context to avoid redundant investigation. Continue the work from where it was interrupted.","=== END RESUME CONTEXT ===",""),n.join(`
137
+ `),_synthetic:!0,_source:"managed-runtime-reminder",turnId:b?.turnId,timestamp:b?.timestamp??new Date().toISOString()},U=_.at(-1);U?.role==="user"&&U._synthetic!==!0&&(typeof U.content=="string"||U.content.some($=>$.type!=="tool_result"))?m=w:(N.push(B),_=[..._,B])}let H=(R.tools??[]).map(b=>({name:b.name,description:b.description,input_schema:b.input_schema})),C=wi(e,R);h.current+=1,e.events?.onIterationStart?.(h.current,p);let E;if(t)E=await t(_,H,S,M);else{let b=Ee(e.provider??"anthropic"),B=e.provider??b.name??"anthropic",U=typeof b.supportsEphemeralSuffix=="function"&&b.supportsEphemeralSuffix(),ye=U?M:void 0,$=o(X=>U?[...X]:_g(X,M),"lowerProviderMessages"),oe=e.context?.contextIdentitySessionId??e.session?.id,de=e.context?.currentAgentId,Ne=e.context?.parentAgentId,gt=oe===void 0?void 0:de===void 0?oe:`${oe}/agent/${encodeURIComponent(de)}`,$t={...gt!==void 0?{contextId:gt}:{},contextKind:de!==void 0?"child":"root",...oe!==void 0&&de!==void 0?{parentContextId:Ne===void 0||Ne==="/root"?oe:`${oe}/agent/${encodeURIComponent(Ne)}`}:{},...de!==void 0?{agentId:de}:{}},$e=gn(e.disablePromptCache)?void 0:Gn({logicalSessionId:oe,...de!==void 0?{agentId:de}:{}}),Qe=o(X=>{if(!(e.context?.contextDiagnostics!==!0||!e.events?.onContextBudgetSnapshot))try{let ne=Qa(S,X,b),fe=l?.contextWindow??b.getEffectiveContextWindow(g),ae=[...ne.messages].reverse().find(j=>j.turnId!==void 0)?.turnId,W=M?.content?[...ne.messages,{role:"user",content:M.content,_synthetic:!0,_source:"managed-run-context",...ae!==void 0?{turnId:ae}:{}}]:ne.messages,be=pa(W,{skillTexts:[l?.skillCatalogText,l?.selectedSkillText].filter(j=>j!==void 0),mcpTexts:l?.mcpCatalogText?[l.mcpCatalogText]:[]});e.events.onContextBudgetSnapshot(vo({sessionId:e.session?.id,turnId:ae,...$t,provider:B,model:g??b.getModel?.()??"unknown",contextWindow:fe,systemPrompt:ne.system,toolDefinitions:H,messageTokenBreakdown:be,reservedResponseTokens:b.getEffectiveMaxOutputTokens(g),profile:"report_only"}))}catch(ne){me("[context-diagnostics:budget-error]",{error:ne instanceof Error?ne.message:String(ne)})}},"emitContextBudgetSnapshot"),Se=o((X,ne,fe="stream")=>ec({events:e.events,enabled:e.context?.contextDiagnostics===!0,provider:b,providerName:B,...$t,model:g??b.getModel?.()??"unknown",reasoning:C,disablePromptCache:e.disablePromptCache,system:S,tools:H,messages:X,...M!==void 0?{ephemeralSuffix:M}:{},...$e!==void 0?{promptCacheKey:$e}:{},attempt:ne,transport:fe}),"beginPromptCacheDiagnostic"),Ze=o((X,ne)=>{tc(e.events,X,ne)},"completePromptCacheDiagnostic"),ke=bo(B,Po(e.timeouts)),Lt=ke.requestTimeoutMs,et=ke.streamIdleTimeoutMs,ue=new xo,un=typeof b.supportsNonStreamingFallback=="function"?b.supportsNonStreamingFallback():!1,Re=new So(ue,{...ke,enableNonStreamingFallback:ke.enableNonStreamingFallback&&un}),P=[..._];P=Pr(P),P=Or(P);let Q=0,G,ht=!1,we=0,he=[...P].reverse().find(X=>X.turnId!==void 0)?.turnId??`response_${xg().replace(/-/g,"")}`,Ie="append";for(;;){Pt(e.abortSignal,P),Q+=1;let X=$(P);ue.beginRequest(B,g??b.getModel?.()??"unknown",X,Q,!1);let ne=ue.snapshot();Un(ne);let fe={providerRequestId:ne.requestId};e.events?.onOutputSegmentStart?.({responseId:he,providerRequestId:ne.requestId,mode:Ie},fe);let ae=new AbortController,W=setTimeout(()=>{ae.abort(new Error("API Hard Timeout (10 minutes)"))},Lt),be=et>0,j;be&&(j=setTimeout(()=>{ae.abort(new Error(`Stream stalled or delayed response (${et}ms idle)`))},et));let je=o(()=>{be&&(j&&clearTimeout(j),ae.signal.aborted||(j=setTimeout(()=>{ae.abort(new Error(`Stream stalled or delayed response (${et}ms idle)`))},et)))},"resetIdleTimer"),z=e.abortSignal?AbortSignal.any([e.abortSignal,ae.signal]):ae.signal,We=Sa(P,S)+Buffer.byteLength(M?.content??"","utf8");me("[resilience:request]",{provider:B,attempt:Q,fallbackActive:!1,payloadBytes:We,payloadBucket:_a(We)});let Ae={promptCacheKey:$e,modelOverride:g,ephemeralSuffix:ye,onTextDelta:o(q=>{ue.markTextDelta(q),je();let Me=q.includes("```")||tn.some(vt=>q.includes(vt))?di(q):q;Me.length!==0&&e.events?.onTextDelta?.(Me,fe)},"onTextDelta"),onThinkingDelta:o(q=>{ue.markThinkingDelta(q),je(),e.events?.onThinkingDelta?.(q,fe)},"onThinkingDelta"),onThinkingEnd:o(q=>{e.events?.onThinkingEnd?.(q,fe)},"onThinkingEnd"),onToolInputDelta:e.events?.onToolInputDelta,onRateLimit:o((q,ce,Me)=>{je(),e.events&&bt(e.events,q,ce,Me)},"onRateLimit"),onRetryAfter:o(q=>{je(),v=hn(v,{provider:q.provider,waitMs:q.waitMs,reason:q.reason,source:q.source}),e.events?.onRetryAfter?.(q)},"onRetryAfter")};try{Qe(P);let q=Se(P,Q);if(G=await b.stream(X,[...H],S,C,Ae,z),Ze(q,G.usage),G.stopReason==="max_tokens"&&!ht&&!process.env.KODAX_MAX_OUTPUT_TOKENS&&b.getEffectiveMaxOutputTokens(g)<64e3){Pt(e.abortSignal,P),ht=!0,b.setMaxOutputTokensOverride(64e3),e.events?.onRetry?.(`Output budget reached, escalating to ${64e3} tokens and retrying the same turn`,1,1),W&&clearTimeout(W),j&&clearTimeout(j),W=void 0,j=void 0,Q-=1,Ie="replace";continue}if(vu(G)&&G.stopReason!=="max_tokens"&&we<En&&!e.abortSignal?.aborted){we+=1,e.events?.onRetry?.(`Provider returned an empty turn, retrying ${we}/${En}`,we,En),W&&clearTimeout(W),j&&clearTimeout(j),W=void 0,j=void 0,Q-=1,Ie="replace",await Ri(Ws*we,e.abortSignal,P);continue}break}catch(q){let ce=q instanceof Error?q:new Error(String(q));if(ce.name==="AbortError"&&ae.signal.aborted&&!e.abortSignal?.aborted){let Ce=ae.signal.reason?.message??"Stream stalled",{KodaXNetworkError:Fe}=await import("./dist-ITTXQHRJ.js");ce=new Fe(Ce,!0)}ki(e.abortSignal,ce,P);let Me=ue.inferFailureStage(),vt=Eo(ce,Me);wa(ce,vt);let Y=Re.decideRecoveryAction(ce,vt,Q);if(ba(Y,Q),e.events?.onProviderRecovery?.({stage:Y.failureStage,errorClass:Y.reasonCode,attempt:Q,maxAttempts:ke.maxRetries,delayMs:Y.delayMs,recoveryAction:Y.action,ladderStep:Y.ladderStep,fallbackUsed:Y.shouldUseNonStreaming,serverRetryAfterMs:Y.serverRetryAfterMs}),Y.reasonCode==="rate_limit"&&e.events&&bt(e.events,Q,ke.maxRetries,Y.delayMs),!e.events?.onProviderRecovery&&Y.action!=="manual_continue"&&e.events?.onRetry?.(`${Ya(ce)} \xB7 retry ${Q}/${ke.maxRetries} in ${Math.round(Y.delayMs/1e3)}s`,Q,ke.maxRetries),Y.shouldUseNonStreaming&&typeof b.complete=="function"){Pt(e.abortSignal,P);let Ce=new AbortController,Fe=e.abortSignal?AbortSignal.any([e.abortSignal,Ce.signal]):Ce.signal,vr=setTimeout(()=>{Ce.abort(new Error("API Hard Timeout (10 minutes)"))},Lt);try{j&&clearTimeout(j),W&&clearTimeout(W),W=void 0,j=void 0;let Be=$(P);ue.beginRequest(B,g??b.getModel?.()??"unknown",Be,Q,!0);let jt=ue.snapshot();Un(jt);let tt={providerRequestId:jt.requestId};e.events?.onOutputSegmentStart?.({responseId:he,providerRequestId:jt.requestId,mode:"replace"},tt),Qe(P);let Ft=Se(P,Q,"complete");G=await b.complete(Be,[...H],S,C,{promptCacheKey:$e,modelOverride:g,ephemeralSuffix:ye,onTextDelta:o(Te=>{ue.markTextDelta(Te),e.events?.onTextDelta?.(Te,tt)},"onTextDelta"),onThinkingDelta:o(Te=>{ue.markThinkingDelta(Te),e.events?.onThinkingDelta?.(Te,tt)},"onThinkingDelta"),onThinkingEnd:o(Te=>{e.events?.onThinkingEnd?.(Te,tt)},"onThinkingEnd"),signal:Fe},Fe),Ze(Ft,G.usage);break}catch(Be){ce=Be instanceof Error?Be:new Error(String(Be)),ki(e.abortSignal,ce,P)}finally{clearTimeout(vr)}}if(Y.action==="sanitize_thinking_and_retry"){let Ce=Re.executeRecovery(P,Y);_o(Y.action,Ce),P=Ce.messages,W&&clearTimeout(W),j&&clearTimeout(j),W=void 0,j=void 0,Q-=1,Ie="replace",await Ri(Y.delayMs,e.abortSignal,P);continue}if(Y.action==="manual_continue"||Q>=ke.maxRetries)throw kt(ce,P),ce;let yt=Re.executeRecovery(P,Y);_o(Y.action,yt),P=yt.messages,Ie="replace",W&&clearTimeout(W),j&&clearTimeout(j),W=void 0,j=void 0,await Ri(Y.delayMs,e.abortSignal,P);continue}finally{W&&clearTimeout(W),j&&clearTimeout(j)}}if(vu(G)){let X=new Er("Provider returned no user-visible text or tool calls after recovery attempts; refusing to commit an empty assistant turn.",B);throw kt(X,P),X}let Le=0,_e=(G.textBlocks??[]).map(X=>X.text).join(""),Tt=G.thinkingBlocks?[...G.thinkingBlocks]:void 0;for(;G.stopReason==="max_tokens"&&(G.toolBlocks?.length??0)===0&&_e.trim().length>0&&Le<3;){Pt(e.abortSignal,P),Le+=1;let X=[...Tt??[],{type:"text",text:_e}];P=[...P,{role:"assistant",content:X},{role:"user",content:[{type:"text",text:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."}]}],e.events?.onRetry?.(`max_tokens mid-text, appending continuation ${Le}/${3}`,Le,3);let ne=e.abortSignal??void 0,fe="";try{let W=$(P);ue.beginRequest(B,g??b.getModel?.()??"unknown",W,Q+Le,!1);let be=ue.snapshot();Un(be);let j={providerRequestId:be.requestId};e.events?.onOutputSegmentStart?.({responseId:he,providerRequestId:be.requestId,mode:"append"},j),Qe(P);let je=Se(P,Q+Le);G=await b.stream(W,[...H],S,C,{promptCacheKey:$e,modelOverride:g,ephemeralSuffix:ye,onTextDelta:o(z=>{let Ae=z.includes("```")||tn.some(q=>z.includes(q))?di(z):z;Ae.length!==0&&(fe+=Ae,ue.markTextDelta(z),e.events?.onTextDelta?.(Ae,j))},"onTextDelta"),onThinkingDelta:o(z=>{ue.markThinkingDelta(z),e.events?.onThinkingDelta?.(z,j)},"onThinkingDelta"),onThinkingEnd:o(z=>{e.events?.onThinkingEnd?.(z,j)},"onThinkingEnd"),onToolInputDelta:e.events?.onToolInputDelta,onRateLimit:o((z,We,Ae)=>{e.events&&bt(e.events,z,We,Ae)},"onRateLimit"),onRetryAfter:o(z=>{v=hn(v,{provider:z.provider,waitMs:z.waitMs,reason:z.reason,source:z.source}),e.events?.onRetryAfter?.(z)},"onRetryAfter")},ne),Ze(je,G.usage)}catch(W){ki(e.abortSignal,W instanceof Error?W:new Error(String(W)),P),_e+=fe;break}let ae=(G.textBlocks??[]).map(W=>W.text).join("");if(ae&&(_e+=ae),G.thinkingBlocks&&Tt&&Tt.push(...G.thinkingBlocks),(G.toolBlocks?.length??0)>0||G.stopReason!=="max_tokens")break}E={textBlocks:_e?[{text:_e}]:G.textBlocks,toolBlocks:G.toolBlocks,thinkingBlocks:Tt??G.thinkingBlocks,usage:G.usage}}if(n&&E.usage){let b=n.current;n.current={totalTokens:E.usage.totalTokens??b.totalTokens,lastUsage:E.usage,source:"api"}}if(E.usage){let b=e.provider??"anthropic";v=Sr(v,{provider:b,model:e.modelOverride??e.model??"unknown",inputTokens:E.usage.inputTokens,outputTokens:E.usage.outputTokens,cacheReadTokens:E.usage.cachedReadTokens,cacheWriteTokens:E.usage.cachedWriteTokens})}if(e.events&&Oa(e.events),e.events?.onIterationEnd){let b=E.usage,B=b?.totalTokens??b?.outputTokens??0;e.events.onIterationEnd({iter:h.current,maxIter:p,tokenCount:B,tokenSource:b?"api":"estimate",usage:b,scope:"worker"})}let K=(E.textBlocks??[]).map(b=>b.text).join(""),te=(E.toolBlocks??[]).map(b=>({id:b.id,name:b.name,input:b.input??{}})),se=E.thinkingBlocks,ge={text:K,toolCalls:te,thinkingBlocks:se,injectedInputMessages:N};if(i){let b=[...y,...N,Ir(ge)],B=E.usage?.totalTokens;if(typeof B=="number"&&Number.isFinite(B)&&B>=0)i.current={currentTokens:B,baselineEstimatedTokens:re(b),source:"api",usage:E.usage};else{let U=[..._,Ir(ge)];i.current={currentTokens:Sg(U,H,S,M),baselineEstimatedTokens:re(b),source:"estimate"}}}return ge}}o(ku,"buildRunnerLlmAdapter");import Ig from"node:path";function lr(e,t,n){return Math.max(t,Math.min(n,e))}o(lr,"clampNumber");function Ru(e,t){return e?.rubricFamily?e.rubricFamily:e?.capabilityHints?.some(n=>/agent-browser|playwright/i.test(n.name))?"frontend":t==="review"?"code-review":t==="bugfix"?"functionality":"code-quality"}o(Ru,"inferVerificationRubricFamily");function Cg(e,t){if(e?.criteria?.length)return e.criteria.map(s=>({...s,threshold:lr(s.threshold,0,100),weight:lr(s.weight,0,1)}));let n=Ru(e,t),r=e?.requiredEvidence??[],i=e?.requiredChecks??[];return n==="frontend"?[{id:"ui-flow",label:"UI flow verification",description:"Critical browser path completes without visible breakage.",threshold:75,weight:.4,requiredEvidence:r},{id:"console-clean",label:"Console and runtime health",description:"Browser or app runtime should not show blocking errors.",threshold:75,weight:.25,requiredEvidence:r},{id:"check-evidence",label:"Deterministic checks",description:"Required checks or tests must be explicitly reported.",threshold:70,weight:.35,requiredEvidence:[...r,...i]}]:n==="code-review"?[{id:"finding-accuracy",label:"Finding accuracy",description:"Reported issues should be grounded in concrete evidence.",threshold:80,weight:.45,requiredEvidence:r},{id:"verification",label:"Independent verification",description:"Claims should be independently verified before acceptance.",threshold:75,weight:.35,requiredEvidence:[...r,...i]},{id:"completeness",label:"Review completeness",description:"High-risk changes should not truncate before the critical findings are delivered.",threshold:70,weight:.2,requiredEvidence:r}]:[{id:"functionality",label:"Functional correctness",description:"The requested behavior is implemented and evidenced.",threshold:75,weight:.5,requiredEvidence:r},{id:"checks",label:"Check coverage",description:"Relevant checks and validation evidence are reported.",threshold:70,weight:.3,requiredEvidence:[...r,...i]},{id:"quality",label:"Quality and safety",description:"The result does not leave obvious correctness or safety gaps behind.",threshold:70,weight:.2,requiredEvidence:r}]}o(Cg,"resolveVerificationCriteria");function wu(e,t){let n=e.contract.verification;if(!n)return;let r=Cg(n,e.contract.primaryTask).map(c=>{let d=[...c.requiredEvidence??[],...e.evidence.entries.filter(u=>u.status==="completed"&&u.summary).map(u=>u.summary).slice(-2)],l=t?.status==="accept"?100:t?.status==="revise"?45:e.verdict.status==="completed"?90:e.verdict.status==="blocked"?35:55,f=lr(l,0,100);return{id:c.id,label:c.label,threshold:c.threshold,score:f,passed:f>=c.threshold,weight:c.weight,requiredEvidence:c.requiredEvidence,evidence:d,reason:t?.reason}}),i=r.reduce((c,d)=>c+d.weight,0)||1,s=lr(Math.round(r.reduce((c,d)=>c+d.score*d.weight,0)/i),0,100),a=r.every(c=>c.passed)?"accept":t?.status==="blocked"||e.verdict.status==="blocked"?"blocked":"revise";return{rubricFamily:Ru(n,e.contract.primaryTask),overallScore:s,verdict:a,criteria:r,trend:t?.status==="accept"?"improving":t?.status==="revise"?"flat":"regressing",summary:t?.reason??e.verdict.summary}}o(wu,"createVerificationScorecard");var Ag=50;function bi(e){let{prompt:t,options:n,recorder:r,rolesEmitted:i,baseCtx:s,signal:a,verdictStatus:c,userAnswer:d,budget:l,plan:f,entries:u,degradedContinue:h,taskId:p,extraArtifacts:m,rawRoutingDecision:v,routingOverrideReason:g,toolOutputTruncated:y,toolOutputTruncationNotes:R}=e,k=new Date().toISOString(),x=p??`runner-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,S=Ve(n),_=Ig.join(Ke(n,S),x),M=a==="BLOCKED"?"blocked":c==="accept"?"completed":"running",w=f?.decision,N={taskId:x,surface:S,objective:t,createdAt:k,updatedAt:k,status:M,primaryTask:w?.primaryTask??"conversation",workIntent:w?.workIntent??"new",complexity:w?.complexity??"simple",riskLevel:w?.riskLevel??"low",harnessProfile:"H0_DIRECT",recommendedMode:w?.recommendedMode??"conversation",requiresBrainstorm:w?.requiresBrainstorm??!1,reason:w?.reason??"Runner-driven AMA path",contractSummary:void 0,successCriteria:[],requiredEvidence:[],constraints:[],verification:n.context?.taskVerification},H=[];for(let U of i)H.includes(U)||H.push(U);let E=(H.length<=1?["direct"]:H).map(U=>({id:U,role:U,title:U.charAt(0).toUpperCase()+U.slice(1),dependsOn:[],status:M})),K="direct",te=d??r.verdict?.payload.verdict?.reason??"",se={contract:N,roleAssignments:E,workItems:[],evidence:{workspaceDir:_,artifacts:Zn(Ic(_),m),entries:u?[...u]:[],routingNotes:f?.decision.routingNotes?[...f.decision.routingNotes]:[]},verdict:{status:c==="blocked"?"blocked":c==="accept"?"completed":"running",decidedByAssignmentId:K,summary:te,signal:a},runtime:{globalWorkBudget:l?.totalBudget??Ag,budgetUsage:l?.spentBudget??i.length,harnessTransitions:[],routingAttempts:f?.decision.routingAttempts,routingSource:f?.decision.routingSource,currentHarness:"H0_DIRECT",upgradeCeiling:f?.decision.upgradeCeiling??"H0_DIRECT",qualityAssuranceMode:Mg(f),degradedContinue:h||void 0,completionContractStatus:mu(n.context?.taskVerification,c),rawRoutingDecision:v,finalRoutingDecision:f?.decision,routingOverrideReason:g,toolOutputTruncated:y||void 0,toolOutputTruncationNotes:R&&R.length>0?[...R]:void 0}},ge=r.verdict?.payload.verdict,b=ge?{status:ge.status,reason:ge.reason}:void 0,B=wu(se,b);return B&&se.runtime?{...se,runtime:{...se.runtime,scorecard:B}}:se}o(bi,"buildManagedTaskPayload");function Mg(e){let t=e?.decision;return t&&(t.assuranceIntent==="explicit-check"||t.needsIndependentQA===!0||t.riskLevel==="high"||t.primaryTask==="qa"||t.primaryTask==="plan"||t.recommendedMode==="pr-review"||t.recommendedMode==="strict-audit")?"required":"optional"}o(Mg,"deriveQualityAssuranceMode");import Og from"node:path";async function bu(e){let t;try{t=await Qo(e)}catch{return}if(!t)return;let n=o(async()=>{try{await ct(t.workspaceDir)}catch{}},"deleteSafely");if(!e.events?.askUser){await n();return}let r=/[一-鿿]/.test(t.managedTask.contract.objective??""),i=Pe(await e.events.askUser({question:r?"\u53D1\u73B0\u672A\u5B8C\u6210\u7684\u4EFB\u52A1":"Found incomplete task",allowCustomInput:!1,options:[{label:r?"\u7EE7\u7EED\u672A\u5B8C\u6210\u7684\u5DE5\u4F5C":"Resume",value:"resume",description:r?"\u5728\u5148\u524D Scout/\u6267\u884C\u7ED3\u679C\u7684\u57FA\u7840\u4E0A\u7EE7\u7EED\uFF08\u4E0A\u4E0B\u6587\u4FDD\u7559\uFF09":"Continue with preserved prior Scout / execution context"},{label:r?"\u91CD\u65B0\u5F00\u59CB":"Restart",value:"restart",description:r?"\u4E22\u5F03\u4E4B\u524D\u7684\u8FDB\u5EA6\uFF0C\u91CD\u65B0\u5F00\u59CB":"Discard previous progress and start fresh"},{label:r?"\u53D6\u6D88":"Cancel",value:"cancel",description:r?"\u4E2D\u6B62\u5F53\u524D\u8BF7\u6C42":"Abort the current request"}],default:"resume"}));if(i==="cancel")throw await n(),new Error("Runner-driven path: user cancelled due to pre-existing checkpoint");if(i==="resume")return{resumeFrom:t};await n()}o(bu,"handlePreRunCheckpoint");function Eu(e){let t=e.managedTask,n=["=== RESUMING INCOMPLETE TASK ===",`Checkpoint from: ${e.checkpoint.createdAt}`,`Original objective: ${t.contract.objective}`,`Roles already executed: ${e.checkpoint.completedWorkerIds.join(", ")||"none"}`],r=t.contract.contractSummary;if(r&&(n.push("","--- Contract (already produced) ---"),n.push(r),t.contract.successCriteria.length>0)){n.push("Success criteria:");for(let i of t.contract.successCriteria)n.push(` - ${i}`)}return t.verdict?.summary&&(n.push("","--- Last verdict ---"),n.push(`Status: ${t.verdict.status}`),n.push(`Summary: ${t.verdict.summary}`)),n.push("","Use this preserved context to avoid redundant investigation. Continue the work from where it was interrupted.","=== END RESUME CONTEXT ===",""),n.join(`
138
138
  `)}o(Eu,"buildResumePreamble");function xu(e){return{recorderSlots:{},harness:"H0_DIRECT",rolesEmitted:[]}}o(xu,"buildStructuralResumeSeed");async function Su(e){let{options:t,managedTask:n,currentRound:r,completedWorkerIds:i,scoutCompleted:s}=e;try{let a=Ve(t),c=Ke(t,a),d=Og.join(c,n.contract.taskId),l=await Jn(t.context?.gitRoot)??"unknown",f=Yo(t),u={version:1,taskId:n.contract.taskId,...f?{sessionId:f}:{},processId:process.pid,createdAt:n.contract.createdAt,gitCommit:l,objective:n.contract.objective,harnessProfile:n.contract.harnessProfile,currentRound:r,completedWorkerIds:[...i],scoutCompleted:s};return await Jo(d,u),d}catch{return}}o(Su,"writeCurrentCheckpoint");function Ei(e){let t=e.actorControl;if(!t)return 0;let n=t.callerPath==="/root"?"/root/":`${t.callerPath}/`;return t.list().actors.filter(r=>r.path.startsWith(n)&&r.currentTurnId!==void 0).length}o(Ei,"activeDescendantTurnCount");function Pg(e){return e.actorQueueAgentId??kn(e.contextIdentitySessionId??e.sessionId,e.actorControl?.callerPath??"/root")}o(Pg,"actorMessageQueueId");function $g(e){let t=e;return typeof t?.bindController=="function"&&typeof t.hydrateSession=="function"}o($g,"isSessionBindableExtensionRuntime");function fr(e,t,n){return{toolId:t,...e?.workflowCorrelation!==void 0?{workflowCorrelation:e.workflowCorrelation}:{},...n?.sessionId?{sessionId:n.sessionId}:{},...n?.agentProfile?{agentProfile:n.agentProfile}:{}}}o(fr,"runnerToolEventMeta");function _u(e,t){let n=qd(t);return n.length===0?e:{...e,runtime:{...e.runtime,todoDriftWarnings:[...n]}}}o(_u,"attachTodoDriftWarnings");function Lg(e){return e.effort?e.effort:e.reasoningMode?nt(e.reasoningMode)??e.reasoningMode:void 0}o(Lg,"resolveInitialRuntimeThinkingLevel");function jg(e){let t=typeof e.instructions=="function"?e.instructions(void 0):e.instructions;return ss(e,t)}o(jg,"resolveAgentSystemPrompt");function Mu(e,t){let n=jg(t),r=0;for(;r<e.length;){let i=e[r];if(!i||i.role!=="system"||typeof i.content!="string"||i.content!==n)break;r+=1}return r>0?e.slice(r):e}o(Mu,"dropRunnerInjectedSystemMessage");function Ou(e){let t;return e.map(n=>{if(n.role==="system")return n;if(n.role==="user"){let r=n.turnId??t;return r===void 0?n:(t=r,n.turnId===void 0?{...n,turnId:r}:n)}return n.turnId!==void 0||t===void 0?n:{...n,turnId:t}})}o(Ou,"attachTurnIdsFromUserBoundaries");function Fg(e,t){let n=t?Mu(e,t):e;return Ou(lt(n))}o(Fg,"buildPersistableManagedTranscript");async function Cu(e,t,n){if(e.session?.persistedByHost===!1){await ic(e,t,n);return}await Lo(e,t,n)}o(Cu,"saveManagedRunBoundary");function Bg(e,t,n){queueMicrotask(()=>{(async()=>{let r=await Mc(e,t).catch(i=>(me("[managed-task:repo-intelligence:error]",{error:i instanceof Error?i.message:String(i)}),t));await Ac(r.evidence.workspaceDir,r,n)})().catch(r=>{me("[managed-task:artifact-projection:error]",{error:r instanceof Error?r.message:String(r)})})})}o(Bg,"scheduleManagedTaskMaintenance");function Iu(e){return{...e,context:{...e.context,excludeTools:[...new Set([...e.context?.excludeTools??[],Ks])]}}}o(Iu,"withoutMemoryIntentTool");async function Ug(e,t,n,r){if(e.context?.currentAgentId!==void 0||e.context?.parentAgentId!==void 0)return{options:Iu(e)};let i=e.context?.memoryIdentity??Lr(e,wn(e.context),n),s={current:void 0};try{let a=ks({cwd:wn(e.context),identity:i,projectDocs:[],discoverSkills:!1,...e.memoryReviewer===void 0?{}:{memoryReviewer:e.memoryReviewer}}),c=await a.buildMemoryPack({task:t,identity:i,maxCandidates:12,maxHints:5,includeSnippets:!1}),d=bn(e,i,a,n).then(()=>{}).catch(u=>{me("[memory:review-inbox:startup-drain-error]",{error:u instanceof Error?u.message:String(u)})}),l=e.session?.storage===void 0?void 0:await Rs(i),f=await Hs({controlPlane:a,initialMemoryPack:c,sourcePolicy:La,...e.memoryRecallRunner===void 0?{}:{recallRunner:e.memoryRecallRunner},persistOutcomeDigest:o(async u=>{if(u.visibility==="prompt_safe"&&e.session?.storage!==void 0&&l!==void 0){let h=await ws(i,u,{expectedBranchEpoch:l,persistOwner:o(async p=>jr(e,n,u,{jobId:p.jobId}),"persistOwner")});s.current=h.entry.jobId;return}await jr(e,n,u)},"persistOutcomeDigest"),...e.session?.storage===void 0&&e.memoryReviewer!==void 0?{reviewEpisode:o(async(u,h)=>{let p=await a.reviewEpisode(u,h);h.aborted||(e.events?.onMemoryReviewReceipt?.({sessionId:n,reviewKey:u.reviewKey,proposalIds:p.proposalIds,completedAt:new Date().toISOString()}),p.appliedProposalIds.length>0&&e.events?.onMemoryNotice?.({sessionId:n,episodeId:u.id,summaries:p.decisions.filter(m=>m.proposalId!==void 0&&p.appliedProposalIds.includes(m.proposalId)).map(m=>p.plan.actions[m.actionIndex]?.summary).filter(m=>m!==void 0).slice(0,3),proposalIds:p.appliedProposalIds}))},"reviewEpisode")}:{},onTrace:o(u=>{me(`[memory:${u.type}]`,"receipt"in u?{receiptId:u.receipt.id}:{key:u.key,detail:u.detail??null})},"onTrace")}).startSession({identity:i,objective:t,episodeId:r});return{runtime:{controller:a,identity:i,session:f,currentUserTurn:{text:e.context?.rawUserInput?.trim()||t,turnId:r},presentationMessages:e.session?.initialMessages??[],preferredReviewJobRef:s,reviewDrain:d,observationSequence:0,handledMemoryOperations:[],finished:!1},options:{...e,context:{...e.context,memoryIdentity:i,memoryPack:c}}}}catch(a){return me("[memory:session-start:error]",{error:a instanceof Error?a.message:String(a)}),{options:Iu(e)}}}o(Ug,"startRunnerMemoryRuntime");async function Au(e,t,n,r){if(t===void 0||t.finished)return;t.finished=!0;let i=new Date().toISOString(),s=Na(r.artifactLedger??[]);try{await t.session.complete({status:r.status,summary:r.summary,evidence:[...r.status==="cancelled"?[]:[...s.length>0?s.map(a=>({ref:a.ref,requestedGrade:"verified",source:a.source,verdict:a.verdict,observedAt:a.observedAt})):[{ref:`host:run-terminal:${n}`,requestedGrade:"observed",source:"host",observedAt:i}]]],...t.handledMemoryOperations.length===0?{}:{handledMemoryOperations:[...t.handledMemoryOperations]}}),await t.session.close()}catch(a){me("[memory:episode-finalize:error]",{error:a instanceof Error?a.message:String(a)}),await t.session.close({drain:!1}).catch(()=>{})}t.reviewDrain=t.reviewDrain.then(()=>bn(e,t.identity,t.controller,"",Date.now()+15e3,t.preferredReviewJobRef.current).then(()=>{})).catch(a=>{me("[memory:review-inbox:drain-error]",{error:a instanceof Error?a.message:String(a)})})}o(Au,"finishRunnerMemoryRuntime");async function Pu(e,t,n,r){let{options:i}=xa(e,t);i.context?.permissionIntent===void 0&&(i={...i,context:{...i.context,permissionIntent:{rootUserIntent:t}}});let s=i.provider??"anthropic";i=$r(i,Ee(s),i.modelOverride??i.model);let a=i.session?.id??`runner-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,c=ls(kn(a,"/root"));try{await Ls(i);let l=!!i.session?.id||!!i.session?.storage||!!i.events?.askUser?{...i,session:{...i.session??{},id:a}}:i,f=i.context?.liveTurn,u=i.context?.currentAgentId,h=i.context?.parentAgentId,p=i.context?.contextIdentitySessionId??a,m=Mo({sessionId:a,deliveryKind:f?.deliveryKind??"initial",turnId:f?.turnId,deliveryId:f?.deliveryId,promptId:f?.promptId,...u!==void 0?{contextId:`${p}/agent/${encodeURIComponent(u)}`,contextKind:"child",parentContextId:h===void 0||h==="/root"?p:`${p}/agent/${encodeURIComponent(h)}`,agentId:u}:{},ownsContextRevision:i.context?.ownsContextRevision}),v={current:m},g=new Set,y=za({events:l.events??{},storage:l.session?.storage,sessionId:a,persistedByHost:l.session?.persistedByHost,currentAgentId:u,sessionScope:l.session?.scope,initialSessionData:{title:t.slice(0,80),gitRoot:l.context?.gitRoot??"",...l.session?.scope!==void 0?{scope:l.session.scope}:{},...l.session?.tag!==void 0?{tag:l.session.tag}:{}}}),R=Ca(y,v),k={...l,context:{...l.context??{},contextIdentitySessionId:p},events:R},x=await Ug(k,t,a,v.current.turnId),S=x.options,_=x.runtime,M=!1,w=o(C=>{let E=v.current;M&&(g.has(E.turnId)||(g.add(E.turnId),Ia(R,E,C)))},"emitLiveTurnCompleted"),N=o(C=>{let E=v.current;M&&(g.has(E.turnId)||(g.add(E.turnId),Aa(R,E,C)))},"emitLiveTurnFailed"),H={currentTurnId:o(()=>v.current.turnId,"currentTurnId"),markInitialInputDurable:o(()=>{M||(M=!0,Ma(R,{provider:s,sessionId:a}),Oo(R,v.current))},"markInitialInputDurable"),prepareTurn:o(C=>{w("completed");let E=Mo({sessionId:a,deliveryKind:C.deliveryKind,promptId:C.promptId,contextId:m.contextId,contextKind:m.contextKind,parentContextId:m.parentContextId,agentId:m.agentId,ownsContextRevision:m.ownsContextRevision}),K=!1;return{turnId:E.turnId,start:o(()=>{K||(K=!0,v.current=E,M=!0,Oo(R,E),_!==void 0&&C.userText!==void 0&&(_.currentUserTurn={text:C.userText,turnId:E.turnId}))},"start")}},"prepareTurn")};try{let C=await Wg(S,t,n,r,a,H,_);return await Au(S,_,a,{status:C.interrupted?"cancelled":C.success?"succeeded":"failed",summary:C.lastText,artifactLedger:C.artifactLedger}),C.success?w(C.interrupted?"interrupted":"completed"):N(new Error(C.errorMetadata?.lastError??C.signalReason??"KodaX managed task failed")),C}catch(C){let E=C instanceof Error?C:new Error(String(C));if(N(E),Da(R,E),S.session?.storage)try{let K=os(C),te=K?[...K]:[];Lo(S,a,{messages:te,title:t.slice(0,80),gitRoot:S.context?.gitRoot??void 0,errorMetadata:{lastError:E.message,lastErrorTime:Date.now(),consecutiveErrors:1}}).catch(se=>{me("[session:error-snapshot:error]",{error:se instanceof Error?se.message:String(se)})})}catch(K){me("[session:error-snapshot:prepare-error]",{error:K instanceof Error?K.message:String(K)})}throw await Au(S,_,a,{status:S.abortSignal?.aborted===!0||E.name==="AbortError"?"cancelled":"failed",summary:E.message}),C}finally{Pa(R)}}finally{c()}}o(Pu,"runManagedTaskViaRunner");async function Wg(e,t,n,r,i,s,a){let c,d,l={truncated:!1,notes:[]};if(r){let T=Dc(r,t,e.context?.repoRoutingSignals);c=T.rawDecision,d=T.routingOverrideReason,r=T.plan}let f;if(e.events?.askUser){let T=await bu(e);T&&(t=`${Eu(T.resumeFrom)}
139
139
  ${t}`,f=xu(T.resumeFrom))}let u=Ve(e),h=`runner-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,p=Dg.join(Ke(e,u),h),m=ti(p),v={current:[]},g=e.context?.skillInvocation;if(g)try{let T=await Cc(p,g,void 0);v.current=T}catch{}let y={files:new Map,totalOps:0,riskyShellOps:0},R="H0_DIRECT",k=e.context?.managedWorkBudget??{totalBudget:$c,spentBudget:0,currentHarness:R},x=e.context?.managedWorkBudget?e:{...e,context:{...e.context,managedWorkBudget:k}},S=e.extensionRuntime,_={current:void 0},M=Va({options:x,sessionId:e.session?.id??i,runtime:S,managedProtocolPayloadRef:_});a!==void 0&&(M.memoryRecall=Vs(a.session,()=>({decisionRevision:`ama:${s.currentTurnId()}:${a.observationSequence}`,...r?.decision.primaryTask===void 0?{}:{actionSignature:`task:${r.decision.primaryTask}`},throughSequence:a.observationSequence})),M.memoryManagementIntent=zs({getCurrentUserTurn:o(()=>a.currentUserTurn,"getCurrentUserTurn"),controlPlane:a.controller,getPresentedTargets:o(()=>Xs(a.presentationMessages),"getPresentedTargets"),onHandledOperation:o(T=>a.handledMemoryOperations.push(T),"onHandledOperation")}));let w=Nc({onChange:o(T=>{e.events?.onTodoUpdate?.(T)},"onChange")}),N={current:!1},H=ud(),C=Fd(),E,K=o((T,O)=>{if(!E){let D=Ee(e.provider??"anthropic"),I=e.modelOverride??e.model;E=Kd({provider:D,model:I,events:e.events})}return E(T,O)},"summarizeBlob"),te=Zs(),se=Gs(),ge=e.provider??"anthropic",b=Ld({mainProvider:Ee(ge),mainProviderName:ge,mainModel:e.modelOverride??e.model}),B=b.detector,U=b.sidecar,ye={current:void 0},$={...M,mutationTracker:y,todoStore:w,summarizeBlob:K,contentHashCache:te,readFileStateCache:se,...g?{skillInvocation:g}:{}};Object.defineProperty($,"siblingSnapshot",{get:o(()=>ye.current,"get"),enumerable:!0,configurable:!0}),Object.defineProperty($,"actorTurnRef",{get:o(()=>$.actorControl===void 0?void 0:{actorPath:$.actorControl.callerPath,turnId:s.currentTurnId()},"get"),enumerable:!0,configurable:!0});let oe={},de={current:R},Ne={emitted:f?[...f.rolesEmitted]:[]},gt={current:0},$t={current:Lc},$e={current:!1},Qe={items:[]},Se={current:e.session?.id??i},Ze=!!e.events?.askUser,ke=[],Lt=o(async()=>{Ze&&await Promise.allSettled(ke)},"flushPendingCheckpointWrites"),et=o(async()=>{if(Ze)try{await ct(p)}catch{}},"deleteRunCheckpoint"),ue=o(async()=>{await Lt(),await et()},"cleanupRunCheckpoint"),un=o(T=>{let O=_u(bi({prompt:t,options:e,recorder:oe,rolesEmitted:Ne.emitted,baseCtx:$,signal:"COMPLETE",budget:k,plan:r,entries:Qe.items,degradedContinue:Q.current,taskId:h,extraArtifacts:v.current,rawRoutingDecision:c,routingOverrideReason:d,toolOutputTruncated:l.truncated,toolOutputTruncationNotes:l.notes}),C),D=ni(O.evidence.workspaceDir,O).then(()=>!0).catch(()=>!1);if(!Ze)return;let I=!1,L=Ne.emitted.length;ke.push(D.then(J=>J?Su({options:e,managedTask:O,currentRound:L,completedWorkerIds:Ne.emitted.map(A=>A),scoutCompleted:I}):void 0))},"checkpointWriter"),Re=Fc(e.events,de,Ne,k,gt,$t,$e,Qe,Se,un);if(b.attachObserver(Re),r&&e.events?.onManagedTaskStatus){let T=jc(r);e.events.onManagedTaskStatus({agentMode:"ama",harnessProfile:r.decision.harnessProfile,phase:"routing",note:T,upgradeCeiling:r.decision.upgradeCeiling??r.decision.harnessProfile,...at(k,$e.current)})}Re.preflight();let P={current:r},Q={current:!1},G={events:e.events,originalTask:t,roundRef:gt,maxRoundsRef:$t,budgetApprovalRef:$e,planRef:P,degradedContinueRef:Q,harnessRef:de},ht={current:{totalTokens:0,source:"estimate"}},we={current:e.context?.contextTokenSnapshot},he=await fi(e),Ie=Pg($),Le=Vd($,T=>T?ir([...T.transcript,...T.pendingMessages],{ctx:$,contextWindow:he.contextWindow,reservedResponseTokens:he.provider.getEffectiveMaxOutputTokens(he.activeModel),contextTokenSnapshotRef:we}):void 0),_e={executionCwd:wn(e.context),gitRoot:e.context?.gitRoot??void 0,scratchDir:da(e),platform:process.platform,osRelease:Ng.release(),provider:e.provider,model:e.modelOverride??e.model},Tt=!e.session?.initialMessages||e.session.initialMessages.length===0,X,ne,fe,ae;try{let T=await ho(e,Tt,_e.executionCwd),O=new Set(["base-system","base-system-suffix","environment-context","runtime-fact","working-directory","session-scratch-directory","repo-intelligence-context","execution-guidance"]),D=T.filter(A=>!O.has(A.id)),I=new Set(["project-agents","self-knowledge-routing","memory-rules","tool-construction"]),L=D.filter(A=>I.has(A.id)),J=D.filter(A=>!I.has(A.id));fe=J.filter(A=>A.id==="skills-addendum").map(A=>A.content).join(`
140
140
 
@@ -1,2 +1,2 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{o}from"./chunk-FBL7IVMK.js";import{a as i}from"./chunk-ONUPGMER.js";function r(u){let e=o(u?.llm);if(!e)return;let t={};return e.requestTimeoutMs!==void 0&&(t.requestTimeoutMs=e.requestTimeoutMs),e.streamIdleTimeoutMs!==void 0&&(t.streamIdleTimeoutMs=e.streamIdleTimeoutMs),e.chunkTimeoutMs!==void 0&&(t.chunkTimeoutMs=e.chunkTimeoutMs),e.maxRetryDelayMs!==void 0&&(t.maxRetryDelayMs=e.maxRetryDelayMs),Object.keys(t).length>0?t:void 0}i(r,"providerResilienceConfigFromTimeouts");export{r as a};
2
+ import{o}from"./chunk-BHE66SP3.js";import{a as i}from"./chunk-ONUPGMER.js";function r(u){let e=o(u?.llm);if(!e)return;let t={};return e.requestTimeoutMs!==void 0&&(t.requestTimeoutMs=e.requestTimeoutMs),e.streamIdleTimeoutMs!==void 0&&(t.streamIdleTimeoutMs=e.streamIdleTimeoutMs),e.chunkTimeoutMs!==void 0&&(t.chunkTimeoutMs=e.chunkTimeoutMs),e.maxRetryDelayMs!==void 0&&(t.maxRetryDelayMs=e.maxRetryDelayMs),Object.keys(t).length>0?t:void 0}i(r,"providerResilienceConfigFromTimeouts");export{r as a};