@kodax-ai/kodax 0.7.60 → 0.7.61

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 (44) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/README.md +2 -0
  3. package/README_CN.md +2 -0
  4. package/dist/chunks/{agent-L5FC3YOY.js → agent-E74WVAFR.js} +1 -1
  5. package/dist/chunks/argument-completer-BBFYCVTM.js +2 -0
  6. package/dist/chunks/{chunk-5TRQBMPR.js → chunk-2OEKUAV4.js} +1 -1
  7. package/dist/chunks/{chunk-ZPD7IUKW.js → chunk-4NSOBQCU.js} +1 -1
  8. package/dist/chunks/{chunk-QFCF3GNT.js → chunk-7COB3EKF.js} +171 -156
  9. package/dist/chunks/chunk-CGGX3FXE.js +19 -0
  10. package/dist/chunks/{chunk-6DWXUZMO.js → chunk-D7CC6YZC.js} +198 -198
  11. package/dist/chunks/{chunk-SGNM3UP6.js → chunk-KIVYMSRH.js} +1 -1
  12. package/dist/chunks/chunk-NJW2LQOP.js +722 -0
  13. package/dist/chunks/{chunk-IJN6ZJVI.js → chunk-PJXKBM3Y.js} +4 -4
  14. package/dist/chunks/{chunk-2RLIKZOZ.js → chunk-QCBKLNN5.js} +2 -2
  15. package/dist/chunks/{chunk-XULI4U7I.js → chunk-XHOPSZVL.js} +1 -1
  16. package/dist/chunks/{compaction-config-E4LN3M53.js → compaction-config-GESEZQVA.js} +1 -1
  17. package/dist/chunks/{construction-bootstrap-GIFDM4L5.js → construction-bootstrap-OSXHEIBB.js} +1 -1
  18. package/dist/chunks/{dist-7PXDYX2R.js → dist-W3OOJP66.js} +1 -1
  19. package/dist/chunks/host-FRQXOEHH.js +2 -0
  20. package/dist/chunks/{run-manager-IU5COC6X.js → run-manager-FGCG7DFF.js} +1 -1
  21. package/dist/chunks/{utils-NP42DKL3.js → utils-47QI5MSP.js} +1 -1
  22. package/dist/index.d.ts +4 -4
  23. package/dist/index.js +1 -1
  24. package/dist/kodax_cli.js +927 -909
  25. package/dist/sdk-agent.d.ts +2 -2
  26. package/dist/sdk-agent.js +1 -1
  27. package/dist/sdk-coding.d.ts +6 -4
  28. package/dist/sdk-coding.js +1 -1
  29. package/dist/sdk-mcp.js +1 -1
  30. package/dist/sdk-repl.d.ts +6 -6
  31. package/dist/sdk-repl.js +1 -1
  32. package/dist/sdk-session.d.ts +3 -3
  33. package/dist/sdk-session.js +1 -1
  34. package/dist/sdk-skills.js +1 -1
  35. package/dist/types-chunks/{bash-prefix-extractor.d-Ds1THKeH.d.ts → bash-prefix-extractor.d-e1LD2IRl.d.ts} +7 -0
  36. package/dist/types-chunks/{run-manager.d-DLK3ed-T.d.ts → run-manager.d-DHPlNYkK.d.ts} +16 -2
  37. package/dist/types-chunks/{sdk-session-CtwN7iBO.d.ts → sdk-session-DINrM1pF.d.ts} +2 -2
  38. package/dist/types-chunks/{storage.d-DlZS0g8w.d.ts → storage.d-xiw7Vgx0.d.ts} +1 -1
  39. package/dist/types-chunks/{utils.d-Boz9k2HB.d.ts → utils.d-Dy19-1XR.d.ts} +2 -2
  40. package/package.json +1 -1
  41. package/dist/chunks/argument-completer-BQDAYT7W.js +0 -2
  42. package/dist/chunks/chunk-4K5BDO7S.js +0 -721
  43. package/dist/chunks/chunk-U6BNMGSK.js +0 -17
  44. package/dist/chunks/host-FLG7FJZT.js +0 -2
@@ -1,19 +1,19 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Ea as qs,P as Hn,b as Xr,c as Vr,d as Jr,fa as Fs,ha as Us,z as it}from"./chunk-S4GVQO3W.js";import{Bc as Ys,H as Ws,Na as ge,Oa as $t,Pa as dn,Qc as Gn,R as Hs,Ra as zs,Rc as Xn,Sd as Zs,T as Rt,Va as Kn,Wc as Qs,ac as ye,b as Yr,bc as Vs,c as ln,cb as Gs,db as zn,eb as Xs,k as Fe,m as Bs,na as Y,va as st,vc as Js,wa as Ks}from"./chunk-4K5BDO7S.js";import{B as Se,G as cn}from"./chunk-ZL5CEANW.js";import{a as i}from"./chunk-V4WSBIXB.js";var h_=2,g_=500,y_=500,Qr="[Cancelled]",Zr=`${Qr} Operation cancelled by user`;import ra from"fs/promises";import oa from"path";import eo from"fs/promises";import Lf from"path";var ta=336*60*60*1e3,Mf=3600*1e3;async function Pf(e,t=ta,n=Date.now()){let r;try{r=await eo.readdir(e)}catch{return{scanned:0,removed:0,failed:0,bytesRemoved:0}}let o=0,s=0,a=0,c=0;for(let l of r){let d=Lf.join(e,l),u;try{u=await eo.stat(d)}catch{a+=1;continue}if(!(!u.isFile()||(o+=1,n-u.mtimeMs<=t)))try{await eo.unlink(d),s+=1,c+=u.size}catch{a+=1}}return{scanned:o,removed:s,failed:a,bytesRemoved:c}}i(Pf,"cleanupExpiredToolOutputs");var ea=0,Ot=null;function na(e,t=ta,n=Date.now()){return Ot||(n-ea<Mf?Promise.resolve(null):(ea=n,Ot=Pf(e,t,n).then(r=>(Ot=null,r)).catch(()=>(Ot=null,null)),Ot))}i(na,"maybeRunToolOutputGc");var sa=2e3,It=50*1024,Nf=500,Vn=2e3,to=256*1024,Lt=2e3,aa=`... [line truncated to ${Lt} chars]`,no=512*1024,Df="KODAX_TOOL_OUTPUT_DIR";function ca(e){return{maxLines:e.maxLines??sa,maxBytes:e.maxBytes??It}}i(ca,"getLimits");function N(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}i(N,"formatSize");function Mt(e,t={}){let{maxLines:n,maxBytes:r}=ca(t),o=Buffer.byteLength(e,"utf-8"),s=e.split(`
2
+ import{Ea as Qs,P as Vn,b as to,c as no,d as ro,fa as Ys,ha as Zs,z as lt}from"./chunk-S4GVQO3W.js";import{Bc as la,H as ta,Na as ut,Oa as Nt,Pa as hn,Qc as Qn,R as na,Ra as oa,Rc as er,Sd as ua,T as Pt,Va as Yn,Wc as da,ac as be,b as oo,bc as aa,c as mn,cb as ia,db as Zn,eb as sa,k as Be,l as Jn,m as ea,na as Y,va as dt,vc as ca,wa as ra}from"./chunk-NJW2LQOP.js";import{B as Ce,G as pn}from"./chunk-ZL5CEANW.js";import{a as i}from"./chunk-V4WSBIXB.js";var xx=2,Ex=500,Sx=500,io="[Cancelled]",so=`${io} Operation cancelled by user`;import ha from"fs/promises";import ga from"path";import ao from"fs/promises";import fp from"path";var pa=336*60*60*1e3,pp=3600*1e3;async function mp(e,t=pa,n=Date.now()){let r;try{r=await ao.readdir(e)}catch{return{scanned:0,removed:0,failed:0,bytesRemoved:0}}let o=0,s=0,a=0,c=0;for(let l of r){let d=fp.join(e,l),u;try{u=await ao.stat(d)}catch{a+=1;continue}if(!(!u.isFile()||(o+=1,n-u.mtimeMs<=t)))try{await ao.unlink(d),s+=1,c+=u.size}catch{a+=1}}return{scanned:o,removed:s,failed:a,bytesRemoved:c}}i(mp,"cleanupExpiredToolOutputs");var fa=0,Dt=null;function ma(e,t=pa,n=Date.now()){return Dt||(n-fa<pp?Promise.resolve(null):(fa=n,Dt=mp(e,t,n).then(r=>(Dt=null,r)).catch(()=>(Dt=null,null)),Dt))}i(ma,"maybeRunToolOutputGc");var wa=2e3,Ft=50*1024,hp=500,tr=2e3,co=256*1024,jt=2e3,ba=`... [line truncated to ${jt} chars]`,lo=512*1024,gp="KODAX_TOOL_OUTPUT_DIR";function ka(e){return{maxLines:e.maxLines??wa,maxBytes:e.maxBytes??Ft}}i(ka,"getLimits");function D(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}i(D,"formatSize");function Ut(e,t={}){let{maxLines:n,maxBytes:r}=ka(t),o=Buffer.byteLength(e,"utf-8"),s=e.split(`
3
3
  `),a=s.length;if(a<=n&&o<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:a,totalBytes:o,outputLines:a,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let c=s[0]??"";if(Buffer.byteLength(c,"utf-8")>r)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines:a,totalBytes:o,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:n,maxBytes:r};let l=[],d=0,u="lines";for(let m=0;m<s.length&&m<n;m++){let h=s[m]??"",p=Buffer.byteLength(h,"utf-8")+(m>0?1:0);if(d+p>r){u="bytes";break}l.push(h),d+=p}l.length>=n&&d<=r&&(u="lines");let f=l.join(`
4
- `);return{content:f,truncated:!0,truncatedBy:u,totalLines:a,totalBytes:o,outputLines:l.length,outputBytes:Buffer.byteLength(f,"utf-8"),lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}i(Mt,"truncateHead");function Pt(e,t={}){let{maxLines:n,maxBytes:r}=ca(t),o=Buffer.byteLength(e,"utf-8"),s=e.split(`
5
- `),a=s.length;if(a<=n&&o<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:a,totalBytes:o,outputLines:a,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let c=[],l=0,d="lines",u=!1;for(let m=s.length-1;m>=0&&c.length<n;m--){let h=s[m]??"",p=Buffer.byteLength(h,"utf-8")+(c.length>0?1:0);if(l+p>r){if(d="bytes",c.length===0&&h.length>0){let g=jf(h,r);c.unshift(g),l=Buffer.byteLength(g,"utf-8"),u=!0}break}c.unshift(h),l+=p}c.length>=n&&l<=r&&(d="lines");let f=c.join(`
6
- `);return{content:f,truncated:!0,truncatedBy:d,totalLines:a,totalBytes:o,outputLines:c.length,outputBytes:Buffer.byteLength(f,"utf-8"),lastLinePartial:u,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}i(Pt,"truncateTail");function ro(e,t){if(t<=0)return e;let n=Math.min(t,e.length);for(;n<e.length&&(e[n]&192)===128;)n++;return e.subarray(n)}i(ro,"trimBufferStartToUtf8Boundary");function jf(e,t){let n=Buffer.from(e,"utf-8");return n.length<=t?e:ro(n,n.length-t).toString("utf-8")}i(jf,"truncateStringToBytesFromEnd");function un(e,t=Nf){return e.length<=t?{text:e,wasTruncated:!1}:{text:`${e.slice(0,t)}... [truncated]`,wasTruncated:!0}}i(un,"truncateLine");function Ff(){return process.env[Df]||Ks("tool-results")}i(Ff,"resolveToolOutputDir");function ia(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"tool"}i(ia,"sanitizePathSegment");async function Nt(e,t,n){let r=Ff(),o=ia(oa.basename(n?.gitRoot??n?.executionCwd??"session")),s=new Date().toISOString().replace(/[:.]/g,"-"),a=Math.random().toString(36).slice(2,8),c=`${s}-${o}-${ia(e)}-${a}.txt`,l=oa.join(r,c);return await ra.mkdir(r,{recursive:!0}),await ra.writeFile(l,t,"utf-8"),na(r),l}i(Nt,"persistToolOutput");async function Ue({diff:e,toolName:t,filePath:n,ctx:r,maxLines:o=200,maxBytes:s=24*1024}){let a=Mt(e,{maxLines:o,maxBytes:s});if(!a.truncated)return e;let c;try{c=await Nt(`${t}-diff`,e,r)}catch{c=void 0}let l=c?` Full diff saved to: ${c}.`:"";return`${a.content}
4
+ `);return{content:f,truncated:!0,truncatedBy:u,totalLines:a,totalBytes:o,outputLines:l.length,outputBytes:Buffer.byteLength(f,"utf-8"),lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}i(Ut,"truncateHead");function ft(e,t={}){let{maxLines:n,maxBytes:r}=ka(t),o=Buffer.byteLength(e,"utf-8"),s=e.split(`
5
+ `),a=s.length;if(a<=n&&o<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:a,totalBytes:o,outputLines:a,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let c=[],l=0,d="lines",u=!1;for(let m=s.length-1;m>=0&&c.length<n;m--){let h=s[m]??"",p=Buffer.byteLength(h,"utf-8")+(c.length>0?1:0);if(l+p>r){if(d="bytes",c.length===0&&h.length>0){let g=yp(h,r);c.unshift(g),l=Buffer.byteLength(g,"utf-8"),u=!0}break}c.unshift(h),l+=p}c.length>=n&&l<=r&&(d="lines");let f=c.join(`
6
+ `);return{content:f,truncated:!0,truncatedBy:d,totalLines:a,totalBytes:o,outputLines:c.length,outputBytes:Buffer.byteLength(f,"utf-8"),lastLinePartial:u,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}i(ft,"truncateTail");function uo(e,t){if(t<=0)return e;let n=Math.min(t,e.length);for(;n<e.length&&(e[n]&192)===128;)n++;return e.subarray(n)}i(uo,"trimBufferStartToUtf8Boundary");function yp(e,t){let n=Buffer.from(e,"utf-8");return n.length<=t?e:uo(n,n.length-t).toString("utf-8")}i(yp,"truncateStringToBytesFromEnd");function gn(e,t=hp){return e.length<=t?{text:e,wasTruncated:!1}:{text:`${e.slice(0,t)}... [truncated]`,wasTruncated:!0}}i(gn,"truncateLine");function wp(){return process.env[gp]||ra("tool-results")}i(wp,"resolveToolOutputDir");function ya(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"tool"}i(ya,"sanitizePathSegment");async function We(e,t,n){let r=wp(),o=ya(ga.basename(n?.gitRoot??n?.executionCwd??"session")),s=new Date().toISOString().replace(/[:.]/g,"-"),a=Math.random().toString(36).slice(2,8),c=`${s}-${o}-${ya(e)}-${a}.txt`,l=ga.join(r,c);return await ha.mkdir(r,{recursive:!0}),await ha.writeFile(l,t,"utf-8"),ma(r),l}i(We,"persistToolOutput");async function He({diff:e,toolName:t,filePath:n,ctx:r,maxLines:o=200,maxBytes:s=24*1024}){let a=Ut(e,{maxLines:o,maxBytes:s});if(!a.truncated)return e;let c;try{c=await We(`${t}-diff`,e,r)}catch{c=void 0}let l=c?` Full diff saved to: ${c}.`:"";return`${a.content}
7
7
 
8
- [Diff preview truncated: showing ${a.outputLines} of ${a.totalLines} lines (${N(a.outputBytes)} of ${N(a.totalBytes)}).${l} Use read on ${n} to inspect the current file.]`}i(Ue,"formatDiffPreview");import io from"fs/promises";import{createReadStream as qf}from"fs";import Bf from"node:path";import{createInterface as Wf}from"readline";import Jn from"path";function Q(e){return Jn.resolve(e?.executionCwd??e?.gitRoot??process.cwd())}i(Q,"resolveExecutionCwd");function q(e,t){let n=Q(t);return Jn.isAbsolute(e)?Jn.resolve(e):Jn.resolve(n,e)}i(q,"resolveExecutionPath");function Dt(e,t){return!e||!e.trim()?Q(t):q(e,t)}i(Dt,"resolveExecutionPathOrCwd");import*as la from"node:fs";var Uf={statSync(e){return{mtimeMs:la.statSync(e).mtimeMs}}};function oo(e,t){return`${e}|${t}`}i(oo,"rangeKey");function L_(e={}){if(e.disabled??process.env.KODAX_READ_DEDUP_KILLSWITCH==="1")return{lookup:i(()=>({kind:"miss"}),"lookup"),record:i(()=>{},"record"),forget:i(()=>{},"forget"),clear:i(()=>{},"clear"),size:i(()=>0,"size")};let n=e.fs??Uf,r=e.clock??Date.now,o=new Map;return{lookup(s,a,c){let l=o.get(s);if(!l)return{kind:"miss"};let d=l.get(oo(a,c));if(!d)return{kind:"miss"};let u;try{u=n.statSync(s).mtimeMs}catch{return{kind:"miss"}}return u!==d.mtimeMs?(l.delete(oo(a,c)),{kind:"miss"}):{kind:"hit",previousReadAtMs:d.readAtMs}},record(s,a,c,l){let d=o.get(s);d||(d=new Map,o.set(s,d)),d.set(oo(a,c),{mtimeMs:l,readAtMs:r()})},forget(s){o.delete(s)},clear(){o.clear()},size(){return o.size}}}i(L_,"createReadFileStateCache");function da(e,t,n){return`[Read Cache] ${e} is unchanged since you read it earlier in this task (offset=${t}, limit=${n}). The content from the earlier read tool_result in this conversation is still current \u2014 refer to that instead of re-reading. If you need different lines, call read with a different offset/limit. If the file is modified externally, this cache invalidates automatically on mtime change.`}i(da,"buildReadFileUnchangedStub");var Hf=4096,Kf={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},ua=10*1024*1024;function zf(e){let{offset:t,linesShown:n,limit:r,totalLines:o,hasMoreLines:s,preflightNote:a,truncatedLongLine:c}=e,l=[];if(a&&l.push(a),c&&l.push(`[Some long lines were shortened to ${Lt} characters.]`),s){let d=t+n,u=Math.max(t,d-1);l.push(`[Showing lines ${t}-${u}. Use offset=${d} limit=${r} to continue.]`)}else l.push(`[End of file${o>0?` - ${o} lines total`:""}]`);return l}i(zf,"buildReadNotes");function Gf(e,t){let n=e.join(`
8
+ [Diff preview truncated: showing ${a.outputLines} of ${a.totalLines} lines (${D(a.outputBytes)} of ${D(a.totalBytes)}).${l} Use read on ${n} to inspect the current file.]`}i(He,"formatDiffPreview");import po from"fs/promises";import{createReadStream as kp}from"fs";import vp from"node:path";import{createInterface as _p}from"readline";import nr from"path";function Z(e){return nr.resolve(e?.executionCwd??e?.gitRoot??process.cwd())}i(Z,"resolveExecutionCwd");function B(e,t){let n=Z(t);return nr.isAbsolute(e)?nr.resolve(e):nr.resolve(n,e)}i(B,"resolveExecutionPath");function qt(e,t){return!e||!e.trim()?Z(t):B(e,t)}i(qt,"resolveExecutionPathOrCwd");import*as va from"node:fs";var bp={statSync(e){return{mtimeMs:va.statSync(e).mtimeMs}}};function fo(e,t){return`${e}|${t}`}i(fo,"rangeKey");function qx(e={}){if(e.disabled??process.env.KODAX_READ_DEDUP_KILLSWITCH==="1")return{lookup:i(()=>({kind:"miss"}),"lookup"),record:i(()=>{},"record"),forget:i(()=>{},"forget"),clear:i(()=>{},"clear"),size:i(()=>0,"size")};let n=e.fs??bp,r=e.clock??Date.now,o=new Map;return{lookup(s,a,c){let l=o.get(s);if(!l)return{kind:"miss"};let d=l.get(fo(a,c));if(!d)return{kind:"miss"};let u;try{u=n.statSync(s).mtimeMs}catch{return{kind:"miss"}}return u!==d.mtimeMs?(l.delete(fo(a,c)),{kind:"miss"}):{kind:"hit",previousReadAtMs:d.readAtMs}},record(s,a,c,l){let d=o.get(s);d||(d=new Map,o.set(s,d)),d.set(fo(a,c),{mtimeMs:l,readAtMs:r()})},forget(s){o.delete(s)},clear(){o.clear()},size(){return o.size}}}i(qx,"createReadFileStateCache");function _a(e,t,n){return`[Read Cache] ${e} is unchanged since you read it earlier in this task (offset=${t}, limit=${n}). The content from the earlier read tool_result in this conversation is still current \u2014 refer to that instead of re-reading. If you need different lines, call read with a different offset/limit. If the file is modified externally, this cache invalidates automatically on mtime change.`}i(_a,"buildReadFileUnchangedStub");var xp=4096,Ep={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},xa=10*1024*1024;function Sp(e){let{offset:t,linesShown:n,limit:r,totalLines:o,hasMoreLines:s,preflightNote:a,truncatedLongLine:c}=e,l=[];if(a&&l.push(a),c&&l.push(`[Some long lines were shortened to ${jt} characters.]`),s){let d=t+n,u=Math.max(t,d-1);l.push(`[Showing lines ${t}-${u}. Use offset=${d} limit=${r} to continue.]`)}else l.push(`[End of file${o>0?` - ${o} lines total`:""}]`);return l}i(Sp,"buildReadNotes");function Tp(e,t){let n=e.join(`
9
9
  `);return n?`${n}
10
10
 
11
11
  ${t.join(`
12
12
  `)}`:t.join(`
13
- `)}i(Gf,"renderReadOutput");async function Xf(e,t){if(t===0)return!1;let n=await io.open(e,"r");try{let r=Math.min(Hf,t),o=Buffer.alloc(r),{bytesRead:s}=await n.read(o,0,r,0);if(s===0)return!1;let a=0;for(let c=0;c<s;c++){let l=o[c];if(l===0)return!0;(l<9||l>13&&l<32)&&a++}return a/s>.3}finally{await n.close()}}i(Xf,"isProbablyBinary");var Vf=5*1024*1024;async function Jf(e,t,n){if(e.contentHashCache&&!(n>Vf))try{let r=await io.readFile(t,"utf-8");e.contentHashCache.recordRead(t,r)}catch{}}i(Jf,"maybeRecordContentHash");async function so(e,t){let n=q(e.path,t),r;try{r=await io.stat(n)}catch(C){if(C.code==="ENOENT")return`[Tool Error] File not found: ${n}`;let T=C instanceof Error?C.message:String(C);return`[Tool Error] Unable to access file: ${n}. ${T}`}if(!r.isFile())return`[Tool Error] Path is not a file: ${n}`;let o=Bf.extname(n).toLowerCase();if(o===".pdf")return[`[Tool Error] PDF files are not parsed by the built-in read tool: ${n}.`,"If the read_pdf tool is available in this session, call read_pdf with this path to extract page-marked text and OCR scanned pages when configured.","If read_pdf is unavailable, ask the user to install or enable the read_pdf extension."].join(" ");let s=Kf[o];if(s)return r.size>ua?`[Tool Error] Image too large to inline (${N(r.size)} > ${N(ua)}): ${n}. Resize before reading.`:[{type:"text",text:`[Read image: ${n} (${N(r.size)}, ${s})] \u2014 image content delivered as inline vision below; describe what you see in your next response.`},{type:"image",path:n,mediaType:s}];if(await Xf(n,r.size))return`[Tool Error] Binary file not supported by read: ${n}`;let a=Number.isFinite(e.offset)?Number(e.offset):1,c=Number.isFinite(e.limit)?Number(e.limit):Vn,l=Math.max(1,Math.floor(a)),d=Math.max(1,Math.floor(c)),u=l-1;if(t.readFileStateCache&&t.readFileStateCache.lookup(n,l,d).kind==="hit")return da(n,l,d);let f=[],m=qf(n,{encoding:"utf-8"}),h=Wf({input:m,crlfDelay:1/0}),p=0,g=0,w=!1,y=!1;try{for await(let C of h){if(p++,p<=u)continue;if(f.length>=d){w=!0;break}let T=l+f.length,x=C.length>Lt?`${C.slice(0,Lt)}${aa}`:C;y||=x!==C;let R=`${T.toString().padStart(6)} ${x}`,A=Buffer.byteLength(R,"utf-8")+(f.length>0?1:0);if(g+A>It){w=!0;break}f.push(R),g+=A}}finally{h.close(),m.destroy()}if(p<l&&!(p===0&&l===1))return`[Tool Error] Offset ${l} is beyond end of file (${p} lines total)`;let b=e.limit===void 0&&r.size>to?`[Large file: ${N(r.size)}. Read returns at most ${Vn} lines or ${N(It)} per call. Use offset/limit or grep to narrow the scope.]`:"",v=[...f],k=w;for(;;){let C=zf({offset:l,linesShown:v.length,limit:d,totalLines:p,hasMoreLines:k,preflightNote:b,truncatedLongLine:y}),T=Gf(v,C);if(Buffer.byteLength(T,"utf-8")<=It||v.length===0)return await Jf(t,n,r.size),t.readFileStateCache?.record(n,l,d,r.mtimeMs),T;v.pop(),k=!0}}i(so,"toolRead");var ao=Object.keys(Fs),Yf=ao.join(", "),fa=["overview","install","quickstart","providers","custom-providers","config","permissions","commands","tools","agents","skills","extensions","mcp","repo-intelligence","sessions","doctor","sdk","troubleshooting"],z_=["providers","custom-providers","config","permissions","tools","skills","extensions","mcp","repo-intelligence","sessions","sdk"],Qf=[{id:"overview",title:"What KodaX is",aliases:["about","what is kodax","intro","\u4ECB\u7ECD","\u662F\u4EC0\u4E48","\u6982\u89C8"],summary:"What KodaX is, what it is for, and how it differs from Claude Code / Codex CLI.",body:["KodaX is a multi-provider AI coding CLI: an interactive REPL + SDK that plans,",`edits code, runs tools, and reviews its own work across ${ao.length} LLM provider aliases.`,"","Boundary: KodaX is its own product. It does NOT read .claude/settings.json (Claude","Code) or config.toml (Codex CLI). KodaX is configured via ~/.kodax/config.json and","KODAX_* env vars. When in doubt about a KodaX behavior, prefer this manual over","general pretraining knowledge."].join(`
13
+ `)}i(Tp,"renderReadOutput");async function Ap(e,t){if(t===0)return!1;let n=await po.open(e,"r");try{let r=Math.min(xp,t),o=Buffer.alloc(r),{bytesRead:s}=await n.read(o,0,r,0);if(s===0)return!1;let a=0;for(let c=0;c<s;c++){let l=o[c];if(l===0)return!0;(l<9||l>13&&l<32)&&a++}return a/s>.3}finally{await n.close()}}i(Ap,"isProbablyBinary");var Cp=5*1024*1024;async function $p(e,t,n){if(e.contentHashCache&&!(n>Cp))try{let r=await po.readFile(t,"utf-8");e.contentHashCache.recordRead(t,r)}catch{}}i($p,"maybeRecordContentHash");async function mo(e,t){let n=B(e.path,t),r;try{r=await po.stat(n)}catch($){if($.code==="ENOENT")return`[Tool Error] File not found: ${n}`;let S=$ instanceof Error?$.message:String($);return`[Tool Error] Unable to access file: ${n}. ${S}`}if(!r.isFile())return`[Tool Error] Path is not a file: ${n}`;let o=vp.extname(n).toLowerCase();if(o===".pdf")return[`[Tool Error] PDF files are not parsed by the built-in read tool: ${n}.`,"If the read_pdf tool is available in this session, call read_pdf with this path to extract page-marked text and OCR scanned pages when configured.","If read_pdf is unavailable, ask the user to install or enable the read_pdf extension."].join(" ");let s=Ep[o];if(s)return r.size>xa?`[Tool Error] Image too large to inline (${D(r.size)} > ${D(xa)}): ${n}. Resize before reading.`:[{type:"text",text:`[Read image: ${n} (${D(r.size)}, ${s})] \u2014 image content delivered as inline vision below; describe what you see in your next response.`},{type:"image",path:n,mediaType:s}];if(await Ap(n,r.size))return`[Tool Error] Binary file not supported by read: ${n}`;let a=Number.isFinite(e.offset)?Number(e.offset):1,c=Number.isFinite(e.limit)?Number(e.limit):tr,l=Math.max(1,Math.floor(a)),d=Math.max(1,Math.floor(c)),u=l-1;if(t.readFileStateCache&&t.readFileStateCache.lookup(n,l,d).kind==="hit")return _a(n,l,d);let f=[],m=kp(n,{encoding:"utf-8"}),h=_p({input:m,crlfDelay:1/0}),p=0,g=0,w=!1,y=!1;try{for await(let $ of h){if(p++,p<=u)continue;if(f.length>=d){w=!0;break}let S=l+f.length,x=$.length>jt?`${$.slice(0,jt)}${ba}`:$;y||=x!==$;let R=`${S.toString().padStart(6)} ${x}`,A=Buffer.byteLength(R,"utf-8")+(f.length>0?1:0);if(g+A>Ft){w=!0;break}f.push(R),g+=A}}finally{h.close(),m.destroy()}if(p<l&&!(p===0&&l===1))return`[Tool Error] Offset ${l} is beyond end of file (${p} lines total)`;let b=e.limit===void 0&&r.size>co?`[Large file: ${D(r.size)}. Read returns at most ${tr} lines or ${D(Ft)} per call. Use offset/limit or grep to narrow the scope.]`:"",v=[...f],k=w;for(;;){let $=Sp({offset:l,linesShown:v.length,limit:d,totalLines:p,hasMoreLines:k,preflightNote:b,truncatedLongLine:y}),S=Tp(v,$);if(Buffer.byteLength(S,"utf-8")<=Ft||v.length===0)return await $p(t,n,r.size),t.readFileStateCache?.record(n,l,d,r.mtimeMs),S;v.pop(),k=!0}}i(mo,"toolRead");var ho=Object.keys(Ys),Rp=ho.join(", "),Ea=["overview","install","quickstart","providers","custom-providers","config","permissions","commands","tools","agents","skills","extensions","mcp","repo-intelligence","sessions","doctor","sdk","troubleshooting"],eE=["providers","custom-providers","config","permissions","tools","skills","extensions","mcp","repo-intelligence","sessions","sdk"],Op=[{id:"overview",title:"What KodaX is",aliases:["about","what is kodax","intro","\u4ECB\u7ECD","\u662F\u4EC0\u4E48","\u6982\u89C8"],summary:"What KodaX is, what it is for, and how it differs from Claude Code / Codex CLI.",body:["KodaX is a multi-provider AI coding CLI: an interactive REPL + SDK that plans,",`edits code, runs tools, and reviews its own work across ${ho.length} LLM provider aliases.`,"","Boundary: KodaX is its own product. It does NOT read .claude/settings.json (Claude","Code) or config.toml (Codex CLI). KodaX is configured via ~/.kodax/config.json and","KODAX_* env vars. When in doubt about a KodaX behavior, prefer this manual over","general pretraining knowledge."].join(`
14
14
  `),sources:[{label:"README",path:"README.md"}],nextTopics:["install","quickstart","providers"]},{id:"install",title:"Install & start KodaX",aliases:["setup","getting started","\u5B89\u88C5","\u542F\u52A8","\u600E\u4E48\u88C5"],summary:"npm install, Node version, first launch, updating.",body:["Install (Node >= 20):"," npm install -g @kodax-ai/kodax","Then run `kodax` in any project directory to start the interactive REPL.","","Native binaries (no Node needed) are published per release on GitHub Releases","(darwin/linux/win, arm64/x64).","Update: re-run the npm install, or download the new binary."].join(`
15
15
  `),sources:[{label:"package",path:"package.json"}],nextTopics:["quickstart","providers","config"]},{id:"quickstart",title:"Quickstart workflow",aliases:["workflow","first task","\u5FEB\u901F\u5F00\u59CB","\u4E0A\u624B","\u600E\u4E48\u7528"],summary:"Open a project, give a task, review, run tests, continue a session.",body:["1. `cd` into your repo and run `kodax`.","2. Describe the task in plain language; KodaX plans, edits, and runs tools.","3. Review proposed edits (permission mode controls auto-accept vs prompt).","4. Ask it to run tests / build to verify.","5. Continue later: `kodax -c` (continue last) or `kodax -r` (resume a picker)."].join(`
16
- `),sources:[{label:"commands",path:"packages/repl/src/interactive/commands.ts"}],nextTopics:["commands","permissions","sessions"]},{id:"providers",title:"Providers & models",aliases:["provider","model","models","llm","\u4F9B\u5E94\u5546","\u6A21\u578B","\u63D0\u4F9B\u5546"],summary:"Built-in providers, choosing a model, credential check, cross-provider fallback.",body:[`KodaX ships ${ao.length} built-in provider aliases:`,` ${Yf}`,"",`Default provider: ${Us} (override with KODAX_PROVIDER env or`,'"provider" in ~/.kodax/config.json). Switch model live with the /model command.',"","Check a key works: `verifyCredential` (SDK) / a configured provider is validated via","its verifyStrategy in provider-capabilities.json.","Cross-provider fallback on hard errors: /fallback slash + KODAX_FALLBACK_PROVIDERS.","Cheap/strong tiers for dispatched children: KODAX_FAST_* / KODAX_DEEP_*."].join(`
16
+ `),sources:[{label:"commands",path:"packages/repl/src/interactive/commands.ts"}],nextTopics:["commands","permissions","sessions"]},{id:"providers",title:"Providers & models",aliases:["provider","model","models","llm","\u4F9B\u5E94\u5546","\u6A21\u578B","\u63D0\u4F9B\u5546"],summary:"Built-in providers, choosing a model, credential check, cross-provider fallback.",body:[`KodaX ships ${ho.length} built-in provider aliases:`,` ${Rp}`,"",`Default provider: ${Zs} (override with KODAX_PROVIDER env or`,'"provider" in ~/.kodax/config.json). Switch model live with the /model command.',"","Check a key works: `verifyCredential` (SDK) / a configured provider is validated via","its verifyStrategy in provider-capabilities.json.","Cross-provider fallback on hard errors: /fallback slash + KODAX_FALLBACK_PROVIDERS.","Cheap/strong tiers for dispatched children: KODAX_FAST_* / KODAX_DEEP_*."].join(`
17
17
  `),sources:[{label:"provider capabilities",path:"packages/llm/src/providers/provider-capabilities.json"}],nextTopics:["custom-providers","config","troubleshooting"]},{id:"custom-providers",title:"Custom providers",aliases:["custom provider","baseurl","openai compatible","\u81EA\u5B9A\u4E49\u4F9B\u5E94\u5546","\u81EA\u5B9A\u4E49\u6A21\u578B"],summary:"Point KodaX at an OpenAI/Anthropic-compatible endpoint, incl. thinking config.",body:["Add a `customProviders` entry in ~/.kodax/config.json for an OpenAI/Anthropic-","compatible endpoint: specify the protocol, baseUrl, auth header(s), and model name(s).","KodaX infers a verifyStrategy from the protocol; you can override it explicitly.","Once added, the custom provider is selectable like any built-in one.","","Thinking / reasoning (set on the provider, or per-model in models[]):","- supportsThinking: true is enough for most non-Claude models. With a bare"," supportsThinking: true (no explicit reasoningPreset/reasoningProfile), openai-compat"," stays passive \u2014 KodaX sends no thinking toggle and just surfaces the reasoning the",' model emits; anthropic-compat sends thinking:{type:"enabled"}, which is what the'," Anthropic-compatible endpoints of zhipu / kimi / minimax / deepseek expect. (An"," explicit reasoningPreset/reasoningProfile can send a toggle on openai-compat too.)","- openai-compat multi-turn caveat: some reasoning models (notably DeepSeek V4) reject a"," later turn whose history drops the prior reasoning_content. If thinking shows on the"," first turn but a follow-up errors, also set replayReasoningContent: true (per-provider"," or per-model).",'- reasoning: { efforts: ["low","high"], default: "high" } adds a tunable effort level.'," On openai-compat it sends reasoning_effort; on anthropic-compat it sends",' thinking:{type:"enabled"} + reasoning_effort (the non-Claude dialect). Include "off"'," in efforts to allow disabling thinking.","- Pointing anthropic-compat at REAL Claude (4.6+)? Claude needs adaptive thinking, not",' the enable toggle \u2014 set reasoningCapability: "native-adaptive" (or an explicit',' reasoningProfile with effortStrategy "anthropic-output-effort").',"- reasoningCapability is the low-level override: native-toggle / native-budget /"," native-effort / native-adaptive / none. It is ignored when supportsThinking is false.","If a relay rejects the chosen thinking shape, KodaX retries the turn once without it, so","it still completes (you just see no thinking) instead of erroring."].join(`
18
18
  `),sources:[{label:"config loader",path:"packages/repl/src/common/utils.ts"},{label:"custom provider reasoning",path:"packages/llm/src/providers/custom-provider.ts"}],nextTopics:["providers","config"]},{id:"config",title:"Configuration",aliases:["settings","config.json","env","\u914D\u7F6E","\u8BBE\u7F6E","\u73AF\u5883\u53D8\u91CF"],summary:"~/.kodax/config.json fields and KODAX_* env precedence (no YAML).",body:["KodaX config is JSON + env vars \u2014 there is no YAML and no single loader entry.","File: ~/.kodax/config.json. Common keys: provider, model, effort, planModeEffort,","permissionMode, customProviders, mcpServers, repoIntelligenceMode, fallbackProviders,","autoMode, verifierLog, stallLog.","Env mirrors / extras: KODAX_PROVIDER, KODAX_EFFORT, KODAX_FALLBACK_PROVIDERS, KODAX_FAST_*/KODAX_DEEP_*,","KODAX_REPO_INTELLIGENCE. Env generally overrides file. Project vs user config:","user config is ~/.kodax; project-scoped state lives under <repo>/.kodax/."].join(`
19
19
  `),sources:[{label:"config loader",path:"packages/repl/src/common/utils.ts"},{label:"permission config",path:"packages/repl/src/common/permission-config.ts"}],nextTopics:["providers","permissions","mcp"]},{id:"permissions",title:"Permission modes",aliases:["permission","approval","dangerous","\u6743\u9650","\u5BA1\u6279","\u6743\u9650\u6A21\u5F0F"],summary:"File/command permission modes, approvals, read-only.",body:["permissionMode controls when KodaX asks before file/command actions:","- accept-edits: auto-apply edits, still gate risky commands.","- plan: read-only planning, no mutations until you switch.","- auto: data-driven classifier decides per action (KODAX_AUTO_MODE_*).",'Set via ~/.kodax/config.json "permissionMode" or the relevant slash command.',"Threat model: KodaX is a single-user CLI; workspace integrity is the user\u2019s responsibility."].join(`
@@ -28,50 +28,57 @@ ${t.join(`
28
28
  `),sources:[{label:"session storage",path:"packages/repl/src/interactive/storage.ts"}],nextTopics:["commands","config","troubleshooting"]},{id:"doctor",title:"kodax doctor",aliases:["doctor","diagnose","health check","ping","\u8BCA\u65AD","\u4F53\u68C0"],summary:"Diagnose config/provider/credential issues; --ping live reachability.",body:["Run `kodax doctor` to print a health report: configured provider(s), credential/config","state, and storage directories. Add `kodax doctor --ping` to live-probe whether each","configured provider is reachable with the current key. This is the first stop for",'connection / 401 / 429 / "provider not working" problems.'].join(`
29
29
  `),sources:[{label:"doctor CLI",path:"src/kodax_doctor.ts"}],nextTopics:["troubleshooting","providers","config"]},{id:"sdk",title:"SDK",aliases:["embed","library","api","sdk\u5165\u95E8","\u5D4C\u5165"],summary:"The 4 packages and the minimal entry to run a task / query capabilities.",body:["KodaX is 4 npm packages: @kodax-ai/llm (provider abstraction), @kodax-ai/agent (agent","framework + skills + mcp + tracing), @kodax-ai/coding (coding tools + prompts +","repo-intelligence), @kodax-ai/repl (interactive REPL).","Embed by importing @kodax-ai/coding to run a task, or @kodax-ai/llm for raw provider","calls. Capability queries (per-model context/limits, verifyCredential, discoverMarkdownAgents)","work without an API key for embedder UIs."].join(`
30
30
  `),sources:[{label:"packages",path:"packages/"}],nextTopics:["providers","agents","tools"]},{id:"troubleshooting",title:"Troubleshooting",aliases:["error","problem","401","429","fix","\u6392\u969C","\u62A5\u9519","\u95EE\u9898"],summary:"First run kodax doctor; provider 401/429, network, Windows paths, Node/npm.",body:["First: run `kodax doctor --ping` to localize the problem.","- 401 / unauthorized: key missing/invalid \u2014 check provider env var or config.json.","- 429 / rate limit: back off, or set KODAX_FALLBACK_PROVIDERS for cross-provider fallback.","- Network: corporate proxy / region blocks can fail provider endpoints.","- Windows: paths use forward slashes internally; case-insensitive workspace match is handled.","- Node/npm: ensure Node >= 20; reinstall the global package if the CLI is stale."].join(`
31
- `),sources:[{label:"doctor CLI",path:"src/kodax_doctor.ts"}],nextTopics:["doctor","providers","config"]}],pa=Object.freeze(Object.fromEntries(Qf.map(e=>[e.id,e])));var Zf=4096,ep=2048,tp="KodaX";function np(e){return{id:String(e.id??""),title:String(e.title??""),aliases:e.aliases??[],summary:String(e.summary??""),body:String(e.body??""),sources:e.sources??[],nextTopics:e.nextTopics??[]}}i(np,"normalizeInjected");function rp(e,t){let n=new Map,r=[],o=t??fa;for(let s of o){if(n.has(s))continue;let a=pa[s];a&&(n.set(s,a),r.push(s))}for(let s of e??[])n.has(s.id)||r.push(s.id),n.set(s.id,np(s));return{ids:r,byId:n}}i(rp,"buildEntries");function co(e){return Buffer.byteLength(e,"utf-8")}i(co,"byteLength");function ga(e,t){if(co(e)<=t)return e;let n=`
32
- \u2026(truncated; ask for a narrower topic)`,r=t-co(n),o=e;for(;co(o)>r&&o.length>0;)o=o.slice(0,Math.max(0,o.length-16));return o+n}i(ga,"truncateToBytes");function op(e,t){return`(${t} ${e} manual \u2014 about ${t} itself, not Claude Code or Codex CLI.`+(t==="KodaX"?" KodaX config lives in ~/.kodax/config.json + KODAX_* env vars.)":")")}i(op,"scopeAnchor");function ya(e){return e.toLowerCase().split(/[^a-z0-9一-鿿]+/u).filter(t=>t.length>0)}i(ya,"tokenize");function ip(e,t,n){return e.includes(n)?t.get(n):void 0}i(ip,"findByExactId");function sp(e,t,n){let r=n.trim().toLowerCase();if(r.length!==0)for(let o of e){let s=t.get(o);if(s.aliases.some(a=>a.toLowerCase()===r))return s}}i(sp,"findByAlias");function ap(e,t){if(t.length===0)return 0;let n=new Set(ya([e.id,e.title,e.summary,...e.aliases].join(" "))),r=0;for(let o of t)n.has(o)&&(r+=1);return r}i(ap,"scoreTopic");function ma(e,t,n){let r=ya(n);return e.map(o=>t.get(o)).map(o=>({topic:o,score:ap(o,r)})).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).map(o=>o.topic)}i(ma,"rankByQuery");function ha(e,t){let n=ga(`${op(e.id,t)}
31
+ `),sources:[{label:"doctor CLI",path:"src/kodax_doctor.ts"}],nextTopics:["doctor","providers","config"]}],Sa=Object.freeze(Object.fromEntries(Op.map(e=>[e.id,e])));var Ip=4096,Lp=2048,Mp="KodaX";function Pp(e){return{id:String(e.id??""),title:String(e.title??""),aliases:e.aliases??[],summary:String(e.summary??""),body:String(e.body??""),sources:e.sources??[],nextTopics:e.nextTopics??[]}}i(Pp,"normalizeInjected");function Np(e,t){let n=new Map,r=[],o=t??Ea;for(let s of o){if(n.has(s))continue;let a=Sa[s];a&&(n.set(s,a),r.push(s))}for(let s of e??[])n.has(s.id)||r.push(s.id),n.set(s.id,Pp(s));return{ids:r,byId:n}}i(Np,"buildEntries");function go(e){return Buffer.byteLength(e,"utf-8")}i(go,"byteLength");function Ca(e,t){if(go(e)<=t)return e;let n=`
32
+ \u2026(truncated; ask for a narrower topic)`,r=t-go(n),o=e;for(;go(o)>r&&o.length>0;)o=o.slice(0,Math.max(0,o.length-16));return o+n}i(Ca,"truncateToBytes");function Dp(e,t){return`(${t} ${e} manual \u2014 about ${t} itself, not Claude Code or Codex CLI.`+(t==="KodaX"?" KodaX config lives in ~/.kodax/config.json + KODAX_* env vars.)":")")}i(Dp,"scopeAnchor");function $a(e){return e.toLowerCase().split(/[^a-z0-9一-鿿]+/u).filter(t=>t.length>0)}i($a,"tokenize");function Fp(e,t,n){return e.includes(n)?t.get(n):void 0}i(Fp,"findByExactId");function jp(e,t,n){let r=n.trim().toLowerCase();if(r.length!==0)for(let o of e){let s=t.get(o);if(s.aliases.some(a=>a.toLowerCase()===r))return s}}i(jp,"findByAlias");function Up(e,t){if(t.length===0)return 0;let n=new Set($a([e.id,e.title,e.summary,...e.aliases].join(" "))),r=0;for(let o of t)n.has(o)&&(r+=1);return r}i(Up,"scoreTopic");function Ta(e,t,n){let r=$a(n);return e.map(o=>t.get(o)).map(o=>({topic:o,score:Up(o,r)})).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).map(o=>o.topic)}i(Ta,"rankByQuery");function Aa(e,t){let n=Ca(`${Dp(e.id,t)}
33
33
 
34
- ${e.body}`,Zf);return{matchedTopic:e.id,title:e.title,content:n,sources:e.sources,nextTopics:e.nextTopics}}i(ha,"buildTopicResult");function lo(e,t,n,r){let o=r&&r.length>0?`No exact ${n} manual topic matched. Closest topics:`:`${n} manual topics (call kodax_manual with one of these as "topic"):`,s=(r&&r.length>0?r:e.map(c=>t.get(c))).map(c=>`- ${c.id}: ${c.summary}`).join(`
35
- `),a=(r??[]).slice(0,3).map(c=>c.id);return{matchedTopic:"index",title:`${n} Manual \u2014 Index`,content:ga(`${o}
34
+ ${e.body}`,Ip);return{matchedTopic:e.id,title:e.title,content:n,sources:e.sources,nextTopics:e.nextTopics}}i(Aa,"buildTopicResult");function yo(e,t,n,r){let o=r&&r.length>0?`No exact ${n} manual topic matched. Closest topics:`:`${n} manual topics (call kodax_manual with one of these as "topic"):`,s=(r&&r.length>0?r:e.map(c=>t.get(c))).map(c=>`- ${c.id}: ${c.summary}`).join(`
35
+ `),a=(r??[]).slice(0,3).map(c=>c.id);return{matchedTopic:"index",title:`${n} Manual \u2014 Index`,content:Ca(`${o}
36
36
 
37
- ${s}`,ep),sources:[],nextTopics:a}}i(lo,"buildIndexResult");function wa(e,t){let n=t?.productName?.trim()||tp,{ids:r,byId:o}=rp(t?.extraTopics,t?.baseTopics),s=e.topic?.trim();if(s){let c=ip(r,o,s)??sp(r,o,s);return c?ha(c,n):lo(r,o,n,ma(r,o,s).slice(0,3))}let a=e.query?.trim();if(a){let c=ma(r,o,a);return c.length>0&&c[0]?ha(c[0],n):lo(r,o,n)}return lo(r,o,n)}i(wa,"resolveKodaXManual");var Yn="KodaX";function uo(e=Yn){let t=e.trim()||Yn,n=t===Yn?` \u2014 ${t} uses ~/.kodax/config.json and KODAX_* env vars, not .claude/settings.json or config.toml.`:".";return[`Look up how to use, install, configure, troubleshoot, or extend ${t} itself.`,"Covers providers, custom providers, config, permissions, slash commands, tools, custom agents, skills, extensions, MCP, repo intelligence, sessions, the doctor command, and the SDK.",`Call this first for any "how do I \u2026 in ${t}" question and answer from its result.`,`Do not answer ${t} product questions from pretraining, because pretraining mixes in Claude Code and Codex CLI details that do not match ${t}${n}`,"Pass an exact topic id, or a free-text query, or neither to get the topic index. It explains where to check a value rather than reading your secrets."].join(`
38
- `)}i(uo,"buildManualToolDescription");function ba(e,t){if(e.name!=="kodax_manual")return e;let n=t?.trim();return!n||n===Yn?e:{...e,description:uo(n)}}i(ba,"withManualToolBranding");import fo from"fs/promises";import mp from"fs";import hp from"path";function qe(e,t,n,r=3){let o=e.split(`
37
+ ${s}`,Lp),sources:[],nextTopics:a}}i(yo,"buildIndexResult");function Ra(e,t){let n=t?.productName?.trim()||Mp,{ids:r,byId:o}=Np(t?.extraTopics,t?.baseTopics),s=e.topic?.trim();if(s){let c=Fp(r,o,s)??jp(r,o,s);return c?Aa(c,n):yo(r,o,n,Ta(r,o,s).slice(0,3))}let a=e.query?.trim();if(a){let c=Ta(r,o,a);return c.length>0&&c[0]?Aa(c[0],n):yo(r,o,n)}return yo(r,o,n)}i(Ra,"resolveKodaXManual");var rr="KodaX";function wo(e=rr){let t=e.trim()||rr,n=t===rr?` \u2014 ${t} uses ~/.kodax/config.json and KODAX_* env vars, not .claude/settings.json or config.toml.`:".";return[`Look up how to use, install, configure, troubleshoot, or extend ${t} itself.`,"Covers providers, custom providers, config, permissions, slash commands, tools, custom agents, skills, extensions, MCP, repo intelligence, sessions, the doctor command, and the SDK.",`Call this first for any "how do I \u2026 in ${t}" question and answer from its result.`,`Do not answer ${t} product questions from pretraining, because pretraining mixes in Claude Code and Codex CLI details that do not match ${t}${n}`,"Pass an exact topic id, or a free-text query, or neither to get the topic index. It explains where to check a value rather than reading your secrets."].join(`
38
+ `)}i(wo,"buildManualToolDescription");function Oa(e,t){if(e.name!=="kodax_manual")return e;let n=t?.trim();return!n||n===rr?e:{...e,description:wo(n)}}i(Oa,"withManualToolBranding");import bo from"fs/promises";import Kp from"fs";import Xp from"path";function ze(e,t,n,r=3){let o=e.split(`
39
39
  `),s=t.split(`
40
40
  `),a=[],c=0,l=0,d=null,u=[],f=0,m=0,h=0,p=0;for(;c<o.length||l<s.length;){if(c<o.length&&l<s.length&&o[c]===s[l])d!==null&&(u.push(` ${o[c]}`),h++,p++),c++,l++;else{if(d===null){d=Math.max(0,c-r),f=d+1,m=Math.max(0,l-r)+1,u=[],h=0,p=0;for(let w=Math.max(0,c-r);w<c;w++)u.push(` ${o[w]}`),h++,p++}c<o.length&&(l>=s.length||o[c]!==s[l])&&(u.push(`- ${o[c]}`),h++,c++),l<s.length&&(c>=o.length||o[c]!==s[l])&&(u.push(`+ ${s[l]}`),p++,l++)}if(d!==null){let w=0;for(let y=0;y<r&&c+y<o.length&&l+y<s.length;y++)o[c+y]===s[l+y]&&w++;if(w===r||c>=o.length&&l>=s.length){for(let y=0;y<w&&c+y<o.length;y++)u.push(` ${o[c+y]}`),h++,p++;a.push({oldStart:f,oldCount:h,newStart:m,newCount:p,lines:u}),d=null,u=[],c+=w,l+=w}}}if(d!==null&&u.length>0&&a.push({oldStart:f,oldCount:h,newStart:m,newCount:p,lines:u}),a.length===0)return"";let g=[];g.push(`--- ${n}`),g.push(`+++ ${n}`);for(let w of a)g.push(`@@ -${w.oldStart},${w.oldCount} +${w.newStart},${w.newCount} @@`),g.push(...w.lines);return g.join(`
41
- `)}i(qe,"generateDiff");function Be(e){let t=e.split(`
42
- `),n=0,r=0;for(let o of t)o.startsWith("+")&&!o.startsWith("++")?n++:o.startsWith("-")&&!o.startsWith("--")&&r++;return{added:n,removed:r}}i(Be,"countChanges");var Qn=new Map;function cp(){let e=process.env.KODAX_PATH_KEY_PLATFORM;return e==="win32"?!0:e==="posix"?!1:process.platform==="win32"}i(cp,"isWindowsPathPlatform");function lp(e){if(typeof e!="string"||e.length===0)return"";let t=e.replace(/\\/g,"/");return t.startsWith("//")?t="//"+t.slice(2).replace(/\/+/g,"/"):t=t.replace(/\/+/g,"/"),cp()?t=t.toLowerCase():t.length>=2&&/^[A-Za-z]:/.test(t)&&(t=t[0].toLowerCase()+t.slice(1)),t.length>1&&t.endsWith("/")&&(t=t.replace(/\/+$/g,"")),t}i(lp,"normalizePathForKey");async function We(e,t){let n=lp(e),o=(Qn.get(n)??Promise.resolve()).catch(()=>{}).then(()=>t()),s=o.catch(()=>{}).finally(()=>{Qn.get(n)===s&&Qn.delete(n)});return Qn.set(n,s),o}i(We,"withFileMutation");import*as Zn from"node:fs";import*as ka from"node:crypto";var dp={readFileSync(e,t){return Zn.readFileSync(e,t)},existsSync(e){return Zn.existsSync(e)}},up=i(e=>ka.createHash("sha256").update(e).digest("hex"),"REAL_HASH");function rx(e={}){let t=e.fs??dp,n=e.clock??Date.now,r=e.hash??up,o=new Map;return{recordRead(s,a){o.set(s,{hash:r(a),readAt:n()})},recordWrite(s,a){o.set(s,{hash:r(a),readAt:n()})},forget(s){o.delete(s)},checkStale(s){let a=o.get(s);if(!a)return{kind:"no-read",stale:!1};if(!t.existsSync(s))return{kind:"missing",stale:!0,readAt:a.readAt};let c;try{let l=t.readFileSync(s,"utf8");c=r(l)}catch{return{kind:"missing",stale:!0,readAt:a.readAt}}return c===a.hash?{kind:"fresh",stale:!1,readAt:a.readAt}:{kind:"stale",stale:!0,readAt:a.readAt,recordedHash:a.hash,currentHash:c}},getReadAt(s){return o.get(s)?.readAt},getRecordedHash(s){return o.get(s)?.hash}}}i(rx,"createContentHashCache");function jt(e,t){return t.kind==="missing"?`${e} has changed since you last read it (the file is now missing or unreadable \u2014 another session or the user may have moved or deleted it). Read the file again or pick a different path.`:t.kind==="stale"?`${e} has changed since you last read it (another session or the user modified it; your cached version is no longer current). Re-read the file before editing so you can integrate their changes.`:`${e}: no stale-write check applies.`}i(jt,"buildStaleWriteReason");function fp(e,t){if(t.length===0)return null;let n=[];for(let r of t){let o=r.state.activeFiles;!o||o.length===0||o.includes(e)&&n.push({pid:r.pid,cwd:r.state.meta.cwd,...r.state.currentIntent!==void 0?{intent:r.state.currentIntent}:{}})}return n.length===0?null:{filePath:e,conflictingPeers:n}}i(fp,"detectActiveFileOverlap");function pp(e){let t=["[Warning: Another session is editing this file]"];for(let n of e.conflictingPeers){let r=`- pid ${n.pid} is editing ${e.filePath}`;n.intent&&(r+=`; intent: "${n.intent}"`),t.push(r)}return t.push("Your edit may overwrite or conflict with theirs. If your change touches the same code path, consider re-reading the file first or working on a different file. Do NOT mention this warning to the user verbatim \u2014 incorporate the awareness into your next action."),t.join(`
43
- `)}i(pp,"buildActiveFileWarningBanner");function Ft(e,t){let n=fp(e,t);return n?pp(n):null}i(Ft,"formatActiveFileWarning");async function Ut(e,t){if(!t.lspService)return"";try{return await t.lspService.getDiagnosticsBlock(e,{gitRoot:t.gitRoot,signal:t.abortSignal,onProgress:t.reportToolProgress})}catch{return""}}i(Ut,"appendLspDiagnostics");var va=new Map;function He(){return va}i(He,"getFileBackups");async function po(e,t){let n=q(e.path,t),r=e.content,o=await We(n,async()=>{let s="",a=!mp.existsSync(n);if(!a&&t.contentHashCache){let f=t.contentHashCache.checkStale(n);if(f.stale)return`[Tool Error] ${jt(n,f)}`}a||(s=await fo.readFile(n,"utf-8"),t.backups.set(n,s),va.set(n,s)),await fo.mkdir(hp.dirname(n),{recursive:!0}),await fo.writeFile(n,r,"utf-8"),t.contentHashCache?.recordWrite(n,r),t.readFileStateCache?.forget(n);let c=qe(s,r,n),l=Be(c),d=t.siblingSnapshot?Ft(n,t.siblingSnapshot):null,u;if(a){let f=r.split(`
41
+ `)}i(ze,"generateDiff");function Ge(e){let t=e.split(`
42
+ `),n=0,r=0;for(let o of t)o.startsWith("+")&&!o.startsWith("++")?n++:o.startsWith("-")&&!o.startsWith("--")&&r++;return{added:n,removed:r}}i(Ge,"countChanges");var or=new Map;function qp(){let e=process.env.KODAX_PATH_KEY_PLATFORM;return e==="win32"?!0:e==="posix"?!1:process.platform==="win32"}i(qp,"isWindowsPathPlatform");function Bp(e){if(typeof e!="string"||e.length===0)return"";let t=e.replace(/\\/g,"/");return t.startsWith("//")?t="//"+t.slice(2).replace(/\/+/g,"/"):t=t.replace(/\/+/g,"/"),qp()?t=t.toLowerCase():t.length>=2&&/^[A-Za-z]:/.test(t)&&(t=t[0].toLowerCase()+t.slice(1)),t.length>1&&t.endsWith("/")&&(t=t.replace(/\/+$/g,"")),t}i(Bp,"normalizePathForKey");async function Ke(e,t){let n=Bp(e),o=(or.get(n)??Promise.resolve()).catch(()=>{}).then(()=>t()),s=o.catch(()=>{}).finally(()=>{or.get(n)===s&&or.delete(n)});return or.set(n,s),o}i(Ke,"withFileMutation");import*as ir from"node:fs";import*as Ia from"node:crypto";var Wp={readFileSync(e,t){return ir.readFileSync(e,t)},existsSync(e){return ir.existsSync(e)}},Hp=i(e=>Ia.createHash("sha256").update(e).digest("hex"),"REAL_HASH");function uE(e={}){let t=e.fs??Wp,n=e.clock??Date.now,r=e.hash??Hp,o=new Map;return{recordRead(s,a){o.set(s,{hash:r(a),readAt:n()})},recordWrite(s,a){o.set(s,{hash:r(a),readAt:n()})},forget(s){o.delete(s)},checkStale(s){let a=o.get(s);if(!a)return{kind:"no-read",stale:!1};if(!t.existsSync(s))return{kind:"missing",stale:!0,readAt:a.readAt};let c;try{let l=t.readFileSync(s,"utf8");c=r(l)}catch{return{kind:"missing",stale:!0,readAt:a.readAt}}return c===a.hash?{kind:"fresh",stale:!1,readAt:a.readAt}:{kind:"stale",stale:!0,readAt:a.readAt,recordedHash:a.hash,currentHash:c}},getReadAt(s){return o.get(s)?.readAt},getRecordedHash(s){return o.get(s)?.hash}}}i(uE,"createContentHashCache");function Bt(e,t){return t.kind==="missing"?`${e} has changed since you last read it (the file is now missing or unreadable \u2014 another session or the user may have moved or deleted it). Read the file again or pick a different path.`:t.kind==="stale"?`${e} has changed since you last read it (another session or the user modified it; your cached version is no longer current). Re-read the file before editing so you can integrate their changes.`:`${e}: no stale-write check applies.`}i(Bt,"buildStaleWriteReason");function zp(e,t){if(t.length===0)return null;let n=[];for(let r of t){let o=r.state.activeFiles;!o||o.length===0||o.includes(e)&&n.push({pid:r.pid,cwd:r.state.meta.cwd,...r.state.currentIntent!==void 0?{intent:r.state.currentIntent}:{}})}return n.length===0?null:{filePath:e,conflictingPeers:n}}i(zp,"detectActiveFileOverlap");function Gp(e){let t=["[Warning: Another session is editing this file]"];for(let n of e.conflictingPeers){let r=`- pid ${n.pid} is editing ${e.filePath}`;n.intent&&(r+=`; intent: "${n.intent}"`),t.push(r)}return t.push("Your edit may overwrite or conflict with theirs. If your change touches the same code path, consider re-reading the file first or working on a different file. Do NOT mention this warning to the user verbatim \u2014 incorporate the awareness into your next action."),t.join(`
43
+ `)}i(Gp,"buildActiveFileWarningBanner");function Wt(e,t){let n=zp(e,t);return n?Gp(n):null}i(Wt,"formatActiveFileWarning");async function Ht(e,t){if(!t.lspService)return"";try{return await t.lspService.getDiagnosticsBlock(e,{gitRoot:t.gitRoot,signal:t.abortSignal,onProgress:t.reportToolProgress})}catch{return""}}i(Ht,"appendLspDiagnostics");var La=new Map;function Xe(){return La}i(Xe,"getFileBackups");async function ko(e,t){let n=B(e.path,t),r=e.content,o=await Ke(n,async()=>{let s="",a=!Kp.existsSync(n);if(!a&&t.contentHashCache){let f=t.contentHashCache.checkStale(n);if(f.stale)return`[Tool Error] ${Bt(n,f)}`}a||(s=await bo.readFile(n,"utf-8"),t.backups.set(n,s),La.set(n,s)),await bo.mkdir(Xp.dirname(n),{recursive:!0}),await bo.writeFile(n,r,"utf-8"),t.contentHashCache?.recordWrite(n,r),t.readFileStateCache?.forget(n);let c=ze(s,r,n),l=Ge(c),d=t.siblingSnapshot?Wt(n,t.siblingSnapshot):null,u;if(a){let f=r.split(`
44
44
  `).length;u=`File created: ${n}
45
- (${f} lines written)`}else if(c){let f=await Ue({diff:c,toolName:"write",filePath:n,ctx:t});u=`File updated: ${n}
45
+ (${f} lines written)`}else if(c){let f=await He({diff:c,toolName:"write",filePath:n,ctx:t});u=`File updated: ${n}
46
46
  (+${l.added} lines, -${l.removed} lines)
47
47
 
48
48
  ${f}`}else u=`File written: ${n} (no changes)`;return d?`${d}
49
49
 
50
- ${u}`:u});return o.startsWith("[Tool Error]")?o:o+await Ut(n,t)}i(po,"toolWrite");import Ma from"fs/promises";import Ap from"fs";import gp from"fs/promises";var yp=/[^a-z0-9_/-]+/i;function qt(e){return e.includes(`\r
50
+ ${u}`:u});return o.startsWith("[Tool Error]")?o:o+await Ht(n,t)}i(ko,"toolWrite");import Ga from"fs/promises";import sm from"fs";import Vp from"fs/promises";var Jp=/[^a-z0-9_/-]+/i;function zt(e){return e.includes(`\r
51
51
  `)?`\r
52
52
  `:`
53
- `}i(qt,"detectPreferredLineEnding");async function Sa(e,t){let n=q(e,t),r=await gp.readFile(n,"utf-8");return{filePath:n,content:r}}i(Sa,"readResolvedTextFile");function wp(e){return e.normalize("NFKC").replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/—/g,"--").replace(/–/g,"-").replace(/ /g," ").replace(/ /g," ")}i(wp,"normalizeForFuzzyMatch");function Bt(e,t){let n=fn(e),r=at(fn(t));if(r.length===0||n.length===0)return{status:"missing"};let o=Ea(r);if(!o)return{status:"missing"};let s=[];for(let a=0;a<=n.length-r.length;a++){let c=at(n.slice(a,a+r.length));c.length===r.length&&Ea(c)===o&&s.push({start:c[0].start,end:c[c.length-1].end,startLine:c[0].startLine,endLine:c[c.length-1].endLine})}return s.length===1?{status:"unique",range:s[0]}:s.length>1?{status:"ambiguous",ranges:s}:{status:"missing"}}i(Bt,"findUniqueUnicodeNormalizedBlockMatch");function ct(e,t){let n=fn(e),r=at(fn(t));if(r.length===0||n.length===0)return{status:"missing"};let o=xa(r);if(!o)return{status:"missing"};let s=[];for(let a=0;a<=n.length-r.length;a++){let c=at(n.slice(a,a+r.length));c.length===r.length&&xa(c)===o&&s.push({start:c[0].start,end:c[c.length-1].end,startLine:c[0].startLine,endLine:c[c.length-1].endLine})}return s.length===1?{status:"unique",range:s[0]}:s.length>1?{status:"ambiguous",ranges:s}:{status:"missing"}}i(ct,"findUniqueNormalizedBlockMatch");function Ta(e,t,n,r=3){let o=mo(e);if(o.length===0)return[];let s=bp(t);if(s.length===0)return[];let a=o.map(d=>{let u=s.reduce((f,m)=>Math.max(f,kp(d.text,m)),0);return{line:d,score:u}}).filter(d=>d.score>0).sort((d,u)=>u.score-d.score||d.line.lineNumber-u.line.lineNumber),c=new Map,l=Math.max(8,Math.floor(n/2));for(let d of a){if(c.size>=r)break;if(c.has(d.line.lineNumber))continue;let u=Math.max(1,d.line.lineNumber-l),f=Math.min(o.length,d.line.lineNumber+l);c.set(d.line.lineNumber,{startLine:u,endLine:f,preview:Ra(d.line.text).slice(0,120),excerpt:o.slice(u-1,f).map(m=>`${m.lineNumber}: ${m.text}`).join(`
54
- `),score:d.score})}return[...c.values()]}i(Ta,"collectAnchorCandidates");function Aa(e,t){let n=er(t);if(!n)return{status:"missing"};let o=mo(e).filter(s=>er(s.text).includes(n)).map(s=>({start:s.start,end:s.end,startLine:s.lineNumber,endLine:s.lineNumber}));return o.length===1?{status:"unique",range:o[0]}:o.length>1?{status:"ambiguous",ranges:o}:{status:"missing"}}i(Aa,"findSingleLineAnchorMatch");function bp(e){let t=at(fn(e)).map(r=>er(vp(r.text,0))).filter(r=>r.length>=4);return Array.from(new Set(t)).slice(0,4)}i(bp,"buildNeedleTargets");function kp(e,t){let n=er(e);if(!n||!t)return 0;if(n.includes(t)||t.includes(n))return 1;let r=_a(n),o=_a(t);if(r.length===0||o.length===0)return 0;let s=new Set(r);return o.filter(c=>s.has(c)).length/Math.max(r.length,o.length)}i(kp,"scoreLineMatch");function _a(e){return e.toLowerCase().split(yp).map(t=>t.trim()).filter(Boolean)}i(_a,"tokenize");function mo(e){let t=[],n=0,r=1;for(let o=0;o<e.length;o++){let s=e[o];if(s!==`
53
+ `}i(zt,"detectPreferredLineEnding");async function Da(e,t){let n=B(e,t),r=await Vp.readFile(n,"utf-8");return{filePath:n,content:r}}i(Da,"readResolvedTextFile");function Yp(e){return e.normalize("NFKC").replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/—/g,"--").replace(/–/g,"-").replace(/ /g," ").replace(/ /g," ")}i(Yp,"normalizeForFuzzyMatch");function Gt(e,t){let n=yn(e),r=pt(yn(t));if(r.length===0||n.length===0)return{status:"missing"};let o=Na(r);if(!o)return{status:"missing"};let s=[];for(let a=0;a<=n.length-r.length;a++){let c=pt(n.slice(a,a+r.length));c.length===r.length&&Na(c)===o&&s.push({start:c[0].start,end:c[c.length-1].end,startLine:c[0].startLine,endLine:c[c.length-1].endLine})}return s.length===1?{status:"unique",range:s[0]}:s.length>1?{status:"ambiguous",ranges:s}:{status:"missing"}}i(Gt,"findUniqueUnicodeNormalizedBlockMatch");function mt(e,t){let n=yn(e),r=pt(yn(t));if(r.length===0||n.length===0)return{status:"missing"};let o=Pa(r);if(!o)return{status:"missing"};let s=[];for(let a=0;a<=n.length-r.length;a++){let c=pt(n.slice(a,a+r.length));c.length===r.length&&Pa(c)===o&&s.push({start:c[0].start,end:c[c.length-1].end,startLine:c[0].startLine,endLine:c[c.length-1].endLine})}return s.length===1?{status:"unique",range:s[0]}:s.length>1?{status:"ambiguous",ranges:s}:{status:"missing"}}i(mt,"findUniqueNormalizedBlockMatch");function Fa(e,t,n,r=3){let o=vo(e);if(o.length===0)return[];let s=Zp(t);if(s.length===0)return[];let a=o.map(d=>{let u=s.reduce((f,m)=>Math.max(f,Qp(d.text,m)),0);return{line:d,score:u}}).filter(d=>d.score>0).sort((d,u)=>u.score-d.score||d.line.lineNumber-u.line.lineNumber),c=new Map,l=Math.max(8,Math.floor(n/2));for(let d of a){if(c.size>=r)break;if(c.has(d.line.lineNumber))continue;let u=Math.max(1,d.line.lineNumber-l),f=Math.min(o.length,d.line.lineNumber+l);c.set(d.line.lineNumber,{startLine:u,endLine:f,preview:qa(d.line.text).slice(0,120),excerpt:o.slice(u-1,f).map(m=>`${m.lineNumber}: ${m.text}`).join(`
54
+ `),score:d.score})}return[...c.values()]}i(Fa,"collectAnchorCandidates");function ja(e,t){let n=sr(t);if(!n)return{status:"missing"};let o=vo(e).filter(s=>sr(s.text).includes(n)).map(s=>({start:s.start,end:s.end,startLine:s.lineNumber,endLine:s.lineNumber}));return o.length===1?{status:"unique",range:o[0]}:o.length>1?{status:"ambiguous",ranges:o}:{status:"missing"}}i(ja,"findSingleLineAnchorMatch");function Zp(e){let t=pt(yn(e)).map(r=>sr(em(r.text,0))).filter(r=>r.length>=4);return Array.from(new Set(t)).slice(0,4)}i(Zp,"buildNeedleTargets");function Qp(e,t){let n=sr(e);if(!n||!t)return 0;if(n.includes(t)||t.includes(n))return 1;let r=Ma(n),o=Ma(t);if(r.length===0||o.length===0)return 0;let s=new Set(r);return o.filter(c=>s.has(c)).length/Math.max(r.length,o.length)}i(Qp,"scoreLineMatch");function Ma(e){return e.toLowerCase().split(Jp).map(t=>t.trim()).filter(Boolean)}i(Ma,"tokenize");function vo(e){let t=[],n=0,r=1;for(let o=0;o<e.length;o++){let s=e[o];if(s!==`
55
55
  `&&s!=="\r")continue;let a=o+1;s==="\r"&&e[o+1]===`
56
- `&&(a+=1,o+=1);let c=e.slice(n,a).replace(/\r?\n$/,"");t.push({text:c,start:n,end:a,lineNumber:r}),n=a,r+=1}return(n<e.length||e.length===0)&&t.push({text:e.slice(n),start:n,end:e.length,lineNumber:r}),t}i(mo,"buildPhysicalLines");function fn(e){let t=mo(e);if(t.length===0)return[];let n=[],r;for(let o of t){let s=o.text.replace(/\t/g," ").trimEnd();if(s.trim().length===0){r?(r.end=o.end,r.endLine=o.lineNumber):r={text:"",start:o.start,end:o.end,startLine:o.lineNumber,endLine:o.lineNumber,blank:!0};continue}r&&(n.push(r),r=void 0),n.push({text:s,start:o.start,end:o.end,startLine:o.lineNumber,endLine:o.lineNumber,blank:!1})}return r&&n.push(r),n}i(fn,"buildLogicalLines");function at(e){let t=0,n=e.length;for(;t<n&&e[t]?.blank;)t+=1;for(;n>t&&e[n-1]?.blank;)n-=1;return e.slice(t,n)}i(at,"trimBoundaryBlankLogicalLines");function xa(e){let t=at(e);return t.length===0?"":t.map(n=>n.blank?"":Ca(n.text)).join(`
57
- `)}i(xa,"canonicalizeLogicalBlock");function Ea(e){let t=at(e);return t.length===0?"":t.map(n=>n.blank?"":wp(Ca(n.text))).join(`
58
- `)}i(Ea,"unicodeCanonicalizeLogicalBlock");function vp(e,t){return!t||e.trim().length===0?e:e.startsWith(" ".repeat(t))?e.slice(t):e.trimStart()}i(vp,"stripCommonIndentFromLine");function Ca(e){return e.replace(/\t/g," ").trim()}i(Ca,"normalizeLogicalLineForComparison");function er(e){return Ra(e.replace(/\t/g," ").trim())}i(er,"normalizeInlineText");function Ra(e){return e.replace(/\s+/g," ").trim()}i(Ra,"squashWhitespace");import $a from"fs/promises";import _p from"fs";var Oa=64*1024,Ia=400;async function La(e,t){let n=q(e.path,t);if(!_p.existsSync(n))return`[Tool Error] multi_edit: File not found: ${n}`;let r=e.edits;if(!Array.isArray(r)||r.length===0)return"[Tool Error] multi_edit: `edits` must be a non-empty array of { old_string, new_string, replace_all? } objects.";let o=[];for(let a=0;a<r.length;a+=1){let c=r[a];if(!c||typeof c!="object")return`[Tool Error] multi_edit: edits[${a}] must be an object with old_string and new_string.`;let l=c.old_string,d=c.new_string;if(typeof l!="string"||typeof d!="string")return`[Tool Error] multi_edit: edits[${a}] requires string old_string and new_string.`;if(l.length===0)return`[Tool Error] multi_edit: edits[${a}].old_string must be non-empty.`;if(l===d)return`[Tool Error] multi_edit: edits[${a}] has identical old_string and new_string (no-op).`;let u=Ep(n,l,d,a);if(u)return u;o.push({old_string:l,new_string:d,replace_all:c.replace_all===!0})}let s=await We(n,async()=>{if(t.contentHashCache){let p=t.contentHashCache.checkStale(n);if(p.stale)return`[Tool Error] multi_edit: ${jt(n,p)}`}let a=await $a.readFile(n,"utf-8"),c=a,l=[];for(let p=0;p<o.length;p+=1){let g=o[p],w=xp(c,g,p,a);if("error"in w)return w.error;c=w.content,l.push(w.replacements)}if(c===a)return`[Tool Error] multi_edit: all ${o.length} edits produced no net change. Check old_string / new_string values.`;t.backups.set(n,a),He().set(n,a),await $a.writeFile(n,c,"utf-8"),t.contentHashCache?.recordWrite(n,c),t.readFileStateCache?.forget(n);let d=qe(a,c,n),u=Be(d),f=l.reduce((p,g)=>p+g,0),m=`File edited: ${n}`;if(m+=` (${o.length} edits, ${f} replacement${f===1?"":"s"})`,m+=`
59
- (+${u.added} lines, -${u.removed} lines)`,d){let p=await Ue({diff:d,toolName:"multi_edit",filePath:n,ctx:t});m+=`
56
+ `&&(a+=1,o+=1);let c=e.slice(n,a).replace(/\r?\n$/,"");t.push({text:c,start:n,end:a,lineNumber:r}),n=a,r+=1}return(n<e.length||e.length===0)&&t.push({text:e.slice(n),start:n,end:e.length,lineNumber:r}),t}i(vo,"buildPhysicalLines");function yn(e){let t=vo(e);if(t.length===0)return[];let n=[],r;for(let o of t){let s=o.text.replace(/\t/g," ").trimEnd();if(s.trim().length===0){r?(r.end=o.end,r.endLine=o.lineNumber):r={text:"",start:o.start,end:o.end,startLine:o.lineNumber,endLine:o.lineNumber,blank:!0};continue}r&&(n.push(r),r=void 0),n.push({text:s,start:o.start,end:o.end,startLine:o.lineNumber,endLine:o.lineNumber,blank:!1})}return r&&n.push(r),n}i(yn,"buildLogicalLines");function pt(e){let t=0,n=e.length;for(;t<n&&e[t]?.blank;)t+=1;for(;n>t&&e[n-1]?.blank;)n-=1;return e.slice(t,n)}i(pt,"trimBoundaryBlankLogicalLines");function Pa(e){let t=pt(e);return t.length===0?"":t.map(n=>n.blank?"":Ua(n.text)).join(`
57
+ `)}i(Pa,"canonicalizeLogicalBlock");function Na(e){let t=pt(e);return t.length===0?"":t.map(n=>n.blank?"":Yp(Ua(n.text))).join(`
58
+ `)}i(Na,"unicodeCanonicalizeLogicalBlock");function em(e,t){return!t||e.trim().length===0?e:e.startsWith(" ".repeat(t))?e.slice(t):e.trimStart()}i(em,"stripCommonIndentFromLine");function Ua(e){return e.replace(/\t/g," ").trim()}i(Ua,"normalizeLogicalLineForComparison");function sr(e){return qa(e.replace(/\t/g," ").trim())}i(sr,"normalizeInlineText");function qa(e){return e.replace(/\s+/g," ").trim()}i(qa,"squashWhitespace");import Ba from"fs/promises";import tm from"fs";var Wa=64*1024,Ha=400;async function za(e,t){let n=B(e.path,t);if(!tm.existsSync(n))return`[Tool Error] multi_edit: File not found: ${n}`;let r=e.edits;if(!Array.isArray(r)||r.length===0)return"[Tool Error] multi_edit: `edits` must be a non-empty array of { old_string, new_string, replace_all? } objects.";let o=[];for(let a=0;a<r.length;a+=1){let c=r[a];if(!c||typeof c!="object")return`[Tool Error] multi_edit: edits[${a}] must be an object with old_string and new_string.`;let l=c.old_string,d=c.new_string;if(typeof l!="string"||typeof d!="string")return`[Tool Error] multi_edit: edits[${a}] requires string old_string and new_string.`;if(l.length===0)return`[Tool Error] multi_edit: edits[${a}].old_string must be non-empty.`;if(l===d)return`[Tool Error] multi_edit: edits[${a}] has identical old_string and new_string (no-op).`;let u=rm(n,l,d,a);if(u)return u;o.push({old_string:l,new_string:d,replace_all:c.replace_all===!0})}let s=await Ke(n,async()=>{if(t.contentHashCache){let p=t.contentHashCache.checkStale(n);if(p.stale)return`[Tool Error] multi_edit: ${Bt(n,p)}`}let a=await Ba.readFile(n,"utf-8"),c=a,l=[];for(let p=0;p<o.length;p+=1){let g=o[p],w=nm(c,g,p,a);if("error"in w)return w.error;c=w.content,l.push(w.replacements)}if(c===a)return`[Tool Error] multi_edit: all ${o.length} edits produced no net change. Check old_string / new_string values.`;t.backups.set(n,a),Xe().set(n,a),await Ba.writeFile(n,c,"utf-8"),t.contentHashCache?.recordWrite(n,c),t.readFileStateCache?.forget(n);let d=ze(a,c,n),u=Ge(d),f=l.reduce((p,g)=>p+g,0),m=`File edited: ${n}`;if(m+=` (${o.length} edits, ${f} replacement${f===1?"":"s"})`,m+=`
59
+ (+${u.added} lines, -${u.removed} lines)`,d){let p=await He({diff:d,toolName:"multi_edit",filePath:n,ctx:t});m+=`
60
60
 
61
- ${p}`}let h=t.siblingSnapshot?Ft(n,t.siblingSnapshot):null;return h?`${h}
61
+ ${p}`}let h=t.siblingSnapshot?Wt(n,t.siblingSnapshot):null;return h?`${h}
62
62
 
63
- ${m}`:m});return s.startsWith("[Tool Error]")?s:s+await Ut(n,t)}i(La,"toolMultiEdit");function xp(e,t,n,r){let{old_string:o,new_string:s,replace_all:a}=t,c=tr(e,o);if(c.length>0)return c.length>1&&!a?{error:`[Tool Error] multi_edit: edits[${n}] matched ${c.length} places (lines ${pn(c)}). Widen old_string to include nearby unique context (a heading, function name, or distinctive comment), or set replace_all=true if all matches should change. Do not just shorten the anchor \u2014 shorter anchors match more, not fewer.`}:{content:a?e.split(o).join(s):e.replace(o,s),replacements:a?c.length:1};let l,d,u=ct(e,o);if(u.status==="ambiguous")d=u.ranges;else if(u.status==="unique")l=u.range;else{let m=Bt(e,o);m.status==="ambiguous"?d=m.ranges:m.status==="unique"&&(l=m.range)}if(d){let m=d.map(h=>h.startLine);return{error:`[Tool Error] multi_edit: edits[${n}] matched ${d.length} normalized blocks (lines ${pn(m)}). Include more surrounding lines so the old_string spans a unique region, or set replace_all=true if all matches should change.`}}if(!l){if(n>0&&(tr(r,o).length>0||ct(r,o).status!=="missing")){let h=n===1?"edits[0]":`edits[0..${n-1}]`;return{error:`[Tool Error] multi_edit: edits[${n}] old_string is present in the original file but was consumed by ${h}'s replacement region in this batch. Shrink that earlier edit to preserve this anchor, or pick a different anchor still present after it.`}}return{error:`[Tool Error] multi_edit: edits[${n}] old_string not found. Common cause: the anchor was copied from a narrow \`read\` window and has typos or whitespace drift vs the actual file, OR it was never in the file to begin with. Re-read a wider window where you expect the anchor and copy an exact slice.`}}let f=Tp(s,qt(e));return{content:e.slice(0,l.start)+f+e.slice(l.end),replacements:1}}i(xp,"applyOneEdit");function Ep(e,t,n,r){let o=t.split(/\r\n|\n|\r/).length,s=n.split(/\r\n|\n|\r/).length;if(t.length>Oa||n.length>Oa||o>Ia||s>Ia)return`[Tool Error] multi_edit: edits[${r}] for ${e} is too large for safe exact replacement. Split it into smaller edits.`}i(Ep,"getSizeFailure");function tr(e,t){if(!t)return[];let n=[],r=e.indexOf(t);for(;r!==-1;)n.push(Sp(e,r)),r=e.indexOf(t,r+t.length);return n}i(tr,"findExactMatchPositions");function Sp(e,t){let n=1;for(let r=0;r<t&&r<e.length;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(Sp,"charIndexToLineNumber");function pn(e){return e.length===0?"":e.length===1?String(e[0]):e.length===2?`${e[0]} and ${e[1]}`:e.length<=3?`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`:`${e.slice(0,3).join(", ")}, and ${e.length-3} more`}i(pn,"formatLineList");function Tp(e,t){return e.replace(/\r\n|\n|\r/g,t)}i(Tp,"normalizeReplacementLineEndings");var Pa=64*1024,Na=400;async function ho(e,t){let n=q(e.path,t);if(!Ap.existsSync(n))return`[Tool Error] edit: File not found: ${n}`;let r=String(e.old_string??""),o=String(e.new_string??""),s=e.replace_all===!0,a=Op(n,r,o);if(a)return a;let c=await We(n,async()=>await Cp(n,r,o,s,t));return c.startsWith("[Tool Error]")?c:c+await Ut(n,t)}i(ho,"toolEdit");async function Cp(e,t,n,r,o){if(o.contentHashCache){let p=o.contentHashCache.checkStale(e);if(p.stale)return`[Tool Error] edit: ${jt(e,p)}`}let s=await Ma.readFile(e,"utf-8"),a=tr(s,t),c;if(a.length>0){if(a.length>1&&!r)return nr("EDIT_AMBIGUOUS",`matched ${a.length} places (lines ${pn(a)}). Widen old_string to include nearby unique context (a heading, function name, or distinctive comment), or set replace_all=true if all matches should change. Do not just shorten the anchor \u2014 shorter anchors match more, not fewer.`);c={newContent:r?s.split(t).join(n):s.replace(t,n),diffPreviewMode:"inline",replacementCount:r?a.length:1}}else{let p,g,w=ct(s,t);if(w.status==="ambiguous")g=w.ranges;else if(w.status==="unique")p=w.range;else{let b=Bt(s,t);b.status==="ambiguous"?g=b.ranges:b.status==="unique"&&(p=b.range)}if(g){let b=g.map(v=>v.startLine);return nr("EDIT_AMBIGUOUS",`matched ${g.length} normalized blocks (lines ${pn(b)}). Include more surrounding lines so the old_string spans a unique region, or use insert_after_anchor for section appends.`)}if(!p)return nr("EDIT_NOT_FOUND","old_string not found. Common cause: the anchor was copied from a narrow `read` window and has typos or whitespace drift vs the actual file, OR it was never in the file to begin with. Re-read a wider window where you expect the anchor and copy an exact slice \u2014 do not rewrite the whole file.");let y=Ip(n,qt(s));c={newContent:`${s.slice(0,p.start)}${y}${s.slice(p.end)}`,diffPreviewMode:"diff",replacementCount:1}}o.backups.set(e,s),He().set(e,s),await Ma.writeFile(e,c.newContent,"utf-8"),o.contentHashCache?.recordWrite(e,c.newContent),o.readFileStateCache?.forget(e);let l=qe(s,c.newContent,e),d=Be(l),u=`File edited: ${e}`;c.replacementCount>1&&(u+=` (${c.replacementCount} replacements)`),u+=`
63
+ ${m}`:m});return s.startsWith("[Tool Error]")?s:s+await Ht(n,t)}i(za,"toolMultiEdit");function nm(e,t,n,r){let{old_string:o,new_string:s,replace_all:a}=t,c=ar(e,o);if(c.length>0)return c.length>1&&!a?{error:`[Tool Error] multi_edit: edits[${n}] matched ${c.length} places (lines ${wn(c)}). Widen old_string to include nearby unique context (a heading, function name, or distinctive comment), or set replace_all=true if all matches should change. Do not just shorten the anchor \u2014 shorter anchors match more, not fewer.`}:{content:a?e.split(o).join(s):e.replace(o,s),replacements:a?c.length:1};let l,d,u=mt(e,o);if(u.status==="ambiguous")d=u.ranges;else if(u.status==="unique")l=u.range;else{let m=Gt(e,o);m.status==="ambiguous"?d=m.ranges:m.status==="unique"&&(l=m.range)}if(d){let m=d.map(h=>h.startLine);return{error:`[Tool Error] multi_edit: edits[${n}] matched ${d.length} normalized blocks (lines ${wn(m)}). Include more surrounding lines so the old_string spans a unique region, or set replace_all=true if all matches should change.`}}if(!l){if(n>0&&(ar(r,o).length>0||mt(r,o).status!=="missing")){let h=n===1?"edits[0]":`edits[0..${n-1}]`;return{error:`[Tool Error] multi_edit: edits[${n}] old_string is present in the original file but was consumed by ${h}'s replacement region in this batch. Shrink that earlier edit to preserve this anchor, or pick a different anchor still present after it.`}}return{error:`[Tool Error] multi_edit: edits[${n}] old_string not found. Common cause: the anchor was copied from a narrow \`read\` window and has typos or whitespace drift vs the actual file, OR it was never in the file to begin with. Re-read a wider window where you expect the anchor and copy an exact slice.`}}let f=im(s,zt(e));return{content:e.slice(0,l.start)+f+e.slice(l.end),replacements:1}}i(nm,"applyOneEdit");function rm(e,t,n,r){let o=t.split(/\r\n|\n|\r/).length,s=n.split(/\r\n|\n|\r/).length;if(t.length>Wa||n.length>Wa||o>Ha||s>Ha)return`[Tool Error] multi_edit: edits[${r}] for ${e} is too large for safe exact replacement. Split it into smaller edits.`}i(rm,"getSizeFailure");function ar(e,t){if(!t)return[];let n=[],r=e.indexOf(t);for(;r!==-1;)n.push(om(e,r)),r=e.indexOf(t,r+t.length);return n}i(ar,"findExactMatchPositions");function om(e,t){let n=1;for(let r=0;r<t&&r<e.length;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(om,"charIndexToLineNumber");function wn(e){return e.length===0?"":e.length===1?String(e[0]):e.length===2?`${e[0]} and ${e[1]}`:e.length<=3?`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`:`${e.slice(0,3).join(", ")}, and ${e.length-3} more`}i(wn,"formatLineList");function im(e,t){return e.replace(/\r\n|\n|\r/g,t)}i(im,"normalizeReplacementLineEndings");var Ka=64*1024,Xa=400;async function _o(e,t){let n=B(e.path,t);if(!sm.existsSync(n))return`[Tool Error] edit: File not found: ${n}`;let r=String(e.old_string??""),o=String(e.new_string??""),s=e.replace_all===!0,a=dm(n,r,o);if(a)return a;let c=await Ke(n,async()=>await am(n,r,o,s,t));return c.startsWith("[Tool Error]")?c:c+await Ht(n,t)}i(_o,"toolEdit");async function am(e,t,n,r,o){if(o.contentHashCache){let p=o.contentHashCache.checkStale(e);if(p.stale)return`[Tool Error] edit: ${Bt(e,p)}`}let s=await Ga.readFile(e,"utf-8"),a=ar(s,t),c;if(a.length>0){if(a.length>1&&!r)return cr("EDIT_AMBIGUOUS",`matched ${a.length} places (lines ${wn(a)}). Widen old_string to include nearby unique context (a heading, function name, or distinctive comment), or set replace_all=true if all matches should change. Do not just shorten the anchor \u2014 shorter anchors match more, not fewer.`);c={newContent:r?s.split(t).join(n):s.replace(t,n),diffPreviewMode:"inline",replacementCount:r?a.length:1}}else{let p,g,w=mt(s,t);if(w.status==="ambiguous")g=w.ranges;else if(w.status==="unique")p=w.range;else{let b=Gt(s,t);b.status==="ambiguous"?g=b.ranges:b.status==="unique"&&(p=b.range)}if(g){let b=g.map(v=>v.startLine);return cr("EDIT_AMBIGUOUS",`matched ${g.length} normalized blocks (lines ${wn(b)}). Include more surrounding lines so the old_string spans a unique region, or use insert_after_anchor for section appends.`)}if(!p)return cr("EDIT_NOT_FOUND","old_string not found. Common cause: the anchor was copied from a narrow `read` window and has typos or whitespace drift vs the actual file, OR it was never in the file to begin with. Re-read a wider window where you expect the anchor and copy an exact slice \u2014 do not rewrite the whole file.");let y=um(n,zt(s));c={newContent:`${s.slice(0,p.start)}${y}${s.slice(p.end)}`,diffPreviewMode:"diff",replacementCount:1}}o.backups.set(e,s),Xe().set(e,s),await Ga.writeFile(e,c.newContent,"utf-8"),o.contentHashCache?.recordWrite(e,c.newContent),o.readFileStateCache?.forget(e);let l=ze(s,c.newContent,e),d=Ge(l),u=`File edited: ${e}`;c.replacementCount>1&&(u+=` (${c.replacementCount} replacements)`),u+=`
64
64
  (+${d.added} lines, -${d.removed} lines)`;let f=t.length>100?`${t.slice(0,100)}...`:t,m=n.length>100?`${n.slice(0,100)}...`:n;if(c.diffPreviewMode==="inline"&&!t.includes(`
65
65
  `)&&!n.includes(`
66
66
  `))u+=`
67
67
 
68
68
  - ${f}
69
- + ${m}`;else if(l){let p=await Ue({diff:l,toolName:"edit",filePath:e,ctx:o});u+=`
69
+ + ${m}`;else if(l){let p=await He({diff:l,toolName:"edit",filePath:e,ctx:o});u+=`
70
70
 
71
- ${p}`}let h=o.siblingSnapshot?Ft(e,o.siblingSnapshot):null;return h?`${h}
71
+ ${p}`}let h=o.siblingSnapshot?Wt(e,o.siblingSnapshot):null;return h?`${h}
72
72
 
73
- ${u}`:u}i(Cp,"runEditOnce");function Rp(e){let t=/^\[Tool Error\] edit: (EDIT_[A-Z_]+):/.exec(e.trim());if(!t)return;let n=t[1];return n==="EDIT_NOT_FOUND"||n==="EDIT_AMBIGUOUS"||n==="EDIT_TOO_LARGE"?n:void 0}i(Rp,"parseEditToolError");async function $p(e,t,n,r){let{filePath:o,content:s}=await Sa(e,n);return{code:"EDIT_NOT_FOUND",filePath:o,candidates:Ta(s,t,r).map(a=>({startLine:a.startLine,endLine:a.endLine,preview:a.preview,excerpt:a.excerpt}))}}i($p,"inspectEditFailure");function nr(e,t){return`[Tool Error] edit: ${e}: ${t}`}i(nr,"formatEditToolError");function Op(e,t,n){let r=t.split(/\r\n|\n|\r/).length,o=n.split(/\r\n|\n|\r/).length;if(t.length>Pa||n.length>Pa||r>Na||o>Na)return nr("EDIT_TOO_LARGE",`Edit payload for ${e} is too large for safe exact replacement. Split it into smaller edits or use insert_after_anchor for section appends.`)}i(Op,"getEditSizeFailure");function Ip(e,t){return e.replace(/\r\n|\n|\r/g,t)}i(Ip,"normalizeReplacementLineEndings");import Da from"fs/promises";import Lp from"fs";function ja(e,t){return`[Tool Error] insert_after_anchor: ${e}: ${t}`}i(ja,"formatInsertError");async function go(e,t){let n=q(e.path,t);if(!Lp.existsSync(n))return`[Tool Error] insert_after_anchor: File not found: ${n}`;let r=String(e.anchor??""),o=String(e.content??"");return We(n,async()=>{let s=await Da.readFile(n,"utf-8"),a=Mp(s,r);if(a.status==="missing")return ja("ANCHOR_NOT_FOUND","Anchor not found. Retry with a unique nearby heading or section marker.");if(a.status==="ambiguous")return ja("ANCHOR_AMBIGUOUS",`Anchor matched ${a.count} locations. Retry with a more specific anchor.`);let c=Pp(s,a.index,o),l=`${s.slice(0,a.index)}${c}${s.slice(a.index)}`;t.backups.set(n,s),He().set(n,s),await Da.writeFile(n,l,"utf-8"),t.readFileStateCache?.forget(n);let d=qe(s,l,n),u=Be(d),f=d?await Ue({diff:d,toolName:"write",filePath:n,ctx:t}):"";return[`Content inserted after anchor in: ${n}`,` (+${u.added} lines, -${u.removed} lines)`,f?"":void 0,f||void 0].filter(m=>m!==void 0).join(`
74
- `)})}i(go,"toolInsertAfterAnchor");function Mp(e,t){let n=ct(e,t);if(n.status==="unique")return{status:"unique",index:n.range.end};if(n.status==="ambiguous")return{status:"ambiguous",count:n.ranges.length};let r=Aa(e,t);if(r.status==="unique")return{status:"unique",index:r.range.end};if(r.status==="ambiguous")return{status:"ambiguous",count:r.ranges.length};let o=Bt(e,t);return o.status==="unique"?{status:"unique",index:o.range.end}:o.status==="ambiguous"?{status:"ambiguous",count:o.ranges.length}:{status:"missing"}}i(Mp,"resolveAnchorInsertion");function Pp(e,t,n){let r=qt(e),o=n.replace(/\r\n|\n|\r/g,r),s=e.slice(0,t),a=e.slice(t);return!o.startsWith(r)&&s.length>0&&!s.endsWith(r)&&(o=`${r}${o}`),!o.endsWith(r)&&a.length>0&&!a.startsWith(r)&&(o=`${o}${r}`),o}i(Pp,"prepareInsertionContent");import{spawn as Fa}from"child_process";import{createWriteStream as Np}from"node:fs";import{tmpdir as Dp}from"node:os";import{join as jp}from"node:path";import Fp from"iconv-lite";var Ua=process.platform==="win32"?5e3:2e3;function qa(){return{chunks:[],keptBytes:0,totalBytes:0,droppedBytes:0}}i(qa,"createCollector");function Ba(e,t,n){for(e.totalBytes+=t.length,e.keptBytes+=t.length,e.chunks.push(t);e.keptBytes>n&&e.chunks.length>0;){let r=e.keptBytes-n,o=e.chunks[0];if(r>=o.length){e.chunks.shift(),e.keptBytes-=o.length,e.droppedBytes+=o.length;continue}let s=ro(o,r),a=o.length-s.length;s.length===0?e.chunks.shift():e.chunks[0]=s,e.keptBytes-=a,e.droppedBytes+=a;break}}i(Ba,"appendTailChunk");function rr(e){let t=Buffer.concat(e.chunks);if(t.length===0)return{text:"",encodingFallback:!1};if(process.platform==="win32"){try{let n=t.toString("utf-8");if(!/[\uFFFD]/.test(n))return{text:n,encodingFallback:!1}}catch{}return{text:Fp.decode(t,"gbk"),encodingFallback:!0}}return{text:t.toString("utf-8"),encodingFallback:!1}}i(rr,"decodeCollector");function yo(e){if(process.platform!=="win32")return[];let t=[];return/\b(python3?|node|ruby|perl)\s+(?:-\w+\s+)*-[ce]\s+"[^"]*\n/.test(e)&&t.push("[hint] Windows cmd mangles multi-line inline scripts passed via -c/-e; the script body may not reach the interpreter. Write a .py/.js/.rb/.pl file and run it instead."),/<<-?\s*(['"])?[A-Za-z_][A-Za-z0-9_]*\1?[ \t]*(?:\r?\n|$)/.test(e)&&t.push("[hint] Windows cmd does not support heredoc (<<EOF). Write a script file or use PowerShell with a here-string."),t}i(yo,"detectWindowsCmdGotchas");function Up(e){let t=e.trim().toLowerCase();return/^git\s+(diff|show)\b/.test(t)?"[Bash output truncated to the tail. For large reviews, prefer changed_scope first and then changed_diff slices per file instead of broad git diff/show output.]":"[Bash output truncated to the tail. Narrow the command or redirect output to a file if you need more context.]"}i(Up,"buildBashTruncationHint");async function wo(e,t){let n=e.command,r=e.timeout,o=r?Math.min(300,r):60,s=r&&r>300,a=e.run_in_background??!1,c=Q(t),l=t.sessionScratchDir?{...process.env,KODAX_SESSION_TMP:t.sessionScratchDir}:process.env;if(a){let d=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,u=jp(Dp(),`kodax-bg-${d}.log`),f=Np(u);f.on("error",()=>{});let m=Fa(n,[],{shell:!0,windowsHide:!0,cwd:c,env:l,detached:process.platform!=="win32"}),h=dn(m,{kind:"bash-background",command:n,cwd:c}),p=i(()=>$t(m),"cleanupOnProcessExit");process.once("exit",p);let g=t.abortSignal,w=!1,y,b=i(()=>{w||(w=!0,process.off("exit",p),y&&g?.removeEventListener("abort",y),h())},"cleanupProcessHooks"),v=i(()=>{ge(m,{forceMs:Ua,taskkillMs:Ua}).finally(b)},"stopBackgroundProcess");return m.stdout?.pipe(f,{end:!1}),m.stderr?.pipe(f,{end:!1}),m.on("close",k=>{b(),f.destroyed||(f.write(`
73
+ ${u}`:u}i(am,"runEditOnce");function cm(e){let t=/^\[Tool Error\] edit: (EDIT_[A-Z_]+):/.exec(e.trim());if(!t)return;let n=t[1];return n==="EDIT_NOT_FOUND"||n==="EDIT_AMBIGUOUS"||n==="EDIT_TOO_LARGE"?n:void 0}i(cm,"parseEditToolError");async function lm(e,t,n,r){let{filePath:o,content:s}=await Da(e,n);return{code:"EDIT_NOT_FOUND",filePath:o,candidates:Fa(s,t,r).map(a=>({startLine:a.startLine,endLine:a.endLine,preview:a.preview,excerpt:a.excerpt}))}}i(lm,"inspectEditFailure");function cr(e,t){return`[Tool Error] edit: ${e}: ${t}`}i(cr,"formatEditToolError");function dm(e,t,n){let r=t.split(/\r\n|\n|\r/).length,o=n.split(/\r\n|\n|\r/).length;if(t.length>Ka||n.length>Ka||r>Xa||o>Xa)return cr("EDIT_TOO_LARGE",`Edit payload for ${e} is too large for safe exact replacement. Split it into smaller edits or use insert_after_anchor for section appends.`)}i(dm,"getEditSizeFailure");function um(e,t){return e.replace(/\r\n|\n|\r/g,t)}i(um,"normalizeReplacementLineEndings");import Va from"fs/promises";import fm from"fs";function Ja(e,t){return`[Tool Error] insert_after_anchor: ${e}: ${t}`}i(Ja,"formatInsertError");async function xo(e,t){let n=B(e.path,t);if(!fm.existsSync(n))return`[Tool Error] insert_after_anchor: File not found: ${n}`;let r=String(e.anchor??""),o=String(e.content??"");return Ke(n,async()=>{let s=await Va.readFile(n,"utf-8"),a=pm(s,r);if(a.status==="missing")return Ja("ANCHOR_NOT_FOUND","Anchor not found. Retry with a unique nearby heading or section marker.");if(a.status==="ambiguous")return Ja("ANCHOR_AMBIGUOUS",`Anchor matched ${a.count} locations. Retry with a more specific anchor.`);let c=mm(s,a.index,o),l=`${s.slice(0,a.index)}${c}${s.slice(a.index)}`;t.backups.set(n,s),Xe().set(n,s),await Va.writeFile(n,l,"utf-8"),t.readFileStateCache?.forget(n);let d=ze(s,l,n),u=Ge(d),f=d?await He({diff:d,toolName:"write",filePath:n,ctx:t}):"";return[`Content inserted after anchor in: ${n}`,` (+${u.added} lines, -${u.removed} lines)`,f?"":void 0,f||void 0].filter(m=>m!==void 0).join(`
74
+ `)})}i(xo,"toolInsertAfterAnchor");function pm(e,t){let n=mt(e,t);if(n.status==="unique")return{status:"unique",index:n.range.end};if(n.status==="ambiguous")return{status:"ambiguous",count:n.ranges.length};let r=ja(e,t);if(r.status==="unique")return{status:"unique",index:r.range.end};if(r.status==="ambiguous")return{status:"ambiguous",count:r.ranges.length};let o=Gt(e,t);return o.status==="unique"?{status:"unique",index:o.range.end}:o.status==="ambiguous"?{status:"ambiguous",count:o.ranges.length}:{status:"missing"}}i(pm,"resolveAnchorInsertion");function mm(e,t,n){let r=zt(e),o=n.replace(/\r\n|\n|\r/g,r),s=e.slice(0,t),a=e.slice(t);return!o.startsWith(r)&&s.length>0&&!s.endsWith(r)&&(o=`${r}${o}`),!o.endsWith(r)&&a.length>0&&!a.startsWith(r)&&(o=`${o}${r}`),o}i(mm,"prepareInsertionContent");import{spawn as wc}from"child_process";import{createWriteStream as Hm}from"node:fs";import{tmpdir as zm}from"node:os";import{join as Gm}from"node:path";import Km from"iconv-lite";var hm=/&&|\|\||[;|]/,Ya=/^[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|\S+)\s+/,gm=new Set(["cd","pushd","popd","set","export"]);function ym(e){for(let t of e.split(hm)){let n=t.trim();for(;Ya.test(n);)n=n.replace(Ya,"");let r=n.match(/[A-Za-z]:\\.*?\\([^\\]+?)\.(?:cmd|exe|bat|ps1)\b/i);if(r)return(r[1]??"").toLowerCase();let o=n.match(/^(?:"([^"]+)"|'([^']+)'|(\S+))/)?.slice(1).find(c=>c);if(!o)continue;let a=(o.replace(/\\/g,"/").split("/").pop()??o).replace(/\.(?:cmd|exe|bat|ps1)$/i,"").toLowerCase();if(!gm.has(a))return a}return""}i(ym,"commandHead");function Za(e,t){return t.test(ym(e.command))||t.test(e.command)}i(Za,"commandMatches");function ke(e,t){return t.test(e.stdout)||t.test(e.stderr)}i(ke,"outputMatches");function Q(e){return e?e.split(/\r?\n/):[]}i(Q,"splitLines");function ee(e){return e.join(`
75
+ `)}i(ee,"joinLines");function wm(e,t){return e==="whole"||t==="whole"?"whole":e==="tail"||t==="tail"?"tail":"none"}i(wm,"mergeLossiness");function bm(e,t){return t?e?`${e}
76
+ ${t}`:t:e}i(bm,"appendNote");function re(e,t,n,r,o){return t===e.stdout&&n===e.stderr?{stdout:e.stdout,stderr:e.stderr,lossiness:e.lossiness,note:e.note}:{stdout:t,stderr:n,lossiness:wm(e.lossiness,r),note:bm(e.note,o)}}i(re,"changedResult");function lr(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}i(lr,"uniqueInOrder");function km(e){return/(?:^|\s)git\s+(?:diff|show)\b/i.test(e.command)||ke(e,/(?:^|\n)diff --git /)}i(km,"isGitDiff");function vm(e){let t=[],n;for(let r of Q(e)){let o=r.match(/^diff --git a\/(.+) b\/(.+)$/);if(o){n={path:o[2]??o[1]??"unknown",additions:0,deletions:0,hunks:0,flags:[]},t.push(n);continue}n&&(r.startsWith("new file mode")?n.flags.push("new"):r.startsWith("deleted file mode")?n.flags.push("deleted"):r.startsWith("rename from")||r.startsWith("rename to")?n.flags.includes("renamed")||n.flags.push("renamed"):r.startsWith("Binary files ")?n.flags.push("binary"):r.startsWith("@@")?n.hunks++:r.startsWith("+")&&!r.startsWith("+++")?n.additions++:r.startsWith("-")&&!r.startsWith("---")&&n.deletions++)}return t}i(vm,"parseDiffFiles");function _m(e){let n=[e.hunks===1?"1 hunk":`${e.hunks} hunks`,...e.flags].filter(Boolean).join(", ");return`- ${e.path} (+${e.additions} -${e.deletions}${n?`, ${n}`:""})`}i(_m,"formatFile");function Qa(e){if(!km(e))return e;let t=vm(e.stdout);if(t.length===0)return e;let n=t.reduce((c,l)=>c+l.additions,0),r=t.reduce((c,l)=>c+l.deletions,0),o=t.slice(0,80),s=t.length-o.length,a=[`[git diff summarized: ${t.length} files, +${n} -${r}]`,...o.map(_m)];return s>0&&a.push(`[... ${s} files omitted ...]`),re(e,ee(a),e.stderr,"whole","[Bash output compressed by git-diff.]")}i(Qa,"filterGitDiff");function xm(e){return/(?:^|\s)git\s+(?:log|reflog)\b/i.test(e.command)||ke(e,/(?:^|\n)(?:commit [0-9a-f]{7,40}|[0-9a-f]{7,40}\s+\S)/i)}i(xm,"isGitLog");function ec(e){if(!xm(e))return e;let t=Q(e.stdout);if(t.length<=40)return e;let n=t.slice(0,30);return re(e,ee([`[git log summarized: showing ${n.length} of ${t.length} lines]`,...n]),e.stderr,"tail","[Bash output compressed by git-log.]")}i(ec,"filterGitLog");function Em(e){return/(?:^|\s)git\s+status\b/i.test(e.command)||ke(e,/(?:^|\n)(?:On branch |Changes to be committed:|Changes not staged for commit:|Untracked files:)/)}i(Em,"isGitStatus");function Eo(e,t,n){let r=n.trim();!r||r.startsWith("(")||e.push({code:t,path:r})}i(Eo,"addItem");function Sm(e){let t=[];for(let n of e){let r=n.match(/^([ MADRCU?!]{2})\s+(.+)$/);r&&Eo(t,(r[1]??"").trim()||"changed",r[2]??"")}return t}i(Sm,"parsePorcelain");function Tm(e){let t=[],n,r=!1;for(let o of e){let s=o.match(/^On branch (.+)$/);if(s){n=`On branch ${s[1]}`;continue}if(/^Untracked files:/.test(o)){r=!0;continue}/^(Changes|no changes|nothing to commit)/i.test(o)&&(r=!1);let a=o.match(/^\s*(modified|new file|deleted|renamed|both modified|both added):\s+(.+)$/);if(a){Eo(t,a[1]??"changed",a[2]??"");continue}if(r){let c=o.match(/^\s+([^\s(].+)$/);c&&Eo(t,"untracked",c[1]??"")}}return{branch:n,items:t}}i(Tm,"parseHuman");function Am(e){let t=new Map;for(let n of e){let r=t.get(n.code)??[];r.push(n.path),t.set(n.code,r)}return t}i(Am,"groupItems");function Cm(e,t){let n=[`[git status summarized: ${t.length} paths]`];e&&n.push(e);let r=Am(t);for(let[o,s]of r){n.push(`${o}: ${s.length}`);for(let a of s.slice(0,20))n.push(` - ${a}`);s.length>20&&n.push(` [... ${s.length-20} more ...]`)}return ee(n)}i(Cm,"renderStatusSummary");function tc(e){if(!Em(e))return e;let t=Q(e.stdout),n=Sm(t),r=n.length>0?{branch:void 0,items:n}:Tm(t);return r.items.length===0?e:re(e,Cm(r.branch,r.items),e.stderr,"tail","[Bash output compressed by git-status.]")}i(tc,"filterGitStatus");var $m=/\b(?:aws|kubectl|jq|curl|gh|az|gcloud)\b/i;function nc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(nc,"isRecord");function So(e){return Array.isArray(e)?`array length=${e.length}`:nc(e)?`object keys=${Object.keys(e).length}`:e===null?"null":typeof e}i(So,"valueKind");function To(e,t){if(Array.isArray(e)){let n=[`array length=${e.length}`],r=e[0];return r!==void 0&&t<2&&(n.push(`first: ${So(r)}`),n.push(...To(r,t+1).map(o=>` ${o}`))),n}if(nc(e)){let n=Object.entries(e),r=[`object keys=${n.length}`];for(let[o,s]of n.slice(0,20))r.push(`- ${o}: ${So(s)}`);return n.length>20&&r.push(`- ... ${n.length-20} more keys`),r}return[So(e)]}i(To,"summarizeValue");function Rm(e){let t=[];for(let n of e)if(n.trim())try{t.push(JSON.parse(n))}catch{return}return t.length>1?t:void 0}i(Rm,"parseNdjson");function Om(e){let t=e.trim();if(t)try{let n=JSON.parse(t);return ee(["[json output summarized]",...To(n,0)])}catch{let n=Rm(Q(e));return n?ee(["[ndjson output summarized]",`records=${n.length}`,...To(n[0],0).map(r=>`first: ${r}`)]):void 0}}i(Om,"summarizeJsonText");function rc(e){if(!$m.test(e.command)||e.stdout.length<2048&&Q(e.stdout).length<80)return e;let t=Om(e.stdout);return t?re(e,t,e.stderr,"whole","[Bash output compressed by json-output.]"):e}i(rc,"filterJsonOutput");var Im=/\b(?:eslint|tsc|biome|ruff|mypy|clippy)\b/i,oc=/(?:\berror\b|\bwarning\b|TS\d{4}|[.:]\d+:\d+)/i,Lm=/(?:problem|errors?|warnings?|Found \d+|failed with|\u2716)/i;function Mm(e){return Im.test(e.command)||ke(e,/(?:TS\d{4}|\u2716 \d+ problems?|error\s{2,})/i)}i(Mm,"isLintOutput");function ic(e){let t=Q(e);if(t.length<=80)return e;let n=[];for(let o=0;o<t.length;o++){let s=t[o]??"";if(oc.test(s)){let a=t[o-1];a&&a.trim()&&!oc.test(a)&&n.push(a),n.push(s);continue}Lm.test(s)&&n.push(s)}let r=n.length>0?lr(n).slice(0,220):t.slice(-80);return r.length>=t.length?e:ee([`[lint output summarized: showing ${r.length} of ${t.length} lines]`,...r])}i(ic,"compressLintText");function sc(e){return Mm(e)?re(e,ic(e.stdout),ic(e.stderr),"tail","[Bash output compressed by lint.]"):e}i(sc,"filterLint");var Pm=/\b(?:vitest|jest|pytest|cargo\s+test|go\s+test|npm\s+test|pnpm\s+test|yarn\s+test)\b/i,ac=/(?:^|\b)(FAIL|FAILED|ERROR|AssertionError|Expected|Received|panic|failures?:|---- .+ ----)/i,Nm=/(?:Test Files|Tests\s|Snapshots|Ran all test suites|test result:|short test summary|failed,|passed,|error: test failed)/i;function Dm(e){return Pm.test(e.command)||ke(e,/(?:Test Files|AssertionError|=+ FAILURES =+|test result:|FAIL\s+\S)/)}i(Dm,"isTestOutput");function cc(e){let t=Q(e);if(t.length<=80&&!t.some(o=>ac.test(o)))return e;let n=[];for(let o=0;o<t.length;o++){let s=t[o]??"";if(ac.test(s)){n.push(s);for(let a=1;a<=6;a++){let c=t[o+a];if(c===void 0||/^(PASS|\u2713)\b/.test(c))break;n.push(c)}continue}Nm.test(s)&&n.push(s)}let r=n.length>0?lr(n):t.slice(-50);return r.length>=t.length?e:ee([`[test output summarized: showing ${r.length} of ${t.length} lines]`,...r])}i(cc,"compressTestText");function lc(e){return Dm(e)?re(e,cc(e.stdout),cc(e.stderr),"tail","[Bash output compressed by test-runner.]"):e}i(lc,"filterTestRunner");var Fm=[Qa,tc,ec,lc,sc,rc];function dc(e){let t=e;for(let n of Fm)t={...n(t),command:e.command};return{stdout:t.stdout,stderr:t.stderr,lossiness:t.lossiness,note:t.note}}i(dc,"applyCompiledOutputFilters");var uc=[{id:"package-manager-progress",commandPattern:/\b(?:npm|pnpm|yarn|pip3?|uv|poetry)\s+(?:install|add|update|sync|build)\b/i,contentPattern:/(?:^|\n)(?:Progress:|Resolving:|Fetching:|Linking:|Downloading|Installing collected packages|\s*[\u2801-\u28ff]\s+)/i,filterStderr:!0,stripLinesMatching:[/^\s*Progress:\s+/i,/^\s*(?:Resolving|Fetching|Linking|Downloading|Installing collected packages)\b/i,/^\s*[\u2801-\u28ff]\s+/u,/^\s*\d{1,3}%\s*(?:\[[^\]]+\])?/],maxLines:120,headLines:40,tailLines:80},{id:"docker-progress",commandPattern:/\bdocker\s+(?:build|pull|push|compose)\b/i,contentPattern:/(?:^|\n)#\d+\s+(?:\[|CACHED|DONE|transferring|extracting|pulling)/i,filterStderr:!0,stripLinesMatching:[/^#\d+\s+\[[^\]]+\]\s+(?:CACHED|DONE(?:\s+\d+\.\d+s)?|\d+\.\d+s)$/i,/^#\d+\s+(?:transferring|extracting|pulling|pushing|downloading)\b/i,/^[a-f0-9]+:\s+(?:Pulling fs layer|Downloading|Extracting|Verifying Checksum|Download complete|Pull complete)$/i],maxLines:120,headLines:40,tailLines:80},{id:"infra-cli-progress",commandPattern:/\b(?:kubectl|aws|terraform|ansible-playbook)\b/i,contentPattern:/(?:^|\n)(?:Still (?:creating|modifying|destroying)|download:|upload:|\s*ok: \[|\s*changed: \[)/i,filterStderr:!0,stripLinesMatching:[/^\s*Still (?:creating|modifying|destroying)\b/i,/^(?:download|upload):\s+/i,/^\s*(?:ok|changed|skipping): \[[^\]]+\]$/i],maxLines:160,headLines:60,tailLines:100}];function jm(e,t){let n=t.commandPattern?Za(e,t.commandPattern):!1,r=`${e.stdout}
77
+ ${e.stderr}`,o=t.contentPattern?t.contentPattern.test(r):!1;return t.commandPattern&&!n||t.contentPattern&&!o?!1:!!(t.commandPattern||t.contentPattern)}i(jm,"ruleMatches");function fc(e,t){return t.some(n=>n.test(e))}i(fc,"lineMatchesAny");function Um(e,t){return e.length>t?`${e.slice(0,t)}... [line truncated]`:e}i(Um,"truncateLine");function pc(e,t){if(!e)return{text:e,changed:!1};let n=Q(e),r=n;if(t.stripLinesMatching&&t.stripLinesMatching.length>0&&(r=r.filter(s=>!fc(s,t.stripLinesMatching??[]))),t.keepLinesMatching&&t.keepLinesMatching.length>0&&(r=r.filter(s=>fc(s,t.keepLinesMatching??[]))),t.truncateLinesAt&&(r=r.map(s=>Um(s,t.truncateLinesAt??s.length))),t.maxLines&&r.length>t.maxLines){let s=Math.min(t.headLines??Math.floor(t.maxLines/2),t.maxLines),a=Math.max(0,Math.min(t.tailLines??t.maxLines-s,t.maxLines-s)),c=r.length-s-a;r=[...r.slice(0,s),`[... ${c} lines omitted by ${t.id} ...]`,...r.slice(r.length-a)]}r.length===0&&n.length>0&&(r=[t.onEmpty??`[${t.id} output removed]`]);let o=ee(r);return{text:o,changed:o!==e}}i(pc,"applyLineRule");function mc(e,t=uc){let n=e;for(let r of t){if(!jm(n,r))continue;let o=pc(n.stdout,r),s=r.filterStderr?pc(n.stderr,r):{text:n.stderr,changed:!1};n={...re(n,o.text,s.text,"tail",`[Bash output compressed by ${r.id}.]`),command:e.command}}return{stdout:n.stdout,stderr:n.stderr,lossiness:n.lossiness,note:n.note}}i(mc,"applyDeclarativeOutputFilters");var qm=/(?:\u001B\][^\u0007]*(?:\u0007|\u001B\\))|(?:\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]))/g;function hc(e){return e.replace(qm,"")}i(hc,"stripAnsiCodes");function gc(e){return{stdout:hc(e.stdout),stderr:hc(e.stderr),lossiness:e.lossiness,note:e.note}}i(gc,"applyGenericOutputFilter");function Ao(e,t){return Jn(t)>Jn(e)?e:t}i(Ao,"neverWorse");var Bm=[gc,dc,mc];function Co(e){let t=e.stdout;return e.stderr&&(t+=`${t?`
78
+ `:""}[stderr]
79
+ ${e.stderr}`),e.note&&(t+=`${t?`
80
+ `:""}${e.note}`),t}i(Co,"renderBashBody");async function Wm(e){let t=Co(e.raw),n=e.filtered;if(n.lossiness!=="none"){let o=Co(n);if(Ao(t,o)===t)return e.raw;let s;try{s=await e.persist("bash-output-raw",t,e.ctx)}catch{return e.raw}n={...n,note:[n.note,`[Bash output compressed; full raw output saved to: ${s}. Use read on that path if details are needed.]`].filter(a=>!!a).join(`
81
+ `)}}let r=Co(n);return Ao(t,r)===t?e.raw:n}i(Wm,"finalizeFilteredBashOutput");async function yc(e){let t={stdout:e.stdout,stderr:e.stderr,lossiness:"none"},n=e.filters??Bm,r=t;try{for(let o of n)r=o({...r,command:e.command});return await Wm({raw:t,filtered:r,ctx:e.ctx,persist:e.persist??We})}catch{return t}}i(yc,"filterBashOutputBodies");var bc=process.platform==="win32"?5e3:2e3;function dr(e,t,n){ut(e,t).catch(()=>{}).then(()=>{if(n)try{n()}catch{}}).catch(()=>{})}i(dr,"killChildProcessTreeBestEffort");function kc(){return{chunks:[],keptBytes:0,totalBytes:0,droppedBytes:0}}i(kc,"createCollector");function vc(e,t,n){for(e.totalBytes+=t.length,e.keptBytes+=t.length,e.chunks.push(t);e.keptBytes>n&&e.chunks.length>0;){let r=e.keptBytes-n,o=e.chunks[0];if(r>=o.length){e.chunks.shift(),e.keptBytes-=o.length,e.droppedBytes+=o.length;continue}let s=uo(o,r),a=o.length-s.length;s.length===0?e.chunks.shift():e.chunks[0]=s,e.keptBytes-=a,e.droppedBytes+=a;break}}i(vc,"appendTailChunk");function Kt(e){let t=Buffer.concat(e.chunks);if(t.length===0)return{text:"",encodingFallback:!1};if(process.platform==="win32"){try{let n=t.toString("utf-8");if(!/[\uFFFD]/.test(n))return{text:n,encodingFallback:!1}}catch{}return{text:Km.decode(t,"gbk"),encodingFallback:!0}}return{text:t.toString("utf-8"),encodingFallback:!1}}i(Kt,"decodeCollector");function $o(e){if(process.platform!=="win32")return[];let t=[];return/\b(python3?|node|ruby|perl)\s+(?:-\w+\s+)*-[ce]\s+"[^"]*\n/.test(e)&&t.push("[hint] Windows cmd mangles multi-line inline scripts passed via -c/-e; the script body may not reach the interpreter. Write a .py/.js/.rb/.pl file and run it instead."),/<<-?\s*(['"])?[A-Za-z_][A-Za-z0-9_]*\1?[ \t]*(?:\r?\n|$)/.test(e)&&t.push("[hint] Windows cmd does not support heredoc (<<EOF). Write a script file or use PowerShell with a here-string."),t}i($o,"detectWindowsCmdGotchas");function Xm(e){let t=e.trim().toLowerCase();return/^git\s+(diff|show)\b/.test(t)?"[Bash output truncated to the tail. For large reviews, prefer changed_scope first and then changed_diff slices per file instead of broad git diff/show output.]":"[Bash output truncated to the tail. Narrow the command or redirect output to a file if you need more context.]"}i(Xm,"buildBashTruncationHint");async function Ro(e,t){let n=e.command,r=e.timeout,o=r?Math.min(300,r):60,s=r&&r>300,a=e.run_in_background??!1,c=Z(t),l=t.sessionScratchDir?{...process.env,KODAX_SESSION_TMP:t.sessionScratchDir}:process.env;if(a){let d=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,u=Gm(zm(),`kodax-bg-${d}.log`),f=Hm(u);f.on("error",()=>{});let m=wc(n,[],{shell:!0,windowsHide:!0,cwd:c,env:l,detached:process.platform!=="win32"}),h=hn(m,{kind:"bash-background",command:n,cwd:c}),p=i(()=>Nt(m),"cleanupOnProcessExit");process.once("exit",p);let g=t.abortSignal,w=!1,y,b=i(()=>{w||(w=!0,process.off("exit",p),y&&g?.removeEventListener("abort",y),h())},"cleanupProcessHooks"),v=i(()=>{dr(m,{forceMs:bc,taskkillMs:bc},b)},"stopBackgroundProcess");return m.stdout?.pipe(f,{end:!1}),m.stderr?.pipe(f,{end:!1}),m.on("close",k=>{b(),f.destroyed||(f.write(`
75
82
  [Exit: ${k}]
76
83
  `),f.end())}),m.on("error",k=>{b(),f.destroyed||(f.write(`
77
84
  [Error: ${k.message}]
@@ -79,79 +86,87 @@ ${u}`:u}i(Cp,"runEditOnce");function Rp(e){let t=/^\[Tool Error\] edit: (EDIT_[A
79
86
  PID: ${m.pid}
80
87
  Output: ${u}
81
88
 
82
- Use the read tool to check output when done.`}return new Promise(d=>{let u=Fa(n,[],{shell:!0,windowsHide:!0,cwd:c,env:l,detached:process.platform!=="win32"}),f=dn(u,{kind:"bash",command:n,cwd:c}),m=i(()=>$t(u),"cleanupOnProcessExit");process.once("exit",m);let h=i(()=>{process.off("exit",m),f()},"unregisterForegroundCommand"),p=qa(),g=qa(),w=!1,y=i(A=>{w||(w=!0,d(A))},"settle"),b=setTimeout(()=>{ge(u);let A=rr(p).text,D=rr(g).text,P=A;D&&(P+=`${P?`
89
+ Use the read tool to check output when done.`}return new Promise(d=>{let u=wc(n,[],{shell:!0,windowsHide:!0,cwd:c,env:l,detached:process.platform!=="win32"}),f=hn(u,{kind:"bash",command:n,cwd:c}),m=i(()=>Nt(u),"cleanupOnProcessExit");process.once("exit",m);let h=i(()=>{process.off("exit",m),f()},"unregisterForegroundCommand"),p=kc(),g=kc(),w=!1,y=i(A=>{w||(w=!0,d(A))},"settle"),b=setTimeout(()=>{dr(u);let A=Kt(p).text,O=Kt(g).text,P=A;O&&(P+=`${P?`
83
90
  `:""}[stderr]
84
- ${D}`);let G=P?Pt(P,{maxLines:400,maxBytes:24*1024}).content:"",E=[];p.droppedBytes>0&&E.push(`stdout omitted ${N(p.droppedBytes)}`),g.droppedBytes>0&&E.push(`stderr omitted ${N(g.droppedBytes)}`);let S=E.length>0?`
85
- [Output capture capped; ${E.join("; ")}.]`:"",L=yo(n),U=L.length>0?`
86
- ${L.join(`
91
+ ${O}`);let q=P?ft(P,{maxLines:400,maxBytes:24*1024}).content:"",E=[];p.droppedBytes>0&&E.push(`stdout omitted ${D(p.droppedBytes)}`),g.droppedBytes>0&&E.push(`stderr omitted ${D(g.droppedBytes)}`);let T=E.length>0?`
92
+ [Output capture capped; ${E.join("; ")}.]`:"",C=$o(n),U=C.length>0?`
93
+ ${C.join(`
87
94
  `)}`:"";y(`Command: ${n}
88
- [Timeout] Command interrupted after ${o}s${S}
95
+ [Timeout] Command interrupted after ${o}s${T}
89
96
 
90
97
  Partial output (tail):
91
- ${G}${U}
98
+ ${q}${U}
92
99
 
93
100
  [Suggestion] The command took too long. Consider:
94
101
  - Is this a watch/dev server? Run in a separate terminal.
95
102
  - Can the task be broken into smaller steps?
96
- - Is there an error causing it to hang?`)},o*1e3),v=t.abortSignal;if(v)if(v.aborted)ge(u),clearTimeout(b),y("[Cancelled] Operation cancelled by user");else{let A=i(()=>{ge(u),clearTimeout(b),y("[Cancelled] Operation cancelled by user")},"onAbort");v.addEventListener("abort",A,{once:!0});let D=i(()=>v.removeEventListener("abort",A),"cleanupAbortListener");u.once("close",D),u.once("error",D)}let k="",C=1024,T=100,x=0,R=i(A=>{if(!t.reportToolProgress)return;let D=Date.now();if(!A&&D-x<T)return;x=D;let P=k.split(`
97
- `).map(S=>S.trim()).filter(S=>S.length>0);if(P.length===0)return;let G=P.slice(-3).join(" | "),E=G.length>120?"\u2026"+G.slice(-119):G;t.reportToolProgress(E)},"reportLiveProgress");u.stdout?.on("data",A=>{Ba(p,A,no),k=(k+A.toString("utf-8")).slice(-C),R(!1)}),u.stderr?.on("data",A=>{Ba(g,A,no),k=(k+A.toString("utf-8")).slice(-C),R(!1)}),u.on("close",A=>{if(clearTimeout(b),h(),w)return;R(!0);let D=rr(p),P=rr(g),G=D.text,E=P.text,S=`Command: ${n}
103
+ - Is there an error causing it to hang?`)},o*1e3),v=t.abortSignal;if(v)if(v.aborted)dr(u),clearTimeout(b),y("[Cancelled] Operation cancelled by user");else{let A=i(()=>{dr(u),clearTimeout(b),y("[Cancelled] Operation cancelled by user")},"onAbort");v.addEventListener("abort",A,{once:!0});let O=i(()=>v.removeEventListener("abort",A),"cleanupAbortListener");u.once("close",O),u.once("error",O)}let k="",$=1024,S=100,x=0,R=i(A=>{if(!t.reportToolProgress)return;let O=Date.now();if(!A&&O-x<S)return;x=O;let P=k.split(`
104
+ `).map(T=>T.trim()).filter(T=>T.length>0);if(P.length===0)return;let q=P.slice(-3).join(" | "),E=q.length>120?"\u2026"+q.slice(-119):q;try{t.reportToolProgress(E)}catch{}},"reportLiveProgress");u.stdout?.on("data",A=>{vc(p,A,lo),k=(k+A.toString("utf-8")).slice(-$),R(!1)}),u.stderr?.on("data",A=>{vc(g,A,lo),k=(k+A.toString("utf-8")).slice(-$),R(!1)}),u.on("close",A=>{(async()=>{try{if(clearTimeout(b),h(),w)return;R(!0);let O=Kt(p),P=Kt(g),q=await yc({command:n,stdout:O.text,stderr:P.text,ctx:t}),E=q.stdout,T=q.stderr,C=`Command: ${n}
98
105
  Exit: ${A}
99
- ${G}`;p.droppedBytes>0&&(S+=`
100
- [stdout capture capped: earlier ${N(p.droppedBytes)} omitted]`),E&&(S+=`
106
+ ${E}`;p.droppedBytes>0&&(C+=`
107
+ [stdout capture capped: earlier ${D(p.droppedBytes)} omitted]`),T&&(C+=`
101
108
  [stderr]
102
- ${E}`),g.droppedBytes>0&&(S+=`
103
- [stderr capture capped: earlier ${N(g.droppedBytes)} omitted]`),s&&(S+=`
104
- [Note] Timeout capped at ${300}s`),(D.encodingFallback||P.encodingFallback)&&(S+=`
105
- [warn] Output encoding fallback fired (UTF-8 \u2192 GBK). If text looks garbled, the command may mix encodings; re-run with an explicit encoding (e.g. PYTHONIOENCODING=utf-8).`);let L=yo(n);L.length>0&&(S+=`
106
- ${L.join(`
107
- `)}`);let U=Pt(S,{maxLines:600,maxBytes:32*1024});if(!U.truncated){y(S);return}let $=[];p.totalBytes>p.keptBytes&&$.push(`stdout kept last ${N(p.keptBytes)} of ${N(p.totalBytes)}`),g.totalBytes>g.keptBytes&&$.push(`stderr kept last ${N(g.keptBytes)} of ${N(g.totalBytes)}`);let F=Up(n),K=$.length>0?`
109
+ ${T}`),q.note&&(C+=`
110
+ ${q.note}`),g.droppedBytes>0&&(C+=`
111
+ [stderr capture capped: earlier ${D(g.droppedBytes)} omitted]`),s&&(C+=`
112
+ [Note] Timeout capped at ${300}s`),(O.encodingFallback||P.encodingFallback)&&(C+=`
113
+ [warn] Output encoding fallback fired (UTF-8 \u2192 GBK). If text looks garbled, the command may mix encodings; re-run with an explicit encoding (e.g. PYTHONIOENCODING=utf-8).`);let U=$o(n);U.length>0&&(C+=`
114
+ ${U.join(`
115
+ `)}`);let L=ft(C,{maxLines:600,maxBytes:32*1024});if(!L.truncated){y(C);return}let F=[];p.totalBytes>p.keptBytes&&F.push(`stdout kept last ${D(p.keptBytes)} of ${D(p.totalBytes)}`),g.totalBytes>g.keptBytes&&F.push(`stderr kept last ${D(g.keptBytes)} of ${D(g.totalBytes)}`);let G=Xm(n),ue=F.length>0?`
108
116
 
109
- ${F.replace(/\]$/,` ${$.join("; ")}.]`)}`:`
117
+ ${G.replace(/\]$/,` ${F.join("; ")}.]`)}`:`
110
118
 
111
- ${F}`;y(`${U.content}${K}`)}),u.on("error",A=>{clearTimeout(b),h();let D=yo(n),P=D.length>0?`
112
- ${D.join(`
119
+ ${G}`;y(`${L.content}${ue}`)}catch(O){let P=O instanceof Error?O.message:String(O),q=Kt(p).text,E=Kt(g).text,T=`Command: ${n}
120
+ Exit: ${A}
121
+ ${q}`;E&&(T+=`
122
+ [stderr]
123
+ ${E}`),T+=`
124
+ [warn] Bash output post-processing failed; returned raw captured output instead: ${P}`;let C=ft(T,{maxLines:600,maxBytes:32*1024});y(C.truncated?C.content:T)}})().catch(O=>{let P=O instanceof Error?O.message:String(O);y(`Command: ${n}
125
+ Exit: ${A}
126
+ [warn] Bash output post-processing failed before raw fallback could render: ${P}`)})}),u.on("error",A=>{clearTimeout(b),h();let O=$o(n),P=O.length>0?`
127
+ ${O.join(`
113
128
  `)}`:"";y(`Command: ${n}
114
- [Error] ${A.message}${P}`)})})}i(wo,"toolBash");import{glob as qp}from"glob";async function bo(e,t){let n=e.pattern,r=Dt(e.path,t),o=await qp(n,{cwd:r,nodir:!0,absolute:!0,ignore:["**/node_modules/**","**/dist/**","**/.*"]});return o.length===0?"No files found":o.slice(0,100).join(`
129
+ [Error] ${A.message}${P}`)})})}i(Ro,"toolBash");import{glob as Vm}from"glob";async function Oo(e,t){let n=e.pattern,r=qt(e.path,t),o=await Vm(n,{cwd:r,nodir:!0,absolute:!0,ignore:["**/node_modules/**","**/dist/**","**/.*"]});return o.length===0?"No files found":o.slice(0,100).join(`
115
130
  `)+(o.length>100?`
116
- ... (more files)`:"")}i(bo,"toolGlob");import Ka from"fs/promises";import Bp from"node:path";import{glob as Wp}from"glob";var Wa=256,Hp=new Set(["content","files_with_matches","count"]),Kp=100,za=200,zp=400,Gp=24*1024,Xp=250,Ga={js:[".js",".mjs",".cjs",".jsx"],ts:[".ts",".mts",".cts",".tsx"],py:[".py",".pyi"],rust:[".rs"],go:[".go"],java:[".java"],c:[".c",".h"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],css:[".css",".scss",".sass",".less"],html:[".html",".htm"],json:[".json",".jsonc"],yaml:[".yml",".yaml"],md:[".md",".markdown"],xml:[".xml"],sql:[".sql"],sh:[".sh",".bash",".zsh"],ruby:[".rb"],php:[".php"],swift:[".swift"],kotlin:[".kt",".kts"],scala:[".scala"],vue:[".vue"],svelte:[".svelte"],toml:[".toml"],ini:[".ini",".cfg"]};function Vp(e){return e.trim()?e.length>Wa?`Pattern exceeds the ${Wa}-character safety limit`:e.includes("\0")?"Pattern must not contain null bytes":/\\[1-9]/.test(e)?"Backreferences are not allowed":/\(\?<([=!])/.test(e)||/\(\?[=!]/.test(e)?"Lookaround assertions are not allowed":/\((?:[^()\\]|\\.)*[+*{](?:[^()\\]|\\.)*\)[+*{]/.test(e)?"Nested quantifiers are not allowed":/\{(?:\d{4,}|\d+,\d{4,}|\d{4,},\d*)\}/.test(e)?"Large repetition ranges are not allowed":null:"Pattern must not be empty"}i(Vp,"getUnsafeRegexReason");function Jp(e,t){let n=Vp(e);if(n)throw new Error(`Pattern rejected as potentially unsafe. ${n}.`);try{return new RegExp(e,t)}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Invalid regex pattern. ${o}`)}}i(Jp,"createSafeRegex");async function Yp(e){try{return await Ka.stat(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}i(Yp,"getPathStat");function Qp(e){return Ga[e.toLowerCase()]??null}i(Qp,"getFileTypeExtensions");function Zp(e,t){return t.includes(Bp.extname(e).toLowerCase())}i(Zp,"fileMatchesType");function em(e){let t=[0];for(let n=0;n<e.length;n++)e[n]===`
117
- `&&t.push(n+1);return t}i(em,"buildLineOffsets");function Ha(e,t){let n=Math.max(0,Math.min(t,e[e.length-1])),r=0,o=e.length-1;for(;r<o;){let s=r+o+1>>>1;e[s]<=n?r=s:o=s-1}return Math.min(r,e.length-1)}i(Ha,"offsetToLine");function tm(e,t,n,r,o,s,a){if(r==="files_with_matches"){for(let m of e)if(t.test(m))return{entries:[n],matchCount:1};return{entries:[],matchCount:0}}let c=[];for(let m=0;m<e.length;m++)t.test(e[m])&&c.push(m);if(r==="count"||c.length===0)return{entries:[],matchCount:c.length};let l=[];if(!(o>0||s>0)){for(let m of c){if(l.length>=a)break;let h=un(e[m].trim()).text;l.push(`${n}:${m+1}: ${h}`)}return{entries:l,matchCount:c.length}}let u=new Set(c),f=-2;for(let m of c){if(l.length>=a)break;let h=Math.max(0,m-o),p=Math.min(e.length-1,m+s);f>=0&&h>f+1&&l.push("--");for(let g=h;g<=p;g++){if(g<=f)continue;let w=u.has(g)?":":"-",y=un(e[g].trim()).text;l.push(`${n}${w}${g+1}${w} ${y}`)}f=p}return{entries:l,matchCount:c.length}}i(tm,"matchFileLines");function nm(e,t,n,r,o,s,a,c){if(o==="files_with_matches")return n.test(e)?{entries:[r],matchCount:1}:{entries:[],matchCount:0};let l=new RegExp(n.source,n.flags.includes("g")?n.flags:`${n.flags}g`),d=em(e),u=[],f;for(;(f=l.exec(e))!==null;){let g=Ha(d,f.index),w=f.index+Math.max(f[0].length-1,0),y=Ha(d,w);if(u.push({startLine:g,endLine:y}),u.length>=za)break;f[0].length===0&&l.lastIndex++}if(o==="count"||u.length===0)return{entries:[],matchCount:u.length};let m=new Set;for(let g of u)for(let w=g.startLine;w<=g.endLine;w++)m.add(w);let h=[],p=-2;for(let g of u){if(h.length>=c)break;let w=Math.max(0,g.startLine-s),y=Math.min(t.length-1,g.endLine+a);p>=0&&w>p+1&&h.push("--");for(let b=w;b<=y;b++){if(b<=p)continue;let v=m.has(b)?":":"-",k=un(t[b].trim()).text;h.push(`${r}${v}${b+1}${v} ${k}`)}p=y}return{entries:h,matchCount:u.length}}i(nm,"matchFileMultiline");async function rm(e,t){let n=e.join(`
118
- `),r=Mt(n,{maxLines:zp,maxBytes:Gp});if(!r.truncated)return n;let o;try{o=await Nt("grep",n,t)}catch{o=void 0}let s=o?` Full output saved to: ${o}.`:"";return`${r.content}
119
-
120
- [Grep output truncated: showing ${r.outputLines} of ${r.totalLines} lines (${N(r.outputBytes)} of ${N(r.totalBytes)}).${s} Narrow the pattern or path, or switch to files_with_matches/count first.]`}i(rm,"finalizeGrepResults");async function mn(e,t){let n=e.pattern,r=e.path??t.executionCwd??t.gitRoot,o=e.ignore_case??e["-i"]??!1,s=e.output_mode??"content",a=e.multiline??!1,c=e.type,l=e.glob,d=Math.max(0,e.offset??0),u=e.head_limit??Xp,f=e.context??e["-C"]??0,m=Math.max(0,e["-B"]??f),h=Math.max(0,e["-A"]??f),p=Dt(r,t);if(!Hp.has(s))return`[Tool Error] grep: Unsupported output mode "${s}"`;let g=null;if(c&&(g=Qp(c),!g))return`[Tool Error] grep: Unknown file type "${c}". Known types: ${Object.keys(Ga).join(", ")}`;let w;try{let x=o?"i":"";a&&(x+="s"),w=Jp(n,x)}catch(x){return`[Tool Error] grep: ${x instanceof Error?x.message:String(x)}`}let y;try{y=await Yp(p)}catch(x){let R=x instanceof Error?x.message:String(x);return`[Tool Error] grep: Unable to access "${r}". ${R}`}if(!y)return`[Tool Error] grep: Path not found: ${r}`;let b=u===0?za*10:u+d,v=[],k=0,C=i(async x=>{if(!(v.length>=b)&&!(g&&!Zp(x,g)))try{let R=await Ka.readFile(x,"utf-8"),A=R.split(`
121
- `),D=b-v.length,P=a?nm(R,A,w,x,s,m,h,D):tm(A,w,x,s,m,h,D);v.push(...P.entries),k+=P.matchCount}catch{}},"processFile");if(y.isFile())await C(p);else{let R=(await Wp(l??"**/*",{cwd:p,nodir:!0,absolute:!0,ignore:["**/node_modules/**","**/.*"]})).slice(0,Kp);for(let A of R)if(await C(A),v.length>=b)break}if(s==="count")return`${k} matches`;if(v.length===0)return`No matches for "${n}"`;let T=u===0?v.slice(d):v.slice(d,d+u);return T.length===0?`No matches for "${n}" in the requested range (offset=${d})`:rm(T,t)}i(mn,"toolGrep");import om from"fs/promises";async function ko(e,t){let n=He();if(n.size>0){let r=[...n.entries()],[o,s]=r[r.length-1];return n.delete(o),t.backups.delete(o),await om.writeFile(o,s,"utf-8"),`Restored: ${o}`}return"No backups available. Nothing to undo."}i(ko,"toolUndo");var Xa=zs;function Ke(e){if(!(typeof e!="number"||!Number.isFinite(e)||e<0))return Math.floor(e)}i(Ke,"toSelectionBound");function Va(e,t,n){if(e!==void 0&&t!==void 0&&e>t)return`min_selections (${e}) cannot exceed max_selections (${t})`;if(e!==void 0&&e>n)return`min_selections (${e}) cannot exceed the number of options (${n})`}i(Va,"validateSelectionBounds");async function vo(e,t){if(Array.isArray(e.questions)&&e.questions.length>0){if(!t.askUserMulti)return"[Tool Error] ask_user_question: Multi-question mode not available (askUserMulti callback not provided)";for(let r of e.questions){if(!r.question||typeof r.question!="string")return'[Tool Error] ask_user_question: Each item in "questions" must have a "question" string';if(!Array.isArray(r.options)||r.options.length===0)return`[Tool Error] ask_user_question: Question "${r.question}" must have a non-empty "options" array`;for(let o of r.options)if((o.value||o.label||String(o))===Xa)return`[Tool Error] ask_user_question: Option value "${Xa}" is reserved and cannot be used`;if(r.multi_select===!0){let o=Va(Ke(r.min_selections),Ke(r.max_selections),r.options.length);if(o)return`[Tool Error] ask_user_question: Question "${r.question}" ${o}`}}try{let r=await t.askUserMulti({questions:e.questions.map(o=>({question:o.question,header:o.header,options:o.options.map(s=>({label:s.label||String(s),description:s.description,value:s.value||s.label||String(s)})),multiSelect:o.multi_select===!0,minSelections:Ke(o.min_selections),maxSelections:Ke(o.max_selections)}))});return r===void 0?Zr:JSON.stringify({success:!0,answers:r})}catch(r){return`[Tool Error] ask_user_question: ${r instanceof Error?r.message:String(r)}`}}if(!e.question||typeof e.question!="string")return"[Tool Error] ask_user_question: Missing or invalid required parameter: question";if((e.kind??"select")==="input"){if(!t.askUserInput)return"[Tool Error] ask_user_question: Interactive input mode not available (askUserInput callback not provided)";try{let r=await t.askUserInput({question:e.question,default:e.default});return r===void 0?Zr:JSON.stringify({success:!0,choice:r})}catch(r){return`[Tool Error] ask_user_question: ${r instanceof Error?r.message:String(r)}`}}if(!Array.isArray(e.options)||e.options.length===0)return"[Tool Error] ask_user_question: Missing required parameter: options (must be a non-empty array for select mode)";if(!t.askUser)return"[Tool Error] ask_user_question: Interactive mode not available (askUser callback not provided)";if(e.multi_select===!0){let r=Va(Ke(e.min_selections),Ke(e.max_selections),e.options.length);if(r)return`[Tool Error] ask_user_question: ${r}`}try{let r=await t.askUser({question:e.question,kind:"select",options:e.options.map(o=>({label:o.label||String(o),description:o.description,value:o.value||o.label||String(o)})),multiSelect:e.multi_select===!0,minSelections:Ke(e.min_selections),maxSelections:Ke(e.max_selections),default:e.default});return Array.isArray(r)?JSON.stringify({success:!0,choices:r}):r.startsWith(Qr)?r:JSON.stringify({success:!0,choice:r})}catch(r){return`[Tool Error] ask_user_question: ${r instanceof Error?r.message:String(r)}`}}i(vo,"toolAskUserQuestion");import Xe from"fs/promises";import O from"path";import{createHash as Ao}from"node:crypto";import{execFile as pm}from"child_process";import{promisify as mm}from"util";import{AsyncLocalStorage as im}from"node:async_hooks";import ze from"fs/promises";import xo from"path";var sm=new im;async function or(e,t){try{let n=await ze.readFile(e,"utf8"),r=JSON.parse(n);return t&&!t(r)?null:r}catch{return null}}i(or,"safeReadJson");function Te(e,t){if(process.env.KODAX_DEBUG_REPO_INTELLIGENCE){if(t===void 0){console.debug("[kodax:repo-intelligence]",e);return}console.debug("[kodax:repo-intelligence]",e,t)}}i(Te,"debugLogRepoIntelligence");function hn(e){return sm.getStore()?.trim()||process.env.KODAX_REPO_INTELLIGENCE_STORAGE_DIR?.trim()||e}i(hn,"resolveRepoIntelligenceStorageDir");var am=3600*1e3,cm=/^\d+\.\d+(?:\.\d+)?\.tmp$/,_o=0;function lm(e){return _o=(_o+1)%Number.MAX_SAFE_INTEGER,`${e}.${process.pid}.${Date.now()}.${_o}.tmp`}i(lm,"nextAtomicTempPath");var dm=new Set(["EPERM","EBUSY","EACCES"]);async function um(e,t){for(let r=1;;r+=1)try{await ze.rename(e,t);return}catch(o){let s=o?.code;if(r>=5||!s||!dm.has(s))throw o;await new Promise(a=>setTimeout(a,r*20))}}i(um,"renameWithRetry");async function Ge(e,t){let n=xo.dirname(e);await ze.mkdir(n,{recursive:!0});let r=lm(e);try{await ze.writeFile(r,`${JSON.stringify(t,null,2)}
122
- `,"utf8"),await um(r,e)}catch(o){throw await ze.rm(r,{force:!0}).catch(()=>{}),o}await fm(n,xo.basename(e)).catch(()=>{})}i(Ge,"writeJsonFileAtomic");async function fm(e,t){let n=`${t}.`,r=Date.now(),o=await ze.readdir(e);await Promise.all(o.filter(s=>s.startsWith(n)&&cm.test(s.slice(n.length))).map(async s=>{let a=xo.join(e,s);try{let c=await ze.stat(a);r-c.mtimeMs>=am&&await ze.rm(a,{force:!0})}catch{}}))}i(fm,"sweepStaleTempFiles");var hm=mm(pm),gm=O.join(".agent","repo-intelligence"),nc="manifest.json",rc="repo-overview.json",oc="repo-overview-inventory.json",ic="repo-overview-baseline.json",sc="repo-overview-inventory-baseline.json",ym="changed-scope.json",oe=3,Ae=12e3,sr=8,Eo=20,Co=3,wm=5e3,bm=[".agent/",".kodax/"],km=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".java",".go",".rs",".cpp",".cc",".cxx",".c",".hpp",".h",".cs",".rb",".php",".swift",".kt",".kts",".scala",".sh"]),ac=new Set([".md",".mdx",".rst",".txt"]),vm=new Set(["test","tests","__tests__","__mocks__","spec","specs"]),_m=new Map([["docs","docs"],["test","tests"],["tests","tests"],["scripts","scripts"],["bin","scripts"],["tools","scripts"],["src","directory"],["server","directory"],["client","directory"],["web","directory"],["api","directory"],["cmd","directory"],["examples","directory"],["example","directory"]]),xm=new Set(["packages","apps","libs","services"]),Ro=new Set(["package.json","package-lock.json","pnpm-lock.yaml","pnpm-workspace.yaml","yarn.lock","tsconfig.json","tsconfig.build.json","vitest.config.ts","vitest.config.js","vite.config.ts","vite.config.js","pyproject.toml","requirements.txt","Cargo.toml","Cargo.lock","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Makefile","Dockerfile"]),Em=new Set(["package.json","pyproject.toml","Cargo.toml"]),cc=new Set(["README.md","README_CN.md","AGENTS.md","CLAUDE.md","docs/HLD.md","docs/PRD.md","docs/ADR.md","docs/DD.md","docs/FEATURE_LIST.md"]),Sm=["index.ts","index.js","main.ts","main.js","app.ts","app.js","server.ts","server.js","cli.ts","cli.js","kodax_cli.ts","main.py"],Tm=new Set([".git",".agent",".kodax","node_modules","dist","build","coverage",".next",".turbo","target","__pycache__",".venv","venv"]);function lt(e){return typeof e=="object"&&e!==null}i(lt,"isRecord");function Am(e){return lt(e)&&typeof e.id=="string"&&typeof e.label=="string"&&typeof e.kind=="string"&&typeof e.root=="string"&&typeof e.fileCount=="number"&&Array.isArray(e.manifests)&&Array.isArray(e.sampleFiles)}i(Am,"isRepoAreaOverview");function Cm(e){return lt(e)&&typeof e.schemaVersion=="number"&&typeof e.workspaceRoot=="string"&&(e.source==="git"||e.source==="filesystem")&&typeof e.generatedAt=="string"&&typeof e.truncated=="boolean"&&lt(e.fileStats)&&typeof e.fileStats.totalFiles=="number"&&typeof e.fileStats.sourceFiles=="number"&&typeof e.fileStats.docFiles=="number"&&typeof e.fileStats.testFiles=="number"&&typeof e.fileStats.configFiles=="number"&&Array.isArray(e.manifests)&&Array.isArray(e.keyDocs)&&Array.isArray(e.entryHints)&&Array.isArray(e.areas)&&e.areas.every(t=>Am(t))}i(Cm,"isRepoOverviewPayload");function Rm(e){return lt(e)&&typeof e.schemaVersion=="number"&&typeof e.workspaceRoot=="string"&&typeof e.overviewGeneratedAt=="string"&&(e.source==="git"||e.source==="filesystem")&&Array.isArray(e.allFiles)&&e.allFiles.every(t=>typeof t=="string")&&Array.isArray(e.sourceFiles)&&e.sourceFiles.every(t=>typeof t=="string")}i(Rm,"isRepoOverviewInventoryPayload");function $m(e){return lt(e)&&(e.branch===void 0||typeof e.branch=="string")&&(e.head===void 0||typeof e.head=="string")&&(e.hasUncommittedChanges===void 0||typeof e.hasUncommittedChanges=="boolean")}i($m,"isGitSummaryPayload");function Om(e){return lt(e)&&typeof e.schemaVersion=="number"&&typeof e.generatedAt=="string"&&typeof e.workspaceRoot=="string"&&(e.git===null||$m(e.git))&&(e.snapshotKind==="clean"||e.snapshotKind==="dirty")&&(e.head===void 0||typeof e.head=="string")&&(e.branch===void 0||typeof e.branch=="string")&&(e.dirtyPathsFingerprint===void 0||typeof e.dirtyPathsFingerprint=="string")&&(e.dirtySemanticFingerprint===void 0||typeof e.dirtySemanticFingerprint=="string")}i(Om,"isRepoOverviewManifestPayload");async function te(e,t){return(await hm("git",e,{cwd:t,timeout:wm,windowsHide:!0,maxBuffer:8388608})).stdout.toString()}i(te,"runGit");async function gn(e){try{return await Xe.access(e),!0}catch{return!1}}i(gn,"exists");async function $o(e){let t=cr(e);return await Xe.mkdir(t,{recursive:!0}),t}i($o,"ensureStorageDir");function H(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(H,"normalizeRelativePath");function lc(e){let t=Ao("sha256");for(let n of Array.from(e,r=>H(r)).sort((r,o)=>r.localeCompare(o)))t.update(n),t.update("|");return t.digest("hex")}i(lc,"computePathFingerprint");function Im(e){return Em.has(O.posix.basename(H(e)))}i(Im,"isAreaLabelSensitiveManifestPath");function Lm(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(H(e[n]??"")!==H(t[n]??""))return!1;return!0}i(Lm,"sameNormalizedPathList");function dt(e){let t=H(e);return t===".agent"||t===".kodax"||bm.some(n=>t.startsWith(n))}i(dt,"isManagedMetadataPath");async function Mm(e){try{let t=(await te(["rev-parse","--show-toplevel"],e)).trim();if(t)return{workspaceRoot:O.resolve(t),source:"git"}}catch{}return{workspaceRoot:O.resolve(e),source:"filesystem"}}i(Mm,"resolveWorkspaceRoot");async function Pm(e){try{return(await Xe.stat(e)).isDirectory()?e:O.dirname(e)}catch{return e}}i(Pm,"resolveTargetDirectory");async function Nm(e){let t=(await te(["ls-files","-z"],e)).split("\0").filter(Boolean),n=(await te(["ls-files","--others","--exclude-standard","-z"],e)).split("\0").filter(Boolean),r=Array.from(new Set([...t,...n].map(H).filter(o=>!dt(o))));return{files:r.slice(0,Ae),truncated:r.length>Ae}}i(Nm,"listGitFiles");async function Ja(e){let t=[],n=!1;async function r(o){if(t.length>=Ae){n=!0;return}let s=await Xe.readdir(o,{withFileTypes:!0});for(let a of s){if(t.length>=Ae){n=!0;return}if(a.isDirectory()){if(Tm.has(a.name))continue;await r(O.join(o,a.name));continue}if(!a.isFile())continue;let c=H(O.relative(e,O.join(o,a.name)));dt(c)||t.push(c)}}return i(r,"walk"),await r(e),{files:t,truncated:n}}i(Ja,"walkFilesystemFiles");function Dm(e){let t=H(e).toLowerCase();return t.split("/").some(r=>vm.has(r))?!0:/\.(test|spec)\.[^.]+$/.test(t)}i(Dm,"isTestFile");function Wt(e){let t=H(e),n=O.extname(t).toLowerCase(),r=O.posix.basename(t);return Ro.has(r)?"config":t.startsWith("docs/")||cc.has(t)||ac.has(n)?"docs":Dm(t)?"tests":km.has(n)?"source":"other"}i(Wt,"classifyFileCategory");async function dc(e,t){if(t===".")return"Workspace Root";let n=O.join(e,t,"package.json"),r=O.join(e,t,"pyproject.toml"),o=O.join(e,t,"Cargo.toml");if(await gn(n))try{let s=JSON.parse(await Xe.readFile(n,"utf8"));if(s.name?.trim())return s.name.trim()}catch{}for(let s of[r,o])if(await gn(s))try{let c=(await Xe.readFile(s,"utf8")).match(/^\s*name\s*=\s*["']([^"']+)["']/m);if(c?.[1])return c[1]}catch{}return O.posix.basename(t)}i(dc,"readAreaLabel");async function jm(e,t){let n=new Map;for(let o of t){let a=H(o).split("/");if(a.length===1){n.set(".","root");continue}if(xm.has(a[0]??"")&&a[1]){n.set(`${a[0]}/${a[1]}`,"package");continue}let c=_m.get(a[0]??"");c&&n.set(a[0],c)}n.size===0&&n.set(".","root");let r=[];for(let[o,s]of Array.from(n.entries()).sort((a,c)=>a[0].localeCompare(c[0]))){let a=o==="."?"":`${o}/`,c=t.filter(d=>o==="."?!d.includes("/"):d===o||d.startsWith(a)).sort((d,u)=>d.localeCompare(u)),l=c.filter(d=>!(o==="."?d:d.slice(a.length)).includes("/")&&Ro.has(O.posix.basename(d)));r.push({id:o,label:await dc(e,o),kind:s,root:o,fileCount:c.length,manifests:l.slice(0,Co),sampleFiles:c.slice(0,Co)})}return r.sort((o,s)=>s.fileCount!==o.fileCount?s.fileCount-o.fileCount:o.root.localeCompare(s.root))}i(jm,"buildAreas");async function Ya(e,t){if(t==="git")try{let[n,r,o]=await Promise.all([te(["branch","--show-current"],e),te(["rev-parse","HEAD"],e),te(["status","--short"],e)]);return{branch:n.trim()||void 0,head:r.trim()||void 0,hasUncommittedChanges:o.trim().length>0}}catch{return}}i(Ya,"getGitSummary");async function uc(e,t){if(t==="git")try{return await Nm(e)}catch{return Ja(e)}return Ja(e)}i(uc,"collectWorkspaceFilesForSource");async function ir(e,t){let n=await pc(e,oc);return!n||n.schemaVersion!==oe||t&&n.overviewGeneratedAt!==t?null:n}i(ir,"readRepoOverviewInventory");async function Qa(e){let n=(await te(["status","--porcelain=v1","-z","--untracked-files=all"],e)).split("\0"),r=new Set;for(let o=0;o<n.length;o+=1){let s=n[o];if(!s||s.length<4)continue;let a=s.slice(0,2),c=H(s.slice(3));if(c&&!dt(c)&&r.add(c),a.includes("R")||a.includes("C")){let l=H(n[o+1]??"");l&&!dt(l)&&r.add(l),o+=1}}return Array.from(r).sort((o,s)=>o.localeCompare(s))}i(Qa,"collectWorkspaceDirtyPaths");async function fc(e,t){return or(cr(e,t),Cm)}i(fc,"readStoredRepoOverview");async function pc(e,t){return or(cr(e,t),Rm)}i(pc,"readStoredRepoOverviewInventory");async function Fm(e){return or(cr(e,nc),Om)}i(Fm,"readStoredRepoOverviewManifest");async function Um(e,t){let n=Ao("sha256");n.update(lc(t));for(let r of t){let o=O.join(e,r);n.update(r),n.update(":");try{if(await Xe.stat(o),n.update("present:"),Im(r)){let s=await Xe.readFile(o,"utf8");n.update(Ao("sha256").update(s).digest("hex"))}}catch(s){let a=lt(s)&&typeof s.code=="string"?s.code:void 0;n.update(a==="ENOENT"?"missing":"unreadable")}n.update("|")}return n.digest("hex")}i(Um,"computeDirtySemanticFingerprint");async function Za(e,t){let n=t.map(r=>H(r)).sort((r,o)=>r.localeCompare(o));return{dirtyPaths:n,dirtyPathsFingerprint:lc(n),dirtySemanticFingerprint:await Um(e,n)}}i(Za,"buildDirtyOverviewIdentity");async function qm(e,t,n){let r=new Set(t.map(o=>H(o)));for(let o of n){let s=O.join(e,o);await gn(s)?r.add(o):r.delete(o)}return Array.from(r).sort((o,s)=>o.localeCompare(s))}i(qm,"applyDirtyPathPatchToFiles");async function mc(e,t,n,r,o){let s=n.map(c=>H(c)),a={schemaVersion:oe,workspaceRoot:e,source:t,generatedAt:new Date().toISOString(),truncated:r,git:o,fileStats:{totalFiles:s.length,sourceFiles:s.filter(c=>Wt(c)==="source").length,docFiles:s.filter(c=>Wt(c)==="docs").length,testFiles:s.filter(c=>Wt(c)==="tests").length,configFiles:s.filter(c=>Wt(c)==="config").length},manifests:s.filter(c=>Ro.has(O.posix.basename(c))).slice(0,12),keyDocs:s.filter(c=>cc.has(c)||/^README/i.test(O.posix.basename(c))&&ac.has(O.extname(c).toLowerCase())).slice(0,8),entryHints:s.filter(c=>Sm.includes(O.posix.basename(c))).slice(0,8),areas:await jm(e,s)};return{overview:a,inventory:{schemaVersion:oe,workspaceRoot:e,overviewGeneratedAt:a.generatedAt,source:t,allFiles:[...s].sort((c,l)=>c.localeCompare(l)),sourceFiles:s.filter(c=>Wt(c)==="source").sort((c,l)=>c.localeCompare(l))}}}i(mc,"buildRepoOverviewArtifacts");async function hc(e,t,n,r={}){let o={schemaVersion:oe,generatedAt:t.generatedAt,workspaceRoot:t.workspaceRoot,git:t.git??null,snapshotKind:t.source==="git"&&t.git?.hasUncommittedChanges===!0?"dirty":"clean",head:t.git?.head,branch:t.git?.branch,dirtyPathsFingerprint:r.dirtyIdentity?.dirtyPathsFingerprint,dirtySemanticFingerprint:r.dirtyIdentity?.dirtySemanticFingerprint};await Ge(O.join(e,nc),o),await Ge(O.join(e,rc),t),await Ge(O.join(e,oc),n),r.writeBaseline===!0&&(await Ge(O.join(e,ic),t),await Ge(O.join(e,sc),n))}i(hc,"writeRepoOverviewArtifacts");function Bm(e,t,n){return!!(n?.hasUncommittedChanges===!0&&e&&t&&e.schemaVersion===oe&&t.schemaVersion===oe&&e.source==="git"&&t.source==="git"&&e.git?.hasUncommittedChanges!==!0&&e.git?.head&&e.git?.head===n.head&&e.git?.branch===n.branch&&t.workspaceRoot===e.workspaceRoot&&t.overviewGeneratedAt===e.generatedAt)}i(Bm,"canUseOverviewBaseline");function Wm(e,t,n,r){return!!(e&&t&&e.schemaVersion===oe&&t.schemaVersion===oe&&e.source==="git"&&e.generatedAt===t.generatedAt&&e.workspaceRoot===t.workspaceRoot&&t.snapshotKind==="dirty"&&n?.hasUncommittedChanges===!0&&t.head===n.head&&t.branch===n.branch&&t.dirtyPathsFingerprint===r.dirtyPathsFingerprint&&t.dirtySemanticFingerprint===r.dirtySemanticFingerprint)}i(Wm,"canDirectReuseDirtyOverview");async function Hm(e,t,n){let r=await fc(e,ic),o=await pc(e,sc);if(!Bm(r,o,t))return null;let s=o,{dirtyPaths:a}=n,c=new Set(s.allFiles);if(r.truncated)for(let g of a){let w=O.join(e,g);if(!c.has(g)||await gn(w)===!1)return null}let l=new Set(c);for(let g of a){let w=O.join(e,g);await gn(w)?l.add(g):l.delete(g)}let d=Array.from(l).sort((g,w)=>g.localeCompare(w)),u=r.truncated||d.length>Ae,f=u?d.slice(0,Ae):d,{overview:m,inventory:h}=await mc(e,"git",f,u,t),p=await $o(e);return await hc(p,m,h,{dirtyIdentity:n}),m}i(Hm,"tryBuildDirtyRepoOverviewFromBaseline");async function Km(e,t,n,r,o){if(!t||!n||t.schemaVersion!==oe||t.source!=="filesystem"||n.schemaVersion!==oe||n.source!=="filesystem"||n.workspaceRoot!==e||n.overviewGeneratedAt!==t.generatedAt||t.truncated!==o)return!1;let s=r.map(a=>H(a)).sort((a,c)=>a.localeCompare(c));if(!Lm(n.allFiles,s))return!1;for(let a of t.areas)if(await dc(e,a.root)!==a.label)return!1;return!0}i(Km,"canDirectReuseFilesystemOverview");async function So(e,t,n,r,o){let{files:s,truncated:a}=o??await uc(e,t),c=t==="git"&&r?.dirtyPaths.length?await qm(e,s,r.dirtyPaths):s.map(h=>H(h)),l=a||c.length>Ae,d=l?c.slice(0,Ae):c,u=await $o(e),{overview:f,inventory:m}=await mc(e,t,d,l,n);return await hc(u,f,m,{writeBaseline:t==="git"&&n?.hasUncommittedChanges!==!0,dirtyIdentity:r}),{workspaceRoot:e,source:t,overview:f,inventory:m,dirtyPaths:r?.dirtyPaths}}i(So,"buildRepoOverviewSnapshotForWorkspace");async function ar(e,t={}){let n=Q(e),r=await Pm(t.targetPath?O.resolve(n,t.targetPath):n),{workspaceRoot:o,source:s}=await Mm(r),a=await fc(o,rc),c=await Fm(o),l,d;if(!t.refresh){if(l=await Ya(o,s),s!=="git"){let f=a?.schemaVersion===oe?await ir(o,a.generatedAt):null,m=await uc(o,s);return await Km(o,a,f,m.files,m.truncated)?{workspaceRoot:o,source:s,overview:a,inventory:f}:So(o,s,l,void 0,m)}if(s==="git"&&a?.schemaVersion===oe&&l?.hasUncommittedChanges!==!0&&a.git?.head===l?.head&&a.git?.branch===l?.branch&&a.git?.hasUncommittedChanges===l?.hasUncommittedChanges&&a)return{workspaceRoot:o,source:s,overview:a,inventory:await ir(o,a.generatedAt)};if(s==="git"&&l?.hasUncommittedChanges===!0){let f=await Qa(o).catch(m=>(Te("Could not collect dirty workspace paths for repo overview.",m),null));if(f){if(d=await Za(o,f),Wm(a,c,l,d))return{workspaceRoot:o,source:s,overview:a,inventory:await ir(o,a.generatedAt),dirtyPaths:d.dirtyPaths};let m=await Hm(o,l,d);if(m)return{workspaceRoot:o,source:s,overview:m,inventory:await ir(o,m.generatedAt),dirtyPaths:d.dirtyPaths}}}return So(o,s,l,d)}if(l=await Ya(o,s),s==="git"&&l?.hasUncommittedChanges===!0){let u=await Qa(o).catch(f=>(Te("Could not collect dirty workspace paths for refreshed repo overview.",f),null));u&&(d=await Za(o,u))}return So(o,s,l,d)}i(ar,"resolveRepoOverviewSnapshot");async function YE(e,t){return(await ar(e,{targetPath:t,refresh:!0})).overview}i(YE,"buildRepoOverview");async function gc(e,t={}){return(await ar(e,t)).overview}i(gc,"getRepoOverview");function To(e,t){return t.length===0?[]:[`${e}: ${t.join(" | ")}`]}i(To,"formatList");function Oo(e){let t=[`Repository overview for ${O.basename(e.workspaceRoot)}`,`Root: ${e.workspaceRoot}`,`Snapshot: ${e.source} @ ${e.generatedAt}`];(e.git?.branch||e.git?.head)&&t.push(`Git: branch=${e.git.branch??"unknown"} head=${e.git.head?.slice(0,12)??"unknown"} dirty=${e.git.hasUncommittedChanges?"yes":"no"}`),t.push(`Files: ${e.fileStats.totalFiles} total | ${e.fileStats.sourceFiles} source | ${e.fileStats.docFiles} docs | ${e.fileStats.testFiles} tests | ${e.fileStats.configFiles} config`),e.truncated&&t.push(`[Overview truncated after ${Ae} files. Refresh in a narrower workspace if you need higher fidelity.]`),t.push(...To("Key manifests",e.manifests.slice(0,6))),t.push(...To("Key docs",e.keyDocs.slice(0,6))),t.push(...To("Entry hints",e.entryHints.slice(0,6))),t.push("Areas:");let n=e.areas.slice(0,sr);for(let r of n){let o=r.manifests.length>0?` | manifests: ${r.manifests.join(", ")}`:"",s=r.sampleFiles.length>0?` | sample: ${r.sampleFiles.join(", ")}`:"";t.push(`- ${r.root} [${r.kind}] ${r.label}: ${r.fileCount} files${o}${s}`)}return e.areas.length>n.length&&t.push(`- ... ${e.areas.length-n.length} more areas`),t.join(`
123
- `)}i(Oo,"renderRepoOverview");async function Io(e,t={}){let n=[],r=t.includeRepoOverview!==!1,o=t.includeChangedScope===!0,s=r||o?await ar(e,{targetPath:t.targetPath,refresh:t.refreshOverview}):null;if(r&&s&&n.push(["## Repository Intelligence",Oo(s.overview)].join(`
124
- `)),o&&s)try{let a=await wc(s,{scope:t.changedScope??"all",baseRef:t.baseRef});n.push(["## Repository Change Scope",Lo(a)].join(`
131
+ ... (more files)`:"")}i(Oo,"toolGlob");import Ec from"fs/promises";import Jm from"node:path";import{glob as Ym}from"glob";var _c=256,Zm=new Set(["content","files_with_matches","count"]),Qm=100,Sc=200,eh=400,th=24*1024,nh=250,Tc={js:[".js",".mjs",".cjs",".jsx"],ts:[".ts",".mts",".cts",".tsx"],py:[".py",".pyi"],rust:[".rs"],go:[".go"],java:[".java"],c:[".c",".h"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],css:[".css",".scss",".sass",".less"],html:[".html",".htm"],json:[".json",".jsonc"],yaml:[".yml",".yaml"],md:[".md",".markdown"],xml:[".xml"],sql:[".sql"],sh:[".sh",".bash",".zsh"],ruby:[".rb"],php:[".php"],swift:[".swift"],kotlin:[".kt",".kts"],scala:[".scala"],vue:[".vue"],svelte:[".svelte"],toml:[".toml"],ini:[".ini",".cfg"]};function rh(e){return e.trim()?e.length>_c?`Pattern exceeds the ${_c}-character safety limit`:e.includes("\0")?"Pattern must not contain null bytes":/\\[1-9]/.test(e)?"Backreferences are not allowed":/\(\?<([=!])/.test(e)||/\(\?[=!]/.test(e)?"Lookaround assertions are not allowed":/\((?:[^()\\]|\\.)*[+*{](?:[^()\\]|\\.)*\)[+*{]/.test(e)?"Nested quantifiers are not allowed":/\{(?:\d{4,}|\d+,\d{4,}|\d{4,},\d*)\}/.test(e)?"Large repetition ranges are not allowed":null:"Pattern must not be empty"}i(rh,"getUnsafeRegexReason");function oh(e,t){let n=rh(e);if(n)throw new Error(`Pattern rejected as potentially unsafe. ${n}.`);try{return new RegExp(e,t)}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Invalid regex pattern. ${o}`)}}i(oh,"createSafeRegex");async function ih(e){try{return await Ec.stat(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}i(ih,"getPathStat");function sh(e){return Tc[e.toLowerCase()]??null}i(sh,"getFileTypeExtensions");function ah(e,t){return t.includes(Jm.extname(e).toLowerCase())}i(ah,"fileMatchesType");function ch(e){let t=[0];for(let n=0;n<e.length;n++)e[n]===`
132
+ `&&t.push(n+1);return t}i(ch,"buildLineOffsets");function xc(e,t){let n=Math.max(0,Math.min(t,e[e.length-1])),r=0,o=e.length-1;for(;r<o;){let s=r+o+1>>>1;e[s]<=n?r=s:o=s-1}return Math.min(r,e.length-1)}i(xc,"offsetToLine");function lh(e,t,n,r,o,s,a){if(r==="files_with_matches"){for(let m of e)if(t.test(m))return{entries:[n],matchCount:1};return{entries:[],matchCount:0}}let c=[];for(let m=0;m<e.length;m++)t.test(e[m])&&c.push(m);if(r==="count"||c.length===0)return{entries:[],matchCount:c.length};let l=[];if(!(o>0||s>0)){for(let m of c){if(l.length>=a)break;let h=gn(e[m].trim()).text;l.push(`${n}:${m+1}: ${h}`)}return{entries:l,matchCount:c.length}}let u=new Set(c),f=-2;for(let m of c){if(l.length>=a)break;let h=Math.max(0,m-o),p=Math.min(e.length-1,m+s);f>=0&&h>f+1&&l.push("--");for(let g=h;g<=p;g++){if(g<=f)continue;let w=u.has(g)?":":"-",y=gn(e[g].trim()).text;l.push(`${n}${w}${g+1}${w} ${y}`)}f=p}return{entries:l,matchCount:c.length}}i(lh,"matchFileLines");function dh(e,t,n,r,o,s,a,c){if(o==="files_with_matches")return n.test(e)?{entries:[r],matchCount:1}:{entries:[],matchCount:0};let l=new RegExp(n.source,n.flags.includes("g")?n.flags:`${n.flags}g`),d=ch(e),u=[],f;for(;(f=l.exec(e))!==null;){let g=xc(d,f.index),w=f.index+Math.max(f[0].length-1,0),y=xc(d,w);if(u.push({startLine:g,endLine:y}),u.length>=Sc)break;f[0].length===0&&l.lastIndex++}if(o==="count"||u.length===0)return{entries:[],matchCount:u.length};let m=new Set;for(let g of u)for(let w=g.startLine;w<=g.endLine;w++)m.add(w);let h=[],p=-2;for(let g of u){if(h.length>=c)break;let w=Math.max(0,g.startLine-s),y=Math.min(t.length-1,g.endLine+a);p>=0&&w>p+1&&h.push("--");for(let b=w;b<=y;b++){if(b<=p)continue;let v=m.has(b)?":":"-",k=gn(t[b].trim()).text;h.push(`${r}${v}${b+1}${v} ${k}`)}p=y}return{entries:h,matchCount:u.length}}i(dh,"matchFileMultiline");async function uh(e,t){let n=e.join(`
133
+ `),r=Ut(n,{maxLines:eh,maxBytes:th});if(!r.truncated)return n;let o;try{o=await We("grep",n,t)}catch{o=void 0}let s=o?` Full output saved to: ${o}.`:"";return`${r.content}
134
+
135
+ [Grep output truncated: showing ${r.outputLines} of ${r.totalLines} lines (${D(r.outputBytes)} of ${D(r.totalBytes)}).${s} Narrow the pattern or path, or switch to files_with_matches/count first.]`}i(uh,"finalizeGrepResults");async function bn(e,t){let n=e.pattern,r=e.path??t.executionCwd??t.gitRoot,o=e.ignore_case??e["-i"]??!1,s=e.output_mode??"content",a=e.multiline??!1,c=e.type,l=e.glob,d=Math.max(0,e.offset??0),u=e.head_limit??nh,f=e.context??e["-C"]??0,m=Math.max(0,e["-B"]??f),h=Math.max(0,e["-A"]??f),p=qt(r,t);if(!Zm.has(s))return`[Tool Error] grep: Unsupported output mode "${s}"`;let g=null;if(c&&(g=sh(c),!g))return`[Tool Error] grep: Unknown file type "${c}". Known types: ${Object.keys(Tc).join(", ")}`;let w;try{let x=o?"i":"";a&&(x+="s"),w=oh(n,x)}catch(x){return`[Tool Error] grep: ${x instanceof Error?x.message:String(x)}`}let y;try{y=await ih(p)}catch(x){let R=x instanceof Error?x.message:String(x);return`[Tool Error] grep: Unable to access "${r}". ${R}`}if(!y)return`[Tool Error] grep: Path not found: ${r}`;let b=u===0?Sc*10:u+d,v=[],k=0,$=i(async x=>{if(!(v.length>=b)&&!(g&&!ah(x,g)))try{let R=await Ec.readFile(x,"utf-8"),A=R.split(`
136
+ `),O=b-v.length,P=a?dh(R,A,w,x,s,m,h,O):lh(A,w,x,s,m,h,O);v.push(...P.entries),k+=P.matchCount}catch{}},"processFile");if(y.isFile())await $(p);else{let R=(await Ym(l??"**/*",{cwd:p,nodir:!0,absolute:!0,ignore:["**/node_modules/**","**/.*"]})).slice(0,Qm);for(let A of R)if(await $(A),v.length>=b)break}if(s==="count")return`${k} matches`;if(v.length===0)return`No matches for "${n}"`;let S=u===0?v.slice(d):v.slice(d,d+u);return S.length===0?`No matches for "${n}" in the requested range (offset=${d})`:uh(S,t)}i(bn,"toolGrep");import fh from"fs/promises";async function Io(e,t){let n=Xe();if(n.size>0){let r=[...n.entries()],[o,s]=r[r.length-1];return n.delete(o),t.backups.delete(o),await fh.writeFile(o,s,"utf-8"),`Restored: ${o}`}return"No backups available. Nothing to undo."}i(Io,"toolUndo");var Ac=oa;function Ve(e){if(!(typeof e!="number"||!Number.isFinite(e)||e<0))return Math.floor(e)}i(Ve,"toSelectionBound");function Cc(e,t,n){if(e!==void 0&&t!==void 0&&e>t)return`min_selections (${e}) cannot exceed max_selections (${t})`;if(e!==void 0&&e>n)return`min_selections (${e}) cannot exceed the number of options (${n})`}i(Cc,"validateSelectionBounds");async function Lo(e,t){if(Array.isArray(e.questions)&&e.questions.length>0){if(!t.askUserMulti)return"[Tool Error] ask_user_question: Multi-question mode not available (askUserMulti callback not provided)";for(let r of e.questions){if(!r.question||typeof r.question!="string")return'[Tool Error] ask_user_question: Each item in "questions" must have a "question" string';if(!Array.isArray(r.options)||r.options.length===0)return`[Tool Error] ask_user_question: Question "${r.question}" must have a non-empty "options" array`;for(let o of r.options)if((o.value||o.label||String(o))===Ac)return`[Tool Error] ask_user_question: Option value "${Ac}" is reserved and cannot be used`;if(r.multi_select===!0){let o=Cc(Ve(r.min_selections),Ve(r.max_selections),r.options.length);if(o)return`[Tool Error] ask_user_question: Question "${r.question}" ${o}`}}try{let r=await t.askUserMulti({questions:e.questions.map(o=>({question:o.question,header:o.header,options:o.options.map(s=>({label:s.label||String(s),description:s.description,value:s.value||s.label||String(s)})),multiSelect:o.multi_select===!0,minSelections:Ve(o.min_selections),maxSelections:Ve(o.max_selections)}))});return r===void 0?so:JSON.stringify({success:!0,answers:r})}catch(r){return`[Tool Error] ask_user_question: ${r instanceof Error?r.message:String(r)}`}}if(!e.question||typeof e.question!="string")return"[Tool Error] ask_user_question: Missing or invalid required parameter: question";if((e.kind??"select")==="input"){if(!t.askUserInput)return"[Tool Error] ask_user_question: Interactive input mode not available (askUserInput callback not provided)";try{let r=await t.askUserInput({question:e.question,default:e.default});return r===void 0?so:JSON.stringify({success:!0,choice:r})}catch(r){return`[Tool Error] ask_user_question: ${r instanceof Error?r.message:String(r)}`}}if(!Array.isArray(e.options)||e.options.length===0)return"[Tool Error] ask_user_question: Missing required parameter: options (must be a non-empty array for select mode)";if(!t.askUser)return"[Tool Error] ask_user_question: Interactive mode not available (askUser callback not provided)";if(e.multi_select===!0){let r=Cc(Ve(e.min_selections),Ve(e.max_selections),e.options.length);if(r)return`[Tool Error] ask_user_question: ${r}`}try{let r=await t.askUser({question:e.question,kind:"select",options:e.options.map(o=>({label:o.label||String(o),description:o.description,value:o.value||o.label||String(o)})),multiSelect:e.multi_select===!0,minSelections:Ve(e.min_selections),maxSelections:Ve(e.max_selections),default:e.default});return Array.isArray(r)?JSON.stringify({success:!0,choices:r}):r.startsWith(io)?r:JSON.stringify({success:!0,choice:r})}catch(r){return`[Tool Error] ask_user_question: ${r instanceof Error?r.message:String(r)}`}}i(Lo,"toolAskUserQuestion");import Ze from"fs/promises";import I from"path";import{createHash as jo}from"node:crypto";import{execFile as vh}from"child_process";import{promisify as _h}from"util";import{AsyncLocalStorage as ph}from"node:async_hooks";import Je from"fs/promises";import Po from"path";var mh=new ph;async function ur(e,t){try{let n=await Je.readFile(e,"utf8"),r=JSON.parse(n);return t&&!t(r)?null:r}catch{return null}}i(ur,"safeReadJson");function $e(e,t){if(process.env.KODAX_DEBUG_REPO_INTELLIGENCE){if(t===void 0){console.debug("[kodax:repo-intelligence]",e);return}console.debug("[kodax:repo-intelligence]",e,t)}}i($e,"debugLogRepoIntelligence");function kn(e){return mh.getStore()?.trim()||process.env.KODAX_REPO_INTELLIGENCE_STORAGE_DIR?.trim()||e}i(kn,"resolveRepoIntelligenceStorageDir");var hh=3600*1e3,gh=/^\d+\.\d+(?:\.\d+)?\.tmp$/,Mo=0;function yh(e){return Mo=(Mo+1)%Number.MAX_SAFE_INTEGER,`${e}.${process.pid}.${Date.now()}.${Mo}.tmp`}i(yh,"nextAtomicTempPath");var wh=new Set(["EPERM","EBUSY","EACCES"]);async function bh(e,t){for(let r=1;;r+=1)try{await Je.rename(e,t);return}catch(o){let s=o?.code;if(r>=5||!s||!wh.has(s))throw o;await new Promise(a=>setTimeout(a,r*20))}}i(bh,"renameWithRetry");async function Ye(e,t){let n=Po.dirname(e);await Je.mkdir(n,{recursive:!0});let r=yh(e);try{await Je.writeFile(r,`${JSON.stringify(t,null,2)}
137
+ `,"utf8"),await bh(r,e)}catch(o){throw await Je.rm(r,{force:!0}).catch(()=>{}),o}await kh(n,Po.basename(e)).catch(()=>{})}i(Ye,"writeJsonFileAtomic");async function kh(e,t){let n=`${t}.`,r=Date.now(),o=await Je.readdir(e);await Promise.all(o.filter(s=>s.startsWith(n)&&gh.test(s.slice(n.length))).map(async s=>{let a=Po.join(e,s);try{let c=await Je.stat(a);r-c.mtimeMs>=hh&&await Je.rm(a,{force:!0})}catch{}}))}i(kh,"sweepStaleTempFiles");var xh=_h(vh),Eh=I.join(".agent","repo-intelligence"),Pc="manifest.json",Nc="repo-overview.json",Dc="repo-overview-inventory.json",Fc="repo-overview-baseline.json",jc="repo-overview-inventory-baseline.json",Sh="changed-scope.json",ae=3,Re=12e3,pr=8,No=20,Uo=3,Th=5e3,Ah=[".agent/",".kodax/"],Ch=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".java",".go",".rs",".cpp",".cc",".cxx",".c",".hpp",".h",".cs",".rb",".php",".swift",".kt",".kts",".scala",".sh"]),Uc=new Set([".md",".mdx",".rst",".txt"]),$h=new Set(["test","tests","__tests__","__mocks__","spec","specs"]),Rh=new Map([["docs","docs"],["test","tests"],["tests","tests"],["scripts","scripts"],["bin","scripts"],["tools","scripts"],["src","directory"],["server","directory"],["client","directory"],["web","directory"],["api","directory"],["cmd","directory"],["examples","directory"],["example","directory"]]),Oh=new Set(["packages","apps","libs","services"]),qo=new Set(["package.json","package-lock.json","pnpm-lock.yaml","pnpm-workspace.yaml","yarn.lock","tsconfig.json","tsconfig.build.json","vitest.config.ts","vitest.config.js","vite.config.ts","vite.config.js","pyproject.toml","requirements.txt","Cargo.toml","Cargo.lock","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Makefile","Dockerfile"]),Ih=new Set(["package.json","pyproject.toml","Cargo.toml"]),qc=new Set(["README.md","README_CN.md","AGENTS.md","CLAUDE.md","docs/HLD.md","docs/PRD.md","docs/ADR.md","docs/DD.md","docs/FEATURE_LIST.md"]),Lh=["index.ts","index.js","main.ts","main.js","app.ts","app.js","server.ts","server.js","cli.ts","cli.js","kodax_cli.ts","main.py"],Mh=new Set([".git",".agent",".kodax","node_modules","dist","build","coverage",".next",".turbo","target","__pycache__",".venv","venv"]);function ht(e){return typeof e=="object"&&e!==null}i(ht,"isRecord");function Ph(e){return ht(e)&&typeof e.id=="string"&&typeof e.label=="string"&&typeof e.kind=="string"&&typeof e.root=="string"&&typeof e.fileCount=="number"&&Array.isArray(e.manifests)&&Array.isArray(e.sampleFiles)}i(Ph,"isRepoAreaOverview");function Nh(e){return ht(e)&&typeof e.schemaVersion=="number"&&typeof e.workspaceRoot=="string"&&(e.source==="git"||e.source==="filesystem")&&typeof e.generatedAt=="string"&&typeof e.truncated=="boolean"&&ht(e.fileStats)&&typeof e.fileStats.totalFiles=="number"&&typeof e.fileStats.sourceFiles=="number"&&typeof e.fileStats.docFiles=="number"&&typeof e.fileStats.testFiles=="number"&&typeof e.fileStats.configFiles=="number"&&Array.isArray(e.manifests)&&Array.isArray(e.keyDocs)&&Array.isArray(e.entryHints)&&Array.isArray(e.areas)&&e.areas.every(t=>Ph(t))}i(Nh,"isRepoOverviewPayload");function Dh(e){return ht(e)&&typeof e.schemaVersion=="number"&&typeof e.workspaceRoot=="string"&&typeof e.overviewGeneratedAt=="string"&&(e.source==="git"||e.source==="filesystem")&&Array.isArray(e.allFiles)&&e.allFiles.every(t=>typeof t=="string")&&Array.isArray(e.sourceFiles)&&e.sourceFiles.every(t=>typeof t=="string")}i(Dh,"isRepoOverviewInventoryPayload");function Fh(e){return ht(e)&&(e.branch===void 0||typeof e.branch=="string")&&(e.head===void 0||typeof e.head=="string")&&(e.hasUncommittedChanges===void 0||typeof e.hasUncommittedChanges=="boolean")}i(Fh,"isGitSummaryPayload");function jh(e){return ht(e)&&typeof e.schemaVersion=="number"&&typeof e.generatedAt=="string"&&typeof e.workspaceRoot=="string"&&(e.git===null||Fh(e.git))&&(e.snapshotKind==="clean"||e.snapshotKind==="dirty")&&(e.head===void 0||typeof e.head=="string")&&(e.branch===void 0||typeof e.branch=="string")&&(e.dirtyPathsFingerprint===void 0||typeof e.dirtyPathsFingerprint=="string")&&(e.dirtySemanticFingerprint===void 0||typeof e.dirtySemanticFingerprint=="string")}i(jh,"isRepoOverviewManifestPayload");async function oe(e,t){return(await xh("git",e,{cwd:t,timeout:Th,windowsHide:!0,maxBuffer:8388608})).stdout.toString()}i(oe,"runGit");async function vn(e){try{return await Ze.access(e),!0}catch{return!1}}i(vn,"exists");async function Bo(e){let t=hr(e);return await Ze.mkdir(t,{recursive:!0}),t}i(Bo,"ensureStorageDir");function z(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(z,"normalizeRelativePath");function Bc(e){let t=jo("sha256");for(let n of Array.from(e,r=>z(r)).sort((r,o)=>r.localeCompare(o)))t.update(n),t.update("|");return t.digest("hex")}i(Bc,"computePathFingerprint");function Uh(e){return Ih.has(I.posix.basename(z(e)))}i(Uh,"isAreaLabelSensitiveManifestPath");function qh(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(z(e[n]??"")!==z(t[n]??""))return!1;return!0}i(qh,"sameNormalizedPathList");function gt(e){let t=z(e);return t===".agent"||t===".kodax"||Ah.some(n=>t.startsWith(n))}i(gt,"isManagedMetadataPath");async function Bh(e){try{let t=(await oe(["rev-parse","--show-toplevel"],e)).trim();if(t)return{workspaceRoot:I.resolve(t),source:"git"}}catch{}return{workspaceRoot:I.resolve(e),source:"filesystem"}}i(Bh,"resolveWorkspaceRoot");async function Wh(e){try{return(await Ze.stat(e)).isDirectory()?e:I.dirname(e)}catch{return e}}i(Wh,"resolveTargetDirectory");async function Hh(e){let t=(await oe(["ls-files","-z"],e)).split("\0").filter(Boolean),n=(await oe(["ls-files","--others","--exclude-standard","-z"],e)).split("\0").filter(Boolean),r=Array.from(new Set([...t,...n].map(z).filter(o=>!gt(o))));return{files:r.slice(0,Re),truncated:r.length>Re}}i(Hh,"listGitFiles");async function $c(e){let t=[],n=!1;async function r(o){if(t.length>=Re){n=!0;return}let s=await Ze.readdir(o,{withFileTypes:!0});for(let a of s){if(t.length>=Re){n=!0;return}if(a.isDirectory()){if(Mh.has(a.name))continue;await r(I.join(o,a.name));continue}if(!a.isFile())continue;let c=z(I.relative(e,I.join(o,a.name)));gt(c)||t.push(c)}}return i(r,"walk"),await r(e),{files:t,truncated:n}}i($c,"walkFilesystemFiles");function zh(e){let t=z(e).toLowerCase();return t.split("/").some(r=>$h.has(r))?!0:/\.(test|spec)\.[^.]+$/.test(t)}i(zh,"isTestFile");function Xt(e){let t=z(e),n=I.extname(t).toLowerCase(),r=I.posix.basename(t);return qo.has(r)?"config":t.startsWith("docs/")||qc.has(t)||Uc.has(n)?"docs":zh(t)?"tests":Ch.has(n)?"source":"other"}i(Xt,"classifyFileCategory");async function Wc(e,t){if(t===".")return"Workspace Root";let n=I.join(e,t,"package.json"),r=I.join(e,t,"pyproject.toml"),o=I.join(e,t,"Cargo.toml");if(await vn(n))try{let s=JSON.parse(await Ze.readFile(n,"utf8"));if(s.name?.trim())return s.name.trim()}catch{}for(let s of[r,o])if(await vn(s))try{let c=(await Ze.readFile(s,"utf8")).match(/^\s*name\s*=\s*["']([^"']+)["']/m);if(c?.[1])return c[1]}catch{}return I.posix.basename(t)}i(Wc,"readAreaLabel");async function Gh(e,t){let n=new Map;for(let o of t){let a=z(o).split("/");if(a.length===1){n.set(".","root");continue}if(Oh.has(a[0]??"")&&a[1]){n.set(`${a[0]}/${a[1]}`,"package");continue}let c=Rh.get(a[0]??"");c&&n.set(a[0],c)}n.size===0&&n.set(".","root");let r=[];for(let[o,s]of Array.from(n.entries()).sort((a,c)=>a[0].localeCompare(c[0]))){let a=o==="."?"":`${o}/`,c=t.filter(d=>o==="."?!d.includes("/"):d===o||d.startsWith(a)).sort((d,u)=>d.localeCompare(u)),l=c.filter(d=>!(o==="."?d:d.slice(a.length)).includes("/")&&qo.has(I.posix.basename(d)));r.push({id:o,label:await Wc(e,o),kind:s,root:o,fileCount:c.length,manifests:l.slice(0,Uo),sampleFiles:c.slice(0,Uo)})}return r.sort((o,s)=>s.fileCount!==o.fileCount?s.fileCount-o.fileCount:o.root.localeCompare(s.root))}i(Gh,"buildAreas");async function Rc(e,t){if(t==="git")try{let[n,r,o]=await Promise.all([oe(["branch","--show-current"],e),oe(["rev-parse","HEAD"],e),oe(["status","--short"],e)]);return{branch:n.trim()||void 0,head:r.trim()||void 0,hasUncommittedChanges:o.trim().length>0}}catch{return}}i(Rc,"getGitSummary");async function Hc(e,t){if(t==="git")try{return await Hh(e)}catch{return $c(e)}return $c(e)}i(Hc,"collectWorkspaceFilesForSource");async function fr(e,t){let n=await Gc(e,Dc);return!n||n.schemaVersion!==ae||t&&n.overviewGeneratedAt!==t?null:n}i(fr,"readRepoOverviewInventory");async function Oc(e){let n=(await oe(["status","--porcelain=v1","-z","--untracked-files=all"],e)).split("\0"),r=new Set;for(let o=0;o<n.length;o+=1){let s=n[o];if(!s||s.length<4)continue;let a=s.slice(0,2),c=z(s.slice(3));if(c&&!gt(c)&&r.add(c),a.includes("R")||a.includes("C")){let l=z(n[o+1]??"");l&&!gt(l)&&r.add(l),o+=1}}return Array.from(r).sort((o,s)=>o.localeCompare(s))}i(Oc,"collectWorkspaceDirtyPaths");async function zc(e,t){return ur(hr(e,t),Nh)}i(zc,"readStoredRepoOverview");async function Gc(e,t){return ur(hr(e,t),Dh)}i(Gc,"readStoredRepoOverviewInventory");async function Kh(e){return ur(hr(e,Pc),jh)}i(Kh,"readStoredRepoOverviewManifest");async function Xh(e,t){let n=jo("sha256");n.update(Bc(t));for(let r of t){let o=I.join(e,r);n.update(r),n.update(":");try{if(await Ze.stat(o),n.update("present:"),Uh(r)){let s=await Ze.readFile(o,"utf8");n.update(jo("sha256").update(s).digest("hex"))}}catch(s){let a=ht(s)&&typeof s.code=="string"?s.code:void 0;n.update(a==="ENOENT"?"missing":"unreadable")}n.update("|")}return n.digest("hex")}i(Xh,"computeDirtySemanticFingerprint");async function Ic(e,t){let n=t.map(r=>z(r)).sort((r,o)=>r.localeCompare(o));return{dirtyPaths:n,dirtyPathsFingerprint:Bc(n),dirtySemanticFingerprint:await Xh(e,n)}}i(Ic,"buildDirtyOverviewIdentity");async function Vh(e,t,n){let r=new Set(t.map(o=>z(o)));for(let o of n){let s=I.join(e,o);await vn(s)?r.add(o):r.delete(o)}return Array.from(r).sort((o,s)=>o.localeCompare(s))}i(Vh,"applyDirtyPathPatchToFiles");async function Kc(e,t,n,r,o){let s=n.map(c=>z(c)),a={schemaVersion:ae,workspaceRoot:e,source:t,generatedAt:new Date().toISOString(),truncated:r,git:o,fileStats:{totalFiles:s.length,sourceFiles:s.filter(c=>Xt(c)==="source").length,docFiles:s.filter(c=>Xt(c)==="docs").length,testFiles:s.filter(c=>Xt(c)==="tests").length,configFiles:s.filter(c=>Xt(c)==="config").length},manifests:s.filter(c=>qo.has(I.posix.basename(c))).slice(0,12),keyDocs:s.filter(c=>qc.has(c)||/^README/i.test(I.posix.basename(c))&&Uc.has(I.extname(c).toLowerCase())).slice(0,8),entryHints:s.filter(c=>Lh.includes(I.posix.basename(c))).slice(0,8),areas:await Gh(e,s)};return{overview:a,inventory:{schemaVersion:ae,workspaceRoot:e,overviewGeneratedAt:a.generatedAt,source:t,allFiles:[...s].sort((c,l)=>c.localeCompare(l)),sourceFiles:s.filter(c=>Xt(c)==="source").sort((c,l)=>c.localeCompare(l))}}}i(Kc,"buildRepoOverviewArtifacts");async function Xc(e,t,n,r={}){let o={schemaVersion:ae,generatedAt:t.generatedAt,workspaceRoot:t.workspaceRoot,git:t.git??null,snapshotKind:t.source==="git"&&t.git?.hasUncommittedChanges===!0?"dirty":"clean",head:t.git?.head,branch:t.git?.branch,dirtyPathsFingerprint:r.dirtyIdentity?.dirtyPathsFingerprint,dirtySemanticFingerprint:r.dirtyIdentity?.dirtySemanticFingerprint};await Ye(I.join(e,Pc),o),await Ye(I.join(e,Nc),t),await Ye(I.join(e,Dc),n),r.writeBaseline===!0&&(await Ye(I.join(e,Fc),t),await Ye(I.join(e,jc),n))}i(Xc,"writeRepoOverviewArtifacts");function Jh(e,t,n){return!!(n?.hasUncommittedChanges===!0&&e&&t&&e.schemaVersion===ae&&t.schemaVersion===ae&&e.source==="git"&&t.source==="git"&&e.git?.hasUncommittedChanges!==!0&&e.git?.head&&e.git?.head===n.head&&e.git?.branch===n.branch&&t.workspaceRoot===e.workspaceRoot&&t.overviewGeneratedAt===e.generatedAt)}i(Jh,"canUseOverviewBaseline");function Yh(e,t,n,r){return!!(e&&t&&e.schemaVersion===ae&&t.schemaVersion===ae&&e.source==="git"&&e.generatedAt===t.generatedAt&&e.workspaceRoot===t.workspaceRoot&&t.snapshotKind==="dirty"&&n?.hasUncommittedChanges===!0&&t.head===n.head&&t.branch===n.branch&&t.dirtyPathsFingerprint===r.dirtyPathsFingerprint&&t.dirtySemanticFingerprint===r.dirtySemanticFingerprint)}i(Yh,"canDirectReuseDirtyOverview");async function Zh(e,t,n){let r=await zc(e,Fc),o=await Gc(e,jc);if(!Jh(r,o,t))return null;let s=o,{dirtyPaths:a}=n,c=new Set(s.allFiles);if(r.truncated)for(let g of a){let w=I.join(e,g);if(!c.has(g)||await vn(w)===!1)return null}let l=new Set(c);for(let g of a){let w=I.join(e,g);await vn(w)?l.add(g):l.delete(g)}let d=Array.from(l).sort((g,w)=>g.localeCompare(w)),u=r.truncated||d.length>Re,f=u?d.slice(0,Re):d,{overview:m,inventory:h}=await Kc(e,"git",f,u,t),p=await Bo(e);return await Xc(p,m,h,{dirtyIdentity:n}),m}i(Zh,"tryBuildDirtyRepoOverviewFromBaseline");async function Qh(e,t,n,r,o){if(!t||!n||t.schemaVersion!==ae||t.source!=="filesystem"||n.schemaVersion!==ae||n.source!=="filesystem"||n.workspaceRoot!==e||n.overviewGeneratedAt!==t.generatedAt||t.truncated!==o)return!1;let s=r.map(a=>z(a)).sort((a,c)=>a.localeCompare(c));if(!qh(n.allFiles,s))return!1;for(let a of t.areas)if(await Wc(e,a.root)!==a.label)return!1;return!0}i(Qh,"canDirectReuseFilesystemOverview");async function Do(e,t,n,r,o){let{files:s,truncated:a}=o??await Hc(e,t),c=t==="git"&&r?.dirtyPaths.length?await Vh(e,s,r.dirtyPaths):s.map(h=>z(h)),l=a||c.length>Re,d=l?c.slice(0,Re):c,u=await Bo(e),{overview:f,inventory:m}=await Kc(e,t,d,l,n);return await Xc(u,f,m,{writeBaseline:t==="git"&&n?.hasUncommittedChanges!==!0,dirtyIdentity:r}),{workspaceRoot:e,source:t,overview:f,inventory:m,dirtyPaths:r?.dirtyPaths}}i(Do,"buildRepoOverviewSnapshotForWorkspace");async function mr(e,t={}){let n=Z(e),r=await Wh(t.targetPath?I.resolve(n,t.targetPath):n),{workspaceRoot:o,source:s}=await Bh(r),a=await zc(o,Nc),c=await Kh(o),l,d;if(!t.refresh){if(l=await Rc(o,s),s!=="git"){let f=a?.schemaVersion===ae?await fr(o,a.generatedAt):null,m=await Hc(o,s);return await Qh(o,a,f,m.files,m.truncated)?{workspaceRoot:o,source:s,overview:a,inventory:f}:Do(o,s,l,void 0,m)}if(s==="git"&&a?.schemaVersion===ae&&l?.hasUncommittedChanges!==!0&&a.git?.head===l?.head&&a.git?.branch===l?.branch&&a.git?.hasUncommittedChanges===l?.hasUncommittedChanges&&a)return{workspaceRoot:o,source:s,overview:a,inventory:await fr(o,a.generatedAt)};if(s==="git"&&l?.hasUncommittedChanges===!0){let f=await Oc(o).catch(m=>($e("Could not collect dirty workspace paths for repo overview.",m),null));if(f){if(d=await Ic(o,f),Yh(a,c,l,d))return{workspaceRoot:o,source:s,overview:a,inventory:await fr(o,a.generatedAt),dirtyPaths:d.dirtyPaths};let m=await Zh(o,l,d);if(m)return{workspaceRoot:o,source:s,overview:m,inventory:await fr(o,m.generatedAt),dirtyPaths:d.dirtyPaths}}}return Do(o,s,l,d)}if(l=await Rc(o,s),s==="git"&&l?.hasUncommittedChanges===!0){let u=await Oc(o).catch(f=>($e("Could not collect dirty workspace paths for refreshed repo overview.",f),null));u&&(d=await Ic(o,u))}return Do(o,s,l,d)}i(mr,"resolveRepoOverviewSnapshot");async function aA(e,t){return(await mr(e,{targetPath:t,refresh:!0})).overview}i(aA,"buildRepoOverview");async function Vc(e,t={}){return(await mr(e,t)).overview}i(Vc,"getRepoOverview");function Fo(e,t){return t.length===0?[]:[`${e}: ${t.join(" | ")}`]}i(Fo,"formatList");function Wo(e){let t=[`Repository overview for ${I.basename(e.workspaceRoot)}`,`Root: ${e.workspaceRoot}`,`Snapshot: ${e.source} @ ${e.generatedAt}`];(e.git?.branch||e.git?.head)&&t.push(`Git: branch=${e.git.branch??"unknown"} head=${e.git.head?.slice(0,12)??"unknown"} dirty=${e.git.hasUncommittedChanges?"yes":"no"}`),t.push(`Files: ${e.fileStats.totalFiles} total | ${e.fileStats.sourceFiles} source | ${e.fileStats.docFiles} docs | ${e.fileStats.testFiles} tests | ${e.fileStats.configFiles} config`),e.truncated&&t.push(`[Overview truncated after ${Re} files. Refresh in a narrower workspace if you need higher fidelity.]`),t.push(...Fo("Key manifests",e.manifests.slice(0,6))),t.push(...Fo("Key docs",e.keyDocs.slice(0,6))),t.push(...Fo("Entry hints",e.entryHints.slice(0,6))),t.push("Areas:");let n=e.areas.slice(0,pr);for(let r of n){let o=r.manifests.length>0?` | manifests: ${r.manifests.join(", ")}`:"",s=r.sampleFiles.length>0?` | sample: ${r.sampleFiles.join(", ")}`:"";t.push(`- ${r.root} [${r.kind}] ${r.label}: ${r.fileCount} files${o}${s}`)}return e.areas.length>n.length&&t.push(`- ... ${e.areas.length-n.length} more areas`),t.join(`
138
+ `)}i(Wo,"renderRepoOverview");async function Ho(e,t={}){let n=[],r=t.includeRepoOverview!==!1,o=t.includeChangedScope===!0,s=r||o?await mr(e,{targetPath:t.targetPath,refresh:t.refreshOverview}):null;if(r&&s&&n.push(["## Repository Intelligence",Wo(s.overview)].join(`
139
+ `)),o&&s)try{let a=await Yc(s,{scope:t.changedScope??"all",baseRef:t.baseRef});n.push(["## Repository Change Scope",zo(a)].join(`
125
140
  `))}catch{}return n.join(`
126
141
 
127
- `)}i(Io,"buildRepoIntelligenceContext");function ec(e){return e.includes("R")?"renamed":e.includes("D")?"deleted":e.includes("A")?"added":e==="??"?"untracked":"modified"}i(ec,"resolveChangedStatus");function zm(e){if(!e.trim())return null;let t=e.slice(0,2),n=e.slice(3).trim(),r=H(n.includes(" -> ")?n.split(" -> ").pop()??n:n),o=t[0]!==" "&&t[0]!=="?",s=t[1]!==" "&&t[1]!=="?";return{status:t,path:r,staged:o,unstaged:s||t==="??"}}i(zm,"parsePorcelainLine");function Gm(e,t){return e?t==="staged"?e.staged:t==="unstaged"?e.unstaged:e.staged||e.unstaged:!1}i(Gm,"includesCandidate");function tc(e,t){let n=H(e),r=[...t].sort((o,s)=>s.root.length-o.root.length);for(let o of r)if(o.root!=="."&&(n===o.root||n.startsWith(`${o.root}/`)))return o;return t.find(o=>o.root===".")??{id:".",label:"Workspace Root",kind:"root",root:".",fileCount:0,manifests:[],sampleFiles:[]}}i(tc,"findAreaForFile");function Xm(e,t){let n=[];t.length>1&&n.push(`Cross-area change touches ${t.length} areas.`);let r=e.filter(s=>s.category==="config").map(s=>s.path);return r.length>0&&n.push(`Config or manifest changes detected: ${r.slice(0,4).join(" | ")}.`),e.length>0&&e.every(s=>s.category==="docs"||s.category==="tests")&&n.push("Changes are currently limited to docs/tests; implementation files are untouched."),e.some(s=>s.areaId===".")&&n.push("Workspace-root files changed; validate repo-wide implications."),n}i(Xm,"buildRiskHints");async function Vm(e,t,n){if(t==="compare"){let a=n?.trim()||"HEAD~1";if(!a||a.startsWith("-")||/[\u0000-\u001f\s]/.test(a))throw new Error(`Invalid base ref "${a}".`);try{await te(["rev-parse","--verify","--quiet",`${a}^{commit}`],e)}catch(l){throw Te(`Rejected compare base ref "${a}".`,l),new Error(`Could not resolve base ref "${a}".`)}return(await te(["diff","--name-status",`${a}...HEAD`],e)).split(/\r?\n/).map(l=>l.trim()).filter(Boolean).map(l=>{let[d,...u]=l.split(/\s+/),f=u.join(" ").split(" -> ").pop()??u.join(" ");return{path:H(f),status:ec(d??"M")}}).filter(l=>!dt(l.path))}let o=(await te(["status","--porcelain=v1","--untracked-files=all"],e)).split(/\r?\n/).map(zm).filter(a=>a!==null).filter(a=>Gm(a,t)),s=new Map;for(let a of o)dt(a.path)||s.set(a.path,{path:a.path,status:ec(a.status)});return Array.from(s.values())}i(Vm,"collectChangedFiles");async function Jm(e,t,n){let r="";if(t==="compare"){let a=n?.trim()||"HEAD~1";r=await te(["diff","--numstat",`${a}...HEAD`],e)}else t==="staged"?r=await te(["diff","--cached","--numstat"],e):t==="unstaged"?r=await te(["diff","--numstat"],e):r=await te(["diff","--numstat","HEAD"],e);let o=0,s=0;for(let a of r.split(/\r?\n/)){let c=a.trim();if(!c)continue;let l=c.match(/^(\d+|-)\s+(\d+|-)\s+(.+)$/);if(!l)continue;let[,d,u,f]=l,m=H(f.split(" -> ").pop()??f);if(dt(m))continue;let h=d==="-"?0:Number.parseInt(d,10),p=u==="-"?0:Number.parseInt(u,10);Number.isFinite(h)&&(o+=h),Number.isFinite(p)&&(s+=p)}return{changedLineCount:o+s,addedLineCount:o,deletedLineCount:s}}i(Jm,"collectChangedLineStats");async function yc(e,t={}){let n=await ar(e,{targetPath:t.targetPath,refresh:t.refreshOverview});return wc(n,t)}i(yc,"analyzeChangedScope");async function wc(e,t={}){let n=t.scope??"all",r=e.overview;if(r.source!=="git")throw new Error("changed_scope requires a git-backed workspace.");let o=await Vm(r.workspaceRoot,n,t.baseRef),s=await Jm(r.workspaceRoot,n,t.baseRef).catch(f=>(Te("Changed scope could not load line stats.",f),{changedLineCount:0,addedLineCount:0,deletedLineCount:0})),a=o.map(f=>{let m=tc(f.path,r.areas);return{path:f.path,status:f.status,category:Wt(f.path),areaId:m.id}}),c=new Map;for(let f of a){let m=tc(f.path,r.areas),h=c.get(m.id)??{areaId:m.id,label:m.label,root:m.root,kind:m.kind,fileCount:0,files:[]};c.set(m.id,{...h,fileCount:h.fileCount+1,files:h.files.length<Co?[...h.files,f.path]:h.files})}let l={source:0,docs:0,tests:0,config:0,other:0};for(let f of a)l[f.category]+=1;let d={schemaVersion:oe,workspaceRoot:r.workspaceRoot,analyzedAt:new Date().toISOString(),scope:n,baseRef:n==="compare"?t.baseRef?.trim()||"HEAD~1":void 0,overviewGeneratedAt:r.generatedAt,totalChangedFiles:a.length,changedLineCount:s.changedLineCount,addedLineCount:s.addedLineCount,deletedLineCount:s.deletedLineCount,categories:l,areasTouched:Array.from(c.values()).sort((f,m)=>m.fileCount!==f.fileCount?m.fileCount-f.fileCount:f.root.localeCompare(m.root)),files:a,riskHints:Xm(a,Array.from(c.values()))},u=await $o(r.workspaceRoot);return await Ge(O.join(u,ym),d),d}i(wc,"analyzeChangedScopeFromSnapshot");function Ym(e){switch(e.scope){case"staged":return"staged (index vs HEAD)";case"unstaged":return"unstaged (working tree vs index)";case"compare":return`compare (${e.baseRef??"HEAD~1"}...HEAD \u2014 committed range)`;default:return"all (uncommitted working tree vs HEAD \u2014 excludes committed history)"}}i(Ym,"describeChangedScope");function Lo(e){let t=[`Changed scope for ${O.basename(e.workspaceRoot)}`,`Root: ${e.workspaceRoot}`,`Scope: ${Ym(e)}`,`Snapshot: ${e.analyzedAt}`,`Changed files: ${e.totalChangedFiles}`,`Changed lines: ${e.changedLineCount} (+${e.addedLineCount} / -${e.deletedLineCount}; line counts cover tracked diffs only, untracked files excluded)`,`Categories: source=${e.categories.source} docs=${e.categories.docs} tests=${e.categories.tests} config=${e.categories.config} other=${e.categories.other}`];if(e.overviewGeneratedAt&&t.push(`Repository overview snapshot: ${e.overviewGeneratedAt}`),t.push("Areas touched:"),e.areasTouched.length===0)t.push("- none");else{for(let n of e.areasTouched.slice(0,sr)){let r=n.files.length>0?` | sample: ${n.files.join(", ")}`:"";t.push(`- ${n.root} [${n.kind}] ${n.label}: ${n.fileCount} changed file(s)${r}`)}e.areasTouched.length>sr&&t.push(`- ... ${e.areasTouched.length-sr} more areas`)}if(e.riskHints.length>0){t.push("Risk hints:");for(let n of e.riskHints)t.push(`- ${n}`)}t.push("Changed files:");for(let n of e.files.slice(0,Eo))t.push(`- ${n.status} ${n.path} [${n.category}] -> ${n.areaId}`);return e.files.length>Eo&&t.push(`- ... ${e.files.length-Eo} more file(s)`),t.join(`
128
- `)}i(Lo,"renderChangedScope");function Qm(){return hn(gm)}i(Qm,"getRepoIntelligenceDir");function cr(e,...t){let n=Qm(),r=O.isAbsolute(n)?n:O.join(e,n);return O.join(r,...t)}i(cr,"resolveRepoIntelligencePath");function _(e,t){let n=e[t];if(!(n==null||n==="")){if(typeof n!="string")throw new Error(`${t} must be a string when provided.`);return n}}i(_,"readOptionalString");async function Mo(e,t){try{let n=await gc(t,{targetPath:_(e,"target_path"),refresh:e.refresh===!0});return Oo(n)}catch(n){return`[Tool Error] repo_overview: ${n instanceof Error?n.message:String(n)}`}}i(Mo,"toolRepoOverview");var bc=new Set(["unstaged","staged","all","compare"]);function Zm(e){let t=e.scope;if(t==null||t==="")return"all";if(typeof t!="string"||!bc.has(t))throw new Error(`scope must be one of: ${Array.from(bc).join(", ")}.`);return t}i(Zm,"readScope");async function Po(e,t){try{let n=await yc(t,{targetPath:_(e,"target_path"),scope:Zm(e),baseRef:_(e,"base_ref"),refreshOverview:e.refresh_overview===!0});return Lo(n)}catch(n){return`[Tool Error] changed_scope: ${n instanceof Error?n.message:String(n)}`}}i(Po,"toolChangedScope");import kc from"node:fs/promises";import le from"node:path";import{execFile as eh}from"node:child_process";import{promisify as th}from"node:util";var nh=th(eh),vc=360,rh=480,lr=800,_c=3,xc=12,oh=200,No=10,ih=1e4;async function dr(e,t){return(await nh("git",e,{cwd:t,timeout:ih,windowsHide:!0,maxBuffer:8388608})).stdout.toString()}i(dr,"runGit");async function Ec(e){try{let n=(await dr(["rev-parse","--show-toplevel"],e)).trim();if(!n)throw new Error("git root not found");return le.resolve(n)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`changed_diff requires a git-backed workspace. ${n}`)}}i(Ec,"resolveWorkspaceRoot");async function Sc(e){let t=le.resolve(e);for(;;)try{return(await kc.stat(t)).isDirectory()?t:le.dirname(t)}catch{let n=le.dirname(t);if(n===t)return e;t=n}}i(Sc,"resolveTargetDirectory");function Ht(e,t,n,r){let o=e[t];if(o==null||o==="")return n;let s=Number(o);if(!Number.isFinite(s)||s<=0)throw new Error(`${t} must be a positive integer.`);return Math.min(r,Math.floor(s))}i(Ht,"readPositiveInteger");function sh(e,t){let n=e[t];if(n==null)return[];if(Array.isArray(n))return n.map(r=>typeof r=="string"?r.trim():"").filter(Boolean);if(typeof n=="string")return n.split(/[,\r\n]/).map(r=>r.trim()).filter(Boolean);throw new Error(`${t} must be an array of strings.`)}i(sh,"readStringArray");function Tc(e,t){return t>=2e3?Math.min(lr,Math.max(e,rh)):t>=1e3?Math.min(lr,Math.max(e,vc)):e}i(Tc,"resolveSuggestedContinuationLimit");function Ac(e,t){let n=e.trim();if(!n)throw new Error("path is required.");let r=le.isAbsolute(n)?le.resolve(n):le.resolve(t,n),o=le.relative(t,r).replace(/\\/g,"/");if(!o||o.startsWith(".."))throw new Error(`path must stay within the workspace root: ${t}`);return o}i(Ac,"normalizeDiffPath");function ah(e,t){let n=e.replace(/\\/g,"/"),r=t.length>0?t.replace(/\r\n/g,`
142
+ `)}i(Ho,"buildRepoIntelligenceContext");function Lc(e){return e.includes("R")?"renamed":e.includes("D")?"deleted":e.includes("A")?"added":e==="??"?"untracked":"modified"}i(Lc,"resolveChangedStatus");function eg(e){if(!e.trim())return null;let t=e.slice(0,2),n=e.slice(3).trim(),r=z(n.includes(" -> ")?n.split(" -> ").pop()??n:n),o=t[0]!==" "&&t[0]!=="?",s=t[1]!==" "&&t[1]!=="?";return{status:t,path:r,staged:o,unstaged:s||t==="??"}}i(eg,"parsePorcelainLine");function tg(e,t){return e?t==="staged"?e.staged:t==="unstaged"?e.unstaged:e.staged||e.unstaged:!1}i(tg,"includesCandidate");function Mc(e,t){let n=z(e),r=[...t].sort((o,s)=>s.root.length-o.root.length);for(let o of r)if(o.root!=="."&&(n===o.root||n.startsWith(`${o.root}/`)))return o;return t.find(o=>o.root===".")??{id:".",label:"Workspace Root",kind:"root",root:".",fileCount:0,manifests:[],sampleFiles:[]}}i(Mc,"findAreaForFile");function ng(e,t){let n=[];t.length>1&&n.push(`Cross-area change touches ${t.length} areas.`);let r=e.filter(s=>s.category==="config").map(s=>s.path);return r.length>0&&n.push(`Config or manifest changes detected: ${r.slice(0,4).join(" | ")}.`),e.length>0&&e.every(s=>s.category==="docs"||s.category==="tests")&&n.push("Changes are currently limited to docs/tests; implementation files are untouched."),e.some(s=>s.areaId===".")&&n.push("Workspace-root files changed; validate repo-wide implications."),n}i(ng,"buildRiskHints");async function rg(e,t,n){if(t==="compare"){let a=n?.trim()||"HEAD~1";if(!a||a.startsWith("-")||/[\u0000-\u001f\s]/.test(a))throw new Error(`Invalid base ref "${a}".`);try{await oe(["rev-parse","--verify","--quiet",`${a}^{commit}`],e)}catch(l){throw $e(`Rejected compare base ref "${a}".`,l),new Error(`Could not resolve base ref "${a}".`)}return(await oe(["diff","--name-status",`${a}...HEAD`],e)).split(/\r?\n/).map(l=>l.trim()).filter(Boolean).map(l=>{let[d,...u]=l.split(/\s+/),f=u.join(" ").split(" -> ").pop()??u.join(" ");return{path:z(f),status:Lc(d??"M")}}).filter(l=>!gt(l.path))}let o=(await oe(["status","--porcelain=v1","--untracked-files=all"],e)).split(/\r?\n/).map(eg).filter(a=>a!==null).filter(a=>tg(a,t)),s=new Map;for(let a of o)gt(a.path)||s.set(a.path,{path:a.path,status:Lc(a.status)});return Array.from(s.values())}i(rg,"collectChangedFiles");async function og(e,t,n){let r="";if(t==="compare"){let a=n?.trim()||"HEAD~1";r=await oe(["diff","--numstat",`${a}...HEAD`],e)}else t==="staged"?r=await oe(["diff","--cached","--numstat"],e):t==="unstaged"?r=await oe(["diff","--numstat"],e):r=await oe(["diff","--numstat","HEAD"],e);let o=0,s=0;for(let a of r.split(/\r?\n/)){let c=a.trim();if(!c)continue;let l=c.match(/^(\d+|-)\s+(\d+|-)\s+(.+)$/);if(!l)continue;let[,d,u,f]=l,m=z(f.split(" -> ").pop()??f);if(gt(m))continue;let h=d==="-"?0:Number.parseInt(d,10),p=u==="-"?0:Number.parseInt(u,10);Number.isFinite(h)&&(o+=h),Number.isFinite(p)&&(s+=p)}return{changedLineCount:o+s,addedLineCount:o,deletedLineCount:s}}i(og,"collectChangedLineStats");async function Jc(e,t={}){let n=await mr(e,{targetPath:t.targetPath,refresh:t.refreshOverview});return Yc(n,t)}i(Jc,"analyzeChangedScope");async function Yc(e,t={}){let n=t.scope??"all",r=e.overview;if(r.source!=="git")throw new Error("changed_scope requires a git-backed workspace.");let o=await rg(r.workspaceRoot,n,t.baseRef),s=await og(r.workspaceRoot,n,t.baseRef).catch(f=>($e("Changed scope could not load line stats.",f),{changedLineCount:0,addedLineCount:0,deletedLineCount:0})),a=o.map(f=>{let m=Mc(f.path,r.areas);return{path:f.path,status:f.status,category:Xt(f.path),areaId:m.id}}),c=new Map;for(let f of a){let m=Mc(f.path,r.areas),h=c.get(m.id)??{areaId:m.id,label:m.label,root:m.root,kind:m.kind,fileCount:0,files:[]};c.set(m.id,{...h,fileCount:h.fileCount+1,files:h.files.length<Uo?[...h.files,f.path]:h.files})}let l={source:0,docs:0,tests:0,config:0,other:0};for(let f of a)l[f.category]+=1;let d={schemaVersion:ae,workspaceRoot:r.workspaceRoot,analyzedAt:new Date().toISOString(),scope:n,baseRef:n==="compare"?t.baseRef?.trim()||"HEAD~1":void 0,overviewGeneratedAt:r.generatedAt,totalChangedFiles:a.length,changedLineCount:s.changedLineCount,addedLineCount:s.addedLineCount,deletedLineCount:s.deletedLineCount,categories:l,areasTouched:Array.from(c.values()).sort((f,m)=>m.fileCount!==f.fileCount?m.fileCount-f.fileCount:f.root.localeCompare(m.root)),files:a,riskHints:ng(a,Array.from(c.values()))},u=await Bo(r.workspaceRoot);return await Ye(I.join(u,Sh),d),d}i(Yc,"analyzeChangedScopeFromSnapshot");function ig(e){switch(e.scope){case"staged":return"staged (index vs HEAD)";case"unstaged":return"unstaged (working tree vs index)";case"compare":return`compare (${e.baseRef??"HEAD~1"}...HEAD \u2014 committed range)`;default:return"all (uncommitted working tree vs HEAD \u2014 excludes committed history)"}}i(ig,"describeChangedScope");function zo(e){let t=[`Changed scope for ${I.basename(e.workspaceRoot)}`,`Root: ${e.workspaceRoot}`,`Scope: ${ig(e)}`,`Snapshot: ${e.analyzedAt}`,`Changed files: ${e.totalChangedFiles}`,`Changed lines: ${e.changedLineCount} (+${e.addedLineCount} / -${e.deletedLineCount}; line counts cover tracked diffs only, untracked files excluded)`,`Categories: source=${e.categories.source} docs=${e.categories.docs} tests=${e.categories.tests} config=${e.categories.config} other=${e.categories.other}`];if(e.overviewGeneratedAt&&t.push(`Repository overview snapshot: ${e.overviewGeneratedAt}`),t.push("Areas touched:"),e.areasTouched.length===0)t.push("- none");else{for(let n of e.areasTouched.slice(0,pr)){let r=n.files.length>0?` | sample: ${n.files.join(", ")}`:"";t.push(`- ${n.root} [${n.kind}] ${n.label}: ${n.fileCount} changed file(s)${r}`)}e.areasTouched.length>pr&&t.push(`- ... ${e.areasTouched.length-pr} more areas`)}if(e.riskHints.length>0){t.push("Risk hints:");for(let n of e.riskHints)t.push(`- ${n}`)}t.push("Changed files:");for(let n of e.files.slice(0,No))t.push(`- ${n.status} ${n.path} [${n.category}] -> ${n.areaId}`);return e.files.length>No&&t.push(`- ... ${e.files.length-No} more file(s)`),t.join(`
143
+ `)}i(zo,"renderChangedScope");function sg(){return kn(Eh)}i(sg,"getRepoIntelligenceDir");function hr(e,...t){let n=sg(),r=I.isAbsolute(n)?n:I.join(e,n);return I.join(r,...t)}i(hr,"resolveRepoIntelligencePath");function _(e,t){let n=e[t];if(!(n==null||n==="")){if(typeof n!="string")throw new Error(`${t} must be a string when provided.`);return n}}i(_,"readOptionalString");async function Go(e,t){try{let n=await Vc(t,{targetPath:_(e,"target_path"),refresh:e.refresh===!0});return Wo(n)}catch(n){return`[Tool Error] repo_overview: ${n instanceof Error?n.message:String(n)}`}}i(Go,"toolRepoOverview");var Zc=new Set(["unstaged","staged","all","compare"]);function ag(e){let t=e.scope;if(t==null||t==="")return"all";if(typeof t!="string"||!Zc.has(t))throw new Error(`scope must be one of: ${Array.from(Zc).join(", ")}.`);return t}i(ag,"readScope");async function Ko(e,t){try{let n=await Jc(t,{targetPath:_(e,"target_path"),scope:ag(e),baseRef:_(e,"base_ref"),refreshOverview:e.refresh_overview===!0});return zo(n)}catch(n){return`[Tool Error] changed_scope: ${n instanceof Error?n.message:String(n)}`}}i(Ko,"toolChangedScope");import Qc from"node:fs/promises";import pe from"node:path";import{execFile as cg}from"node:child_process";import{promisify as lg}from"node:util";var dg=lg(cg),el=360,ug=480,gr=800,tl=3,nl=12,fg=200,Xo=10,pg=1e4;async function yr(e,t){return(await dg("git",e,{cwd:t,timeout:pg,windowsHide:!0,maxBuffer:8388608})).stdout.toString()}i(yr,"runGit");async function rl(e){try{let n=(await yr(["rev-parse","--show-toplevel"],e)).trim();if(!n)throw new Error("git root not found");return pe.resolve(n)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`changed_diff requires a git-backed workspace. ${n}`)}}i(rl,"resolveWorkspaceRoot");async function ol(e){let t=pe.resolve(e);for(;;)try{return(await Qc.stat(t)).isDirectory()?t:pe.dirname(t)}catch{let n=pe.dirname(t);if(n===t)return e;t=n}}i(ol,"resolveTargetDirectory");function Vt(e,t,n,r){let o=e[t];if(o==null||o==="")return n;let s=Number(o);if(!Number.isFinite(s)||s<=0)throw new Error(`${t} must be a positive integer.`);return Math.min(r,Math.floor(s))}i(Vt,"readPositiveInteger");function mg(e,t){let n=e[t];if(n==null)return[];if(Array.isArray(n))return n.map(r=>typeof r=="string"?r.trim():"").filter(Boolean);if(typeof n=="string")return n.split(/[,\r\n]/).map(r=>r.trim()).filter(Boolean);throw new Error(`${t} must be an array of strings.`)}i(mg,"readStringArray");function il(e,t){return t>=2e3?Math.min(gr,Math.max(e,ug)):t>=1e3?Math.min(gr,Math.max(e,el)):e}i(il,"resolveSuggestedContinuationLimit");function sl(e,t){let n=e.trim();if(!n)throw new Error("path is required.");let r=pe.isAbsolute(n)?pe.resolve(n):pe.resolve(t,n),o=pe.relative(t,r).replace(/\\/g,"/");if(!o||o.startsWith(".."))throw new Error(`path must stay within the workspace root: ${t}`);return o}i(sl,"normalizeDiffPath");function hg(e,t){let n=e.replace(/\\/g,"/"),r=t.length>0?t.replace(/\r\n/g,`
129
144
  `).split(`
130
145
  `):[],o=`@@ -0,0 +1,${Math.max(r.length,1)} @@`;return["diff --git a/dev/null b/"+n,"new file mode 100644","--- /dev/null",`+++ b/${n}`,o,...r.map(s=>`+${s}`)].join(`
131
- `)}i(ah,"buildSyntheticAddedDiff");async function Cc(e,t,n){for(let l of[["diff","--no-ext-diff",`--unified=${n}`,"HEAD","--",t],["diff","--no-ext-diff",`--unified=${n}`,"--",t]])try{let d=await dr(l,e);if(d.trim())return d.trimEnd()}catch{}if(!(await dr(["status","--porcelain=v1","--untracked-files=all","--",t],e)).split(/\r?\n/).map(l=>l.trim()).filter(Boolean).some(l=>l.startsWith("??")))return"";let a=le.join(e,t),c=await kc.readFile(a,"utf8");return ah(t,c)}i(Cc,"buildWorkspaceDiff");async function Rc(e,t,n,r,o){let s=r?.trim()?`${n.trim()}...${r.trim()}`:`${n.trim()}...HEAD`;return(await dr(["diff","--no-ext-diff",`--unified=${o}`,s,"--",t],e)).trimEnd()}i(Rc,"buildCompareDiff");function ch(e){let{diff:t,relativePath:n,offset:r,limit:o,baseRef:s,targetRef:a,contextLines:c}=e;if(!t.trim())return[`Changed diff for ${n}`,`Context lines: ${c}`,s?`Range: ${s}...${a?.trim()||"HEAD"}`:"Range: current workspace vs HEAD/worktree","[No diff for the requested path.]"].join(`
146
+ `)}i(hg,"buildSyntheticAddedDiff");async function al(e,t,n){for(let l of[["diff","--no-ext-diff",`--unified=${n}`,"HEAD","--",t],["diff","--no-ext-diff",`--unified=${n}`,"--",t]])try{let d=await yr(l,e);if(d.trim())return d.trimEnd()}catch{}if(!(await yr(["status","--porcelain=v1","--untracked-files=all","--",t],e)).split(/\r?\n/).map(l=>l.trim()).filter(Boolean).some(l=>l.startsWith("??")))return"";let a=pe.join(e,t),c=await Qc.readFile(a,"utf8");return hg(t,c)}i(al,"buildWorkspaceDiff");async function cl(e,t,n,r,o){let s=r?.trim()?`${n.trim()}...${r.trim()}`:`${n.trim()}...HEAD`;return(await yr(["diff","--no-ext-diff",`--unified=${o}`,s,"--",t],e)).trimEnd()}i(cl,"buildCompareDiff");function gg(e){let{diff:t,relativePath:n,offset:r,limit:o,baseRef:s,targetRef:a,contextLines:c}=e;if(!t.trim())return[`Changed diff for ${n}`,`Context lines: ${c}`,s?`Range: ${s}...${a?.trim()||"HEAD"}`:"Range: current workspace vs HEAD/worktree","[No diff for the requested path.]"].join(`
132
147
  `);let l=t.replace(/\r\n/g,`
133
148
  `).split(`
134
- `),d=Math.max(1,r),u=d-1;if(u>=l.length)return`[Tool Error] Offset ${d} is beyond the diff length (${l.length} lines total).`;let f=l.slice(u,u+o),m=d+f.length-1,h=m<l.length,p=Tc(o,l.length),g=[`Changed diff for ${n}`,`Context lines: ${c}`,s?`Range: ${s}...${a?.trim()||"HEAD"}`:"Range: current workspace vs HEAD/worktree",`Showing diff lines ${d}-${m} of ${l.length}`],w=h?p>o?`[Large diff detected. Continue with changed_diff offset=${m+1} limit=${p} path=${n} to reduce serial paging.]`:`[Use changed_diff with offset=${m+1} limit=${o} path=${n} to continue.]`:"[End of diff]";return[...g,"",...f,"",w].join(`
135
- `)}i(ch,"renderDiffSlice");function lh(e){let{diff:t,relativePath:n,offset:r,limit:o,baseRef:s,targetRef:a,contextLines:c}=e,l=[`=== ${n} ===`,`Context lines: ${c}`,s?`Range: ${s}...${a?.trim()||"HEAD"}`:"Range: current workspace vs HEAD/worktree"];if(!t.trim())return[...l,"[No diff for the requested path.]"].join(`
149
+ `),d=Math.max(1,r),u=d-1;if(u>=l.length)return`[Tool Error] Offset ${d} is beyond the diff length (${l.length} lines total).`;let f=l.slice(u,u+o),m=d+f.length-1,h=m<l.length,p=il(o,l.length),g=[`Changed diff for ${n}`,`Context lines: ${c}`,s?`Range: ${s}...${a?.trim()||"HEAD"}`:"Range: current workspace vs HEAD/worktree",`Showing diff lines ${d}-${m} of ${l.length}`],w=h?p>o?`[Large diff detected. Continue with changed_diff offset=${m+1} limit=${p} path=${n} to reduce serial paging.]`:`[Use changed_diff with offset=${m+1} limit=${o} path=${n} to continue.]`:"[End of diff]";return[...g,"",...f,"",w].join(`
150
+ `)}i(gg,"renderDiffSlice");function yg(e){let{diff:t,relativePath:n,offset:r,limit:o,baseRef:s,targetRef:a,contextLines:c}=e,l=[`=== ${n} ===`,`Context lines: ${c}`,s?`Range: ${s}...${a?.trim()||"HEAD"}`:"Range: current workspace vs HEAD/worktree"];if(!t.trim())return[...l,"[No diff for the requested path.]"].join(`
136
151
  `);let d=t.replace(/\r\n/g,`
137
152
  `).split(`
138
153
  `),u=Math.max(1,r),f=u-1;if(f>=d.length)return[...l,`[Tool Error] Offset ${u} is beyond the diff length (${d.length} lines total).`].join(`
139
- `);let m=d.slice(f,f+o),h=u+m.length-1,p=h<d.length,g=Tc(o,d.length),w=p?g>o?`[Large diff detected. Continue ${n} with changed_diff path=${n} offset=${h+1} limit=${g}.]`:`[Continue ${n} with changed_diff path=${n} offset=${h+1} limit=${o}.]`:"[End of diff]";return[...l,`Showing diff lines ${u}-${h} of ${d.length}`,"",...m,"",w].join(`
140
- `)}i(lh,"renderBundleSection");async function Do(e,t){try{let n=Q(t),r=_(e,"target_path"),o=r?await Sc(le.resolve(n,r)):n,s=await Ec(o),a=_(e,"path");if(!a)throw new Error("path must be provided.");let c=Ac(a,s),l=Ht(e,"offset",1,Number.MAX_SAFE_INTEGER),d=Ht(e,"limit",vc,lr),u=Ht(e,"context_lines",_c,xc),f=_(e,"base_ref"),m=_(e,"target_ref"),h=f?await Rc(s,c,f,m,u):await Cc(s,c,u);return ch({diff:h,relativePath:c,offset:l,limit:d,baseRef:f,targetRef:m,contextLines:u})}catch(n){return`[Tool Error] changed_diff: ${n instanceof Error?n.message:String(n)}`}}i(Do,"toolChangedDiff");async function jo(e,t){try{let n=Q(t),r=_(e,"target_path"),o=r?await Sc(le.resolve(n,r)):n,s=await Ec(o),a=sh(e,"paths");if(a.length===0)throw new Error("paths must contain at least one changed file path.");let c=Array.from(new Set(a.slice(0,No).map(p=>Ac(p,s)))),l=Ht(e,"offset",1,Number.MAX_SAFE_INTEGER),d=Ht(e,"limit_per_path",oh,lr),u=Ht(e,"context_lines",_c,xc),f=_(e,"base_ref"),m=_(e,"target_ref"),h=await Promise.all(c.map(async p=>{let g=f?await Rc(s,p,f,m,u):await Cc(s,p,u);return lh({diff:g,relativePath:p,offset:l,limit:d,baseRef:f,targetRef:m,contextLines:u})}));return[`Changed diff bundle for ${c.length} file(s)`,`Limit per path: ${d}`,"",...h.flatMap((p,g)=>g===0?[p]:["",p]),"",c.length>=No&&a.length>c.length?`[Additional paths omitted after ${No} entries. Re-run changed_diff_bundle with a narrower path batch.]`:"[Bundle complete]"].join(`
141
- `)}catch(n){return`[Tool Error] changed_diff_bundle: ${n instanceof Error?n.message:String(n)}`}}i(jo,"toolChangedDiffBundle");function ur(e){return e>=.8?"high":e>=.65?"medium":"low"}i(ur,"confidenceLabel");function fr(e){return!e||e.status==="ok"&&e.warnings.length===0?[]:[`Capability: ${e.engine}/${e.status}`,...e.warnings.map(t=>`Warning: ${t}`)]}i(fr,"capabilityLines");function Fo(e){let{module:t}=e;return[`Module context for ${t.label}`,`Module: ${t.moduleId} [${t.kind}]`,`Freshness: ${e.freshness}`,`Confidence: ${ur(e.confidence)} (${e.confidence.toFixed(2)})`,`Files: ${t.fileCount} total | ${t.sourceFileCount} source | ${t.symbolCount} symbols`,`Languages: ${t.languages.map(n=>`${n.language}/${n.capabilityTier}:${n.fileCount}`).join(" | ")||"none"}`,`Dependencies: ${t.dependencies.join(" | ")||"none"}`,`Dependents: ${t.dependents.join(" | ")||"none"}`,`Entry files: ${t.entryFiles.join(" | ")||"none"}`,`Top symbols: ${t.topSymbols.join(" | ")||"none"}`,`Tests: ${t.keyTests.join(" | ")||"none"}`,`Docs: ${t.keyDocs.join(" | ")||"none"}`,`Processes: ${t.processIds.join(" | ")||"none"}`,`Evidence: ${e.evidence.join(" | ")||"none"}`,...fr(e.capability)].join(`
142
- `)}i(Fo,"renderModuleContext");function Uo(e){let{symbol:t}=e;return[`Symbol context for ${t.name}`,`Definition: ${t.filePath}:${t.line}`,`Module: ${t.moduleId} | Kind: ${t.kind} | Exported: ${t.exported?"yes":"no"}`,`Language: ${t.language}/${t.capabilityTier}`,`Freshness: ${e.freshness}`,`Confidence: ${ur(e.confidence)} (${e.confidence.toFixed(2)})`,`Signature: ${t.signature}`,`Possible callees: ${t.callTargets.map(n=>`${n.name} -> ${n.filePath}`).join(" | ")||"none"}`,`Possible callers: ${e.callers.map(n=>`${n.name} -> ${n.filePath}`).join(" | ")||"none"}`,`Imports: ${t.importPaths.join(" | ")||"none"}`,e.alternatives.length>0?`Alternatives: ${e.alternatives.map(n=>`${n.name} @ ${n.filePath}:${n.line}`).join(" | ")}`:"Alternatives: none",...fr(e.capability)].join(`
143
- `)}i(Uo,"renderSymbolContext");function qo(e){let{process:t}=e;return[`Process context for ${t.label}`,`Module: ${t.moduleId}`,`Entry: ${t.entryFile}${t.entrySymbol?` -> ${t.entrySymbol}`:""}`,`Freshness: ${e.freshness}`,`Confidence: ${ur(e.confidence)} (${e.confidence.toFixed(2)})`,`Summary: ${t.summary}`,"Steps:",...t.steps.map(n=>`- ${n.kind} ${n.symbolName} @ ${n.filePath}${n.line?`:${n.line}`:""} | ${n.note}`),e.alternatives.length>0?`Alternatives: ${e.alternatives.map(n=>n.label).join(" | ")}`:"Alternatives: none",...fr(e.capability)].join(`
144
- `)}i(qo,"renderProcessContext");function Bo(e){return[`Impact estimate for ${e.target.label}`,`Target: ${e.target.kind}${e.target.moduleId?` | module=${e.target.moduleId}`:""}${e.target.filePath?` | file=${e.target.filePath}`:""}`,`Freshness: ${e.freshness}`,`Confidence: ${ur(e.confidence)} (${e.confidence.toFixed(2)})`,`Summary: ${e.summary}`,`Impacted modules: ${e.impactedModules.map(t=>`${t.label}(${t.moduleId})`).join(" | ")||"none"}`,`Impacted symbols: ${e.impactedSymbols.map(t=>`${t.name} -> ${t.filePath}:${t.line}`).join(" | ")||"none"}`,`Possible callers: ${e.callers.map(t=>`${t.name} -> ${t.filePath}:${t.line}`).join(" | ")||"none"}`,e.changedScope?`Changed-scope overlap: ${e.changedScope.files.filter(t=>e.impactedModules.some(n=>n.moduleId===t.areaId)||e.impactedSymbols.some(n=>n.filePath===t.path)).length} file(s)`:"Changed-scope overlap: unavailable",...fr(e.capability)].join(`
145
- `)}i(Bo,"renderImpactEstimate");import yn from"node:fs/promises";import Vo from"node:path";import dh from"path";var $c=dh.join(".agent","repo-intelligence");var _S=512*1024;import{existsSync as uh}from"node:fs";import{basename as fh,dirname as Wo,join as Oc}from"node:path";import{fileURLToPath as Ho,pathToFileURL as Ic}from"node:url";import{Worker as ph}from"node:worker_threads";var mh=2048,hh=12e4,gh=1,ut,Mc=new WeakMap;function yh(){let e=Number(process.env.KODAX_REPO_INTELLIGENCE_WORKER_OLD_SPACE_MB);return Number.isFinite(e)&&e>=512?Math.floor(e):mh}i(yh,"readWorkerOldSpaceMb");function wh(){let e=Number(process.env.KODAX_REPO_INTELLIGENCE_WORKER_TIMEOUT_MS);return Number.isFinite(e)&&e>=5e3?Math.floor(e):hh}i(wh,"readWorkerTimeoutMs");function Pc(){if(import.meta.url.endsWith(".ts")){let n=new URL("../../dist/repo-intelligence/semantic-worker.js",import.meta.url);return uh(Ho(n))?n:new URL("./semantic-worker.ts",import.meta.url)}if(process.env.KODAX_BUNDLED==="true")return Ic(Oc(Wo(process.execPath),"semantic-worker.js"));let e=Wo(Ho(import.meta.url)),t=fh(e)==="chunks"?Wo(e):e;return Ic(Oc(t,"semantic-worker.js"))}i(Pc,"resolveWorkerUrl");function Nc(){return Ho(Pc())}i(Nc,"getRepoIntelligenceWorkerPathForDiagnostics");function bh(e){return e.href.endsWith(".ts")?["--import","tsx"]:[]}i(bh,"resolveWorkerExecArgv");function Lc(e){return typeof e=="object"&&e!==null}i(Lc,"isRecord");function kh(e){return!Lc(e)||typeof e.id!="number"||typeof e.ok!="boolean"?!1:e.ok===!0?"result"in e:Lc(e.error)&&typeof e.error.message=="string"}i(kh,"isWorkerResponse");function vh(e){return{executionCwd:e.executionCwd,gitRoot:e.gitRoot}}i(vh,"cloneableRepoContext");function _h(e){return{targetPath:e.targetPath,refresh:e.refresh,profile:e.profile}}i(_h,"cloneableOptions");function xh(e,t){let n={context:vh(e.context),options:_h(e.options),id:t};switch(e.kind){case"buildIndex":case"getIndex":case"cyclicDeps":case"routing":return{...n,kind:e.kind};case"semanticLookup":return{...n,kind:e.kind,options:{...n.options,query:e.options.query,lookupKind:e.options.lookupKind,limit:e.options.limit}};case"module":return{...n,kind:e.kind,options:{...n.options,module:e.options.module}};case"symbol":return{...n,kind:e.kind,options:{...n.options,symbol:e.options.symbol,module:e.options.module}};case"process":return{...n,kind:e.kind,options:{...n.options,entry:e.options.entry,module:e.options.module}};case"impact":return{...n,kind:e.kind,options:{...n.options,symbol:e.options.symbol,module:e.options.module,path:e.options.path}}}}i(xh,"cloneableWorkerRequest");function Ko(e,t){for(let n of e.pending.values())clearTimeout(n.timer),n.reject(t);e.pending.clear()}i(Ko,"rejectAll");function Dc(e,t){Ko(e,t),ut===e&&(ut=void 0),e.worker.terminate().catch(()=>{})}i(Dc,"failWorker");function pr(e){[...e.pending.values()].some(t=>t.keepAlive)?e.worker.ref():e.worker.unref()}i(pr,"updateWorkerRef");function Eh(){if(ut)return ut;let e={resourceLimits:{maxOldGenerationSizeMb:yh()}},t=Pc();e.execArgv=bh(t);let n={worker:new ph(t,e),pending:new Map};return n.worker.on("message",r=>{if(!kh(r))return;let o=n.pending.get(r.id);if(!o)return;if(n.pending.delete(r.id),clearTimeout(o.timer),pr(n),r.ok){o.resolve(r.result);return}let s=new Error(r.error.message);r.error.stack&&(s.stack=r.error.stack),o.reject(s)}),n.worker.on("error",r=>{Dc(n,r)}),n.worker.on("exit",r=>{if(ut===n&&(ut=void 0),n.pending.size>0){Ko(n,new Error(`Repo intelligence worker exited with code ${r}.`));return}r!==0&&Ko(n,new Error(`Repo intelligence worker exited with code ${r}.`))}),n.worker.unref(),ut=n,n}i(Eh,"getWorkerState");function jc(e){let t=Mc.get(e);if(!t)return!1;let n=t.state.pending.get(t.id);return n?(n.keepAlive=!1,pr(t.state),!0):!1}i(jc,"detachRepoIntelligenceWorkerRequest");function Ce(e){let t=Eh(),n=gh++,r=xh(e,n),o=wh(),s=new Promise((a,c)=>{let l=setTimeout(()=>{Dc(t,new Error(`Repo intelligence worker request timed out after ${o}ms.`))},o);typeof l=="object"&&typeof l.unref=="function"&&l.unref(),t.pending.set(n,{resolve:i(d=>a(d),"resolve"),reject:c,timer:l,keepAlive:!0}),pr(t);try{t.worker.postMessage(r)}catch(d){let u=t.pending.get(n);u&&(clearTimeout(u.timer),t.pending.delete(n)),pr(t),c(d instanceof Error?d:new Error(String(d)))}});return Mc.set(s,{state:t,id:n}),s}i(Ce,"callWorker");function Fc(e,t={}){return Ce({kind:"buildIndex",context:e,options:t})}i(Fc,"buildRepoIntelligenceIndex");function Uc(e,t={}){return Ce({kind:"getIndex",context:e,options:t})}i(Uc,"getRepoIntelligenceIndex");function zo(e,t={}){return Ce({kind:"module",context:e,options:t})}i(zo,"getModuleContext");function qc(e,t){return Ce({kind:"symbol",context:e,options:t})}i(qc,"getSymbolContext");function Bc(e,t){return Ce({kind:"process",context:e,options:t})}i(Bc,"getProcessContext");function Go(e,t){return Ce({kind:"impact",context:e,options:t})}i(Go,"getImpactEstimate");function Xo(e,t={}){return Ce({kind:"routing",context:e,options:t})}i(Xo,"getRepoRoutingSignals");function Wc(e,t){return Ce({kind:"semanticLookup",context:e,options:t})}i(Wc,"semanticLookup");function Hc(e,t={}){return Ce({kind:"cyclicDeps",context:e,options:t})}i(Hc,"getCyclicDependencyAnalysis");var Sh=new Set(["auto","off","light","full"]),Th=new Set(["oss","premium-native","premium-shared"]);function Kc(e){let t=e?.trim().toLowerCase();return t?Sh.has(t)?{mode:t}:Th.has(t)?{warning:`Ignoring legacy repo-intelligence mode "${t}". Use auto, full, light, or off.`}:{warning:`Ignoring unknown repo-intelligence mode "${e}". Expected auto, full, light, or off.`}:{}}i(Kc,"readModeValue");function Ah(){let e=[];return process.env.KODAX_REPOINTEL_BIN?.trim()&&e.push("Ignoring legacy KODAX_REPOINTEL_BIN; repo intelligence is built into KodaX."),process.env.KODAX_REPOINTEL_ENDPOINT?.trim()&&e.push("Ignoring legacy KODAX_REPOINTEL_ENDPOINT; repo intelligence no longer uses a daemon endpoint."),process.env.KODAX_REPOINTEL_BUILD_ID?.trim()&&e.push("Ignoring legacy KODAX_REPOINTEL_BUILD_ID; built-in repo intelligence has no external build-id probe."),e}i(Ah,"legacyBridgeWarnings");async function Ch(e){if(!e)return process.cwd();try{if((await yn.stat(e)).isDirectory())return e}catch{}return process.cwd()}i(Ch,"resolveProbeWorkspaceRoot");function wn(e,t){let n=Ah(),r=Kc(process.env.KODAX_REPO_INTELLIGENCE),o=Kc(process.env.KODAX_REPO_INTELLIGENCE_MODE);return r.warning&&n.push(r.warning),o.warning&&n.push(o.warning),process.env.KODAX_REPO_INTELLIGENCE_MODE?.trim()&&n.push("Ignoring deprecated KODAX_REPO_INTELLIGENCE_MODE; use KODAX_REPO_INTELLIGENCE."),{mode:e??r.mode??"auto",trace:t??process.env.KODAX_REPO_INTELLIGENCE_TRACE==="1",warnings:n}}i(wn,"resolveRepoIntelligenceRuntimeConfig");function X(e){let t=wn(e).mode;return t==="auto"?"full":t}i(X,"resolveRepoIntelligenceMode");async function Rh(e={}){let t=wn(e.mode,e.trace),n=X(t.mode),r={configuredMode:t.mode,requestedMode:n,traceEnabled:t.trace,effectiveEngine:n,status:n==="off"?"disabled":"ok",fallbackToLight:!1,warnings:t.warnings};if(n==="off"||e.probe!==!0)return r;let o=Nc();r.workerPath=o;try{await yn.access(o)}catch(d){return r.status="unavailable",r.error=d instanceof Error?d.message:String(d),r.warnings.push(`Repo intelligence worker sidecar is not readable: ${o}`),r}let s=hn($c),a=await Ch(e.workspaceRoot),c=Vo.isAbsolute(s)?s:Vo.join(a,s);r.storageRoot=c;let l=Vo.join(c,`.repo-intelligence-status-${process.pid}-${Date.now()}.tmp`);try{await yn.mkdir(c,{recursive:!0}),await yn.writeFile(l,"ok","utf8")}catch(d){r.status="limited",r.error=d instanceof Error?d.message:String(d),r.warnings.push(`Repo intelligence cache directory is not writable: ${c}`)}finally{await yn.rm(l,{force:!0}).catch(()=>{})}return r}i(Rh,"inspectRepoIntelligenceRuntime");import $h from"node:path";var Oh="0",Ih=1500,Lh=2e3,Mh=250;function ne(){let e=Number(process.env.KODAX_REPO_INTELLIGENCE_TOOL_WAIT_MS);return Number.isFinite(e)&&e>=Mh?Math.floor(e):Lh}i(ne,"readRepoIntelligenceToolWaitMs");function Kt(e){if(!e)return"";try{return $h.resolve(e)}catch{return e}}i(Kt,"normalizeCachePath");function Yo(e,t){return t??(e.executionCwd?".":void 0)}i(Yo,"normalizePreturnTargetPath");var Ph=1500,Jc=6e4,hr=new Map,Qo=64,gr=new Map,yr=new Map;function Zo(e,t,n=Date.now()){for(let[o,s]of e.entries())s.expiresAt<=n&&e.delete(o);if(e.size<=t)return;let r=Array.from(e.keys());for(let o of r.slice(0,e.size-t))e.delete(o)}i(Zo,"pruneCacheEntries");function zc(e=Date.now()){Zo(hr,Qo,e)}i(zc,"pruneExpiredFullPreturnCache");function Gc(e=Date.now()){Zo(gr,Qo,e)}i(Gc,"pruneRoutingSignalsCache");function Xc(e=Date.now()){Zo(yr,Qo,e)}i(Xc,"prunePreturnBundleCache");function ei(e){return e==="full"}i(ei,"isFullRepoIntelligenceMode");function Yc(e,t="ok",n=[]){return{mode:e,engine:"full",level:"enhanced",status:t,warnings:n,contractVersion:1}}i(Yc,"buildFullCapability");function z(e,t="ok",n=[]){return e==="full"?Yc(e,t,n):{mode:e,engine:"light",level:"basic",status:t,warnings:n,contractVersion:1}}i(z,"buildWorkerCapability");function ti(e){if(e==="full")return"full";if(e==="light")return"light"}i(ti,"profileForMode");function Qc(e){return e.gitRoot??e.executionCwd??process.cwd()}i(Qc,"workspaceRootForContext");function we(e){return[`Repo intelligence ${e} unavailable; worker fallback stayed lightweight to keep the UI responsive.`,"Validate critical edits with read, grep, and targeted repo-intelligence tools after the worker recovers."]}i(we,"limitedWarnings");function zt(e,t){let n=t===void 0?"the short tool budget":`${t}ms`;return[`Repo intelligence ${e} is still warming and did not finish within ${n}.`,"The background worker continues indexing; retry this tool shortly for full structural results.","Use read, grep, glob, and LSP tools for immediate exploration while the index finishes."]}i(zt,"warmingWarnings");function Zc(e,t){return{moduleId:".",label:"Workspace Root (limited)",kind:"root",root:".",fileCount:0,sourceFileCount:0,symbolCount:0,languages:[],topSymbols:[],dependencies:[],dependents:[],entryFiles:t?[t]:[],keyTests:[],keyDocs:[],sampleFiles:t?[t]:[],processIds:[],confidence:.1}}i(Zc,"buildLimitedModule");function Nh(e,t){return{id:`limited:${e}`,name:e,qualifiedName:e,kind:"function",filePath:t??"",moduleId:".",language:"unknown",capabilityTier:"low",line:1,signature:e,exported:!1,calls:[],callTargets:[],importPaths:[],confidence:.1}}i(Nh,"buildLimitedSymbol");function el(e,t){return t.status==="warming"?`Repo intelligence ${e} is still warming; retry this tool shortly for full structural results.`:`Repo intelligence ${e} is unavailable because the worker did not respond.`}i(el,"unavailableSummary");function Dh(e,t){return{id:"limited",label:"Limited repo-intelligence process",moduleId:".",entryFile:t??"",summary:el("process context",e),steps:[],confidence:.1}}i(Dh,"buildLimitedProcess");function tl(e,t,n){let r=new Date().toISOString(),o=Zc(e,n);return{schemaVersion:1,workspaceRoot:Qc(e),generatedAt:r,overviewGeneratedAt:r,sourceFileCount:0,sourceFingerprint:"limited",languages:[],modules:[o],symbols:[],processes:[],capability:t}}i(tl,"buildLimitedIndex");function nl(e,t,n){return{module:Zc(e,n),freshness:"limited",confidence:.1,evidence:[],capability:t}}i(nl,"buildLimitedModuleContext");function jh(e,t,n){return{symbol:Nh(t,n),alternatives:[],callers:[],freshness:"limited",confidence:.1,capability:e}}i(jh,"buildLimitedSymbolContext");function Fh(e,t){return{process:Dh(e,t),alternatives:[],freshness:"limited",confidence:.1,capability:e}}i(Fh,"buildLimitedProcessContext");function rl(e,t){let n=t.symbol??t.module??t.path??t.targetPath??"workspace";return{target:t.symbol?{kind:"symbol",label:n}:t.module?{kind:"module",label:n,moduleId:t.module}:{kind:"path",label:n,filePath:t.path??t.targetPath},summary:el("impact estimate",e),impactedModules:[],impactedSymbols:[],callers:[],freshness:"limited",confidence:.1,capability:e}}i(rl,"buildLimitedImpactEstimate");function Jo(e,t){return{workspaceRoot:Qc(e),changedFileCount:0,changedLineCount:0,addedLineCount:0,deletedLineCount:0,touchedModuleCount:0,changedModules:[],crossModule:!1,riskHints:["repo-intelligence-worker-unavailable"],plannerBias:!1,investigationBias:!0,lowConfidence:!0,capability:t}}i(Jo,"buildLimitedRoutingSignals");function Uh(e,t){return{mode:e,engine:"full",triggeredAt:new Date(t).toISOString(),source:"full"}}i(Uh,"buildFullTrace");function bn(e,t,n){return{...e,capability:t,...n?{trace:n}:{}}}i(bn,"attachRepoIntelligenceMeta");async function mr(e,t,n){try{return await n}catch(r){t.push(`${e} unavailable`),Te(`Full repo-intelligence ${e} unavailable.`,r);return}}i(mr,"captureFullPreturnValue");function qh(e,t){let n=[];return e?.module.label&&n.push(`active module: ${e.module.label}`),t?.summary&&n.push(t.summary),n.length>0?n.join(" | "):void 0}i(qh,"buildContextPackSummary");async function ni(e,t,n){return(await ft(e,t,n)).result}i(ni,"tryWorkerQuery");function Bh(e){if(e!==void 0&&!(!Number.isFinite(e)||e<0))return Math.floor(e)}i(Bh,"normalizeMaxWaitMs");async function Wh(e,t,n,r){let o=Bh(n);if(o===void 0)return{result:await t,timedOut:!1};let s,a=t.then(d=>({result:d,timedOut:!1}),d=>(Te(`Repo-intelligence worker ${e} failed after budget race.`,d),{result:void 0,timedOut:!1})),c=new Promise(d=>{s=setTimeout(()=>{d({result:void 0,timedOut:!0})},o),typeof s=="object"&&typeof s.unref=="function"&&s.unref()}),l=await Promise.race([a,c]);return s&&clearTimeout(s),l.timedOut&&jc(r??t),l}i(Wh,"settleWorkerQueryWithinBudget");async function ft(e,t,n,r){let o=ti(e);if(!o)return{result:void 0,timedOut:!1};try{let s=n(o);return await Wh(t,s.then(a=>bn(a,z(e))),r,s)}catch(s){return Te(`Repo-intelligence worker ${t} unavailable.`,s),{result:void 0,timedOut:!1}}}i(ft,"tryWorkerQueryOutcome");async function ol(e,t={}){let n=wn(t.mode,t.trace),r=X(n.mode);if(!ei(r))return null;let o=Yo(e,t.targetPath),s=JSON.stringify({mode:r,executionCwd:Kt(e.executionCwd),gitRoot:Kt(e.gitRoot),targetPath:o??"",refresh:t.refresh??!1,trace:n.trace}),a=Date.now();zc(a);let c=hr.get(s);if(c&&(c.pending||c.expiresAt>a))return c.promise;let l,d=(async()=>{let u=[],f=Date.now(),m=await mr("repo context",u,Io(e,{includeRepoOverview:!0,includeChangedScope:!0,refreshOverview:t.refresh,changedScope:"all",targetPath:o})),h=await mr("routing signals",u,Xo(e,{targetPath:o,refresh:t.refresh,profile:"full"})),p=o?await mr("module context",u,zo(e,{targetPath:o,refresh:t.refresh,profile:"full"})):void 0,g=o?await mr("impact estimate",u,Go(e,{targetPath:o,refresh:t.refresh,profile:"full"})):void 0,w=m||p||g||h?{routingSignals:h,moduleContext:p,impactEstimate:g,repoContext:m,summary:qh(p,g),recommendedFiles:[...p?.module.entryFiles??[],...g?.impactedSymbols.slice(0,4).map(y=>y.filePath)??[]].slice(0,6),lowConfidence:(h?.lowConfidence??!1)||(p?.confidence??1)<.72||(g?.confidence??1)<.72}:null;return w?{bundle:w,capability:Yc(r,u.length>0?"limited":"ok",u),trace:n.trace?Uh(r,f):void 0}:null})().then(u=>(l.pending=!1,l.expiresAt=Date.now()+Ph,u)).catch(u=>{throw hr.delete(s),u});return l={pending:!0,expiresAt:Number.POSITIVE_INFINITY,promise:d},hr.set(s,l),zc(a),d}i(ol,"tryFullPreturn");function Hh(e){return X(e)}i(Hh,"resolveKodaXAutoRepoMode");function zS(e){return X(e)}i(zS,"resolveKodaXHotPathRepoMode");async function GS(e,t={}){let n=X();if(ti(n)){let o=await ni(n,"index build",s=>Fc(e,{...t,profile:s}));if(o)return o}return tl(e,z(n,"unavailable",we("index build")),t.targetPath)}i(GS,"buildRepoIntelligenceIndex");async function XS(e,t={}){let n=X();if(ti(n)){let o=await ni(n,"index",s=>Uc(e,{...t,profile:s}));if(o)return o}return tl(e,z(n,"unavailable",we("index")),t.targetPath)}i(XS,"getRepoIntelligenceIndex");async function il(e,t){let n=X(t.mode),r=await ft(n,"semantic lookup",a=>Wc(e,{targetPath:t.targetPath,refresh:t.refresh,profile:a,query:t.query,lookupKind:t.kind,limit:t.limit}),t.maxWaitMs),o=r.result;if(o){let a=z(n);return{...o,capability:a,capabilityEngine:o.capabilityEngine??a.engine}}let s=r.timedOut?z(n,"warming",zt("semantic lookup",t.maxWaitMs)):z(n,"unavailable",we("semantic lookup"));return{items:[],artifacts:[],generatedAt:new Date().toISOString(),sourceFileCount:0,capability:s,capabilityEngine:s.engine}}i(il,"semanticLookup");async function sl(e,t={}){let n=X(t.mode),r=await ft(n,"cyclic dependency analysis",s=>Hc(e,{targetPath:t.targetPath,refresh:t.refresh,profile:s}),t.maxWaitMs),o=r.result;return o||(r.timedOut?{cycles:[],scanned:{modules:0,edges:0},summary:zt("cyclic dependency analysis",t.maxWaitMs).join(" ")}:{cycles:[],scanned:{modules:0,edges:0},summary:"Cyclic dependency analysis unavailable because the repo-intelligence worker did not respond."})}i(sl,"getCyclicDependencyAnalysis");async function kn(e,t={}){let n=X(t.mode),r=await ft(n,"module context",s=>zo(e,{...t,profile:s}),t.maxWaitMs),o=r.result;return o||nl(e,r.timedOut?z(n,"warming",zt("module context",t.maxWaitMs)):z(n,"unavailable",we("module context")),t.targetPath)}i(kn,"getModuleContext");async function wr(e,t){let n=X(t.mode),r=await ft(n,"symbol context",s=>qc(e,{...t,profile:s}),t.maxWaitMs),o=r.result;return o||jh(r.timedOut?z(n,"warming",zt("symbol context",t.maxWaitMs)):z(n,"unavailable",we("symbol context")),t.symbol,t.targetPath)}i(wr,"getSymbolContext");async function br(e,t){let n=X(t.mode),r=await ft(n,"process context",s=>Bc(e,{...t,profile:s}),t.maxWaitMs),o=r.result;return o||Fh(r.timedOut?z(n,"warming",zt("process context",t.maxWaitMs)):z(n,"unavailable",we("process context")),t.targetPath)}i(br,"getProcessContext");async function vn(e,t){let n=X(t.mode),r=await ft(n,"impact estimate",s=>Go(e,{...t,profile:s}),t.maxWaitMs),o=r.result;return o||rl(r.timedOut?z(n,"warming",zt("impact estimate",t.maxWaitMs)):z(n,"unavailable",we("impact estimate")),t)}i(vn,"getImpactEstimate");async function Kh(e,t={}){let n=X(t.mode),r=Yo(e,t.targetPath),o=JSON.stringify({mode:n,executionCwd:Kt(e.executionCwd),gitRoot:Kt(e.gitRoot),targetPath:r??""}),s=Date.now();Gc(s);let a=gr.get(o);if(a&&(a.pending||a.expiresAt>s))return a.promise;let c,l=(async()=>{if(ei(n)){let d=await ol(e,t);return d?.bundle.routingSignals?bn(d.bundle.routingSignals,d.capability,d.trace):Jo(e,z(n,"unavailable",we("routing signals")))}if(n==="light"){let d=await ni(n,"routing signals",u=>Xo(e,{targetPath:r,refresh:t.refresh,profile:u}));if(d)return d}return Jo(e,z(n,"unavailable",we("routing signals")))})().then(d=>(c.pending=!1,c.expiresAt=Date.now()+Jc,d)).catch(d=>{throw gr.delete(o),d});return c={pending:!0,expiresAt:Number.POSITIVE_INFINITY,promise:l},gr.set(o,c),Gc(s),l}i(Kh,"getRepoRoutingSignals");async function zh(e,t={}){let n=X(t.mode),r=Yo(e,t.targetPath),o=JSON.stringify({mode:n,executionCwd:Kt(e.executionCwd),gitRoot:Kt(e.gitRoot),targetPath:r??""}),s=Date.now();Xc(s);let a=yr.get(o);if(a&&(a.pending||a.expiresAt>s))return a.promise;let c,l=Gh(e,t).then(d=>(c.pending=!1,c.expiresAt=Date.now()+Jc,d)).catch(d=>{throw yr.delete(o),d});return c={pending:!0,expiresAt:Number.POSITIVE_INFINITY,promise:l},yr.set(o,c),Xc(s),l}i(zh,"getRepoPreturnBundle");async function Gh(e,t={}){let n=X(t.mode);if(n==="off"){let u=z(n,"unavailable",we("preturn bundle"));return{routingSignals:Jo(e,u),moduleContext:t.targetPath?nl(e,u,t.targetPath):void 0,impactEstimate:t.targetPath?rl(u,t):void 0,summary:"Repo intelligence is disabled.",lowConfidence:!0,capability:u}}if(ei(n)){let u=await ol(e,t);if(u)return{routingSignals:u.bundle.routingSignals?bn(u.bundle.routingSignals,u.capability,u.trace):void 0,moduleContext:u.bundle.moduleContext?bn(u.bundle.moduleContext,u.capability,u.trace):void 0,impactEstimate:u.bundle.impactEstimate?bn(u.bundle.impactEstimate,u.capability,u.trace):void 0,repoContext:u.bundle.repoContext,summary:u.bundle.summary,recommendedFiles:u.bundle.recommendedFiles,lowConfidence:u.bundle.lowConfidence,capability:u.capability,trace:u.trace}}let r=t.targetPath??(e.executionCwd?".":void 0),[o,s,a,c]=await Promise.all([Kh(e,{targetPath:t.targetPath,refresh:t.refresh,mode:"light"}),r?kn(e,{targetPath:r,refresh:t.refresh,mode:"light"}).catch(()=>{}):Promise.resolve(void 0),r?vn(e,{targetPath:r,refresh:t.refresh,mode:"light"}).catch(()=>{}):Promise.resolve(void 0),Io(e,{includeRepoOverview:!0,includeChangedScope:!0,refreshOverview:t.refresh,changedScope:"all",targetPath:t.targetPath}).catch(()=>"")]),l=z("light",n==="full"?"limited":"ok",n==="full"?["Full repo intelligence unavailable; used worker-isolated light context."]:[]),d=[...s?.module?.entryFiles??[],...a?.impactedSymbols?.slice(0,4).map(u=>u.filePath)??[]].slice(0,6);return{routingSignals:o,moduleContext:s,impactEstimate:a,repoContext:c||void 0,summary:c||a?.summary||(s?`active module: ${s.module.label}`:void 0),recommendedFiles:d.length>0?d:void 0,lowConfidence:(o?.lowConfidence??!1)||(s?.confidence??1)<.72||(a?.confidence??1)<.72,capability:l}}i(Gh,"fetchRepoPreturnBundleInner");function VS(e,t={}){if(process.env.KODAX_PREWARM_REPO_INTELLIGENCE===Oh)return;let n=Hh(t.mode);if(n==="off"||!e.executionCwd&&!e.gitRoot||n!=="full")return;let r=setTimeout(()=>{zh(e,{mode:t.mode,refresh:!1,targetPath:"."}).catch(()=>{})},Ih);typeof r=="object"&&typeof r.unref=="function"&&r.unref()}i(VS,"prewarmRepoIntelligenceCaches");async function ri(e,t){try{let n=await kn(t,{module:_(e,"module"),targetPath:_(e,"target_path"),refresh:e.refresh===!0,maxWaitMs:ne()});return Fo(n)}catch(n){return`[Tool Error] module_context: ${n instanceof Error?n.message:String(n)}`}}i(ri,"toolModuleContext");async function oi(e,t){try{let n=_(e,"symbol");if(!n)throw new Error("symbol is required.");let r=await wr(t,{symbol:n,module:_(e,"module"),targetPath:_(e,"target_path"),refresh:e.refresh===!0,maxWaitMs:ne()});return Uo(r)}catch(n){return`[Tool Error] symbol_context: ${n instanceof Error?n.message:String(n)}`}}i(oi,"toolSymbolContext");async function ii(e,t){try{let n=_(e,"entry"),r=_(e,"module"),o=_(e,"target_path");if(!n&&!r&&!o)throw new Error("one of entry, module, or target_path is required.");let s=await br(t,{entry:n,module:r,targetPath:o,refresh:e.refresh===!0,maxWaitMs:ne()});return qo(s)}catch(n){return`[Tool Error] process_context: ${n instanceof Error?n.message:String(n)}`}}i(ii,"toolProcessContext");async function si(e,t){try{let n=_(e,"symbol"),r=_(e,"module"),o=_(e,"path");if(!n&&!r&&!o)throw new Error("one of symbol, module, or path is required.");let s=await vn(t,{symbol:n,module:r,path:o,targetPath:_(e,"target_path"),refresh:e.refresh===!0,maxWaitMs:ne()});return Bo(s)}catch(n){return`[Tool Error] impact_estimate: ${n instanceof Error?n.message:String(n)}`}}i(si,"toolImpactEstimate");var Xh={maxLines:1200,maxBytes:40*1024,direction:"head",spillToFile:!0},Vh={read:{maxLines:2e3,maxBytes:50*1024,direction:"head",spillToFile:!0},bash:{maxLines:600,maxBytes:32*1024,direction:"tail",spillToFile:!0},grep:{maxLines:400,maxBytes:24*1024,direction:"head",spillToFile:!0},web_search:{maxLines:240,maxBytes:20*1024,direction:"head",spillToFile:!0},web_fetch:{maxLines:320,maxBytes:24*1024,direction:"head",spillToFile:!0},code_search:{maxLines:320,maxBytes:24*1024,direction:"head",spillToFile:!0},semantic_lookup:{maxLines:260,maxBytes:20*1024,direction:"head",spillToFile:!0},changed_diff:{maxLines:1400,maxBytes:48*1024,direction:"head",spillToFile:!0},changed_diff_bundle:{maxLines:1600,maxBytes:56*1024,direction:"head",spillToFile:!0},write:{maxLines:350,maxBytes:24*1024,direction:"head",spillToFile:!0},edit:{maxLines:350,maxBytes:24*1024,direction:"head",spillToFile:!0},child_task_summary:{maxLines:1500,maxBytes:50*1024,direction:"head",spillToFile:!0}};function al(e){return Vh[e]??Xh}i(al,"getToolResultPolicy");function Jh(e){switch(e){case"read":return"Use read with offset/limit or grep to continue with a smaller slice.";case"bash":return"Narrow the command, or redirect output to a file before reading it.";case"grep":return"Narrow the pattern or path, or switch to files_with_matches/count first.";case"web_search":return"Refine the query or fetch a specific result URL for higher-confidence source capture.";case"web_fetch":return"Fetch a narrower page or follow up with read/grep on the saved output file.";case"code_search":return"Narrow the search root or query, or follow up with read on the matched file.";case"semantic_lookup":return"Narrow the query or use symbol_context/module_context for a deeper semantic follow-up.";case"changed_diff":return"Continue with changed_diff offset/limit, or switch to read for current-file context after identifying the relevant patch slice.";case"changed_diff_bundle":return"Use changed_diff_bundle to sweep high-priority files first, then switch to changed_diff or read for a specific suspicious file.";case"write":case"edit":return"Inspect the file with read instead of relying on a huge diff preview.";case"child_task_summary":return"Use the Read tool on the saved output path to view the full child task report.";default:return"Use a narrower follow-up tool call to inspect the missing details."}}i(Jh,"buildToolResultHint");async function _n(e,t,n,r){let o=al(e),s=r?.forceSpill?{...o,maxBytes:Math.min(o.maxBytes,2*1024),maxLines:Math.min(o.maxLines,20)}:o,a=s.direction==="tail"?Pt(t,s):Mt(t,s);if(!a.truncated&&!r?.forceSpill)return{content:t,truncated:!1,policy:o};let c,l=!1,d;if(o.spillToFile)try{c=await Nt(e,t,n)}catch(w){c=void 0,l=!0,d=w}if(l)return console.warn(`[ToolGuardrail] persistToolOutput failed for ${e}; inlining ${Buffer.byteLength(t,"utf-8")} bytes to preserve data. Cause: ${d instanceof Error?d.message:String(d)}`),{content:t,truncated:!1,policy:o,spillFailed:!0};let u=a.firstLineExceedsLimit&&!a.content?"[Output preview omitted because the first line alone exceeded the tool-output byte limit.]":a.content,m=`${o.direction==="tail"?"Tool output truncated to the most recent portion.":"Tool output truncated."} Showing ${a.outputLines} of ${a.totalLines} lines (${N(a.outputBytes)} of ${N(a.totalBytes)}).`,h=c?` Full output saved to: ${c}.`:"",p=` ${Jh(e)}`,g=`${u}
146
-
147
- [${m}${h}${p}]`;return process.env.KODAX_DEBUG_TOOL_GUARDRAILS&&console.error("[ToolGuardrail]",{toolName:e,outputPath:c,totalBytes:a.totalBytes,shownBytes:a.outputBytes,truncatedBy:a.truncatedBy}),{content:g,truncated:!0,outputPath:c,policy:o}}i(_n,"applyToolResultGuardrail");function ll(e){if(!(!e||Array.isArray(e)||typeof e!="object"))return e}i(ll,"asRecord");function V(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}i(V,"readString");function Yh(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}i(Yh,"stringifyScalar");function dl(e){let t=Yh(e);if(t!==void 0)return t;try{return JSON.stringify(e)}catch{return}}i(dl,"formatMetadataValue");function xn(e,t=240){return e.length>t?`${e.slice(0,t-3)}...`:e}i(xn,"truncateValue");function cl(e){return e?Object.entries(e).map(([t,n])=>{let r=dl(n);return r?`- ${t}: ${xn(r,320)}`:void 0}).filter(t=>t!==void 0):[]}i(cl,"collectMetadataLines");function pt(e){return e.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi," ").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi," ").replace(/<noscript\b[^>]*>[\s\S]*?<\/noscript>/gi," ").replace(/<(?:br|\/p|\/div|\/li|\/tr|\/h\d)>/gi,`
154
+ `);let m=d.slice(f,f+o),h=u+m.length-1,p=h<d.length,g=il(o,d.length),w=p?g>o?`[Large diff detected. Continue ${n} with changed_diff path=${n} offset=${h+1} limit=${g}.]`:`[Continue ${n} with changed_diff path=${n} offset=${h+1} limit=${o}.]`:"[End of diff]";return[...l,`Showing diff lines ${u}-${h} of ${d.length}`,"",...m,"",w].join(`
155
+ `)}i(yg,"renderBundleSection");async function Vo(e,t){try{let n=Z(t),r=_(e,"target_path"),o=r?await ol(pe.resolve(n,r)):n,s=await rl(o),a=_(e,"path");if(!a)throw new Error("path must be provided.");let c=sl(a,s),l=Vt(e,"offset",1,Number.MAX_SAFE_INTEGER),d=Vt(e,"limit",el,gr),u=Vt(e,"context_lines",tl,nl),f=_(e,"base_ref"),m=_(e,"target_ref"),h=f?await cl(s,c,f,m,u):await al(s,c,u);return gg({diff:h,relativePath:c,offset:l,limit:d,baseRef:f,targetRef:m,contextLines:u})}catch(n){return`[Tool Error] changed_diff: ${n instanceof Error?n.message:String(n)}`}}i(Vo,"toolChangedDiff");async function Jo(e,t){try{let n=Z(t),r=_(e,"target_path"),o=r?await ol(pe.resolve(n,r)):n,s=await rl(o),a=mg(e,"paths");if(a.length===0)throw new Error("paths must contain at least one changed file path.");let c=Array.from(new Set(a.slice(0,Xo).map(p=>sl(p,s)))),l=Vt(e,"offset",1,Number.MAX_SAFE_INTEGER),d=Vt(e,"limit_per_path",fg,gr),u=Vt(e,"context_lines",tl,nl),f=_(e,"base_ref"),m=_(e,"target_ref"),h=await Promise.all(c.map(async p=>{let g=f?await cl(s,p,f,m,u):await al(s,p,u);return yg({diff:g,relativePath:p,offset:l,limit:d,baseRef:f,targetRef:m,contextLines:u})}));return[`Changed diff bundle for ${c.length} file(s)`,`Limit per path: ${d}`,"",...h.flatMap((p,g)=>g===0?[p]:["",p]),"",c.length>=Xo&&a.length>c.length?`[Additional paths omitted after ${Xo} entries. Re-run changed_diff_bundle with a narrower path batch.]`:"[Bundle complete]"].join(`
156
+ `)}catch(n){return`[Tool Error] changed_diff_bundle: ${n instanceof Error?n.message:String(n)}`}}i(Jo,"toolChangedDiffBundle");function wr(e){return e>=.8?"high":e>=.65?"medium":"low"}i(wr,"confidenceLabel");function br(e){return!e||e.status==="ok"&&e.warnings.length===0?[]:[`Capability: ${e.engine}/${e.status}`,...e.warnings.map(t=>`Warning: ${t}`)]}i(br,"capabilityLines");function Yo(e){let{module:t}=e;return[`Module context for ${t.label}`,`Module: ${t.moduleId} [${t.kind}]`,`Freshness: ${e.freshness}`,`Confidence: ${wr(e.confidence)} (${e.confidence.toFixed(2)})`,`Files: ${t.fileCount} total | ${t.sourceFileCount} source | ${t.symbolCount} symbols`,`Languages: ${t.languages.map(n=>`${n.language}/${n.capabilityTier}:${n.fileCount}`).join(" | ")||"none"}`,`Dependencies: ${t.dependencies.join(" | ")||"none"}`,`Dependents: ${t.dependents.join(" | ")||"none"}`,`Entry files: ${t.entryFiles.join(" | ")||"none"}`,`Top symbols: ${t.topSymbols.join(" | ")||"none"}`,`Tests: ${t.keyTests.join(" | ")||"none"}`,`Docs: ${t.keyDocs.join(" | ")||"none"}`,`Processes: ${t.processIds.join(" | ")||"none"}`,`Evidence: ${e.evidence.join(" | ")||"none"}`,...br(e.capability)].join(`
157
+ `)}i(Yo,"renderModuleContext");function Zo(e){let{symbol:t}=e;return[`Symbol context for ${t.name}`,`Definition: ${t.filePath}:${t.line}`,`Module: ${t.moduleId} | Kind: ${t.kind} | Exported: ${t.exported?"yes":"no"}`,`Language: ${t.language}/${t.capabilityTier}`,`Freshness: ${e.freshness}`,`Confidence: ${wr(e.confidence)} (${e.confidence.toFixed(2)})`,`Signature: ${t.signature}`,`Possible callees: ${t.callTargets.map(n=>`${n.name} -> ${n.filePath}`).join(" | ")||"none"}`,`Possible callers: ${e.callers.map(n=>`${n.name} -> ${n.filePath}`).join(" | ")||"none"}`,`Imports: ${t.importPaths.join(" | ")||"none"}`,e.alternatives.length>0?`Alternatives: ${e.alternatives.map(n=>`${n.name} @ ${n.filePath}:${n.line}`).join(" | ")}`:"Alternatives: none",...br(e.capability)].join(`
158
+ `)}i(Zo,"renderSymbolContext");function Qo(e){let{process:t}=e;return[`Process context for ${t.label}`,`Module: ${t.moduleId}`,`Entry: ${t.entryFile}${t.entrySymbol?` -> ${t.entrySymbol}`:""}`,`Freshness: ${e.freshness}`,`Confidence: ${wr(e.confidence)} (${e.confidence.toFixed(2)})`,`Summary: ${t.summary}`,"Steps:",...t.steps.map(n=>`- ${n.kind} ${n.symbolName} @ ${n.filePath}${n.line?`:${n.line}`:""} | ${n.note}`),e.alternatives.length>0?`Alternatives: ${e.alternatives.map(n=>n.label).join(" | ")}`:"Alternatives: none",...br(e.capability)].join(`
159
+ `)}i(Qo,"renderProcessContext");function ei(e){return[`Impact estimate for ${e.target.label}`,`Target: ${e.target.kind}${e.target.moduleId?` | module=${e.target.moduleId}`:""}${e.target.filePath?` | file=${e.target.filePath}`:""}`,`Freshness: ${e.freshness}`,`Confidence: ${wr(e.confidence)} (${e.confidence.toFixed(2)})`,`Summary: ${e.summary}`,`Impacted modules: ${e.impactedModules.map(t=>`${t.label}(${t.moduleId})`).join(" | ")||"none"}`,`Impacted symbols: ${e.impactedSymbols.map(t=>`${t.name} -> ${t.filePath}:${t.line}`).join(" | ")||"none"}`,`Possible callers: ${e.callers.map(t=>`${t.name} -> ${t.filePath}:${t.line}`).join(" | ")||"none"}`,e.changedScope?`Changed-scope overlap: ${e.changedScope.files.filter(t=>e.impactedModules.some(n=>n.moduleId===t.areaId)||e.impactedSymbols.some(n=>n.filePath===t.path)).length} file(s)`:"Changed-scope overlap: unavailable",...br(e.capability)].join(`
160
+ `)}i(ei,"renderImpactEstimate");import _n from"node:fs/promises";import ai from"node:path";import wg from"path";var ll=wg.join(".agent","repo-intelligence");var IA=512*1024;import{existsSync as bg}from"node:fs";import{basename as kg,dirname as ti,join as dl}from"node:path";import{fileURLToPath as ni,pathToFileURL as ul}from"node:url";import{Worker as vg}from"node:worker_threads";var _g=2048,xg=12e4,Eg=1,yt,pl=new WeakMap;function Sg(){let e=Number(process.env.KODAX_REPO_INTELLIGENCE_WORKER_OLD_SPACE_MB);return Number.isFinite(e)&&e>=512?Math.floor(e):_g}i(Sg,"readWorkerOldSpaceMb");function Tg(){let e=Number(process.env.KODAX_REPO_INTELLIGENCE_WORKER_TIMEOUT_MS);return Number.isFinite(e)&&e>=5e3?Math.floor(e):xg}i(Tg,"readWorkerTimeoutMs");function ml(){if(import.meta.url.endsWith(".ts")){let n=new URL("../../dist/repo-intelligence/semantic-worker.js",import.meta.url);return bg(ni(n))?n:new URL("./semantic-worker.ts",import.meta.url)}if(process.env.KODAX_BUNDLED==="true")return ul(dl(ti(process.execPath),"semantic-worker.js"));let e=ti(ni(import.meta.url)),t=kg(e)==="chunks"?ti(e):e;return ul(dl(t,"semantic-worker.js"))}i(ml,"resolveWorkerUrl");function hl(){return ni(ml())}i(hl,"getRepoIntelligenceWorkerPathForDiagnostics");function Ag(e){return e.href.endsWith(".ts")?["--import","tsx"]:[]}i(Ag,"resolveWorkerExecArgv");function fl(e){return typeof e=="object"&&e!==null}i(fl,"isRecord");function Cg(e){return!fl(e)||typeof e.id!="number"||typeof e.ok!="boolean"?!1:e.ok===!0?"result"in e:fl(e.error)&&typeof e.error.message=="string"}i(Cg,"isWorkerResponse");function $g(e){return{executionCwd:e.executionCwd,gitRoot:e.gitRoot}}i($g,"cloneableRepoContext");function Rg(e){return{targetPath:e.targetPath,refresh:e.refresh,profile:e.profile}}i(Rg,"cloneableOptions");function Og(e,t){let n={context:$g(e.context),options:Rg(e.options),id:t};switch(e.kind){case"buildIndex":case"getIndex":case"cyclicDeps":case"routing":return{...n,kind:e.kind};case"semanticLookup":return{...n,kind:e.kind,options:{...n.options,query:e.options.query,lookupKind:e.options.lookupKind,limit:e.options.limit}};case"module":return{...n,kind:e.kind,options:{...n.options,module:e.options.module}};case"symbol":return{...n,kind:e.kind,options:{...n.options,symbol:e.options.symbol,module:e.options.module}};case"process":return{...n,kind:e.kind,options:{...n.options,entry:e.options.entry,module:e.options.module}};case"impact":return{...n,kind:e.kind,options:{...n.options,symbol:e.options.symbol,module:e.options.module,path:e.options.path}}}}i(Og,"cloneableWorkerRequest");function ri(e,t){for(let n of e.pending.values())clearTimeout(n.timer),n.reject(t);e.pending.clear()}i(ri,"rejectAll");function gl(e,t){ri(e,t),yt===e&&(yt=void 0),e.worker.terminate().catch(()=>{})}i(gl,"failWorker");function kr(e){[...e.pending.values()].some(t=>t.keepAlive)?e.worker.ref():e.worker.unref()}i(kr,"updateWorkerRef");function Ig(){if(yt)return yt;let e={resourceLimits:{maxOldGenerationSizeMb:Sg()}},t=ml();e.execArgv=Ag(t);let n={worker:new vg(t,e),pending:new Map};return n.worker.on("message",r=>{if(!Cg(r))return;let o=n.pending.get(r.id);if(!o)return;if(n.pending.delete(r.id),clearTimeout(o.timer),kr(n),r.ok){o.resolve(r.result);return}let s=new Error(r.error.message);r.error.stack&&(s.stack=r.error.stack),o.reject(s)}),n.worker.on("error",r=>{gl(n,r)}),n.worker.on("exit",r=>{if(yt===n&&(yt=void 0),n.pending.size>0){ri(n,new Error(`Repo intelligence worker exited with code ${r}.`));return}r!==0&&ri(n,new Error(`Repo intelligence worker exited with code ${r}.`))}),n.worker.unref(),yt=n,n}i(Ig,"getWorkerState");function yl(e){let t=pl.get(e);if(!t)return!1;let n=t.state.pending.get(t.id);return n?(n.keepAlive=!1,kr(t.state),!0):!1}i(yl,"detachRepoIntelligenceWorkerRequest");function Oe(e){let t=Ig(),n=Eg++,r=Og(e,n),o=Tg(),s=new Promise((a,c)=>{let l=setTimeout(()=>{gl(t,new Error(`Repo intelligence worker request timed out after ${o}ms.`))},o);typeof l=="object"&&typeof l.unref=="function"&&l.unref(),t.pending.set(n,{resolve:i(d=>a(d),"resolve"),reject:c,timer:l,keepAlive:!0}),kr(t);try{t.worker.postMessage(r)}catch(d){let u=t.pending.get(n);u&&(clearTimeout(u.timer),t.pending.delete(n)),kr(t),c(d instanceof Error?d:new Error(String(d)))}});return pl.set(s,{state:t,id:n}),s}i(Oe,"callWorker");function wl(e,t={}){return Oe({kind:"buildIndex",context:e,options:t})}i(wl,"buildRepoIntelligenceIndex");function bl(e,t={}){return Oe({kind:"getIndex",context:e,options:t})}i(bl,"getRepoIntelligenceIndex");function oi(e,t={}){return Oe({kind:"module",context:e,options:t})}i(oi,"getModuleContext");function kl(e,t){return Oe({kind:"symbol",context:e,options:t})}i(kl,"getSymbolContext");function vl(e,t){return Oe({kind:"process",context:e,options:t})}i(vl,"getProcessContext");function ii(e,t){return Oe({kind:"impact",context:e,options:t})}i(ii,"getImpactEstimate");function si(e,t={}){return Oe({kind:"routing",context:e,options:t})}i(si,"getRepoRoutingSignals");function _l(e,t){return Oe({kind:"semanticLookup",context:e,options:t})}i(_l,"semanticLookup");function xl(e,t={}){return Oe({kind:"cyclicDeps",context:e,options:t})}i(xl,"getCyclicDependencyAnalysis");var Lg=new Set(["auto","off","light","full"]),Mg=new Set(["oss","premium-native","premium-shared"]);function El(e){let t=e?.trim().toLowerCase();return t?Lg.has(t)?{mode:t}:Mg.has(t)?{warning:`Ignoring legacy repo-intelligence mode "${t}". Use auto, full, light, or off.`}:{warning:`Ignoring unknown repo-intelligence mode "${e}". Expected auto, full, light, or off.`}:{}}i(El,"readModeValue");function Pg(){let e=[];return process.env.KODAX_REPOINTEL_BIN?.trim()&&e.push("Ignoring legacy KODAX_REPOINTEL_BIN; repo intelligence is built into KodaX."),process.env.KODAX_REPOINTEL_ENDPOINT?.trim()&&e.push("Ignoring legacy KODAX_REPOINTEL_ENDPOINT; repo intelligence no longer uses a daemon endpoint."),process.env.KODAX_REPOINTEL_BUILD_ID?.trim()&&e.push("Ignoring legacy KODAX_REPOINTEL_BUILD_ID; built-in repo intelligence has no external build-id probe."),e}i(Pg,"legacyBridgeWarnings");async function Ng(e){if(!e)return process.cwd();try{if((await _n.stat(e)).isDirectory())return e}catch{}return process.cwd()}i(Ng,"resolveProbeWorkspaceRoot");function xn(e,t){let n=Pg(),r=El(process.env.KODAX_REPO_INTELLIGENCE),o=El(process.env.KODAX_REPO_INTELLIGENCE_MODE);return r.warning&&n.push(r.warning),o.warning&&n.push(o.warning),process.env.KODAX_REPO_INTELLIGENCE_MODE?.trim()&&n.push("Ignoring deprecated KODAX_REPO_INTELLIGENCE_MODE; use KODAX_REPO_INTELLIGENCE."),{mode:e??r.mode??"auto",trace:t??process.env.KODAX_REPO_INTELLIGENCE_TRACE==="1",warnings:n}}i(xn,"resolveRepoIntelligenceRuntimeConfig");function X(e){let t=xn(e).mode;return t==="auto"?"full":t}i(X,"resolveRepoIntelligenceMode");async function Dg(e={}){let t=xn(e.mode,e.trace),n=X(t.mode),r={configuredMode:t.mode,requestedMode:n,traceEnabled:t.trace,effectiveEngine:n,status:n==="off"?"disabled":"ok",fallbackToLight:!1,warnings:t.warnings};if(n==="off"||e.probe!==!0)return r;let o=hl();r.workerPath=o;try{await _n.access(o)}catch(d){return r.status="unavailable",r.error=d instanceof Error?d.message:String(d),r.warnings.push(`Repo intelligence worker sidecar is not readable: ${o}`),r}let s=kn(ll),a=await Ng(e.workspaceRoot),c=ai.isAbsolute(s)?s:ai.join(a,s);r.storageRoot=c;let l=ai.join(c,`.repo-intelligence-status-${process.pid}-${Date.now()}.tmp`);try{await _n.mkdir(c,{recursive:!0}),await _n.writeFile(l,"ok","utf8")}catch(d){r.status="limited",r.error=d instanceof Error?d.message:String(d),r.warnings.push(`Repo intelligence cache directory is not writable: ${c}`)}finally{await _n.rm(l,{force:!0}).catch(()=>{})}return r}i(Dg,"inspectRepoIntelligenceRuntime");import Fg from"node:path";var jg="0",Ug=1500,qg=2e3,Bg=250;function ie(){let e=Number(process.env.KODAX_REPO_INTELLIGENCE_TOOL_WAIT_MS);return Number.isFinite(e)&&e>=Bg?Math.floor(e):qg}i(ie,"readRepoIntelligenceToolWaitMs");function Jt(e){if(!e)return"";try{return Fg.resolve(e)}catch{return e}}i(Jt,"normalizeCachePath");function li(e,t){return t??(e.executionCwd?".":void 0)}i(li,"normalizePreturnTargetPath");var Wg=1500,$l=6e4,_r=new Map,di=64,xr=new Map,Er=new Map;function ui(e,t,n=Date.now()){for(let[o,s]of e.entries())s.expiresAt<=n&&e.delete(o);if(e.size<=t)return;let r=Array.from(e.keys());for(let o of r.slice(0,e.size-t))e.delete(o)}i(ui,"pruneCacheEntries");function Sl(e=Date.now()){ui(_r,di,e)}i(Sl,"pruneExpiredFullPreturnCache");function Tl(e=Date.now()){ui(xr,di,e)}i(Tl,"pruneRoutingSignalsCache");function Al(e=Date.now()){ui(Er,di,e)}i(Al,"prunePreturnBundleCache");function fi(e){return e==="full"}i(fi,"isFullRepoIntelligenceMode");function Rl(e,t="ok",n=[]){return{mode:e,engine:"full",level:"enhanced",status:t,warnings:n,contractVersion:1}}i(Rl,"buildFullCapability");function K(e,t="ok",n=[]){return e==="full"?Rl(e,t,n):{mode:e,engine:"light",level:"basic",status:t,warnings:n,contractVersion:1}}i(K,"buildWorkerCapability");function pi(e){if(e==="full")return"full";if(e==="light")return"light"}i(pi,"profileForMode");function Ol(e){return e.gitRoot??e.executionCwd??process.cwd()}i(Ol,"workspaceRootForContext");function ve(e){return[`Repo intelligence ${e} unavailable; worker fallback stayed lightweight to keep the UI responsive.`,"Validate critical edits with read, grep, and targeted repo-intelligence tools after the worker recovers."]}i(ve,"limitedWarnings");function Yt(e,t){let n=t===void 0?"the short tool budget":`${t}ms`;return[`Repo intelligence ${e} is still warming and did not finish within ${n}.`,"The background worker continues indexing; retry this tool shortly for full structural results.","Use read, grep, glob, and LSP tools for immediate exploration while the index finishes."]}i(Yt,"warmingWarnings");function Il(e,t){return{moduleId:".",label:"Workspace Root (limited)",kind:"root",root:".",fileCount:0,sourceFileCount:0,symbolCount:0,languages:[],topSymbols:[],dependencies:[],dependents:[],entryFiles:t?[t]:[],keyTests:[],keyDocs:[],sampleFiles:t?[t]:[],processIds:[],confidence:.1}}i(Il,"buildLimitedModule");function Hg(e,t){return{id:`limited:${e}`,name:e,qualifiedName:e,kind:"function",filePath:t??"",moduleId:".",language:"unknown",capabilityTier:"low",line:1,signature:e,exported:!1,calls:[],callTargets:[],importPaths:[],confidence:.1}}i(Hg,"buildLimitedSymbol");function Ll(e,t){return t.status==="warming"?`Repo intelligence ${e} is still warming; retry this tool shortly for full structural results.`:`Repo intelligence ${e} is unavailable because the worker did not respond.`}i(Ll,"unavailableSummary");function zg(e,t){return{id:"limited",label:"Limited repo-intelligence process",moduleId:".",entryFile:t??"",summary:Ll("process context",e),steps:[],confidence:.1}}i(zg,"buildLimitedProcess");function Ml(e,t,n){let r=new Date().toISOString(),o=Il(e,n);return{schemaVersion:1,workspaceRoot:Ol(e),generatedAt:r,overviewGeneratedAt:r,sourceFileCount:0,sourceFingerprint:"limited",languages:[],modules:[o],symbols:[],processes:[],capability:t}}i(Ml,"buildLimitedIndex");function Pl(e,t,n){return{module:Il(e,n),freshness:"limited",confidence:.1,evidence:[],capability:t}}i(Pl,"buildLimitedModuleContext");function Gg(e,t,n){return{symbol:Hg(t,n),alternatives:[],callers:[],freshness:"limited",confidence:.1,capability:e}}i(Gg,"buildLimitedSymbolContext");function Kg(e,t){return{process:zg(e,t),alternatives:[],freshness:"limited",confidence:.1,capability:e}}i(Kg,"buildLimitedProcessContext");function Nl(e,t){let n=t.symbol??t.module??t.path??t.targetPath??"workspace";return{target:t.symbol?{kind:"symbol",label:n}:t.module?{kind:"module",label:n,moduleId:t.module}:{kind:"path",label:n,filePath:t.path??t.targetPath},summary:Ll("impact estimate",e),impactedModules:[],impactedSymbols:[],callers:[],freshness:"limited",confidence:.1,capability:e}}i(Nl,"buildLimitedImpactEstimate");function ci(e,t){return{workspaceRoot:Ol(e),changedFileCount:0,changedLineCount:0,addedLineCount:0,deletedLineCount:0,touchedModuleCount:0,changedModules:[],crossModule:!1,riskHints:["repo-intelligence-worker-unavailable"],plannerBias:!1,investigationBias:!0,lowConfidence:!0,capability:t}}i(ci,"buildLimitedRoutingSignals");function Xg(e,t){return{mode:e,engine:"full",triggeredAt:new Date(t).toISOString(),source:"full"}}i(Xg,"buildFullTrace");function En(e,t,n){return{...e,capability:t,...n?{trace:n}:{}}}i(En,"attachRepoIntelligenceMeta");async function vr(e,t,n){try{return await n}catch(r){t.push(`${e} unavailable`),$e(`Full repo-intelligence ${e} unavailable.`,r);return}}i(vr,"captureFullPreturnValue");function Vg(e,t){let n=[];return e?.module.label&&n.push(`active module: ${e.module.label}`),t?.summary&&n.push(t.summary),n.length>0?n.join(" | "):void 0}i(Vg,"buildContextPackSummary");async function mi(e,t,n){return(await wt(e,t,n)).result}i(mi,"tryWorkerQuery");function Jg(e){if(e!==void 0&&!(!Number.isFinite(e)||e<0))return Math.floor(e)}i(Jg,"normalizeMaxWaitMs");async function Yg(e,t,n,r){let o=Jg(n);if(o===void 0)return{result:await t,timedOut:!1};let s,a=t.then(d=>({result:d,timedOut:!1}),d=>($e(`Repo-intelligence worker ${e} failed after budget race.`,d),{result:void 0,timedOut:!1})),c=new Promise(d=>{s=setTimeout(()=>{d({result:void 0,timedOut:!0})},o),typeof s=="object"&&typeof s.unref=="function"&&s.unref()}),l=await Promise.race([a,c]);return s&&clearTimeout(s),l.timedOut&&yl(r??t),l}i(Yg,"settleWorkerQueryWithinBudget");async function wt(e,t,n,r){let o=pi(e);if(!o)return{result:void 0,timedOut:!1};try{let s=n(o);return await Yg(t,s.then(a=>En(a,K(e))),r,s)}catch(s){return $e(`Repo-intelligence worker ${t} unavailable.`,s),{result:void 0,timedOut:!1}}}i(wt,"tryWorkerQueryOutcome");async function Dl(e,t={}){let n=xn(t.mode,t.trace),r=X(n.mode);if(!fi(r))return null;let o=li(e,t.targetPath),s=JSON.stringify({mode:r,executionCwd:Jt(e.executionCwd),gitRoot:Jt(e.gitRoot),targetPath:o??"",refresh:t.refresh??!1,trace:n.trace}),a=Date.now();Sl(a);let c=_r.get(s);if(c&&(c.pending||c.expiresAt>a))return c.promise;let l,d=(async()=>{let u=[],f=Date.now(),m=await vr("repo context",u,Ho(e,{includeRepoOverview:!0,includeChangedScope:!0,refreshOverview:t.refresh,changedScope:"all",targetPath:o})),h=await vr("routing signals",u,si(e,{targetPath:o,refresh:t.refresh,profile:"full"})),p=o?await vr("module context",u,oi(e,{targetPath:o,refresh:t.refresh,profile:"full"})):void 0,g=o?await vr("impact estimate",u,ii(e,{targetPath:o,refresh:t.refresh,profile:"full"})):void 0,w=m||p||g||h?{routingSignals:h,moduleContext:p,impactEstimate:g,repoContext:m,summary:Vg(p,g),recommendedFiles:[...p?.module.entryFiles??[],...g?.impactedSymbols.slice(0,4).map(y=>y.filePath)??[]].slice(0,6),lowConfidence:(h?.lowConfidence??!1)||(p?.confidence??1)<.72||(g?.confidence??1)<.72}:null;return w?{bundle:w,capability:Rl(r,u.length>0?"limited":"ok",u),trace:n.trace?Xg(r,f):void 0}:null})().then(u=>(l.pending=!1,l.expiresAt=Date.now()+Wg,u)).catch(u=>{throw _r.delete(s),u});return l={pending:!0,expiresAt:Number.POSITIVE_INFINITY,promise:d},_r.set(s,l),Sl(a),d}i(Dl,"tryFullPreturn");function Zg(e){return X(e)}i(Zg,"resolveKodaXAutoRepoMode");function nC(e){return X(e)}i(nC,"resolveKodaXHotPathRepoMode");async function rC(e,t={}){let n=X();if(pi(n)){let o=await mi(n,"index build",s=>wl(e,{...t,profile:s}));if(o)return o}return Ml(e,K(n,"unavailable",ve("index build")),t.targetPath)}i(rC,"buildRepoIntelligenceIndex");async function oC(e,t={}){let n=X();if(pi(n)){let o=await mi(n,"index",s=>bl(e,{...t,profile:s}));if(o)return o}return Ml(e,K(n,"unavailable",ve("index")),t.targetPath)}i(oC,"getRepoIntelligenceIndex");async function Fl(e,t){let n=X(t.mode),r=await wt(n,"semantic lookup",a=>_l(e,{targetPath:t.targetPath,refresh:t.refresh,profile:a,query:t.query,lookupKind:t.kind,limit:t.limit}),t.maxWaitMs),o=r.result;if(o){let a=K(n);return{...o,capability:a,capabilityEngine:o.capabilityEngine??a.engine}}let s=r.timedOut?K(n,"warming",Yt("semantic lookup",t.maxWaitMs)):K(n,"unavailable",ve("semantic lookup"));return{items:[],artifacts:[],generatedAt:new Date().toISOString(),sourceFileCount:0,capability:s,capabilityEngine:s.engine}}i(Fl,"semanticLookup");async function jl(e,t={}){let n=X(t.mode),r=await wt(n,"cyclic dependency analysis",s=>xl(e,{targetPath:t.targetPath,refresh:t.refresh,profile:s}),t.maxWaitMs),o=r.result;return o||(r.timedOut?{cycles:[],scanned:{modules:0,edges:0},summary:Yt("cyclic dependency analysis",t.maxWaitMs).join(" ")}:{cycles:[],scanned:{modules:0,edges:0},summary:"Cyclic dependency analysis unavailable because the repo-intelligence worker did not respond."})}i(jl,"getCyclicDependencyAnalysis");async function Sn(e,t={}){let n=X(t.mode),r=await wt(n,"module context",s=>oi(e,{...t,profile:s}),t.maxWaitMs),o=r.result;return o||Pl(e,r.timedOut?K(n,"warming",Yt("module context",t.maxWaitMs)):K(n,"unavailable",ve("module context")),t.targetPath)}i(Sn,"getModuleContext");async function Sr(e,t){let n=X(t.mode),r=await wt(n,"symbol context",s=>kl(e,{...t,profile:s}),t.maxWaitMs),o=r.result;return o||Gg(r.timedOut?K(n,"warming",Yt("symbol context",t.maxWaitMs)):K(n,"unavailable",ve("symbol context")),t.symbol,t.targetPath)}i(Sr,"getSymbolContext");async function Tr(e,t){let n=X(t.mode),r=await wt(n,"process context",s=>vl(e,{...t,profile:s}),t.maxWaitMs),o=r.result;return o||Kg(r.timedOut?K(n,"warming",Yt("process context",t.maxWaitMs)):K(n,"unavailable",ve("process context")),t.targetPath)}i(Tr,"getProcessContext");async function Tn(e,t){let n=X(t.mode),r=await wt(n,"impact estimate",s=>ii(e,{...t,profile:s}),t.maxWaitMs),o=r.result;return o||Nl(r.timedOut?K(n,"warming",Yt("impact estimate",t.maxWaitMs)):K(n,"unavailable",ve("impact estimate")),t)}i(Tn,"getImpactEstimate");async function Qg(e,t={}){let n=X(t.mode),r=li(e,t.targetPath),o=JSON.stringify({mode:n,executionCwd:Jt(e.executionCwd),gitRoot:Jt(e.gitRoot),targetPath:r??""}),s=Date.now();Tl(s);let a=xr.get(o);if(a&&(a.pending||a.expiresAt>s))return a.promise;let c,l=(async()=>{if(fi(n)){let d=await Dl(e,t);return d?.bundle.routingSignals?En(d.bundle.routingSignals,d.capability,d.trace):ci(e,K(n,"unavailable",ve("routing signals")))}if(n==="light"){let d=await mi(n,"routing signals",u=>si(e,{targetPath:r,refresh:t.refresh,profile:u}));if(d)return d}return ci(e,K(n,"unavailable",ve("routing signals")))})().then(d=>(c.pending=!1,c.expiresAt=Date.now()+$l,d)).catch(d=>{throw xr.delete(o),d});return c={pending:!0,expiresAt:Number.POSITIVE_INFINITY,promise:l},xr.set(o,c),Tl(s),l}i(Qg,"getRepoRoutingSignals");async function ey(e,t={}){let n=X(t.mode),r=li(e,t.targetPath),o=JSON.stringify({mode:n,executionCwd:Jt(e.executionCwd),gitRoot:Jt(e.gitRoot),targetPath:r??""}),s=Date.now();Al(s);let a=Er.get(o);if(a&&(a.pending||a.expiresAt>s))return a.promise;let c,l=ty(e,t).then(d=>(c.pending=!1,c.expiresAt=Date.now()+$l,d)).catch(d=>{throw Er.delete(o),d});return c={pending:!0,expiresAt:Number.POSITIVE_INFINITY,promise:l},Er.set(o,c),Al(s),l}i(ey,"getRepoPreturnBundle");async function ty(e,t={}){let n=X(t.mode);if(n==="off"){let u=K(n,"unavailable",ve("preturn bundle"));return{routingSignals:ci(e,u),moduleContext:t.targetPath?Pl(e,u,t.targetPath):void 0,impactEstimate:t.targetPath?Nl(u,t):void 0,summary:"Repo intelligence is disabled.",lowConfidence:!0,capability:u}}if(fi(n)){let u=await Dl(e,t);if(u)return{routingSignals:u.bundle.routingSignals?En(u.bundle.routingSignals,u.capability,u.trace):void 0,moduleContext:u.bundle.moduleContext?En(u.bundle.moduleContext,u.capability,u.trace):void 0,impactEstimate:u.bundle.impactEstimate?En(u.bundle.impactEstimate,u.capability,u.trace):void 0,repoContext:u.bundle.repoContext,summary:u.bundle.summary,recommendedFiles:u.bundle.recommendedFiles,lowConfidence:u.bundle.lowConfidence,capability:u.capability,trace:u.trace}}let r=t.targetPath??(e.executionCwd?".":void 0),[o,s,a,c]=await Promise.all([Qg(e,{targetPath:t.targetPath,refresh:t.refresh,mode:"light"}),r?Sn(e,{targetPath:r,refresh:t.refresh,mode:"light"}).catch(()=>{}):Promise.resolve(void 0),r?Tn(e,{targetPath:r,refresh:t.refresh,mode:"light"}).catch(()=>{}):Promise.resolve(void 0),Ho(e,{includeRepoOverview:!0,includeChangedScope:!0,refreshOverview:t.refresh,changedScope:"all",targetPath:t.targetPath}).catch(()=>"")]),l=K("light",n==="full"?"limited":"ok",n==="full"?["Full repo intelligence unavailable; used worker-isolated light context."]:[]),d=[...s?.module?.entryFiles??[],...a?.impactedSymbols?.slice(0,4).map(u=>u.filePath)??[]].slice(0,6);return{routingSignals:o,moduleContext:s,impactEstimate:a,repoContext:c||void 0,summary:c||a?.summary||(s?`active module: ${s.module.label}`:void 0),recommendedFiles:d.length>0?d:void 0,lowConfidence:(o?.lowConfidence??!1)||(s?.confidence??1)<.72||(a?.confidence??1)<.72,capability:l}}i(ty,"fetchRepoPreturnBundleInner");function iC(e,t={}){if(process.env.KODAX_PREWARM_REPO_INTELLIGENCE===jg)return;let n=Zg(t.mode);if(n==="off"||!e.executionCwd&&!e.gitRoot||n!=="full")return;let r=setTimeout(()=>{ey(e,{mode:t.mode,refresh:!1,targetPath:"."}).catch(()=>{})},Ug);typeof r=="object"&&typeof r.unref=="function"&&r.unref()}i(iC,"prewarmRepoIntelligenceCaches");async function hi(e,t){try{let n=await Sn(t,{module:_(e,"module"),targetPath:_(e,"target_path"),refresh:e.refresh===!0,maxWaitMs:ie()});return Yo(n)}catch(n){return`[Tool Error] module_context: ${n instanceof Error?n.message:String(n)}`}}i(hi,"toolModuleContext");async function gi(e,t){try{let n=_(e,"symbol");if(!n)throw new Error("symbol is required.");let r=await Sr(t,{symbol:n,module:_(e,"module"),targetPath:_(e,"target_path"),refresh:e.refresh===!0,maxWaitMs:ie()});return Zo(r)}catch(n){return`[Tool Error] symbol_context: ${n instanceof Error?n.message:String(n)}`}}i(gi,"toolSymbolContext");async function yi(e,t){try{let n=_(e,"entry"),r=_(e,"module"),o=_(e,"target_path");if(!n&&!r&&!o)throw new Error("one of entry, module, or target_path is required.");let s=await Tr(t,{entry:n,module:r,targetPath:o,refresh:e.refresh===!0,maxWaitMs:ie()});return Qo(s)}catch(n){return`[Tool Error] process_context: ${n instanceof Error?n.message:String(n)}`}}i(yi,"toolProcessContext");async function wi(e,t){try{let n=_(e,"symbol"),r=_(e,"module"),o=_(e,"path");if(!n&&!r&&!o)throw new Error("one of symbol, module, or path is required.");let s=await Tn(t,{symbol:n,module:r,path:o,targetPath:_(e,"target_path"),refresh:e.refresh===!0,maxWaitMs:ie()});return ei(s)}catch(n){return`[Tool Error] impact_estimate: ${n instanceof Error?n.message:String(n)}`}}i(wi,"toolImpactEstimate");var ny={maxLines:1200,maxBytes:40*1024,direction:"head",spillToFile:!0},ry={read:{maxLines:2e3,maxBytes:50*1024,direction:"head",spillToFile:!0},bash:{maxLines:600,maxBytes:32*1024,direction:"tail",spillToFile:!0},grep:{maxLines:400,maxBytes:24*1024,direction:"head",spillToFile:!0},web_search:{maxLines:240,maxBytes:20*1024,direction:"head",spillToFile:!0},web_fetch:{maxLines:320,maxBytes:24*1024,direction:"head",spillToFile:!0},code_search:{maxLines:320,maxBytes:24*1024,direction:"head",spillToFile:!0},semantic_lookup:{maxLines:260,maxBytes:20*1024,direction:"head",spillToFile:!0},changed_diff:{maxLines:1400,maxBytes:48*1024,direction:"head",spillToFile:!0},changed_diff_bundle:{maxLines:1600,maxBytes:56*1024,direction:"head",spillToFile:!0},write:{maxLines:350,maxBytes:24*1024,direction:"head",spillToFile:!0},edit:{maxLines:350,maxBytes:24*1024,direction:"head",spillToFile:!0},child_task_summary:{maxLines:1500,maxBytes:50*1024,direction:"head",spillToFile:!0}};function Ul(e){return ry[e]??ny}i(Ul,"getToolResultPolicy");function oy(e){switch(e){case"read":return"Use read with offset/limit or grep to continue with a smaller slice.";case"bash":return"Narrow the command, or redirect output to a file before reading it.";case"grep":return"Narrow the pattern or path, or switch to files_with_matches/count first.";case"web_search":return"Refine the query or fetch a specific result URL for higher-confidence source capture.";case"web_fetch":return"Fetch a narrower page or follow up with read/grep on the saved output file.";case"code_search":return"Narrow the search root or query, or follow up with read on the matched file.";case"semantic_lookup":return"Narrow the query or use symbol_context/module_context for a deeper semantic follow-up.";case"changed_diff":return"Continue with changed_diff offset/limit, or switch to read for current-file context after identifying the relevant patch slice.";case"changed_diff_bundle":return"Use changed_diff_bundle to sweep high-priority files first, then switch to changed_diff or read for a specific suspicious file.";case"write":case"edit":return"Inspect the file with read instead of relying on a huge diff preview.";case"child_task_summary":return"Use the Read tool on the saved output path to view the full child task report.";default:return"Use a narrower follow-up tool call to inspect the missing details."}}i(oy,"buildToolResultHint");async function An(e,t,n,r){let o=Ul(e),s=r?.forceSpill?{...o,maxBytes:Math.min(o.maxBytes,2*1024),maxLines:Math.min(o.maxLines,20)}:o,a=s.direction==="tail"?ft(t,s):Ut(t,s);if(!a.truncated&&!r?.forceSpill)return{content:t,truncated:!1,policy:o};let c,l=!1,d;if(o.spillToFile)try{c=await We(e,t,n)}catch(w){c=void 0,l=!0,d=w}if(l)return console.warn(`[ToolGuardrail] persistToolOutput failed for ${e}; inlining ${Buffer.byteLength(t,"utf-8")} bytes to preserve data. Cause: ${d instanceof Error?d.message:String(d)}`),{content:t,truncated:!1,policy:o,spillFailed:!0};let u=a.firstLineExceedsLimit&&!a.content?"[Output preview omitted because the first line alone exceeded the tool-output byte limit.]":a.content,m=`${o.direction==="tail"?"Tool output truncated to the most recent portion.":"Tool output truncated."} Showing ${a.outputLines} of ${a.totalLines} lines (${D(a.outputBytes)} of ${D(a.totalBytes)}).`,h=c?` Full output saved to: ${c}.`:"",p=` ${oy(e)}`,g=`${u}
161
+
162
+ [${m}${h}${p}]`;return process.env.KODAX_DEBUG_TOOL_GUARDRAILS&&console.error("[ToolGuardrail]",{toolName:e,outputPath:c,totalBytes:a.totalBytes,shownBytes:a.outputBytes,truncatedBy:a.truncatedBy}),{content:g,truncated:!0,outputPath:c,policy:o}}i(An,"applyToolResultGuardrail");function Bl(e){if(!(!e||Array.isArray(e)||typeof e!="object"))return e}i(Bl,"asRecord");function V(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}i(V,"readString");function iy(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}i(iy,"stringifyScalar");function Wl(e){let t=iy(e);if(t!==void 0)return t;try{return JSON.stringify(e)}catch{return}}i(Wl,"formatMetadataValue");function Cn(e,t=240){return e.length>t?`${e.slice(0,t-3)}...`:e}i(Cn,"truncateValue");function ql(e){return e?Object.entries(e).map(([t,n])=>{let r=Wl(n);return r?`- ${t}: ${Cn(r,320)}`:void 0}).filter(t=>t!==void 0):[]}i(ql,"collectMetadataLines");function bt(e){return e.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi," ").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi," ").replace(/<noscript\b[^>]*>[\s\S]*?<\/noscript>/gi," ").replace(/<(?:br|\/p|\/div|\/li|\/tr|\/h\d)>/gi,`
148
163
  `).replace(/<\/(?:p|div|li|tr|section|article|header|footer|main|aside)>/gi,`
149
164
  `).replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/\r/g,"").replace(/[ \t]+\n/g,`
150
165
  `).replace(/\n{3,}/g,`
151
166
 
152
- `).replace(/[ \t]{2,}/g," ").trim()}i(pt,"stripHtmlToText");function ai(e){let t=e.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(t?.[1])return pt(t[1])}i(ai,"extractHtmlTitle");async function kr(e,t){if(!e.body)return{text:await e.text(),truncated:!1,bytesRead:0};let n=e.body.getReader(),r=[],o=0,s=!1;try{for(;;){let{done:c,value:l}=await n.read();if(c)break;if(!l||l.length===0)continue;let d=t-o;if(d<=0){s=!0,await n.cancel();break}if(l.length>d){r.push(l.slice(0,d)),o+=d,s=!0,await n.cancel();break}r.push(l),o+=l.length}}finally{n.releaseLock()}return{text:Buffer.concat(r.map(c=>Buffer.from(c))).toString("utf-8"),truncated:s,bytesRead:o}}i(kr,"readResponseTextLimited");function Gt(e,t){let n=[];for(let r of e.slice(0,Math.max(1,t))){let o=ll(r);if(!o){let u=dl(r);u&&n.push({title:xn(u,120)});continue}let s=V(o.title)??V(o.name)??V(o.label)??V(o.id)??"provider result",a=V(o.url)??V(o.path)??V(o.uri)??V(o.locator),c=V(o.snippet)??V(o.summary)??V(o.description)??V(o.preview),l=o.score,d=typeof l=="number"&&Number.isFinite(l)?l:void 0;n.push({title:s,locator:a,snippet:c,score:d,metadata:o})}return n}i(Gt,"convertProviderSearchResults");function ci(e,t,n,r,o){let s=ll(r.structuredContent),a=V(s?.url)??V(s?.path)??V(s?.uri)??n,c=a?[{kind:V(s?.path)?"path":"provider",label:n,value:a}]:[];return{tool:e,scope:e==="web_fetch"?"remote":"workspace",trust:"provider",freshness:"unknown",provider:t,summary:o,content:V(r.content),items:s?Gt([s],1):[],artifacts:c,metadata:{capabilityId:n,capabilityKind:r.kind,...r.metadata??{}}}}i(ci,"convertCapabilityReadResult");function ul(e){let t=[`Retrieval result for ${e.tool}`,`Scope: ${e.scope} | Trust: ${e.trust} | Freshness: ${e.freshness}`];e.query&&t.push(`Query: ${e.query}`),e.provider&&t.push(`Provider: ${e.provider}`),t.push(`Summary: ${e.summary}`),e.content?.trim()&&t.push("","Content:",e.content.trim()),e.items.length>0&&(t.push("","Results:"),e.items.forEach((r,o)=>{t.push(`${o+1}. ${r.title}`),r.locator&&t.push(` Locator: ${xn(r.locator,240)}`),r.snippet&&t.push(` Snippet: ${xn(r.snippet,320)}`),r.score!==void 0&&t.push(` Score: ${r.score.toFixed(2)}`),cl(r.metadata).slice(0,3).forEach(a=>{t.push(` ${a}`)})})),e.artifacts&&e.artifacts.length>0&&(t.push("","Artifacts:"),e.artifacts.forEach(r=>{t.push(`- ${r.kind}: ${r.label} -> ${xn(r.value,280)}`)}));let n=cl(e.metadata);return n.length>0&&t.push("","Metadata:",...n),t.join(`
153
- `)}i(ul,"renderRetrievalResult");async function B(e,t){let n=ul(e);return(await _n(e.tool,n,t)).content}i(B,"finalizeRetrievalResult");var Qh=5,Zh=10,eg=12e3,tg=256*1024,ng="KODAX_WEB_SEARCH_ENDPOINT",rg="https://www.bing.com/search";function og(e){let t=typeof e=="number"&&Number.isFinite(e)?Math.floor(e):Qh;return Math.max(1,Math.min(Zh,t))}i(og,"clampLimit");function ig(e){let t=new AbortController;return setTimeout(()=>t.abort(),e).unref?.(),t.signal}i(ig,"createFetchTimeoutSignal");function sg(e){let t=process.env[ng]||rg;if(t.includes("{query}"))return new URL(t.replace("{query}",encodeURIComponent(e)));let n=new URL(t);return n.searchParams.has("q"),n.searchParams.set("q",e),n}i(sg,"buildSearchUrl");function ag(e,t){try{let n=new URL(e,t),r=n.searchParams.get("uddg");return r?decodeURIComponent(r):n.protocol!=="http:"&&n.protocol!=="https:"?void 0:n.toString()}catch{return}}i(ag,"resolveSearchHref");function cg(e,t,n){let r=[],o=new Set,s=/<a\b[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi;for(let a of e.matchAll(s)){let c=a[1]?.trim(),l=pt(a[2]??"").trim();if(!c||!l)continue;let d=ag(c,t);if(!(!d||o.has(d))&&(o.add(d),r.push({title:l,locator:d}),r.length>=n))break}return r}i(cg,"parseSearchResults");function lg(e){return e==="bing.com"||e.endsWith(".bing.com")}i(lg,"isBingHost");function dg(e,t){let n=[],r=new Set,o=/<h2\b[^>]*>\s*<a\b[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,s=e.indexOf("b_algo"),a=s>=0?e.slice(s):e;for(let c of a.matchAll(o)){let l=(c[1]??"").trim().replace(/&amp;/g,"&"),d=pt(c[2]??"").trim();if(!(!l||!d||!/^https?:\/\//i.test(l))&&!(/\/(aclk|aclick)\b/i.test(l)||/\/ck\/a\b/i.test(l))&&!r.has(l)&&(r.add(l),n.push({title:d,locator:l}),n.length>=t))break}return n}i(dg,"parseBingResults");async function li(e,t){try{let n=_(e,"query");if(!n)throw new Error("query is required.");let r=og(e.limit),o=_(e,"provider_id");if(o){if(!t.extensionRuntime)throw new Error("provider-backed web_search requires an active extension runtime.");let f=await t.extensionRuntime.searchCapabilities(o,n,{limit:r});return B({tool:"web_search",query:n,scope:"remote",trust:"provider",freshness:"unknown",provider:o,summary:f.length>0?`Provider ${o} returned ${f.length} search result(s).`:`Provider ${o} returned no search results for "${n}".`,items:Gt(f,r),metadata:{endpoint:"provider-search"}},t)}let s=sg(n),a=await fetch(s,{signal:ig(eg),headers:{"user-agent":"KodaX/0.7 retrieval",accept:"text/html,text/plain;q=0.8,*/*;q=0.5"}}),{text:c,truncated:l,bytesRead:d}=await kr(a,tg),u=lg(s.hostname)?dg(c,r):cg(c,s,r);return B({tool:"web_search",query:n,scope:"remote",trust:"open-world",freshness:"fresh",summary:u.length>0?`Found ${u.length} web search result(s) for "${n}".`:`No web search results for "${n}".`,items:u,artifacts:u.map(f=>({kind:"url",label:f.title,value:f.locator})),metadata:{endpoint:s.origin,status:a.status,bytesRead:d,truncated:l}},t)}catch(n){return`[Tool Error] web_search: ${n instanceof Error?n.message:String(n)}`}}i(li,"toolWebSearch");var ug=12e3,fg=512*1024;function pg(e){let t=new AbortController;return setTimeout(()=>t.abort(),e).unref?.(),t.signal}i(pg,"createFetchTimeoutSignal");function mg(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}i(mg,"isSupportedUrl");function hg(e){if(typeof e.content=="string"&&e.content.trim().length>0)return e.content.trim()}i(hg,"readCapabilityContent");async function di(e,t){try{let n=_(e,"provider_id"),r=_(e,"capability_id");if(n&&r){if(!t.extensionRuntime)throw new Error("provider-backed web_fetch requires an active extension runtime.");let{provider_id:p,capability_id:g,...w}=e,y=await t.extensionRuntime.readCapability(n,r,w);return B(ci("web_fetch",n,r,y,`Fetched provider capability ${r} from ${n}.`),t)}let o=_(e,"url");if(!o)throw new Error("url is required unless provider_id + capability_id are supplied.");if(!mg(o))throw new Error("url must use http or https.");let s=await fetch(o,{method:"GET",signal:pg(ug),headers:{"user-agent":"KodaX/0.7 retrieval",accept:"text/html,application/json,text/plain;q=0.9,*/*;q=0.8"}}),a=s.headers.get("content-type")??"unknown",{text:c,truncated:l,bytesRead:d}=await kr(s,fg),u=a.includes("text/html"),f=u?ai(c):void 0,m=u?pt(c):c.trim(),h=s.url||o;return B({tool:"web_fetch",scope:"remote",trust:"open-world",freshness:"fresh",summary:s.ok?`Fetched ${h} (${s.status}).`:`Fetched ${h} with non-success status ${s.status}.`,content:hg({kind:"resource",content:m})??m,items:f?[{title:f,locator:h,snippet:m.slice(0,240).trim(),metadata:{status:s.status,contentType:a}}]:[],artifacts:[{kind:"url",label:f??h,value:h}],metadata:{status:s.status,contentType:a,title:f,bytesRead:d,truncated:l}},t)}catch(n){return`[Tool Error] web_fetch: ${n instanceof Error?n.message:String(n)}`}}i(di,"toolWebFetch");import fl from"node:fs/promises";import{glob as gg}from"glob";var yg=20,wg=50,bg=300,kg=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json",".md",".yml",".yaml",".py",".java",".go",".rs",".c",".cc",".cpp",".cxx",".h",".hpp"]);function vg(e){let t=e.slice(e.lastIndexOf(".")).toLowerCase();return kg.has(t)}i(vg,"isSearchableFile");async function _g(e){return(await fl.stat(e)).isFile()?[e]:(await gg("**/*",{cwd:e,nodir:!0,absolute:!0,ignore:["**/node_modules/**","**/.git/**","**/.agent/**","**/dist/**","**/coverage/**"]})).filter(vg).slice(0,bg)}i(_g,"collectCandidateFiles");function ui(e){let t=typeof e=="number"&&Number.isFinite(e)?Math.floor(e):yg;return Math.max(1,Math.min(wg,t))}i(ui,"clampLimit");function xg(e,t,n){let r=n?e:e.toLowerCase(),o=n?t:t.toLowerCase(),s=r.indexOf(o);if(s<0)return e.trim();let a=Math.max(0,s-48),c=Math.min(e.length,s+t.length+72),l=e.slice(a,c).trim();return a>0?`...${l}`:l}i(xg,"buildSnippet");async function fi(e,t){try{let n=_(e,"query");if(!n)throw new Error("query is required.");let r=_(e,"provider_id");if(r){if(!t.extensionRuntime)throw new Error("provider-backed code_search requires an active extension runtime.");let u=await t.extensionRuntime.searchCapabilities(r,n,{limit:ui(e.limit)});return B({tool:"code_search",query:n,scope:"workspace",trust:"provider",freshness:"unknown",provider:r,summary:u.length>0?`Provider ${r} returned ${u.length} code search result(s).`:`Provider ${r} returned no code search results for "${n}".`,items:Gt(u,ui(e.limit)),metadata:{searchRoot:"provider-search"}},t)}let o=Dt(_(e,"path"),t),s=e.case_sensitive===!0,a=ui(e.limit),c=s?n:n.toLowerCase(),l=await _g(o),d=[];for(let u of l){if(d.length>=a||(s?u:u.toLowerCase()).includes(c)&&(d.push({title:u,locator:u,snippet:"Filename/path match",score:1,metadata:{matchType:"path"}}),d.length>=a))break;let m;try{m=await fl.readFile(u,"utf-8")}catch{continue}let h=m.split(`
154
- `);for(let p=0;p<h.length&&d.length<a;p++){let g=h[p]??"";(s?g:g.toLowerCase()).includes(c)&&d.push({title:`${u}:${p+1}`,locator:`${u}:${p+1}`,snippet:xg(g,n,s),score:.8,metadata:{matchType:"content",line:p+1}})}}return B({tool:"code_search",query:n,scope:"workspace",trust:"workspace",freshness:"snapshot",summary:d.length>0?`Found ${d.length} code search matches under ${o}.`:`No code search matches for "${n}" under ${o}.`,items:d,artifacts:d.map(u=>({kind:"path",label:u.title,value:u.locator??u.title})),metadata:{searchRoot:o,scannedFiles:l.length}},t)}catch(n){return`[Tool Error] code_search: ${n instanceof Error?n.message:String(n)}`}}i(fi,"toolCodeSearch");var Eg=8,Sg=20;function Tg(e){let t=typeof e=="number"&&Number.isFinite(e)?Math.floor(e):Eg;return Math.max(1,Math.min(Sg,t))}i(Tg,"clampLimit");async function pi(e,t){try{let n=_(e,"query");if(!n)throw new Error("query is required.");let r=_(e,"kind")??"auto",o=["auto","symbol","module","process"].includes(r)?r:"auto",s=Tg(e.limit),a=await il(t,{query:n,kind:o,limit:s,targetPath:_(e,"target_path"),refresh:e.refresh===!0,maxWaitMs:ne()}),c=a.capability?.status==="warming";return B({tool:"semantic_lookup",query:n,scope:"workspace",trust:"workspace",freshness:"snapshot",summary:c?"Repository intelligence index is still warming; retry semantic_lookup shortly for full structural matches. Use read, grep, glob, and LSP tools for immediate exploration.":a.items.length>0?`Found ${a.items.length} semantic match(es) for "${n}" in repository intelligence.`:`No semantic matches for "${n}" in repository intelligence.`,items:a.items,artifacts:a.artifacts,metadata:{kind:o,generatedAt:a.generatedAt,sourceFileCount:a.sourceFileCount,capability:a.capabilityEngine??"light",capabilityStatus:a.capability?.status,warnings:a.capability?.warnings.join(" | ")}},t)}catch(n){return`[Tool Error] semantic_lookup: ${n instanceof Error?n.message:String(n)}`}}i(pi,"toolSemanticLookup");import{readFileSync as Ag,statSync as Cg}from"node:fs";import{join as pl,parse as Rg,resolve as mi}from"node:path";var $g=["AGENTS.md"];function Og(){return st()}i(Og,"getKodaxGlobalDir");var vr=new Map;function Ig(e){let t;try{t=Cg(e).mtimeMs}catch{return vr.delete(e),null}let n=vr.get(e);if(n&&n.mtimeMs===t)return n.content;try{let r=Ag(e,"utf-8");return vr.set(e,{mtimeMs:t,content:r}),r}catch{return vr.delete(e),null}}i(Ig,"readFileWithMtimeCache");function hi(e,t){for(let n of t){let r=pl(e,n),o=Ig(r);if(o!==null)return{path:r,content:o,scope:"directory"}}return null}i(hi,"loadAgentsFile");function Lg(e){return hi(e,$g)}i(Lg,"loadContextFileFromDir");function ml(e){let t=mi(e?.cwd??process.cwd()),n=e?.kodaxDir??Og(),r=e?.projectRoot?mi(e.projectRoot):null,o=r??Rg(t).root,s=[],a=new Set,c=hi(n,["AGENTS.md"]);c&&(c.scope="global",s.push(c),a.add(c.path));let l=[],d=t,u=new Set;for(;!u.has(d);){u.add(d);let f=Lg(d);if(f&&!a.has(f.path)&&(f.scope="directory",l.unshift(f),a.add(f.path)),d===o)break;let m=mi(d,"..");if(m===d)break;d=m}if(s.push(...l),r){let f=hi(pl(r,".kodax"),["AGENTS.md"]);f&&!a.has(f.path)&&(f.scope="project",s.push(f))}return s}i(ml,"loadAgentsFiles");function hl(e){return e.length===0?"":`
167
+ `).replace(/[ \t]{2,}/g," ").trim()}i(bt,"stripHtmlToText");function bi(e){let t=e.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(t?.[1])return bt(t[1])}i(bi,"extractHtmlTitle");async function Ar(e,t){if(!e.body)return{text:await e.text(),truncated:!1,bytesRead:0};let n=e.body.getReader(),r=[],o=0,s=!1;try{for(;;){let{done:c,value:l}=await n.read();if(c)break;if(!l||l.length===0)continue;let d=t-o;if(d<=0){s=!0,await n.cancel();break}if(l.length>d){r.push(l.slice(0,d)),o+=d,s=!0,await n.cancel();break}r.push(l),o+=l.length}}finally{n.releaseLock()}return{text:Buffer.concat(r.map(c=>Buffer.from(c))).toString("utf-8"),truncated:s,bytesRead:o}}i(Ar,"readResponseTextLimited");function Zt(e,t){let n=[];for(let r of e.slice(0,Math.max(1,t))){let o=Bl(r);if(!o){let u=Wl(r);u&&n.push({title:Cn(u,120)});continue}let s=V(o.title)??V(o.name)??V(o.label)??V(o.id)??"provider result",a=V(o.url)??V(o.path)??V(o.uri)??V(o.locator),c=V(o.snippet)??V(o.summary)??V(o.description)??V(o.preview),l=o.score,d=typeof l=="number"&&Number.isFinite(l)?l:void 0;n.push({title:s,locator:a,snippet:c,score:d,metadata:o})}return n}i(Zt,"convertProviderSearchResults");function ki(e,t,n,r,o){let s=Bl(r.structuredContent),a=V(s?.url)??V(s?.path)??V(s?.uri)??n,c=a?[{kind:V(s?.path)?"path":"provider",label:n,value:a}]:[];return{tool:e,scope:e==="web_fetch"?"remote":"workspace",trust:"provider",freshness:"unknown",provider:t,summary:o,content:V(r.content),items:s?Zt([s],1):[],artifacts:c,metadata:{capabilityId:n,capabilityKind:r.kind,...r.metadata??{}}}}i(ki,"convertCapabilityReadResult");function Hl(e){let t=[`Retrieval result for ${e.tool}`,`Scope: ${e.scope} | Trust: ${e.trust} | Freshness: ${e.freshness}`];e.query&&t.push(`Query: ${e.query}`),e.provider&&t.push(`Provider: ${e.provider}`),t.push(`Summary: ${e.summary}`),e.content?.trim()&&t.push("","Content:",e.content.trim()),e.items.length>0&&(t.push("","Results:"),e.items.forEach((r,o)=>{t.push(`${o+1}. ${r.title}`),r.locator&&t.push(` Locator: ${Cn(r.locator,240)}`),r.snippet&&t.push(` Snippet: ${Cn(r.snippet,320)}`),r.score!==void 0&&t.push(` Score: ${r.score.toFixed(2)}`),ql(r.metadata).slice(0,3).forEach(a=>{t.push(` ${a}`)})})),e.artifacts&&e.artifacts.length>0&&(t.push("","Artifacts:"),e.artifacts.forEach(r=>{t.push(`- ${r.kind}: ${r.label} -> ${Cn(r.value,280)}`)}));let n=ql(e.metadata);return n.length>0&&t.push("","Metadata:",...n),t.join(`
168
+ `)}i(Hl,"renderRetrievalResult");async function W(e,t){let n=Hl(e);return(await An(e.tool,n,t)).content}i(W,"finalizeRetrievalResult");var sy=5,ay=10,cy=12e3,ly=256*1024,dy="KODAX_WEB_SEARCH_ENDPOINT",uy="https://www.bing.com/search";function fy(e){let t=typeof e=="number"&&Number.isFinite(e)?Math.floor(e):sy;return Math.max(1,Math.min(ay,t))}i(fy,"clampLimit");function py(e){let t=new AbortController;return setTimeout(()=>t.abort(),e).unref?.(),t.signal}i(py,"createFetchTimeoutSignal");function my(e){let t=process.env[dy]||uy;if(t.includes("{query}"))return new URL(t.replace("{query}",encodeURIComponent(e)));let n=new URL(t);return n.searchParams.has("q"),n.searchParams.set("q",e),n}i(my,"buildSearchUrl");function hy(e,t){try{let n=new URL(e,t),r=n.searchParams.get("uddg");return r?decodeURIComponent(r):n.protocol!=="http:"&&n.protocol!=="https:"?void 0:n.toString()}catch{return}}i(hy,"resolveSearchHref");function gy(e,t,n){let r=[],o=new Set,s=/<a\b[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi;for(let a of e.matchAll(s)){let c=a[1]?.trim(),l=bt(a[2]??"").trim();if(!c||!l)continue;let d=hy(c,t);if(!(!d||o.has(d))&&(o.add(d),r.push({title:l,locator:d}),r.length>=n))break}return r}i(gy,"parseSearchResults");function yy(e){return e==="bing.com"||e.endsWith(".bing.com")}i(yy,"isBingHost");function wy(e,t){let n=[],r=new Set,o=/<h2\b[^>]*>\s*<a\b[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,s=e.indexOf("b_algo"),a=s>=0?e.slice(s):e;for(let c of a.matchAll(o)){let l=(c[1]??"").trim().replace(/&amp;/g,"&"),d=bt(c[2]??"").trim();if(!(!l||!d||!/^https?:\/\//i.test(l))&&!(/\/(aclk|aclick)\b/i.test(l)||/\/ck\/a\b/i.test(l))&&!r.has(l)&&(r.add(l),n.push({title:d,locator:l}),n.length>=t))break}return n}i(wy,"parseBingResults");async function vi(e,t){try{let n=_(e,"query");if(!n)throw new Error("query is required.");let r=fy(e.limit),o=_(e,"provider_id");if(o){if(!t.extensionRuntime)throw new Error("provider-backed web_search requires an active extension runtime.");let f=await t.extensionRuntime.searchCapabilities(o,n,{limit:r});return W({tool:"web_search",query:n,scope:"remote",trust:"provider",freshness:"unknown",provider:o,summary:f.length>0?`Provider ${o} returned ${f.length} search result(s).`:`Provider ${o} returned no search results for "${n}".`,items:Zt(f,r),metadata:{endpoint:"provider-search"}},t)}let s=my(n),a=await fetch(s,{signal:py(cy),headers:{"user-agent":"KodaX/0.7 retrieval",accept:"text/html,text/plain;q=0.8,*/*;q=0.5"}}),{text:c,truncated:l,bytesRead:d}=await Ar(a,ly),u=yy(s.hostname)?wy(c,r):gy(c,s,r);return W({tool:"web_search",query:n,scope:"remote",trust:"open-world",freshness:"fresh",summary:u.length>0?`Found ${u.length} web search result(s) for "${n}".`:`No web search results for "${n}".`,items:u,artifacts:u.map(f=>({kind:"url",label:f.title,value:f.locator})),metadata:{endpoint:s.origin,status:a.status,bytesRead:d,truncated:l}},t)}catch(n){return`[Tool Error] web_search: ${n instanceof Error?n.message:String(n)}`}}i(vi,"toolWebSearch");var by=12e3,ky=512*1024;function vy(e){let t=new AbortController;return setTimeout(()=>t.abort(),e).unref?.(),t.signal}i(vy,"createFetchTimeoutSignal");function _y(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}i(_y,"isSupportedUrl");function xy(e){if(typeof e.content=="string"&&e.content.trim().length>0)return e.content.trim()}i(xy,"readCapabilityContent");async function _i(e,t){try{let n=_(e,"provider_id"),r=_(e,"capability_id");if(n&&r){if(!t.extensionRuntime)throw new Error("provider-backed web_fetch requires an active extension runtime.");let{provider_id:p,capability_id:g,...w}=e,y=await t.extensionRuntime.readCapability(n,r,w);return W(ki("web_fetch",n,r,y,`Fetched provider capability ${r} from ${n}.`),t)}let o=_(e,"url");if(!o)throw new Error("url is required unless provider_id + capability_id are supplied.");if(!_y(o))throw new Error("url must use http or https.");let s=await fetch(o,{method:"GET",signal:vy(by),headers:{"user-agent":"KodaX/0.7 retrieval",accept:"text/html,application/json,text/plain;q=0.9,*/*;q=0.8"}}),a=s.headers.get("content-type")??"unknown",{text:c,truncated:l,bytesRead:d}=await Ar(s,ky),u=a.includes("text/html"),f=u?bi(c):void 0,m=u?bt(c):c.trim(),h=s.url||o;return W({tool:"web_fetch",scope:"remote",trust:"open-world",freshness:"fresh",summary:s.ok?`Fetched ${h} (${s.status}).`:`Fetched ${h} with non-success status ${s.status}.`,content:xy({kind:"resource",content:m})??m,items:f?[{title:f,locator:h,snippet:m.slice(0,240).trim(),metadata:{status:s.status,contentType:a}}]:[],artifacts:[{kind:"url",label:f??h,value:h}],metadata:{status:s.status,contentType:a,title:f,bytesRead:d,truncated:l}},t)}catch(n){return`[Tool Error] web_fetch: ${n instanceof Error?n.message:String(n)}`}}i(_i,"toolWebFetch");import zl from"node:fs/promises";import{glob as Ey}from"glob";var Sy=20,Ty=50,Ay=300,Cy=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json",".md",".yml",".yaml",".py",".java",".go",".rs",".c",".cc",".cpp",".cxx",".h",".hpp"]);function $y(e){let t=e.slice(e.lastIndexOf(".")).toLowerCase();return Cy.has(t)}i($y,"isSearchableFile");async function Ry(e){return(await zl.stat(e)).isFile()?[e]:(await Ey("**/*",{cwd:e,nodir:!0,absolute:!0,ignore:["**/node_modules/**","**/.git/**","**/.agent/**","**/dist/**","**/coverage/**"]})).filter($y).slice(0,Ay)}i(Ry,"collectCandidateFiles");function xi(e){let t=typeof e=="number"&&Number.isFinite(e)?Math.floor(e):Sy;return Math.max(1,Math.min(Ty,t))}i(xi,"clampLimit");function Oy(e,t,n){let r=n?e:e.toLowerCase(),o=n?t:t.toLowerCase(),s=r.indexOf(o);if(s<0)return e.trim();let a=Math.max(0,s-48),c=Math.min(e.length,s+t.length+72),l=e.slice(a,c).trim();return a>0?`...${l}`:l}i(Oy,"buildSnippet");async function Ei(e,t){try{let n=_(e,"query");if(!n)throw new Error("query is required.");let r=_(e,"provider_id");if(r){if(!t.extensionRuntime)throw new Error("provider-backed code_search requires an active extension runtime.");let u=await t.extensionRuntime.searchCapabilities(r,n,{limit:xi(e.limit)});return W({tool:"code_search",query:n,scope:"workspace",trust:"provider",freshness:"unknown",provider:r,summary:u.length>0?`Provider ${r} returned ${u.length} code search result(s).`:`Provider ${r} returned no code search results for "${n}".`,items:Zt(u,xi(e.limit)),metadata:{searchRoot:"provider-search"}},t)}let o=qt(_(e,"path"),t),s=e.case_sensitive===!0,a=xi(e.limit),c=s?n:n.toLowerCase(),l=await Ry(o),d=[];for(let u of l){if(d.length>=a||(s?u:u.toLowerCase()).includes(c)&&(d.push({title:u,locator:u,snippet:"Filename/path match",score:1,metadata:{matchType:"path"}}),d.length>=a))break;let m;try{m=await zl.readFile(u,"utf-8")}catch{continue}let h=m.split(`
169
+ `);for(let p=0;p<h.length&&d.length<a;p++){let g=h[p]??"";(s?g:g.toLowerCase()).includes(c)&&d.push({title:`${u}:${p+1}`,locator:`${u}:${p+1}`,snippet:Oy(g,n,s),score:.8,metadata:{matchType:"content",line:p+1}})}}return W({tool:"code_search",query:n,scope:"workspace",trust:"workspace",freshness:"snapshot",summary:d.length>0?`Found ${d.length} code search matches under ${o}.`:`No code search matches for "${n}" under ${o}.`,items:d,artifacts:d.map(u=>({kind:"path",label:u.title,value:u.locator??u.title})),metadata:{searchRoot:o,scannedFiles:l.length}},t)}catch(n){return`[Tool Error] code_search: ${n instanceof Error?n.message:String(n)}`}}i(Ei,"toolCodeSearch");var Iy=8,Ly=20;function My(e){let t=typeof e=="number"&&Number.isFinite(e)?Math.floor(e):Iy;return Math.max(1,Math.min(Ly,t))}i(My,"clampLimit");async function Si(e,t){try{let n=_(e,"query");if(!n)throw new Error("query is required.");let r=_(e,"kind")??"auto",o=["auto","symbol","module","process"].includes(r)?r:"auto",s=My(e.limit),a=await Fl(t,{query:n,kind:o,limit:s,targetPath:_(e,"target_path"),refresh:e.refresh===!0,maxWaitMs:ie()}),c=a.capability?.status==="warming";return W({tool:"semantic_lookup",query:n,scope:"workspace",trust:"workspace",freshness:"snapshot",summary:c?"Repository intelligence index is still warming; retry semantic_lookup shortly for full structural matches. Use read, grep, glob, and LSP tools for immediate exploration.":a.items.length>0?`Found ${a.items.length} semantic match(es) for "${n}" in repository intelligence.`:`No semantic matches for "${n}" in repository intelligence.`,items:a.items,artifacts:a.artifacts,metadata:{kind:o,generatedAt:a.generatedAt,sourceFileCount:a.sourceFileCount,capability:a.capabilityEngine??"light",capabilityStatus:a.capability?.status,warnings:a.capability?.warnings.join(" | ")}},t)}catch(n){return`[Tool Error] semantic_lookup: ${n instanceof Error?n.message:String(n)}`}}i(Si,"toolSemanticLookup");import{readFileSync as Py,statSync as Ny}from"node:fs";import{join as Gl,parse as Dy,resolve as Ti}from"node:path";var Fy=["AGENTS.md"];function jy(){return dt()}i(jy,"getKodaxGlobalDir");var Cr=new Map;function Uy(e){let t;try{t=Ny(e).mtimeMs}catch{return Cr.delete(e),null}let n=Cr.get(e);if(n&&n.mtimeMs===t)return n.content;try{let r=Py(e,"utf-8");return Cr.set(e,{mtimeMs:t,content:r}),r}catch{return Cr.delete(e),null}}i(Uy,"readFileWithMtimeCache");function Ai(e,t){for(let n of t){let r=Gl(e,n),o=Uy(r);if(o!==null)return{path:r,content:o,scope:"directory"}}return null}i(Ai,"loadAgentsFile");function qy(e){return Ai(e,Fy)}i(qy,"loadContextFileFromDir");function Kl(e){let t=Ti(e?.cwd??process.cwd()),n=e?.kodaxDir??jy(),r=e?.projectRoot?Ti(e.projectRoot):null,o=r??Dy(t).root,s=[],a=new Set,c=Ai(n,["AGENTS.md"]);c&&(c.scope="global",s.push(c),a.add(c.path));let l=[],d=t,u=new Set;for(;!u.has(d);){u.add(d);let f=qy(d);if(f&&!a.has(f.path)&&(f.scope="directory",l.unshift(f),a.add(f.path)),d===o)break;let m=Ti(d,"..");if(m===d)break;d=m}if(s.push(...l),r){let f=Ai(Gl(r,".kodax"),["AGENTS.md"]);f&&!a.has(f.path)&&(f.scope="project",s.push(f))}return s}i(Kl,"loadAgentsFiles");function Xl(e){return e.length===0?"":`
155
170
  ---
156
171
 
157
172
  # Project Context
@@ -163,65 +178,65 @@ ${n.content}
163
178
  `).join(`
164
179
  ---
165
180
  `)}
166
- `}i(hl,"formatAgentsForPrompt");var GT="kodax/role/scout",XT="kodax/role/planner",VT="kodax/role/generator",Mg="kodax/role/worker",_r=Bs({name:Mg,instructions:"KodaX single primary role: plan via todo_update, execute via tool calls, terminate text-only when done \u2014 Sidecar Verifier runs verification out-of-band."}),JT=Object.freeze({worker:_r});function En(e,t){let n;try{let r=JSON.stringify(t);if(r===void 0)return`${e}: [unserializable input]`;n=r}catch{return`${e}: [unserializable input]`}return n.length>200&&(n=n.slice(0,200)+"\u2026"),`${e}: ${n}`}i(En,"defaultToClassifierInput");function xr(e,t,n){let r=`MCP[${e}.${t}]`;if(n==null||typeof n!="object"){let c=jg(n,200);return`${r}: ${c}`}let o=n,s=Ng(o);if(s){let c=yl(String(s.value),200),l=gl(o,s.field);return l?`${r}: ${c} | ${l}`:`${r}: ${c}`}let a=gl(o,null);return`${r}: ${a||"{}"}`}i(xr,"mcpToClassifierInput");var Pg=["method","command","url","query","action"];function Ng(e){for(let t of Pg)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(n!=null&&n!=="")return{field:t,value:n}}}i(Ng,"pickActionField");function gl(e,t){let n=Object.entries(e).filter(([c])=>c!==t);if(n.length===0)return"";let r=32,o=[],s=0;for(let[c,l]of n){if(o.length>=3){s+=1;continue}let d=Dg(l,r);d?o.push(`${c}=${d}`):s+=1}let a=[];if(o.length>0&&a.push(o.join(", ")),s>0){let c=n.filter(([l])=>!o.some(d=>d.startsWith(`${l}=`))).map(([l])=>l);a.push(`+${s} key${s>1?"s":""}: ${c.join(", ")}`)}return a.join(", ")}i(gl,"describeStructure");function Dg(e,t){if(e===null)return"null";if(typeof e=="string")return e.length<=t?e:void 0;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e)&&e.length<=3){let n=e.map(r=>typeof r=="string"?r:JSON.stringify(r)).join(",");if(n.length<=t)return`[${n}]`}}i(Dg,"formatScalarOrShortStructure");function jg(e,t){if(e===void 0)return"[undefined]";if(e===null)return"null";let n;try{n=typeof e=="string"?e:JSON.stringify(e)??String(e)}catch{n=String(e)}return yl(n,t)}i(jg,"formatValue");function yl(e,t){return e.length>t?e.slice(0,t)+"\u2026":e}i(yl,"truncate");async function wl(e,t){let n=typeof e.topic=="string"?e.topic:void 0,r=typeof e.query=="string"?e.query:void 0,o=wa({topic:n,query:r},{extraTopics:t.selfManual?.topics,productName:t.selfManual?.productName,baseTopics:t.selfManual?.baseTopics}),s=[`# ${o.title}`,"",o.content];return o.sources.length>0&&s.push("",`Sources: ${o.sources.map(a=>a.path).join(", ")}`),o.nextTopics.length>0&&s.push(`Related topics (pass as "topic"): ${o.nextTopics.join(", ")}`),s.join(`
167
- `)}i(wl,"toolKodaxManual");function Fg(e){let t=e.trim();return t.startsWith("/skill:")?t.slice(7):t.startsWith("skill:")?t.slice(6):t.startsWith("/")?t.slice(1):t}i(Fg,"normalizeSkillToolName");async function bl(e,t){let n=e.skill;if(typeof n!="string"||n.trim().length===0)return"[Tool Error] skill: missing required argument `skill` (string).";let r=Fg(n),o=typeof e.args=="string"?e.args:"",s=t.executionCwd??process.cwd(),a=t.gitRoot??s,c=Gn(a);if(c.size===0&&await Xn(a),!c.has(r)){let l=c.list().map(d=>d.name).sort().join(", ");return`[Tool Error] skill: unknown skill "${r}". Available skills: ${l||"(none)"}.`}try{let l=await c.loadFull(r);return l.disableModelInvocation?`[Tool Error] skill ${r}: Skill "${r}" has model invocation disabled`:(await Qs(l,o,{workingDirectory:s,projectRoot:a,executeDynamicContext:t.skillDynamicContext?.execute,disableDynamicContext:t.skillDynamicContext?.disable})).content}catch(l){return`[Tool Error] skill ${r}: ${l instanceof Error?l.message:String(l)}`}}i(bl,"toolSkill");async function gi(e,t){let n=e.plan;if(!n||typeof n!="string"||n.trim().length===0)return"[Tool Error] exit_plan_mode: Missing required parameter: plan (the finalized plan to present to the user for approval)";if(!t.exitPlanMode)return"[Tool Error] exit_plan_mode: Only available in interactive REPL sessions (no approval UI is wired for this run)";let r=await t.exitPlanMode(n);return r==="not-in-plan-mode"?"[Tool Error] exit_plan_mode: Not currently in plan mode. This tool is only valid while the session is in plan mode. The session is already in implementation mode \u2014 proceed directly with the work.":JSON.stringify(r===!0?{approved:!0,note:"User approved the plan. Permission mode is now accept-edits. Proceed with implementation."}:{approved:!1,note:"User did not approve the plan. Remain in plan mode. Revise the plan based on user feedback and propose again."})}i(gi,"toolExitPlanMode");import Sr from"node:fs/promises";import ie from"node:path";var kl=10,vl=1800,Ug=3;function qg(e){return e==="upstream"||e==="downstream"||e==="both"?e:"both"}i(qg,"readDirection");function Bg(e){return e===2||e===3?e:1}i(Bg,"readDepth");function Tl(e){return e instanceof Error?e.message:String(e)}i(Tl,"errorMessage");async function Xt(e,t,n){try{return await n()}catch(r){t.push(`${e}: ${Tl(r)}`);return}}i(Xt,"capture");function Er(e,t,n){let r=t?.capability;if(r?.status!=="warming")return!1;let o=r.warnings.join(" ");return n.push(`${e}: ${o||"repo-intelligence index is still warming; retry shortly."}`),!0}i(Er,"recordWarmingGap");function Sn(e){return`${e.name} (${e.filePath}:${e.line})`}i(Sn,"symbolRef");function Al(e){return`${e.label} (${e.root})`}i(Al,"moduleRef");async function _l(e){try{return(await Sr.stat(e)).isFile()}catch{return!1}}i(_l,"isFile");function Cl(e){let t=[];e.gitRoot&&t.push(e.gitRoot),e.executionCwd&&t.push(e.executionCwd),t.push(process.cwd());let n=new Set;for(let r of t){let o=ie.resolve(r);for(let s=0;s<=Ug&&!n.has(o);s+=1){n.add(o);let a=ie.dirname(o);if(a===o)break;o=a}}return[...n]}i(Cl,"candidateRoots");function Wg(e,t){let n=ie.normalize(t);if(!n||ie.isAbsolute(n))return;let r=ie.normalize(e);if(!r.endsWith(n))return;let o=r.slice(0,r.length-n.length);return o?ie.resolve(o):void 0}i(Wg,"inferWorkspaceRoot");async function Hg(e,t){if(ie.isAbsolute(e)){let n=ie.resolve(e);return await _l(n)?{filePath:n}:void 0}for(let n of Cl(t)){let r=ie.resolve(n,e);if(await _l(r))return{filePath:r,workspaceRoot:Wg(r,e)??n}}}i(Hg,"resolveRepoFilePath");async function Kg(e,t){if(ie.isAbsolute(e)){let n=ie.resolve(e);try{return await Sr.stat(n),n}catch{return}}for(let n of Cl(t)){let r=ie.resolve(n,e);try{return await Sr.stat(r),r}catch{}}}i(Kg,"resolveExistingPath");function Rl(e){return[...new Set(e.filter(t=>!!t?.trim()))]}i(Rl,"uniqueStrings");function zg(e,t,n){let r=e.split(/\r?\n/),o=Math.max(0,Math.min(r.length-1,t-1)),s=Rl([String(o),String(o-1),String(o+1),String(o-2),String(o+2),String(o-3),String(o+3)]).map(a=>Number(a)).filter(a=>a>=0&&a<r.length);for(let a of s){let c=r[a]??"";for(let l of n){let d=c.indexOf(l);if(d>=0)return{line:a+1,column:d+1}}}return{line:o+1,column:1}}i(zg,"locateSymbolLineColumn");async function $l(e,t){let n=await Hg(e.filePath,t);if(!n)return;let r=await Sr.readFile(n.filePath,"utf8"),o=Rl([e.name,e.qualifiedName.split(".").at(-1)]),s=zg(r,e.line,o);return{filePath:n.filePath,workspaceRoot:n.workspaceRoot,line:s.line,column:s.column}}i($l,"locateSymbol");function Gg(e){return{gitRoot:e.gitRoot,signal:e.abortSignal,onProgress:e.reportToolProgress}}i(Gg,"navRequest");async function Xg(e,t,n,r){if(!e.symbolContext)return r.push("LSP validation: symbol identity is required for call hierarchy expansion."),[];if(!n.lspService)return r.push("LSP validation: LSP service is unavailable in this runtime."),[];let o=await $l(e.symbolContext.symbol,n);if(!o)return r.push(`LSP validation: source file not found for ${e.symbolContext.symbol.filePath}.`),[];let s={line:o.line-1,character:o.column-1},a={...Gg(n),gitRoot:n.gitRoot??o.workspaceRoot},c=[];if(t==="upstream"||t==="both"){let l=await n.lspService.getIncomingCalls(o.filePath,s,a);c.push({label:`lsp_incoming_calls at ${e.symbolContext.symbol.filePath}:${o.line}:${o.column}`,output:l})}if(t==="downstream"||t==="both"){let l=await n.lspService.getOutgoingCalls(o.filePath,s,a);c.push({label:`lsp_outgoing_calls at ${e.symbolContext.symbol.filePath}:${o.line}:${o.column}`,output:l})}return c}i(Xg,"buildLspEvidence");function Vg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(Vg,"escapeRegexPattern");function Jg(e,t,n,r,o){return e.symbolContext?.symbol.name??t??n??o??(r?ie.basename(r):void 0)}i(Jg,"firstEvidenceTarget");async function Yg(e,t,n,r,o,s,a,c){let l=Jg(e,t,n,r,o);if(!l?.trim())return c.push("Text-search validation: no searchable target was available."),[];if(l.length>128)return c.push("Text-search validation: target is too long for a bounded exact-name search."),[];let d=e.symbolContext?await $l(e.symbolContext.symbol,a):void 0,u=s??d?.workspaceRoot??a.gitRoot??e.moduleContext?.module.root??r??".",f=await Kg(u,a)??u,m=await mn({pattern:Vg(l),path:f,output_mode:"content",head_limit:16},a);return[{label:`grep exact-name evidence for "${l}"`,output:m}]}i(Yg,"buildTextSearchEvidence");function mt(e,t,n){if(n.length===0){e.push(`- ${t}`);return}for(let r of n)e.push(`- ${r}`)}i(mt,"pushList");function Vt(){return"semantic-index"}i(Vt,"edgeSource");function Qg(e){return Math.max(0,Math.min(1,e))}i(Qg,"clampConfidence");function Jt(e){let t=e.filter(n=>typeof n=="number"&&Number.isFinite(n));return t.length===0?"unknown":Qg(Math.min(...t)).toFixed(2)}i(Jt,"edgeConfidence");function Yt(e,t,n){return`[source=${e} confidence=${t} evidence=${n}]`}i(Yt,"edgeMeta");function yi(e){return`${e.filePath}:${e.line}`}i(yi,"symbolEvidence");function xl(e,t){let n=e.impactEstimate?.impactedSymbols.find(r=>r.id===t.symbolId||r.name===t.name&&r.filePath===t.filePath);return n?yi(n):`${t.filePath}:line-unknown`}i(xl,"referenceEvidence");function Zg(e,t){return e.impactEstimate?.impactedSymbols.find(n=>n.id===t.symbolId||n.name===t.name&&n.filePath===t.filePath)?.confidence}i(Zg,"targetConfidence");function Ol(e){return e.entryFiles[0]??e.sampleFiles[0]??e.root}i(Ol,"moduleEvidence");function El(e){return(e.symbolContext?.capability??e.moduleContext?.capability??e.processContext?.capability??e.impactEstimate?.capability)?.engine==="full"?"full":"light"}i(El,"formatEngine");function ey(e){let t=[e.symbolContext?.confidence,e.moduleContext?.confidence,e.processContext?.confidence,e.impactEstimate?.confidence].filter(r=>typeof r=="number"&&Number.isFinite(r));return t.length===0?"unknown":(t.reduce((r,o)=>r+o,0)/t.length).toFixed(2)}i(ey,"formatConfidence");function ty(e,t,n){e.push("Identity"),t.symbolContext?(e.push(`- Symbol: ${Sn(t.symbolContext.symbol)}`),e.push(`- Symbol module: ${t.symbolContext.symbol.moduleId}`),t.symbolContext.alternatives.length>0&&e.push(`- Alternatives: ${t.symbolContext.alternatives.map(Sn).join("; ")}`)):t.moduleContext?e.push(`- Module: ${Al(t.moduleContext.module)}`):t.processContext?e.push(`- Process: ${t.processContext.process.label} (${t.processContext.process.entryFile})`):e.push(`- Target: ${n}`),e.push("")}i(ty,"renderIdentity");function ny(e,t){if(e.push("Upstream"),t.symbolContext){let n=Vt();mt(e,"No direct callers found in the light index.",t.symbolContext.callers.map(r=>`${Sn(r)} ${Yt(n,Jt([t.symbolContext?.confidence,r.confidence]),yi(r))}`))}if(t.moduleContext){let n=Vt(),r=t.moduleContext.module;mt(e,"No module dependents found in the light index.",r.dependents.map(o=>`Dependent module: ${o} ${Yt(n,Jt([t.moduleContext?.confidence]),Ol(r))}`))}if(t.impactEstimate?.callers.length){let n=Vt();for(let r of t.impactEstimate.callers)e.push(`- Impact caller: ${Sn(r)} ${Yt(n,Jt([t.impactEstimate.confidence,r.confidence]),yi(r))}`)}e.push("")}i(ny,"renderUpstream");function ry(e,t){if(e.push("Downstream"),t.symbolContext){let n=t.symbolContext.symbol.callTargets.map(r=>`${r.name} (${xl(t,r)}) ${Yt(Vt(),Jt([t.symbolContext?.confidence,t.symbolContext?.symbol.confidence,Zg(t,r)]),xl(t,r))}`);mt(e,"No direct callees found in the light index.",n)}if(t.moduleContext){let n=Vt(),r=t.moduleContext.module;mt(e,"No module dependencies found in the light index.",r.dependencies.map(o=>`Dependency module: ${o} ${Yt(n,Jt([t.moduleContext?.confidence]),Ol(r))}`))}if(t.processContext)for(let n of t.processContext.process.steps.slice(0,8)){let r=n.line===void 0?"":`:${n.line}`,o=n.line===void 0?`${n.filePath}:line-unknown`:`${n.filePath}:${n.line}`;e.push(`- Process ${n.kind}: ${n.symbolName} (${n.filePath}${r}) ${Yt(Vt(),Jt([t.processContext.confidence]),o)}`)}e.push("")}i(ry,"renderDownstream");function oy(e,t){if(e.push("Impact"),!t){e.push("- Impact estimate unavailable for this target."),e.push("");return}e.push(`- ${t.summary}`),mt(e,"No impacted modules found in the light index.",t.impactedModules.map(n=>Al(n))),t.impactedSymbols.length>0&&e.push(`- Impacted symbols: ${t.impactedSymbols.map(Sn).join("; ")}`),e.push("")}i(oy,"renderImpact");function iy(e,t){e.push("Evidence"),t.symbolContext&&e.push(`- symbol_context freshness=${t.symbolContext.freshness} confidence=${t.symbolContext.confidence.toFixed(2)}`),t.moduleContext&&e.push(`- module_context freshness=${t.moduleContext.freshness} confidence=${t.moduleContext.confidence.toFixed(2)}`),t.processContext&&e.push(`- process_context freshness=${t.processContext.freshness} confidence=${t.processContext.confidence.toFixed(2)}`),t.impactEstimate&&e.push(`- impact_estimate freshness=${t.impactEstimate.freshness} confidence=${t.impactEstimate.confidence.toFixed(2)}`),e.push("")}i(iy,"renderEvidence");function sy(e){let t=e.trim();if(!t)return["(no output)"];let n=t.length>vl?`${t.slice(0,vl)}...`:t,r=n.split(/\r?\n/).slice(0,kl);return n.split(/\r?\n/).length>kl&&r.push("..."),r}i(sy,"compactSupplementOutput");function Sl(e,t,n){if(n.length!==0){e.push(t);for(let r of n){e.push(`- ${r.label}`);for(let o of sy(r.output))e.push(` ${o}`)}e.push("")}}i(Sl,"renderSupplementalEvidence");function ay(e,t,n,r){e.push("Gaps"),n==="light"&&e.push("- Light engine uses static heuristics; compiler-accurate call hierarchy is not included yet."),r>1&&e.push(`- Requested depth ${r}; light-mode relationship_scan reports bounded direct edges first.`),mt(e,"No additional gaps recorded.",t)}i(ay,"renderGaps");function cy(e,t,n){let r=[`Relationship scan for ${e}`,"Engine: warming",`Direction: ${t}`,"Status: index warming","","Structural relationships unavailable","- The repository intelligence index is still warming; upstream, downstream, and impact edges are not available yet.",'- This is NOT a "no relationships found" result \u2014 the analysis has not completed.',"- Retry relationship_scan shortly for full structural results.","- Use read, grep, glob, and LSP tools for immediate exploration while the index finishes.","","Gaps"];return mt(r,"No additional gaps recorded.",n),r.join(`
168
- `)}i(cy,"renderWarmingRelationshipScan");function ly(e,t,n,r,o,s,a){let c=[`Relationship scan for ${e}`,`Engine: ${El(r)}`,`Direction: ${t}`,`Confidence: ${ey(r)}`,""];return ty(c,r,e),(t==="upstream"||t==="both")&&ny(c,r),(t==="downstream"||t==="both")&&ry(c,r),oy(c,r.impactEstimate),iy(c,r),Sl(c,"LSP validation",s),Sl(c,"Text-search validation",a),ay(c,o,El(r),n),c.join(`
169
- `)}i(ly,"renderRelationshipScan");async function Il(e,t){try{let n=_(e,"symbol"),r=_(e,"module"),o=_(e,"path"),s=_(e,"entry"),a=_(e,"target_path")??o,c=qg(e.direction),l=Bg(e.depth),d=e.refresh===!0,u=e.include_lsp===!0,f=e.include_text_search===!0,m=n??r??o??s;if(!m)throw new Error("one of symbol, module, path, or entry is required.");let h=[],p={},g=ne(),w=!1,y=n??(!r&&!o?s:void 0);if(y&&(p.symbolContext=await Xt("symbol_context",h,()=>wr(t,{symbol:y,module:r,targetPath:a,refresh:d,maxWaitMs:g})),w=Er("symbol_context",p.symbolContext,h)),!w&&(r||o||p.symbolContext)&&(p.moduleContext=await Xt("module_context",h,()=>kn(t,{module:r??p.symbolContext?.symbol.moduleId,targetPath:a,refresh:!1,maxWaitMs:g})),w=Er("module_context",p.moduleContext,h)),!w&&((c==="downstream"||c==="both")&&(s||y))&&(p.processContext=await Xt("process_context",h,()=>br(t,{entry:s,module:r,targetPath:a??p.symbolContext?.symbol.filePath,refresh:!1,maxWaitMs:g})),w=Er("process_context",p.processContext,h)),w||(p.impactEstimate=await Xt("impact_estimate",h,()=>vn(t,{symbol:y,module:r,path:o,targetPath:a,refresh:!1,maxWaitMs:g})),w=Er("impact_estimate",p.impactEstimate,h)),w)return cy(m,c,h);let v=u&&!w?await Xt("lsp_validation",h,()=>Xg(p,c,t,h))??[]:[],k=f&&!w?await Xt("text_search_validation",h,()=>Yg(p,y,r,o,s,a,t,h))??[]:[];return ly(m,c,l,p,h,v,k)}catch(n){return`[Tool Error] relationship_scan: ${Tl(n)}`}}i(Il,"toolRelationshipScan");function Ll(e){let t=[e.summary,`Scanned ${e.scanned.modules} modules, ${e.scanned.edges} edges.`];for(let n of e.cycles)t.push(`- [${n.severity}] ${n.hopCount}-hop: ${n.chain.join(" -> ")}`);return t.join(`
170
- `)}i(Ll,"renderCycleAnalysis");async function Ml(e,t){try{return Ll(await sl(t,{maxWaitMs:ne()}))}catch(n){return`[Tool Error] cyclic_dependencies: ${n instanceof Error?n.message:String(n)}`}}i(Ml,"toolCyclicDependencies");var Re="LSP is unavailable (disabled via KODAX_LSP=0, or no service wired).";function $e(e){return{gitRoot:e.gitRoot,signal:e.abortSignal,onProgress:e.reportToolProgress}}i($e,"navRequest");function ht(e){let t=Number(e.line);if(!Number.isInteger(t)||t<1)return"`line` is required and must be a 1-based line number.";let n=e.character??e.column,r=n==null?1:Number(n);return!Number.isInteger(r)||r<1?"`character`/`column` must be a 1-based column number.":{line:t-1,character:r-1}}i(ht,"toPosition");function gt(e,t){if(typeof e.path!="string"||!e.path.trim())return`[Tool Error] ${t}: \`path\` is required.`}i(gt,"requiredPath");async function Pl(e,t){if(!t.lspService)return Re;let n=gt(e,"lsp_definition");if(n)return n;let r=ht(e);if(typeof r=="string")return`[Tool Error] lsp_definition: ${r}`;let o=q(e.path,t);return t.lspService.getDefinition(o,r,$e(t))}i(Pl,"toolLspDefinition");async function Nl(e,t){if(!t.lspService)return Re;let n=gt(e,"lsp_hover");if(n)return n;let r=ht(e);if(typeof r=="string")return`[Tool Error] lsp_hover: ${r}`;let o=q(e.path,t);return t.lspService.getHover(o,r,$e(t))}i(Nl,"toolLspHover");async function Dl(e,t){if(!t.lspService)return Re;let n=gt(e,"lsp_references");if(n)return n;let r=ht(e);if(typeof r=="string")return`[Tool Error] lsp_references: ${r}`;let o=q(e.path,t);return t.lspService.getReferences(o,r,$e(t))}i(Dl,"toolLspReferences");async function jl(e,t){if(!t.lspService)return Re;if(typeof e.path!="string"||!e.path.trim())return"[Tool Error] lsp_document_symbols: `path` is required.";let n=q(e.path,t);return t.lspService.getDocumentSymbols(n,$e(t))}i(jl,"toolLspDocumentSymbols");async function Fl(e,t){if(!t.lspService)return Re;let n=typeof e.query=="string"?e.query:"";return t.lspService.getWorkspaceSymbols(n,$e(t))}i(Fl,"toolLspWorkspaceSymbols");async function Ul(e,t){if(!t.lspService)return Re;let n=gt(e,"lsp_implementation");if(n)return n;let r=ht(e);if(typeof r=="string")return`[Tool Error] lsp_implementation: ${r}`;let o=q(e.path,t);return t.lspService.getImplementation(o,r,$e(t))}i(Ul,"toolLspImplementation");async function ql(e,t){if(!t.lspService)return Re;let n=gt(e,"lsp_prepare_call_hierarchy");if(n)return n;let r=ht(e);if(typeof r=="string")return`[Tool Error] lsp_prepare_call_hierarchy: ${r}`;let o=q(e.path,t);return t.lspService.getPrepareCallHierarchy(o,r,$e(t))}i(ql,"toolLspPrepareCallHierarchy");async function Bl(e,t){if(!t.lspService)return Re;let n=gt(e,"lsp_incoming_calls");if(n)return n;let r=ht(e);if(typeof r=="string")return`[Tool Error] lsp_incoming_calls: ${r}`;let o=q(e.path,t);return t.lspService.getIncomingCalls(o,r,$e(t))}i(Bl,"toolLspIncomingCalls");async function Wl(e,t){if(!t.lspService)return Re;let n=gt(e,"lsp_outgoing_calls");if(n)return n;let r=ht(e);if(typeof r=="string")return`[Tool Error] lsp_outgoing_calls: ${r}`;let o=q(e.path,t);return t.lspService.getOutgoingCalls(o,r,$e(t))}i(Wl,"toolLspOutgoingCalls");function dy(e){if(!(!e||Array.isArray(e)||typeof e!="object"))return e}i(dy,"asRecord");function Ve(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}i(Ve,"readString");function uy(e){let t=typeof e=="number"&&Number.isFinite(e)?Math.floor(e):10;return Math.max(1,Math.min(20,t))}i(uy,"clampLimit");function fy(e,t){return e>0?t?`Found ${e} MCP capability result(s) for "${t}".`:`Found ${e} MCP capability result(s).`:t?`No MCP capability results for "${t}".`:"No MCP capabilities found."}i(fy,"formatSearchSummary");async function wi(e,t){try{if(!t.extensionRuntime)throw new Error("mcp_search requires an active extension runtime.");let n=_(e,"query")?.trim()??"",r=_(e,"kind"),o=_(e,"server"),s=uy(e.limit),c=(await t.extensionRuntime.searchCapabilities("mcp",n,{kind:r,limit:s,server:o})).map(d=>{let u=dy(d),f=Ve(u?.kind)??"capability",m=Ve(u?.title)??Ve(u?.name)??Ve(u?.id)??"mcp capability";return{title:`[${f}] ${m}`,locator:Ve(u?.id),snippet:Ve(u?.summary),metadata:{serverId:Ve(u?.serverId),risk:Ve(u?.risk),kind:f}}}),l=c.reduce((d,u)=>(u.locator&&d.push({kind:"provider",label:u.title,value:u.locator}),d),[]);return B({tool:"mcp_search",query:n,scope:"remote",trust:"provider",freshness:"unknown",provider:o?`mcp:${o}`:"mcp",summary:fy(c.length,n),items:c,artifacts:l,metadata:{kind:r??"all",server:o??"all"}},t)}catch(n){return`[Tool Error] mcp_search: ${n instanceof Error?n.message:String(n)}`}}i(wi,"toolMcpSearch");function se(e,t){if(!(t==null||t==="")){if(typeof t=="string")return`${e}: ${t}`;try{return`${e}: ${JSON.stringify(t,null,2)}`}catch{return`${e}: ${String(t)}`}}}i(se,"formatValue");async function bi(e,t){try{if(!t.extensionRuntime)throw new Error("mcp_describe requires an active extension runtime.");let n=_(e,"id");if(!n)throw new Error("id is required.");let r=ye(n),o=await t.extensionRuntime.describeCapability("mcp",r);if(!o)throw new Error(`Unknown MCP capability: ${r}`);let s=[se("ID",o.id),se("Server",o.serverId),se("Kind",o.kind),se("Name",o.name),se("Title",o.title),se("Summary",o.summary),se("Risk",o.risk),se("URI",o.uri),se("MIME",o.mimeType),se("Input Schema",o.inputSchema),se("Output Schema",o.outputSchema),se("Prompt Args Schema",o.promptArgsSchema),se("Annotations",o.annotations)].filter(a=>a!==void 0).join(`
171
- `);return B({tool:"mcp_describe",scope:"remote",trust:"provider",freshness:"unknown",provider:"mcp",summary:`Described MCP capability ${r}.`,content:s,items:[],artifacts:[{kind:"provider",label:String(o.name??o.id??r),value:r}],metadata:{capabilityId:r,kind:o.kind,serverId:o.serverId}},t)}catch(n){return`[Tool Error] mcp_describe: ${n instanceof Error?n.message:String(n)}`}}i(bi,"toolMcpDescribe");function Hl(e){if(e!=null){if(typeof e=="string")return e.trim()||void 0;try{return JSON.stringify(e,null,2)}catch{return String(e)}}}i(Hl,"stringifyValue");async function ki(e,t){try{if(!t.extensionRuntime)throw new Error("mcp_call requires an active extension runtime.");let n=_(e,"id");if(!n)throw new Error("id is required.");let r=ye(n),o=e.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},s=await t.extensionRuntime.executeCapability("mcp",r,o);return B({tool:"mcp_call",scope:"remote",trust:"provider",freshness:"unknown",provider:"mcp",summary:`Executed MCP tool ${r}.`,content:Hl(s.content)??Hl(s.structuredContent),items:[],artifacts:[{kind:"provider",label:r,value:r}],metadata:{capabilityId:r,capabilityKind:s.kind,...s.metadata??{}}},t)}catch(n){return`[Tool Error] mcp_call: ${n instanceof Error?n.message:String(n)}`}}i(ki,"toolMcpCall");function Kl(e){if(e!=null){if(typeof e=="string")return e.trim()||void 0;try{return JSON.stringify(e,null,2)}catch{return String(e)}}}i(Kl,"stringifyValue");async function vi(e,t){try{if(!t.extensionRuntime)throw new Error("mcp_read_resource requires an active extension runtime.");let n=_(e,"id");if(!n)throw new Error("id is required.");let r=ye(n),{id:o,...s}=e,a=await t.extensionRuntime.readCapability("mcp",r,s);return B({tool:"mcp_read_resource",scope:"remote",trust:"provider",freshness:"unknown",provider:"mcp",summary:`Read MCP resource ${r}.`,content:Kl(a.content)??Kl(a.structuredContent),items:[],artifacts:[{kind:"provider",label:r,value:r}],metadata:{capabilityId:r,capabilityKind:a.kind,...a.metadata??{}}},t)}catch(n){return`[Tool Error] mcp_read_resource: ${n instanceof Error?n.message:String(n)}`}}i(vi,"toolMcpReadResource");function py(e){if(e!=null){if(typeof e=="string")return e.trim()||void 0;try{return JSON.stringify(e,null,2)}catch{return String(e)}}}i(py,"stringifyValue");async function _i(e,t){try{if(!t.extensionRuntime)throw new Error("mcp_get_prompt requires an active extension runtime.");let n=_(e,"id");if(!n)throw new Error("id is required.");let r=ye(n),o=e.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},s=await t.extensionRuntime.getCapabilityPrompt("mcp",r,o);return B({tool:"mcp_get_prompt",scope:"remote",trust:"provider",freshness:"unknown",provider:"mcp",summary:`Retrieved MCP prompt ${r}.`,content:py(s),items:[],artifacts:[{kind:"provider",label:r,value:r}],metadata:{capabilityId:r,capabilityKind:"prompt"}},t)}catch(n){return`[Tool Error] mcp_get_prompt: ${n instanceof Error?n.message:String(n)}`}}i(_i,"toolMcpGetPrompt");import{execFile as my}from"child_process";import{promisify as hy}from"util";import{mkdirSync as gy}from"fs";import xi from"path";var Qt=hy(my);function yy(e){return e?`kodax-wt-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}`:`kodax-wt-${Date.now()}`}i(yy,"generateBranchName");function wy(e){return/^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,62}[a-zA-Z0-9]$|^[a-zA-Z0-9]$/.test(e)}i(wy,"isValidBranchName");async function Tn(e,t){let n=e.branch_name,r=e.description,o=n??yy(r);if(!wy(o))throw new Error(`Invalid branch name: ${o}. Must start and end with alphanumeric, contain only alphanumeric, dots, dashes, or slashes (max 64 chars).`);if(/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(o))throw new Error(`Invalid branch name: ${o}. Path traversal sequences (..) are not allowed.`);let s=t.executionCwd??t.gitRoot??process.cwd(),a=typeof e.base_dir=="string"&&e.base_dir.length>0?xi.resolve(e.base_dir):void 0,c=a??xi.resolve(s,".."),l=xi.resolve(c,`.kodax-worktree-${o}`);if(!l.startsWith(c))throw new Error(`Worktree path escaped expected directory. Resolved to: ${l}`);a&&gy(a,{recursive:!0});try{await Qt("git",["worktree","add","-b",o,l],{cwd:s})}catch(d){let u=d instanceof Error?d.message:String(d);throw new Error(`Failed to create worktree: ${u}`)}return JSON.stringify({path:l,branch:o})}i(Tn,"toolWorktreeCreate");async function An(e,t){let n=e.action,r=e.worktree_path,o=e.discard_changes;if(!n||n!=="keep"&&n!=="remove")throw new Error('action must be "keep" or "remove"');if(!r)throw new Error("worktree_path is required");let s=t.executionCwd??t.gitRoot??process.cwd();if(n==="keep")return JSON.stringify({restored:!0,message:`Worktree kept at ${r}. Restored CWD.`});if(!o)try{let{stdout:c}=await Qt("git",["status","--porcelain"],{cwd:r}),l=c.trim().split(`
172
- `).filter(f=>f.trim().length>0).length,{stdout:d}=await Qt("git",["rev-list","--count","HEAD","--not","--remotes"],{cwd:r}),u=parseInt(d.trim(),10)||0;if(l>0||u>0)throw new Error(`Worktree has ${l} uncommitted file(s) and ${u} local commit(s). Use discard_changes=true to force removal, or commit/push your work first.`)}catch(c){throw c instanceof Error&&c.message.includes("uncommitted")?c:new Error(`Cannot verify worktree state: ${c instanceof Error?c.message:String(c)}`)}let a="";try{let{stdout:c}=await Qt("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:r});a=c.trim()}catch{}try{await Qt("git",["worktree","remove",r,"--force"],{cwd:s})}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to remove worktree: ${l}`)}if(a)try{await Qt("git",["branch","-D",a],{cwd:s})}catch{}return JSON.stringify({restored:!0,message:`Worktree removed. Branch ${a||"(unknown)"} deleted. Restored CWD.`})}i(An,"toolWorktreeRemove");import{execFileSync as Cy}from"child_process";import Ry from"fs/promises";import ed from"os";function zl(e,t,n){let r=e?.provider?.trim()||process.env[t]?.trim()||void 0,o=e?.model?.trim()||process.env[n]?.trim()||void 0;if(!(!r&&!o))return{provider:r,model:o}}i(zl,"resolveTier");function Ei(e,t){let n=Hn()?.modelTiers;if(e==="fast")return t?zl(n?.fast,"KODAX_FAST_PROVIDER","KODAX_FAST_MODEL"):void 0;if(e==="deep")return zl(n?.deep,"KODAX_DEEP_PROVIDER","KODAX_DEEP_MODEL")}i(Ei,"resolveModelHintTier");function by(){let e=process.env.KODAX_FALLBACK_PROVIDERS?.trim();return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}i(by,"resolveFallbackChain");function Gl(e){return e instanceof Vr||e instanceof Jr||e instanceof Xr}i(Gl,"isFallbackEligibleError");function ky(e){return e instanceof Vr?"rate-limit exhausted":e instanceof Jr?"network error":e instanceof Xr?"provider error":e instanceof Error?e.message:String(e)}i(ky,"errorReason");async function Si(e,t,n,r){let o=e.provider??"anthropic";try{return await n(e,t)}catch(s){if(e.abortSignal?.aborted||!Gl(s))throw s;let a=by().filter(l=>l!==o),c=s;for(let l of a){r?.onFallback?.({fromProvider:o,toProvider:l,reason:ky(c)});try{return await n({...e,provider:l,model:void 0},t)}catch(d){if(e.abortSignal?.aborted||!Gl(d))throw d;c=d}}throw c}}i(Si,"invokeChildWithFallback");function vy(e){if(!e.trim())return[];let t=[],n=/(^|\s)\/skill:([\w](?:[\w.\-:]*[\w])?)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"",s=r[2]??"";if(!s)continue;let a=r.index+o.length,c=`/skill:${s}`;t.push({name:s,raw:c,start:a,end:a+c.length})}return t}i(vy,"parseInlineSkillReferences");function _y(e){if(!e.trim())return[];let t=[],n=/(^|\s)\/(?!skill:)([\w](?:[\w.\-:]*[\w])?)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"",s=r[2]??"";if(!s)continue;let a=r.index+o.length,c=`/${s}`;t.push({name:s,raw:c,start:a,end:a+c.length})}return t}i(_y,"parseBareInlineSlashReferences");function Xl(e){return Array.from(new Set(vy(e).map(t=>t.name)))}i(Xl,"uniqueInlineSkillNames");function Vl(e){return Array.from(new Set(_y(e).map(t=>t.name)))}i(Vl,"uniqueBareInlineSlashNames");function be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(be,"isRecord");function xy(e){return e instanceof Error?e.message:String(e)}i(xy,"errorMessage");function Ar(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}i(Ar,"safeStringify");function Jl(e,t){switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number";case"integer":return typeof e=="number"&&Number.isInteger(e);case"boolean":return typeof e=="boolean";case"object":return be(e);case"array":return Array.isArray(e);case"null":return e===null;default:return!0}}i(Jl,"matchesType");function Ey(e,t){return e.some(n=>n===t?!0:typeof n!="object"||typeof t!="object"?!1:Ar(n)===Ar(t))}i(Ey,"enumMatches");function Tr(e,t){return e?`${e}.${t}`:t}i(Tr,"joinPath");function Ti(e,t,n=""){if(!be(t))return[];let r=[],o=n||"(root)",s=t.type;if(typeof s=="string"&&!Jl(e,s))return[`${o}: expected type ${s}`];if(Array.isArray(s)&&!s.some(a=>typeof a=="string"&&Jl(e,a)))return[`${o}: expected one of types ${s.join("|")}`];if(Array.isArray(t.enum)&&!Ey(t.enum,e)&&r.push(`${o}: value is not one of the allowed enum values`),be(e)){let a=be(t.properties)?t.properties:void 0;if(Array.isArray(t.required))for(let c of t.required)typeof c=="string"&&!(c in e)&&r.push(`${Tr(n,c)}: required field is missing`);if(a){for(let[c,l]of Object.entries(e))c in a&&r.push(...Ti(l,a[c],Tr(n,c)));if(t.additionalProperties===!1)for(let c of Object.keys(e))c in a||r.push(`${Tr(n,c)}: unexpected property (additionalProperties is false)`)}}return Array.isArray(e)&&be(t.items)&&e.forEach((a,c)=>{r.push(...Ti(a,t.items,`${o}[${c}]`))}),r}i(Ti,"validateAgainstSchema");var Sy=["$ref","$defs","definitions","oneOf","allOf","anyOf","not","if","then","else","const","patternProperties","propertyNames","dependencies","dependentSchemas","dependentRequired","contains","unevaluatedProperties","unevaluatedItems","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties"];function Ai(e,t,n){if(be(e)){for(let r of Sy)r in e&&!n.has(r)&&n.set(r,t||"(root)");if(be(e.properties))for(let[r,o]of Object.entries(e.properties))Ai(o,Tr(t,r),n);be(e.items)&&Ai(e.items,`${t||"(root)"}[]`,n),be(e.additionalProperties)&&!n.has("additionalProperties (schema form)")&&n.set("additionalProperties (schema form)",t||"(root)")}}i(Ai,"collectUnsupportedKeywords");function cC(e){if(!be(e))return;let t=new Map;if(Ai(e,"",t),t.size===0)return;let n=[...t.entries()].map(([r,o])=>`\`${r}\` (at ${o})`).join(", ");throw new Error(`outputSchema uses unsupported JSON-Schema keyword(s): ${n}. The workflow validator supports only type, enum, required, properties, items, and additionalProperties: false (nested object arrays included). Inline the referenced shapes, drop value-constraint keywords, and use that subset.`)}i(cC,"assertSupportedOutputSchema");function Ty(e){let t=e.indexOf("{"),n=e.indexOf("[");return t<0?n:n<0?t:Math.min(t,n)}i(Ty,"firstStructureStart");function Yl(e){let t=Ty(e);if(t<0)return;let n=e[t],r=n==="{"?"}":"]",o=0,s=!1,a=!1;for(let c=t;c<e.length;c+=1){let l=e[c];if(s){a?a=!1:l==="\\"?a=!0:l==='"'&&(s=!1);continue}if(l==='"'){s=!0;continue}if(l===n)o+=1;else if(l===r&&(o-=1,o===0))return e.slice(t,c+1)}}i(Yl,"balancedStructure");function Ay(e){if(typeof e!="string"||e.trim().length===0)return;let t=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(n=t.exec(e))!==null;){let o=n[1]?.trim();o&&(r=o)}return r?Yl(r)??r:Yl(e)}i(Ay,"extractJsonCandidate");function Ci(e,t){let n=Ay(e);if(n===void 0)return{ok:!1,errors:["no JSON value was found in the output"]};let r;try{r=JSON.parse(n)}catch(s){return{ok:!1,errors:[`output was not valid JSON: ${xy(s)}`]}}let o=Ti(r,t);return{ok:o.length===0,value:r,errors:o}}i(Ci,"evaluateStructuredOutput");function Ql(e){return["## Required Output Format","After your analysis, end your response with a single fenced ```json code block containing ONLY a JSON value that matches the JSON Schema below. Put nothing after the closing fence.","Schema:","```json",Ar(e),"```"].join(`
173
- `)}i(Ql,"buildStructuredOutputInstruction");function Zl(e,t){return["Your previous response did not produce a valid result object for the workflow.","Problems:",...e.map(n=>`- ${n}`),"Re-emit ONLY a single fenced ```json code block containing a JSON value that matches this schema. No prose, nothing after the closing fence.","Schema:","```json",Ar(t),"```"].join(`
174
- `)}i(Zl,"buildStructuredOutputRepairPrompt");var Ri,Cr;async function id(){if(Ri)return Ri;if(!Cr){let e="./agent.js";Cr=import("./agent-L5FC3YOY.js").then(t=>{let n=t.runKodaX;if(typeof n!="function")throw new Error("[child-executor] Agent module loaded but `runKodaX` export is missing or not a function. This indicates an API break in packages/coding/src/agent.ts. Check that `export { runKodaX }` is still present.");return Ri=n,n}).catch(t=>{if(Cr=void 0,t instanceof Error&&t.message.startsWith("[child-executor]"))throw t;let n=t instanceof Error?t.message:String(t);throw new Error(`[child-executor] Failed to lazy-load agent module (\`${e}\`) for dispatch_child_task. This usually means the @kodax-ai/coding build is broken or out of date. Underlying cause: ${n}`)})}return Cr}i(id,"getRunKodaX");var $y=["You are summarizing your own just-completed child-agent report for a parent workflow.","Do not use tools. Do not continue investigation. Produce only the digest."].join(`
175
- `),Oy=["Create a short user-facing digest of your previous report for the parent workflow.","Return only 2-4 bullet lines.","Each bullet must be concrete: a finding, decision, risk, evidence pointer, unresolved question, or next action.","Use the same natural language as the user request or your report.","Do not include a title, table, generic preamble, or workflow handoff markers."].join(`
176
- `),Iy=4,sd=1e4,Ly=45e3,My=40;function Rr(e){let t={};return e.parentOptions.repoIntelligenceMode!==void 0&&(t.repoIntelligenceMode=e.parentOptions.repoIntelligenceMode),e.parentOptions.repoIntelligenceTrace!==void 0&&(t.repoIntelligenceTrace=e.parentOptions.repoIntelligenceTrace),t}i(Rr,"inheritRepoIntelligenceContext");async function Oi(e,t,n){if(e.length===0)return od;let r=e.filter(f=>f.readOnly),o=e.filter(f=>!f.readOnly),s=nw(o,n.parentRole,n.parentHarness),a=[...r,...s];if(a.length===0)return od;let c=[],l=[],d=n.onProgress??(()=>{});d(`Starting ${a.length} child tasks in parallel`);let u=await Gs({bundles:a,runOne:i(f=>f.readOnly?Ky(f,t,n):Gy(f,t,n),"runOne"),maxParallel:n.maxParallel,abortSignal:n.abortSignal,onProgress:i((f,m)=>{f.kind==="start"?d(`[${m.completedCount}/${m.totalCount}] Running: ${f.bundle.id}`):f.kind==="item-done"&&d(`[${m.completedCount}/${m.totalCount}] Done: ${f.bundle.id} \u2192 ${f.result.status}`)},"onProgress")});for(let f of u.results)f.status==="fulfilled"?c.push(f.value):c.push(yt(f.bundle,`[Crash] ${f.reason.message}`,"failed"));for(let f of u.cancelled)l.push(f.id);return tw(a,c,l)}i(Oi,"executeChildAgents");function Py(e){let t=JSON.parse(e);if(typeof t!="object"||t===null||!("path"in t))throw new Error("worktree_create returned an invalid payload");let n=t.path;if(typeof n!="string"||n.length===0)throw new Error("worktree_create returned an invalid path");return n}i(Py,"readWorktreePath");async function ad(e,t){if(e.isolation!=="worktree")return{ctx:t};let n=await Tn({description:`workflow-${e.id}`,...t.workflowWorktreeBaseDir?{base_dir:t.workflowWorktreeBaseDir}:{}},t),r=Py(n);return{ctx:{...t,gitRoot:r,executionCwd:r},worktreePath:r}}i(ad,"prepareChildIsolationScope");function cd(e,t){return t.worktreePath?[`[Workflow worktree: ${t.worktreePath}]`,e].join(`
177
- `):e}i(cd,"annotateWorktreeSummary");async function td(e,t){if(e.worktreePath)try{await An({action:"remove",worktree_path:e.worktreePath,discard_changes:!1},t);return}catch(n){return`[Workflow worktree cleanup failed: ${n instanceof Error?n.message:String(n)}]`}}i(td,"cleanupChildIsolationScope");function Ny(e,t){return t?{...e,summary:`${e.summary}
178
- ${t}`}:e}i(Ny,"appendCleanupWarning");async function ld(e,t,n){let r;try{r=await n()}catch(s){throw await td(e,t),s}let o=await td(e,t);return Ny(r,o)}i(ld,"withChildIsolationCleanup");function Ii(e){let t=e.usage?.totalTokens??e.contextTokenSnapshot?.usage?.totalTokens??e.contextTokenSnapshot?.currentTokens??0;return Number.isFinite(t)&&t>0?t:0}i(Ii,"readChildTokenUsage");function Dy(e){let t=e.split(/\r?\n+/).map(n=>n.trim()).filter(n=>n.length>0).filter(n=>!/\[\/?workflow handoff\]/i.test(n)).filter(n=>!/^```/.test(n));if(t.length!==0)return t.slice(0,Iy).join(`
179
- `)}i(Dy,"normalizeWorkflowChildDigest");function dd(e,t){return e.workflowChild===!0&&e.abortSignal?.aborted!==!0&&t.success===!0&&t.interrupted!==!0&&t.lastText.trim().length>0}i(dd,"shouldCreateWorkflowChildDigest");function jy(e){return e.replace(/[\\/]+SKILL\.md$/i,"")}i(jy,"deriveSkillRootFromSkillFile");function Fy(e,t){return e.split(/\r?\n/).find(r=>r.trim().startsWith(t))?.trim().slice(t.length).trim()||void 0}i(Fy,"extractPrefixedLine");function nd(e,t,n){let r=e.split(/\r?\n/),o=r.findIndex(a=>a.trim()===t);if(o<0)return[];let s=[];for(let a of r.slice(o+1)){let c=a.trim();if(!c){if(s.length>0)break;continue}if(!c.startsWith("- ")||(s.push(c),s.length>=n))break}return s}i(nd,"extractListSection");function Uy(e){if(!e)return;let t=Fy(e.expandedContent,"Skill root:")??jy(e.path),n=nd(e.expandedContent,"Support roots:",12),r=nd(e.expandedContent,"Support file inventory:",My);return["## Active Skill Resources",`Parent task is using skill "${e.name}". If this child needs skill support files, use these exact paths instead of broad home/workspace searches.`,`- Skill file: ${e.path}`,t?`- Skill root: ${t}`:void 0,n.length>0?"Support roots:":void 0,...n,r.length>0?"Selected support files:":void 0,...r,n.length>0?"If a needed support file is not listed above, combine its relative path with the matching support root.":void 0].filter(s=>!!s).join(`
180
- `)}i(Uy,"buildActiveSkillResourceBriefing");async function qy(e,t,n){let r=Vl(e).filter(o=>!t.includes(o)&&!e.includes(`<skill name="${o}"`));if(r.length===0)return[];try{let o=Gn(n);return o.size===0&&await Xn(n),r.filter(s=>o.has(s))}catch{return[]}}i(qy,"resolveKnownBareSlashSkillNames");async function By(e,t){let n=Xl(e).filter(s=>!e.includes(`<skill name="${s}"`)),r=await qy(e,n,t),o=Array.from(new Set([...n,...r]));if(o.length!==0)return["## Referenced Skills",`The objective mentions skill reference(s): ${o.map(s=>`/skill:${s}`).join(", ")}.`,"Before acting on those instructions, invoke the `skill` tool for each referenced skill that is not already expanded in this briefing, then follow the returned skill instructions. Do not infer skill-specific rules from the slash token alone."].join(`
181
- `)}i(By,"buildReferencedSkillBriefing");function ud(e,t,n){return t.workflowDigestMode==="async"&&e.isolation!=="worktree"&&t.onWorkflowChildDigest!==void 0&&dd(t,n)}i(ud,"shouldRunWorkflowDigestAsync");async function Li(e){if(!dd(e.options,e.result))return{totalTokensUsed:0};let t=new AbortController,n=i(()=>t.abort(),"onParentAbort");e.options.abortSignal?.addEventListener("abort",n);let r=setTimeout(()=>t.abort(),e.timeoutMs);try{let o=await e.runFn({provider:e.provider,...e.model?{model:e.model}:{},effort:e.effort??e.options.parentOptions.effort,reasoningMode:e.options.parentOptions.reasoningMode,agentMode:"sa",maxIter:1,abortSignal:t.signal,extensionRuntime:e.options.parentOptions.extensionRuntime,guardrails:e.options.guardrails,session:{initialMessages:e.result.messages},context:{gitRoot:e.scopeCtx.gitRoot,executionCwd:e.scopeCtx.executionCwd??e.scopeCtx.gitRoot,...Rr(e.options),systemPromptOverride:$y,excludeTools:Cn().map(c=>c.name),currentAgentId:e.bundle.id,parentAgentId:e.scopeCtx.currentAgentId,inheritedChildTaskRegistry:e.scopeCtx.childTaskRegistry}},Oy),s=Dy(o.lastText),a=Ii(o);return s?{digest:s,totalTokensUsed:a}:{totalTokensUsed:a,attemptFailed:!0}}catch{return{totalTokensUsed:0,attemptFailed:!0}}finally{clearTimeout(r),e.options.abortSignal?.removeEventListener("abort",n)}}i(Li,"createWorkflowChildDigest");function fd(e){Li({...e,timeoutMs:Ly}).then(t=>{try{e.options.onWorkflowChildDigest?.({childId:e.bundle.id,...t.digest?{digest:t.digest}:{},...t.attemptFailed?{digestFailed:!0}:{},totalTokensUsed:t.totalTokensUsed})}catch{}})}i(fd,"scheduleWorkflowChildDigest");var Wy=["You are re-formatting your own just-completed report into the JSON a parent workflow requires.","Do not use tools. Do not continue investigation. Output only the JSON block."].join(`
182
- `),Hy=15e3;async function pd(e){let t=e.bundle.outputSchema;if(t===void 0)return;let n=Ci(e.result.lastText,t);if(n.ok||e.options.abortSignal?.aborted===!0||e.result.success!==!0||e.result.interrupted===!0)return n.value;let r=new AbortController,o=i(()=>r.abort(),"onParentAbort");e.options.abortSignal?.addEventListener("abort",o);let s=setTimeout(()=>r.abort(),Hy);try{let a=await e.runFn({provider:e.provider,...e.model?{model:e.model}:{},effort:e.effort??e.options.parentOptions.effort,reasoningMode:e.options.parentOptions.reasoningMode,agentMode:"sa",maxIter:1,abortSignal:r.signal,extensionRuntime:e.options.parentOptions.extensionRuntime,guardrails:e.options.guardrails,session:{initialMessages:e.result.messages},context:{gitRoot:e.scopeCtx.gitRoot,executionCwd:e.scopeCtx.executionCwd??e.scopeCtx.gitRoot,...Rr(e.options),systemPromptOverride:Wy,excludeTools:Cn().map(l=>l.name),currentAgentId:e.bundle.id,parentAgentId:e.scopeCtx.currentAgentId,inheritedChildTaskRegistry:e.scopeCtx.childTaskRegistry}},Zl(n.errors,t));return Ci(a.lastText,t).value??n.value}catch{return n.value}finally{clearTimeout(s),e.options.abortSignal?.removeEventListener("abort",o)}}i(pd,"resolveChildStructuredOutput");function md(e,t,n){if(!e.specialistName)return{systemPromptOverride:t,excludeTools:n};let r=Oe(e.specialistName);if(!r)return{systemPromptOverride:t,excludeTools:n};let o={...r.model?{modelOverride:r.model}:{},...r.provider?{providerOverride:r.provider}:{},...r.effort?{effortOverride:r.effort}:{}},s=typeof r.instructions=="string"?r.instructions:t;if(!r.tools||r.tools.length===0)return{systemPromptOverride:s,excludeTools:n,...o};let a=new Set(r.tools.map(u=>u.name)),c=new Set(n),d=Cn().map(u=>u.name).filter(u=>c.has(u)||!a.has(u));return{systemPromptOverride:s,excludeTools:d,...o}}i(md,"resolveSpecialistOverride");function rd(e){if(e===void 0||e.trim().length===0)return;let t=it(e);return t==="auto"?void 0:t}i(rd,"normalizeChildEffort");function hd(e,t,n){let r=rd(t),o=rd(e.effort);if(r!==void 0&&o!==void 0&&o!==r)throw new Error(`specialist "${e.specialistName??"unknown"}" locks effort "${r}", but dispatch requested "${o}". Remove the dispatch effort or match the specialist effort.`);return r??o??n}i(hd,"resolveChildEffort");async function Ky(e,t,n){let r=await ad(e,t);return ld(r,t,()=>zy(e,r,n))}i(Ky,"executeReadChild");async function zy(e,t,n){let r;try{r=await gd(e,t.ctx,n.maxIterationsPerChild)}catch(p){return yt(e,p instanceof Error?p.message:String(p),"failed",{actualIterations:0,interrupted:!1})}let o=bd(e.id,n.onProgress,n.planModeBlockCheck,n.snapshotUpdater,n.parentOptions.events,n.workflowCorrelation,n.childActivityName,n.maxIterationsPerChild,!0),{systemPromptOverride:s,excludeTools:a,modelOverride:c,providerOverride:l,effortOverride:d}=md(e,$i,yd),u=e.provider===void 0&&e.model===void 0&&l===void 0&&c===void 0?Ei(e.modelHint,!0):void 0,f=e.provider??l??u?.provider??n.parentOptions.provider??"anthropic",m=e.model??c??u?.model??n.parentOptions.model,h;try{let p=await id(),g=hd(e,d,n.parentOptions.effort),w=await Si({provider:f,model:m,effort:g,reasoningMode:n.parentOptions.reasoningMode,agentMode:"sa",maxIter:n.maxIterationsPerChild,abortSignal:n.abortSignal,extensionRuntime:n.parentOptions.extensionRuntime,guardrails:n.guardrails,selfManual:t.ctx.selfManual,skillDynamicContext:t.ctx.skillDynamicContext,context:{gitRoot:t.ctx.gitRoot,executionCwd:t.ctx.executionCwd??t.ctx.gitRoot,...Rr(n),systemPromptOverride:s,excludeTools:a,currentAgentId:e.id,parentAgentId:t.ctx.currentAgentId,inheritedChildTaskRegistry:t.ctx.childTaskRegistry,...t.ctx.skillInvocation?{skillInvocation:t.ctx.skillInvocation}:{}},events:o},r,p,{onFallback:i(({fromProvider:x,toProvider:R,reason:A})=>n.onProgress?.(`[fallback] ${e.id}: ${x} \u2192 ${R} (${A})`),"onFallback")}),y=w.messages.filter(x=>x.role==="assistant").length,b=Ii(w),v={runFn:p,result:w,provider:f,...m?{model:m}:{},...g?{effort:g}:{},scopeCtx:t.ctx,bundle:e,options:n},k=ud(e,n,w),C=k?{totalTokensUsed:0}:await Li({...v,timeoutMs:sd});k&&fd(v);let T=await pd(v);h=yt(e,cd(w.lastText,t),w.success?"completed":"failed",{actualIterations:y,interrupted:w.interrupted===!0,limitReached:w.limitReached===!0,totalTokensUsed:b+C.totalTokensUsed,sessionId:w.sessionId,artifactPaths:kd(w),digest:C.digest,digestFailed:C.attemptFailed,digestPending:k,provider:f,model:m,structured:T})}catch(p){h=yt(e,p instanceof Error?p.message:String(p),"failed",{actualIterations:0,interrupted:!1})}finally{wd(e.id,n.parentOptions.events,n.workflowCorrelation,n.childActivityName)}return h}i(zy,"runReadChildBody");async function Gy(e,t,n){let r={...t,backups:new Map},o=await ad(e,r);return ld(o,r,()=>Xy(e,o,n))}i(Gy,"executeWriteChild");async function Xy(e,t,n){let r=t.ctx,o;try{o=await gd(e,r,n.maxIterationsPerChild)}catch(w){return yt(e,w instanceof Error?w.message:String(w),"failed",{actualIterations:0,interrupted:!1})}let s=bd(e.id,n.onProgress,n.planModeBlockCheck,n.snapshotUpdater,n.parentOptions.events,n.workflowCorrelation,n.childActivityName,n.maxIterationsPerChild,!1),a=Yy(r.gitRoot??r.executionCwd??process.cwd()),{systemPromptOverride:c,excludeTools:l,modelOverride:d,providerOverride:u,effortOverride:f}=md(e,a,Mi),m=e.provider===void 0&&e.model===void 0&&u===void 0&&d===void 0?Ei(e.modelHint,!1):void 0,h=e.provider??u??m?.provider??n.parentOptions.provider??"anthropic",p=e.model??d??m?.model??n.parentOptions.model,g;try{let w=await id(),y=hd(e,f,n.parentOptions.effort),b=await Si({provider:h,model:p,effort:y,reasoningMode:n.parentOptions.reasoningMode,agentMode:"sa",maxIter:n.maxIterationsPerChild,abortSignal:n.abortSignal,extensionRuntime:n.parentOptions.extensionRuntime,guardrails:n.guardrails,selfManual:r.selfManual,skillDynamicContext:r.skillDynamicContext,context:{gitRoot:r.gitRoot,executionCwd:r.executionCwd??r.gitRoot,...Rr(n),systemPromptOverride:c,excludeTools:l,currentAgentId:e.id,parentAgentId:r.currentAgentId,inheritedChildTaskRegistry:r.childTaskRegistry,...r.skillInvocation?{skillInvocation:r.skillInvocation}:{}},events:s},o,w,{onFallback:i(({fromProvider:A,toProvider:D,reason:P})=>n.onProgress?.(`[fallback] ${e.id}: ${A} \u2192 ${D} (${P})`),"onFallback")}),v=b.messages.filter(A=>A.role==="assistant").length,k=Ii(b),C={runFn:w,result:b,provider:h,...p?{model:p}:{},...y?{effort:y}:{},scopeCtx:r,bundle:e,options:n},T=ud(e,n,b),x=T?{totalTokensUsed:0}:await Li({...C,timeoutMs:sd});T&&fd(C);let R=await pd(C);g=yt(e,cd(b.lastText,t),b.success?"completed":"failed",{actualIterations:v,interrupted:b.interrupted===!0,limitReached:b.limitReached===!0,totalTokensUsed:k+x.totalTokensUsed,sessionId:b.sessionId,artifactPaths:kd(b),digest:x.digest,digestFailed:x.attemptFailed,digestPending:T,provider:h,model:p,structured:R})}catch(w){g=yt(e,w instanceof Error?w.message:String(w),"failed",{actualIterations:0,interrupted:!1})}finally{wd(e.id,n.parentOptions.events,n.workflowCorrelation,n.childActivityName)}return g}i(Xy,"runWriteChildBody");async function gd(e,t,n){let r=Q(t),o=t.gitRoot,s=ed.platform(),a=s==="win32"?"Windows":s==="darwin"?"macOS":s,c=s==="win32"?"Shell defaults: Windows. Use: dir, move, copy, del, type. Avoid Unix-only tools like `head`, `tail`, `rm`, `cp`, `mv`.":"Shell defaults: Unix. Use: ls, mv, cp, rm, cat, head, tail.",l=Uy(t.skillInvocation),d=await By(e.objective,o??r),u=["# Child Agent Task","","You are a focused sub-agent executing a specific task in parallel with siblings.",`Complete this task efficiently \u2014 every iteration the parent waits on adds end-to-end latency. You have a hard limit of ${n} iterations.`,"","## Environment",`Working Directory: ${r}`,...e.isolation==="worktree"?["Workflow Isolation: dedicated git worktree requested by the workflow coordinator."]:[],...o&&o!==r?[`Git Root: ${o}`]:[],`Platform: ${a} (${ed.release()})`,c,"All relative paths in your tool calls (read/write/edit/bash) resolve against the Working Directory above. Do NOT `cd` into invented paths \u2014 the working directory is fixed for the duration of this task, and each `bash` call runs in a fresh subprocess so a `cd` would not persist across calls anyway.","","## Objective",e.objective,...d?["",d]:[],"","## Scope",e.scopeSummary??(e.constraints.join(", ")||"No specific scope constraints."),...l?["",l]:[],"","## Constraints",e.readOnly?"- This is a READ-ONLY task. Do NOT modify any files \u2014 the parent dispatched this child specifically for investigation, and a sibling write-child (or the parent itself) will handle any mutations the findings imply.":"- You may modify files within the scope listed above.","- You CANNOT spawn child agents or call dispatch_child_tasks \u2014 recursion is disabled at the tool layer to keep fan-out bounded.",...e.readOnly?[]:["","## Coordination with peers","Other agents may be working in parallel in this same repository. Before making any file modification, briefly check whether your target path could be touched by a peer (e.g. the coordinator dispatched another sibling whose scope overlaps yours, or the user mentioned a parallel thread). If you cannot confidently rule out a conflict, STOP and report back to the coordinator with what you observed rather than proceeding with the edit. The coordinator will resolve the conflict or hand you an updated scope."],"","## Execution Strategy (use parallel tool calls)","- Open broad: scope-scan turn emits parallel `glob` for structure + `grep` for key patterns + `read` on the obvious entry files, all in one response.","- Iterate narrow: deep-read on files identified by the scope scan, again emitting multiple reads in parallel per turn.","- Synthesize early: stop investigating once the evidence is sufficient to answer the objective. Extra iterations waste tokens and delay the parent's synthesis.","- Signal completion with a text-only response (no tool calls). Any final tool call re-opens the turn and forces another LLM round without giving the parent new information."];if(e.evidenceRefs.length>0){u.push("","## Known Evidence");for(let f of e.evidenceRefs){let m=await Jy(f,t);u.push(m)}}return u.push("","## Output Format","When done, provide a concise text summary:","- Key findings (file:line references)","- Severity assessment (if applicable)","- Specific recommendations","Do NOT call any more tools in your final response."),e.outputSchema!==void 0&&u.push("",Ql(e.outputSchema)),u.join(`
183
- `)}i(gd,"buildChildBriefing");var Vy=["file:","diff:","finding:","task_id:"];function SC(e,t,n){for(let r of t??[]){if(!Vy.some(o=>r.startsWith(o)))throw new Error(`wf.runAgent("${e}") evidenceRefs entry "${r}" is not a valid evidence reference. Use one of: file:<path>, diff:<path>, finding:<text>, task_id:<id>. To pass another agent's output, use "task_id:" + that agent's result.taskId \u2014 not its name.`);if(r.startsWith("task_id:")){let o=r.slice(8).trim();if(o.length===0)throw new Error(`wf.runAgent("${e}") evidenceRefs contains an empty "task_id:" reference.`);if(n!==void 0&&!n.has(o))throw new Error(`wf.runAgent("${e}") evidenceRefs references unknown workflow task id "${o}". Pass the taskId from a prior result/handle (result.taskId from wf.runAgent, or handle.taskId from wf.spawnAgent) of an agent spawned earlier in this run \u2014 not an agent name or a guessed id.`)}}}i(SC,"assertValidWorkflowEvidenceRefs");async function Jy(e,t){if(e.startsWith("file:")){let n=e.slice(5);try{let o=(await Ry.readFile(n,"utf-8")).split(`
181
+ `}i(Xl,"formatAgentsForPrompt");var r$="kodax/role/scout",o$="kodax/role/planner",i$="kodax/role/generator",By="kodax/role/worker",$r=ea({name:By,instructions:"KodaX single primary role: plan via todo_update, execute via tool calls, terminate text-only when done \u2014 Sidecar Verifier runs verification out-of-band."}),s$=Object.freeze({worker:$r});function $n(e,t){let n;try{let r=JSON.stringify(t);if(r===void 0)return`${e}: [unserializable input]`;n=r}catch{return`${e}: [unserializable input]`}return n.length>200&&(n=n.slice(0,200)+"\u2026"),`${e}: ${n}`}i($n,"defaultToClassifierInput");function Rr(e,t,n){let r=`MCP[${e}.${t}]`;if(n==null||typeof n!="object"){let c=Gy(n,200);return`${r}: ${c}`}let o=n,s=Hy(o);if(s){let c=Jl(String(s.value),200),l=Vl(o,s.field);return l?`${r}: ${c} | ${l}`:`${r}: ${c}`}let a=Vl(o,null);return`${r}: ${a||"{}"}`}i(Rr,"mcpToClassifierInput");var Wy=["method","command","url","query","action"];function Hy(e){for(let t of Wy)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(n!=null&&n!=="")return{field:t,value:n}}}i(Hy,"pickActionField");function Vl(e,t){let n=Object.entries(e).filter(([c])=>c!==t);if(n.length===0)return"";let r=32,o=[],s=0;for(let[c,l]of n){if(o.length>=3){s+=1;continue}let d=zy(l,r);d?o.push(`${c}=${d}`):s+=1}let a=[];if(o.length>0&&a.push(o.join(", ")),s>0){let c=n.filter(([l])=>!o.some(d=>d.startsWith(`${l}=`))).map(([l])=>l);a.push(`+${s} key${s>1?"s":""}: ${c.join(", ")}`)}return a.join(", ")}i(Vl,"describeStructure");function zy(e,t){if(e===null)return"null";if(typeof e=="string")return e.length<=t?e:void 0;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e)&&e.length<=3){let n=e.map(r=>typeof r=="string"?r:JSON.stringify(r)).join(",");if(n.length<=t)return`[${n}]`}}i(zy,"formatScalarOrShortStructure");function Gy(e,t){if(e===void 0)return"[undefined]";if(e===null)return"null";let n;try{n=typeof e=="string"?e:JSON.stringify(e)??String(e)}catch{n=String(e)}return Jl(n,t)}i(Gy,"formatValue");function Jl(e,t){return e.length>t?e.slice(0,t)+"\u2026":e}i(Jl,"truncate");async function Yl(e,t){let n=typeof e.topic=="string"?e.topic:void 0,r=typeof e.query=="string"?e.query:void 0,o=Ra({topic:n,query:r},{extraTopics:t.selfManual?.topics,productName:t.selfManual?.productName,baseTopics:t.selfManual?.baseTopics}),s=[`# ${o.title}`,"",o.content];return o.sources.length>0&&s.push("",`Sources: ${o.sources.map(a=>a.path).join(", ")}`),o.nextTopics.length>0&&s.push(`Related topics (pass as "topic"): ${o.nextTopics.join(", ")}`),s.join(`
182
+ `)}i(Yl,"toolKodaxManual");function Ky(e){let t=e.trim();return t.startsWith("/skill:")?t.slice(7):t.startsWith("skill:")?t.slice(6):t.startsWith("/")?t.slice(1):t}i(Ky,"normalizeSkillToolName");async function Zl(e,t){let n=e.skill;if(typeof n!="string"||n.trim().length===0)return"[Tool Error] skill: missing required argument `skill` (string).";let r=Ky(n),o=typeof e.args=="string"?e.args:"",s=t.executionCwd??process.cwd(),a=t.gitRoot??s,c=Qn(a);if(c.size===0&&await er(a),!c.has(r)){let l=c.list().map(d=>d.name).sort().join(", ");return`[Tool Error] skill: unknown skill "${r}". Available skills: ${l||"(none)"}.`}try{let l=await c.loadFull(r);return l.disableModelInvocation?`[Tool Error] skill ${r}: Skill "${r}" has model invocation disabled`:(await da(l,o,{workingDirectory:s,projectRoot:a,executeDynamicContext:t.skillDynamicContext?.execute,disableDynamicContext:t.skillDynamicContext?.disable})).content}catch(l){return`[Tool Error] skill ${r}: ${l instanceof Error?l.message:String(l)}`}}i(Zl,"toolSkill");async function Ci(e,t){let n=e.plan;if(!n||typeof n!="string"||n.trim().length===0)return"[Tool Error] exit_plan_mode: Missing required parameter: plan (the finalized plan to present to the user for approval)";if(!t.exitPlanMode)return"[Tool Error] exit_plan_mode: Only available in interactive REPL sessions (no approval UI is wired for this run)";let r=await t.exitPlanMode(n);return r==="not-in-plan-mode"?"[Tool Error] exit_plan_mode: Not currently in plan mode. This tool is only valid while the session is in plan mode. The session is already in implementation mode \u2014 proceed directly with the work.":JSON.stringify(r===!0?{approved:!0,note:"User approved the plan. Permission mode is now accept-edits. Proceed with implementation."}:{approved:!1,note:"User did not approve the plan. Remain in plan mode. Revise the plan based on user feedback and propose again."})}i(Ci,"toolExitPlanMode");import Ir from"node:fs/promises";import ce from"node:path";var Ql=10,ed=1800,Xy=3;function Vy(e){return e==="upstream"||e==="downstream"||e==="both"?e:"both"}i(Vy,"readDirection");function Jy(e){return e===2||e===3?e:1}i(Jy,"readDepth");function id(e){return e instanceof Error?e.message:String(e)}i(id,"errorMessage");async function Qt(e,t,n){try{return await n()}catch(r){t.push(`${e}: ${id(r)}`);return}}i(Qt,"capture");function Or(e,t,n){let r=t?.capability;if(r?.status!=="warming")return!1;let o=r.warnings.join(" ");return n.push(`${e}: ${o||"repo-intelligence index is still warming; retry shortly."}`),!0}i(Or,"recordWarmingGap");function Rn(e){return`${e.name} (${e.filePath}:${e.line})`}i(Rn,"symbolRef");function sd(e){return`${e.label} (${e.root})`}i(sd,"moduleRef");async function td(e){try{return(await Ir.stat(e)).isFile()}catch{return!1}}i(td,"isFile");function ad(e){let t=[];e.gitRoot&&t.push(e.gitRoot),e.executionCwd&&t.push(e.executionCwd),t.push(process.cwd());let n=new Set;for(let r of t){let o=ce.resolve(r);for(let s=0;s<=Xy&&!n.has(o);s+=1){n.add(o);let a=ce.dirname(o);if(a===o)break;o=a}}return[...n]}i(ad,"candidateRoots");function Yy(e,t){let n=ce.normalize(t);if(!n||ce.isAbsolute(n))return;let r=ce.normalize(e);if(!r.endsWith(n))return;let o=r.slice(0,r.length-n.length);return o?ce.resolve(o):void 0}i(Yy,"inferWorkspaceRoot");async function Zy(e,t){if(ce.isAbsolute(e)){let n=ce.resolve(e);return await td(n)?{filePath:n}:void 0}for(let n of ad(t)){let r=ce.resolve(n,e);if(await td(r))return{filePath:r,workspaceRoot:Yy(r,e)??n}}}i(Zy,"resolveRepoFilePath");async function Qy(e,t){if(ce.isAbsolute(e)){let n=ce.resolve(e);try{return await Ir.stat(n),n}catch{return}}for(let n of ad(t)){let r=ce.resolve(n,e);try{return await Ir.stat(r),r}catch{}}}i(Qy,"resolveExistingPath");function cd(e){return[...new Set(e.filter(t=>!!t?.trim()))]}i(cd,"uniqueStrings");function ew(e,t,n){let r=e.split(/\r?\n/),o=Math.max(0,Math.min(r.length-1,t-1)),s=cd([String(o),String(o-1),String(o+1),String(o-2),String(o+2),String(o-3),String(o+3)]).map(a=>Number(a)).filter(a=>a>=0&&a<r.length);for(let a of s){let c=r[a]??"";for(let l of n){let d=c.indexOf(l);if(d>=0)return{line:a+1,column:d+1}}}return{line:o+1,column:1}}i(ew,"locateSymbolLineColumn");async function ld(e,t){let n=await Zy(e.filePath,t);if(!n)return;let r=await Ir.readFile(n.filePath,"utf8"),o=cd([e.name,e.qualifiedName.split(".").at(-1)]),s=ew(r,e.line,o);return{filePath:n.filePath,workspaceRoot:n.workspaceRoot,line:s.line,column:s.column}}i(ld,"locateSymbol");function tw(e){return{gitRoot:e.gitRoot,signal:e.abortSignal,onProgress:e.reportToolProgress}}i(tw,"navRequest");async function nw(e,t,n,r){if(!e.symbolContext)return r.push("LSP validation: symbol identity is required for call hierarchy expansion."),[];if(!n.lspService)return r.push("LSP validation: LSP service is unavailable in this runtime."),[];let o=await ld(e.symbolContext.symbol,n);if(!o)return r.push(`LSP validation: source file not found for ${e.symbolContext.symbol.filePath}.`),[];let s={line:o.line-1,character:o.column-1},a={...tw(n),gitRoot:n.gitRoot??o.workspaceRoot},c=[];if(t==="upstream"||t==="both"){let l=await n.lspService.getIncomingCalls(o.filePath,s,a);c.push({label:`lsp_incoming_calls at ${e.symbolContext.symbol.filePath}:${o.line}:${o.column}`,output:l})}if(t==="downstream"||t==="both"){let l=await n.lspService.getOutgoingCalls(o.filePath,s,a);c.push({label:`lsp_outgoing_calls at ${e.symbolContext.symbol.filePath}:${o.line}:${o.column}`,output:l})}return c}i(nw,"buildLspEvidence");function rw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(rw,"escapeRegexPattern");function ow(e,t,n,r,o){return e.symbolContext?.symbol.name??t??n??o??(r?ce.basename(r):void 0)}i(ow,"firstEvidenceTarget");async function iw(e,t,n,r,o,s,a,c){let l=ow(e,t,n,r,o);if(!l?.trim())return c.push("Text-search validation: no searchable target was available."),[];if(l.length>128)return c.push("Text-search validation: target is too long for a bounded exact-name search."),[];let d=e.symbolContext?await ld(e.symbolContext.symbol,a):void 0,u=s??d?.workspaceRoot??a.gitRoot??e.moduleContext?.module.root??r??".",f=await Qy(u,a)??u,m=await bn({pattern:rw(l),path:f,output_mode:"content",head_limit:16},a);return[{label:`grep exact-name evidence for "${l}"`,output:m}]}i(iw,"buildTextSearchEvidence");function kt(e,t,n){if(n.length===0){e.push(`- ${t}`);return}for(let r of n)e.push(`- ${r}`)}i(kt,"pushList");function en(){return"semantic-index"}i(en,"edgeSource");function sw(e){return Math.max(0,Math.min(1,e))}i(sw,"clampConfidence");function tn(e){let t=e.filter(n=>typeof n=="number"&&Number.isFinite(n));return t.length===0?"unknown":sw(Math.min(...t)).toFixed(2)}i(tn,"edgeConfidence");function nn(e,t,n){return`[source=${e} confidence=${t} evidence=${n}]`}i(nn,"edgeMeta");function $i(e){return`${e.filePath}:${e.line}`}i($i,"symbolEvidence");function nd(e,t){let n=e.impactEstimate?.impactedSymbols.find(r=>r.id===t.symbolId||r.name===t.name&&r.filePath===t.filePath);return n?$i(n):`${t.filePath}:line-unknown`}i(nd,"referenceEvidence");function aw(e,t){return e.impactEstimate?.impactedSymbols.find(n=>n.id===t.symbolId||n.name===t.name&&n.filePath===t.filePath)?.confidence}i(aw,"targetConfidence");function dd(e){return e.entryFiles[0]??e.sampleFiles[0]??e.root}i(dd,"moduleEvidence");function rd(e){return(e.symbolContext?.capability??e.moduleContext?.capability??e.processContext?.capability??e.impactEstimate?.capability)?.engine==="full"?"full":"light"}i(rd,"formatEngine");function cw(e){let t=[e.symbolContext?.confidence,e.moduleContext?.confidence,e.processContext?.confidence,e.impactEstimate?.confidence].filter(r=>typeof r=="number"&&Number.isFinite(r));return t.length===0?"unknown":(t.reduce((r,o)=>r+o,0)/t.length).toFixed(2)}i(cw,"formatConfidence");function lw(e,t,n){e.push("Identity"),t.symbolContext?(e.push(`- Symbol: ${Rn(t.symbolContext.symbol)}`),e.push(`- Symbol module: ${t.symbolContext.symbol.moduleId}`),t.symbolContext.alternatives.length>0&&e.push(`- Alternatives: ${t.symbolContext.alternatives.map(Rn).join("; ")}`)):t.moduleContext?e.push(`- Module: ${sd(t.moduleContext.module)}`):t.processContext?e.push(`- Process: ${t.processContext.process.label} (${t.processContext.process.entryFile})`):e.push(`- Target: ${n}`),e.push("")}i(lw,"renderIdentity");function dw(e,t){if(e.push("Upstream"),t.symbolContext){let n=en();kt(e,"No direct callers found in the light index.",t.symbolContext.callers.map(r=>`${Rn(r)} ${nn(n,tn([t.symbolContext?.confidence,r.confidence]),$i(r))}`))}if(t.moduleContext){let n=en(),r=t.moduleContext.module;kt(e,"No module dependents found in the light index.",r.dependents.map(o=>`Dependent module: ${o} ${nn(n,tn([t.moduleContext?.confidence]),dd(r))}`))}if(t.impactEstimate?.callers.length){let n=en();for(let r of t.impactEstimate.callers)e.push(`- Impact caller: ${Rn(r)} ${nn(n,tn([t.impactEstimate.confidence,r.confidence]),$i(r))}`)}e.push("")}i(dw,"renderUpstream");function uw(e,t){if(e.push("Downstream"),t.symbolContext){let n=t.symbolContext.symbol.callTargets.map(r=>`${r.name} (${nd(t,r)}) ${nn(en(),tn([t.symbolContext?.confidence,t.symbolContext?.symbol.confidence,aw(t,r)]),nd(t,r))}`);kt(e,"No direct callees found in the light index.",n)}if(t.moduleContext){let n=en(),r=t.moduleContext.module;kt(e,"No module dependencies found in the light index.",r.dependencies.map(o=>`Dependency module: ${o} ${nn(n,tn([t.moduleContext?.confidence]),dd(r))}`))}if(t.processContext)for(let n of t.processContext.process.steps.slice(0,8)){let r=n.line===void 0?"":`:${n.line}`,o=n.line===void 0?`${n.filePath}:line-unknown`:`${n.filePath}:${n.line}`;e.push(`- Process ${n.kind}: ${n.symbolName} (${n.filePath}${r}) ${nn(en(),tn([t.processContext.confidence]),o)}`)}e.push("")}i(uw,"renderDownstream");function fw(e,t){if(e.push("Impact"),!t){e.push("- Impact estimate unavailable for this target."),e.push("");return}e.push(`- ${t.summary}`),kt(e,"No impacted modules found in the light index.",t.impactedModules.map(n=>sd(n))),t.impactedSymbols.length>0&&e.push(`- Impacted symbols: ${t.impactedSymbols.map(Rn).join("; ")}`),e.push("")}i(fw,"renderImpact");function pw(e,t){e.push("Evidence"),t.symbolContext&&e.push(`- symbol_context freshness=${t.symbolContext.freshness} confidence=${t.symbolContext.confidence.toFixed(2)}`),t.moduleContext&&e.push(`- module_context freshness=${t.moduleContext.freshness} confidence=${t.moduleContext.confidence.toFixed(2)}`),t.processContext&&e.push(`- process_context freshness=${t.processContext.freshness} confidence=${t.processContext.confidence.toFixed(2)}`),t.impactEstimate&&e.push(`- impact_estimate freshness=${t.impactEstimate.freshness} confidence=${t.impactEstimate.confidence.toFixed(2)}`),e.push("")}i(pw,"renderEvidence");function mw(e){let t=e.trim();if(!t)return["(no output)"];let n=t.length>ed?`${t.slice(0,ed)}...`:t,r=n.split(/\r?\n/).slice(0,Ql);return n.split(/\r?\n/).length>Ql&&r.push("..."),r}i(mw,"compactSupplementOutput");function od(e,t,n){if(n.length!==0){e.push(t);for(let r of n){e.push(`- ${r.label}`);for(let o of mw(r.output))e.push(` ${o}`)}e.push("")}}i(od,"renderSupplementalEvidence");function hw(e,t,n,r){e.push("Gaps"),n==="light"&&e.push("- Light engine uses static heuristics; compiler-accurate call hierarchy is not included yet."),r>1&&e.push(`- Requested depth ${r}; light-mode relationship_scan reports bounded direct edges first.`),kt(e,"No additional gaps recorded.",t)}i(hw,"renderGaps");function gw(e,t,n){let r=[`Relationship scan for ${e}`,"Engine: warming",`Direction: ${t}`,"Status: index warming","","Structural relationships unavailable","- The repository intelligence index is still warming; upstream, downstream, and impact edges are not available yet.",'- This is NOT a "no relationships found" result \u2014 the analysis has not completed.',"- Retry relationship_scan shortly for full structural results.","- Use read, grep, glob, and LSP tools for immediate exploration while the index finishes.","","Gaps"];return kt(r,"No additional gaps recorded.",n),r.join(`
183
+ `)}i(gw,"renderWarmingRelationshipScan");function yw(e,t,n,r,o,s,a){let c=[`Relationship scan for ${e}`,`Engine: ${rd(r)}`,`Direction: ${t}`,`Confidence: ${cw(r)}`,""];return lw(c,r,e),(t==="upstream"||t==="both")&&dw(c,r),(t==="downstream"||t==="both")&&uw(c,r),fw(c,r.impactEstimate),pw(c,r),od(c,"LSP validation",s),od(c,"Text-search validation",a),hw(c,o,rd(r),n),c.join(`
184
+ `)}i(yw,"renderRelationshipScan");async function ud(e,t){try{let n=_(e,"symbol"),r=_(e,"module"),o=_(e,"path"),s=_(e,"entry"),a=_(e,"target_path")??o,c=Vy(e.direction),l=Jy(e.depth),d=e.refresh===!0,u=e.include_lsp===!0,f=e.include_text_search===!0,m=n??r??o??s;if(!m)throw new Error("one of symbol, module, path, or entry is required.");let h=[],p={},g=ie(),w=!1,y=n??(!r&&!o?s:void 0);if(y&&(p.symbolContext=await Qt("symbol_context",h,()=>Sr(t,{symbol:y,module:r,targetPath:a,refresh:d,maxWaitMs:g})),w=Or("symbol_context",p.symbolContext,h)),!w&&(r||o||p.symbolContext)&&(p.moduleContext=await Qt("module_context",h,()=>Sn(t,{module:r??p.symbolContext?.symbol.moduleId,targetPath:a,refresh:!1,maxWaitMs:g})),w=Or("module_context",p.moduleContext,h)),!w&&((c==="downstream"||c==="both")&&(s||y))&&(p.processContext=await Qt("process_context",h,()=>Tr(t,{entry:s,module:r,targetPath:a??p.symbolContext?.symbol.filePath,refresh:!1,maxWaitMs:g})),w=Or("process_context",p.processContext,h)),w||(p.impactEstimate=await Qt("impact_estimate",h,()=>Tn(t,{symbol:y,module:r,path:o,targetPath:a,refresh:!1,maxWaitMs:g})),w=Or("impact_estimate",p.impactEstimate,h)),w)return gw(m,c,h);let v=u&&!w?await Qt("lsp_validation",h,()=>nw(p,c,t,h))??[]:[],k=f&&!w?await Qt("text_search_validation",h,()=>iw(p,y,r,o,s,a,t,h))??[]:[];return yw(m,c,l,p,h,v,k)}catch(n){return`[Tool Error] relationship_scan: ${id(n)}`}}i(ud,"toolRelationshipScan");function fd(e){let t=[e.summary,`Scanned ${e.scanned.modules} modules, ${e.scanned.edges} edges.`];for(let n of e.cycles)t.push(`- [${n.severity}] ${n.hopCount}-hop: ${n.chain.join(" -> ")}`);return t.join(`
185
+ `)}i(fd,"renderCycleAnalysis");async function pd(e,t){try{return fd(await jl(t,{maxWaitMs:ie()}))}catch(n){return`[Tool Error] cyclic_dependencies: ${n instanceof Error?n.message:String(n)}`}}i(pd,"toolCyclicDependencies");var Ie="LSP is unavailable (disabled via KODAX_LSP=0, or no service wired).";function Le(e){return{gitRoot:e.gitRoot,signal:e.abortSignal,onProgress:e.reportToolProgress}}i(Le,"navRequest");function vt(e){let t=Number(e.line);if(!Number.isInteger(t)||t<1)return"`line` is required and must be a 1-based line number.";let n=e.character??e.column,r=n==null?1:Number(n);return!Number.isInteger(r)||r<1?"`character`/`column` must be a 1-based column number.":{line:t-1,character:r-1}}i(vt,"toPosition");function _t(e,t){if(typeof e.path!="string"||!e.path.trim())return`[Tool Error] ${t}: \`path\` is required.`}i(_t,"requiredPath");async function md(e,t){if(!t.lspService)return Ie;let n=_t(e,"lsp_definition");if(n)return n;let r=vt(e);if(typeof r=="string")return`[Tool Error] lsp_definition: ${r}`;let o=B(e.path,t);return t.lspService.getDefinition(o,r,Le(t))}i(md,"toolLspDefinition");async function hd(e,t){if(!t.lspService)return Ie;let n=_t(e,"lsp_hover");if(n)return n;let r=vt(e);if(typeof r=="string")return`[Tool Error] lsp_hover: ${r}`;let o=B(e.path,t);return t.lspService.getHover(o,r,Le(t))}i(hd,"toolLspHover");async function gd(e,t){if(!t.lspService)return Ie;let n=_t(e,"lsp_references");if(n)return n;let r=vt(e);if(typeof r=="string")return`[Tool Error] lsp_references: ${r}`;let o=B(e.path,t);return t.lspService.getReferences(o,r,Le(t))}i(gd,"toolLspReferences");async function yd(e,t){if(!t.lspService)return Ie;if(typeof e.path!="string"||!e.path.trim())return"[Tool Error] lsp_document_symbols: `path` is required.";let n=B(e.path,t);return t.lspService.getDocumentSymbols(n,Le(t))}i(yd,"toolLspDocumentSymbols");async function wd(e,t){if(!t.lspService)return Ie;let n=typeof e.query=="string"?e.query:"";return t.lspService.getWorkspaceSymbols(n,Le(t))}i(wd,"toolLspWorkspaceSymbols");async function bd(e,t){if(!t.lspService)return Ie;let n=_t(e,"lsp_implementation");if(n)return n;let r=vt(e);if(typeof r=="string")return`[Tool Error] lsp_implementation: ${r}`;let o=B(e.path,t);return t.lspService.getImplementation(o,r,Le(t))}i(bd,"toolLspImplementation");async function kd(e,t){if(!t.lspService)return Ie;let n=_t(e,"lsp_prepare_call_hierarchy");if(n)return n;let r=vt(e);if(typeof r=="string")return`[Tool Error] lsp_prepare_call_hierarchy: ${r}`;let o=B(e.path,t);return t.lspService.getPrepareCallHierarchy(o,r,Le(t))}i(kd,"toolLspPrepareCallHierarchy");async function vd(e,t){if(!t.lspService)return Ie;let n=_t(e,"lsp_incoming_calls");if(n)return n;let r=vt(e);if(typeof r=="string")return`[Tool Error] lsp_incoming_calls: ${r}`;let o=B(e.path,t);return t.lspService.getIncomingCalls(o,r,Le(t))}i(vd,"toolLspIncomingCalls");async function _d(e,t){if(!t.lspService)return Ie;let n=_t(e,"lsp_outgoing_calls");if(n)return n;let r=vt(e);if(typeof r=="string")return`[Tool Error] lsp_outgoing_calls: ${r}`;let o=B(e.path,t);return t.lspService.getOutgoingCalls(o,r,Le(t))}i(_d,"toolLspOutgoingCalls");function ww(e){if(!(!e||Array.isArray(e)||typeof e!="object"))return e}i(ww,"asRecord");function Qe(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}i(Qe,"readString");function bw(e){let t=typeof e=="number"&&Number.isFinite(e)?Math.floor(e):10;return Math.max(1,Math.min(20,t))}i(bw,"clampLimit");function kw(e,t){return e>0?t?`Found ${e} MCP capability result(s) for "${t}".`:`Found ${e} MCP capability result(s).`:t?`No MCP capability results for "${t}".`:"No MCP capabilities found."}i(kw,"formatSearchSummary");async function Ri(e,t){try{if(!t.extensionRuntime)throw new Error("mcp_search requires an active extension runtime.");let n=_(e,"query")?.trim()??"",r=_(e,"kind"),o=_(e,"server"),s=bw(e.limit),c=(await t.extensionRuntime.searchCapabilities("mcp",n,{kind:r,limit:s,server:o})).map(d=>{let u=ww(d),f=Qe(u?.kind)??"capability",m=Qe(u?.title)??Qe(u?.name)??Qe(u?.id)??"mcp capability";return{title:`[${f}] ${m}`,locator:Qe(u?.id),snippet:Qe(u?.summary),metadata:{serverId:Qe(u?.serverId),risk:Qe(u?.risk),kind:f}}}),l=c.reduce((d,u)=>(u.locator&&d.push({kind:"provider",label:u.title,value:u.locator}),d),[]);return W({tool:"mcp_search",query:n,scope:"remote",trust:"provider",freshness:"unknown",provider:o?`mcp:${o}`:"mcp",summary:kw(c.length,n),items:c,artifacts:l,metadata:{kind:r??"all",server:o??"all"}},t)}catch(n){return`[Tool Error] mcp_search: ${n instanceof Error?n.message:String(n)}`}}i(Ri,"toolMcpSearch");function le(e,t){if(!(t==null||t==="")){if(typeof t=="string")return`${e}: ${t}`;try{return`${e}: ${JSON.stringify(t,null,2)}`}catch{return`${e}: ${String(t)}`}}}i(le,"formatValue");async function Oi(e,t){try{if(!t.extensionRuntime)throw new Error("mcp_describe requires an active extension runtime.");let n=_(e,"id");if(!n)throw new Error("id is required.");let r=be(n),o=await t.extensionRuntime.describeCapability("mcp",r);if(!o)throw new Error(`Unknown MCP capability: ${r}`);let s=[le("ID",o.id),le("Server",o.serverId),le("Kind",o.kind),le("Name",o.name),le("Title",o.title),le("Summary",o.summary),le("Risk",o.risk),le("URI",o.uri),le("MIME",o.mimeType),le("Input Schema",o.inputSchema),le("Output Schema",o.outputSchema),le("Prompt Args Schema",o.promptArgsSchema),le("Annotations",o.annotations)].filter(a=>a!==void 0).join(`
186
+ `);return W({tool:"mcp_describe",scope:"remote",trust:"provider",freshness:"unknown",provider:"mcp",summary:`Described MCP capability ${r}.`,content:s,items:[],artifacts:[{kind:"provider",label:String(o.name??o.id??r),value:r}],metadata:{capabilityId:r,kind:o.kind,serverId:o.serverId}},t)}catch(n){return`[Tool Error] mcp_describe: ${n instanceof Error?n.message:String(n)}`}}i(Oi,"toolMcpDescribe");function xd(e){if(e!=null){if(typeof e=="string")return e.trim()||void 0;try{return JSON.stringify(e,null,2)}catch{return String(e)}}}i(xd,"stringifyValue");async function Ii(e,t){try{if(!t.extensionRuntime)throw new Error("mcp_call requires an active extension runtime.");let n=_(e,"id");if(!n)throw new Error("id is required.");let r=be(n),o=e.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},s=await t.extensionRuntime.executeCapability("mcp",r,o);return W({tool:"mcp_call",scope:"remote",trust:"provider",freshness:"unknown",provider:"mcp",summary:`Executed MCP tool ${r}.`,content:xd(s.content)??xd(s.structuredContent),items:[],artifacts:[{kind:"provider",label:r,value:r}],metadata:{capabilityId:r,capabilityKind:s.kind,...s.metadata??{}}},t)}catch(n){return`[Tool Error] mcp_call: ${n instanceof Error?n.message:String(n)}`}}i(Ii,"toolMcpCall");function Ed(e){if(e!=null){if(typeof e=="string")return e.trim()||void 0;try{return JSON.stringify(e,null,2)}catch{return String(e)}}}i(Ed,"stringifyValue");async function Li(e,t){try{if(!t.extensionRuntime)throw new Error("mcp_read_resource requires an active extension runtime.");let n=_(e,"id");if(!n)throw new Error("id is required.");let r=be(n),{id:o,...s}=e,a=await t.extensionRuntime.readCapability("mcp",r,s);return W({tool:"mcp_read_resource",scope:"remote",trust:"provider",freshness:"unknown",provider:"mcp",summary:`Read MCP resource ${r}.`,content:Ed(a.content)??Ed(a.structuredContent),items:[],artifacts:[{kind:"provider",label:r,value:r}],metadata:{capabilityId:r,capabilityKind:a.kind,...a.metadata??{}}},t)}catch(n){return`[Tool Error] mcp_read_resource: ${n instanceof Error?n.message:String(n)}`}}i(Li,"toolMcpReadResource");function vw(e){if(e!=null){if(typeof e=="string")return e.trim()||void 0;try{return JSON.stringify(e,null,2)}catch{return String(e)}}}i(vw,"stringifyValue");async function Mi(e,t){try{if(!t.extensionRuntime)throw new Error("mcp_get_prompt requires an active extension runtime.");let n=_(e,"id");if(!n)throw new Error("id is required.");let r=be(n),o=e.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},s=await t.extensionRuntime.getCapabilityPrompt("mcp",r,o);return W({tool:"mcp_get_prompt",scope:"remote",trust:"provider",freshness:"unknown",provider:"mcp",summary:`Retrieved MCP prompt ${r}.`,content:vw(s),items:[],artifacts:[{kind:"provider",label:r,value:r}],metadata:{capabilityId:r,capabilityKind:"prompt"}},t)}catch(n){return`[Tool Error] mcp_get_prompt: ${n instanceof Error?n.message:String(n)}`}}i(Mi,"toolMcpGetPrompt");import{execFile as _w}from"child_process";import{promisify as xw}from"util";import{mkdirSync as Ew}from"fs";import Pi from"path";var rn=xw(_w);function Sw(e){return e?`kodax-wt-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}`:`kodax-wt-${Date.now()}`}i(Sw,"generateBranchName");function Tw(e){return/^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,62}[a-zA-Z0-9]$|^[a-zA-Z0-9]$/.test(e)}i(Tw,"isValidBranchName");async function On(e,t){let n=e.branch_name,r=e.description,o=n??Sw(r);if(!Tw(o))throw new Error(`Invalid branch name: ${o}. Must start and end with alphanumeric, contain only alphanumeric, dots, dashes, or slashes (max 64 chars).`);if(/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(o))throw new Error(`Invalid branch name: ${o}. Path traversal sequences (..) are not allowed.`);let s=t.executionCwd??t.gitRoot??process.cwd(),a=typeof e.base_dir=="string"&&e.base_dir.length>0?Pi.resolve(e.base_dir):void 0,c=a??Pi.resolve(s,".."),l=Pi.resolve(c,`.kodax-worktree-${o}`);if(!l.startsWith(c))throw new Error(`Worktree path escaped expected directory. Resolved to: ${l}`);a&&Ew(a,{recursive:!0});try{await rn("git",["worktree","add","-b",o,l],{cwd:s})}catch(d){let u=d instanceof Error?d.message:String(d);throw new Error(`Failed to create worktree: ${u}`)}return JSON.stringify({path:l,branch:o})}i(On,"toolWorktreeCreate");async function In(e,t){let n=e.action,r=e.worktree_path,o=e.discard_changes;if(!n||n!=="keep"&&n!=="remove")throw new Error('action must be "keep" or "remove"');if(!r)throw new Error("worktree_path is required");let s=t.executionCwd??t.gitRoot??process.cwd();if(n==="keep")return JSON.stringify({restored:!0,message:`Worktree kept at ${r}. Restored CWD.`});if(!o)try{let{stdout:c}=await rn("git",["status","--porcelain"],{cwd:r}),l=c.trim().split(`
187
+ `).filter(f=>f.trim().length>0).length,{stdout:d}=await rn("git",["rev-list","--count","HEAD","--not","--remotes"],{cwd:r}),u=parseInt(d.trim(),10)||0;if(l>0||u>0)throw new Error(`Worktree has ${l} uncommitted file(s) and ${u} local commit(s). Use discard_changes=true to force removal, or commit/push your work first.`)}catch(c){throw c instanceof Error&&c.message.includes("uncommitted")?c:new Error(`Cannot verify worktree state: ${c instanceof Error?c.message:String(c)}`)}let a="";try{let{stdout:c}=await rn("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:r});a=c.trim()}catch{}try{await rn("git",["worktree","remove",r,"--force"],{cwd:s})}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to remove worktree: ${l}`)}if(a)try{await rn("git",["branch","-D",a],{cwd:s})}catch{}return JSON.stringify({restored:!0,message:`Worktree removed. Branch ${a||"(unknown)"} deleted. Restored CWD.`})}i(In,"toolWorktreeRemove");import{execFileSync as Nw}from"child_process";import Dw from"fs/promises";import Ld from"os";function Sd(e,t,n){let r=e?.provider?.trim()||process.env[t]?.trim()||void 0,o=e?.model?.trim()||process.env[n]?.trim()||void 0;if(!(!r&&!o))return{provider:r,model:o}}i(Sd,"resolveTier");function Ni(e,t){let n=Vn()?.modelTiers;if(e==="fast")return t?Sd(n?.fast,"KODAX_FAST_PROVIDER","KODAX_FAST_MODEL"):void 0;if(e==="deep")return Sd(n?.deep,"KODAX_DEEP_PROVIDER","KODAX_DEEP_MODEL")}i(Ni,"resolveModelHintTier");function Aw(){let e=process.env.KODAX_FALLBACK_PROVIDERS?.trim();return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}i(Aw,"resolveFallbackChain");function Td(e){return e instanceof no||e instanceof ro||e instanceof to}i(Td,"isFallbackEligibleError");function Cw(e){return e instanceof no?"rate-limit exhausted":e instanceof ro?"network error":e instanceof to?"provider error":e instanceof Error?e.message:String(e)}i(Cw,"errorReason");async function Di(e,t,n,r){let o=e.provider??"anthropic";try{return await n(e,t)}catch(s){if(e.abortSignal?.aborted||!Td(s))throw s;let a=Aw().filter(l=>l!==o),c=s;for(let l of a){r?.onFallback?.({fromProvider:o,toProvider:l,reason:Cw(c)});try{return await n({...e,provider:l,model:void 0},t)}catch(d){if(e.abortSignal?.aborted||!Td(d))throw d;c=d}}throw c}}i(Di,"invokeChildWithFallback");function $w(e){if(!e.trim())return[];let t=[],n=/(^|\s)\/skill:([\w](?:[\w.\-:]*[\w])?)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"",s=r[2]??"";if(!s)continue;let a=r.index+o.length,c=`/skill:${s}`;t.push({name:s,raw:c,start:a,end:a+c.length})}return t}i($w,"parseInlineSkillReferences");function Rw(e){if(!e.trim())return[];let t=[],n=/(^|\s)\/(?!skill:)([\w](?:[\w.\-:]*[\w])?)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"",s=r[2]??"";if(!s)continue;let a=r.index+o.length,c=`/${s}`;t.push({name:s,raw:c,start:a,end:a+c.length})}return t}i(Rw,"parseBareInlineSlashReferences");function Ad(e){return Array.from(new Set($w(e).map(t=>t.name)))}i(Ad,"uniqueInlineSkillNames");function Cd(e){return Array.from(new Set(Rw(e).map(t=>t.name)))}i(Cd,"uniqueBareInlineSlashNames");function _e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(_e,"isRecord");function Ow(e){return e instanceof Error?e.message:String(e)}i(Ow,"errorMessage");function Mr(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}i(Mr,"safeStringify");function $d(e,t){switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number";case"integer":return typeof e=="number"&&Number.isInteger(e);case"boolean":return typeof e=="boolean";case"object":return _e(e);case"array":return Array.isArray(e);case"null":return e===null;default:return!0}}i($d,"matchesType");function Iw(e,t){return e.some(n=>n===t?!0:typeof n!="object"||typeof t!="object"?!1:Mr(n)===Mr(t))}i(Iw,"enumMatches");function Lr(e,t){return e?`${e}.${t}`:t}i(Lr,"joinPath");function Fi(e,t,n=""){if(!_e(t))return[];let r=[],o=n||"(root)",s=t.type;if(typeof s=="string"&&!$d(e,s))return[`${o}: expected type ${s}`];if(Array.isArray(s)&&!s.some(a=>typeof a=="string"&&$d(e,a)))return[`${o}: expected one of types ${s.join("|")}`];if(Array.isArray(t.enum)&&!Iw(t.enum,e)&&r.push(`${o}: value is not one of the allowed enum values`),_e(e)){let a=_e(t.properties)?t.properties:void 0;if(Array.isArray(t.required))for(let c of t.required)typeof c=="string"&&!(c in e)&&r.push(`${Lr(n,c)}: required field is missing`);if(a){for(let[c,l]of Object.entries(e))c in a&&r.push(...Fi(l,a[c],Lr(n,c)));if(t.additionalProperties===!1)for(let c of Object.keys(e))c in a||r.push(`${Lr(n,c)}: unexpected property (additionalProperties is false)`)}}return Array.isArray(e)&&_e(t.items)&&e.forEach((a,c)=>{r.push(...Fi(a,t.items,`${o}[${c}]`))}),r}i(Fi,"validateAgainstSchema");var Lw=["$ref","$defs","definitions","oneOf","allOf","anyOf","not","if","then","else","const","patternProperties","propertyNames","dependencies","dependentSchemas","dependentRequired","contains","unevaluatedProperties","unevaluatedItems","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties"];function ji(e,t,n){if(_e(e)){for(let r of Lw)r in e&&!n.has(r)&&n.set(r,t||"(root)");if(_e(e.properties))for(let[r,o]of Object.entries(e.properties))ji(o,Lr(t,r),n);_e(e.items)&&ji(e.items,`${t||"(root)"}[]`,n),_e(e.additionalProperties)&&!n.has("additionalProperties (schema form)")&&n.set("additionalProperties (schema form)",t||"(root)")}}i(ji,"collectUnsupportedKeywords");function wR(e){if(!_e(e))return;let t=new Map;if(ji(e,"",t),t.size===0)return;let n=[...t.entries()].map(([r,o])=>`\`${r}\` (at ${o})`).join(", ");throw new Error(`outputSchema uses unsupported JSON-Schema keyword(s): ${n}. The workflow validator supports only type, enum, required, properties, items, and additionalProperties: false (nested object arrays included). Inline the referenced shapes, drop value-constraint keywords, and use that subset.`)}i(wR,"assertSupportedOutputSchema");function Mw(e){let t=e.indexOf("{"),n=e.indexOf("[");return t<0?n:n<0?t:Math.min(t,n)}i(Mw,"firstStructureStart");function Rd(e){let t=Mw(e);if(t<0)return;let n=e[t],r=n==="{"?"}":"]",o=0,s=!1,a=!1;for(let c=t;c<e.length;c+=1){let l=e[c];if(s){a?a=!1:l==="\\"?a=!0:l==='"'&&(s=!1);continue}if(l==='"'){s=!0;continue}if(l===n)o+=1;else if(l===r&&(o-=1,o===0))return e.slice(t,c+1)}}i(Rd,"balancedStructure");function Pw(e){if(typeof e!="string"||e.trim().length===0)return;let t=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(n=t.exec(e))!==null;){let o=n[1]?.trim();o&&(r=o)}return r?Rd(r)??r:Rd(e)}i(Pw,"extractJsonCandidate");function Ui(e,t){let n=Pw(e);if(n===void 0)return{ok:!1,errors:["no JSON value was found in the output"]};let r;try{r=JSON.parse(n)}catch(s){return{ok:!1,errors:[`output was not valid JSON: ${Ow(s)}`]}}let o=Fi(r,t);return{ok:o.length===0,value:r,errors:o}}i(Ui,"evaluateStructuredOutput");function Od(e){return["## Required Output Format","After your analysis, end your response with a single fenced ```json code block containing ONLY a JSON value that matches the JSON Schema below. Put nothing after the closing fence.","Schema:","```json",Mr(e),"```"].join(`
188
+ `)}i(Od,"buildStructuredOutputInstruction");function Id(e,t){return["Your previous response did not produce a valid result object for the workflow.","Problems:",...e.map(n=>`- ${n}`),"Re-emit ONLY a single fenced ```json code block containing a JSON value that matches this schema. No prose, nothing after the closing fence.","Schema:","```json",Mr(t),"```"].join(`
189
+ `)}i(Id,"buildStructuredOutputRepairPrompt");var qi,Pr;async function Fd(){if(qi)return qi;if(!Pr){let e="./agent.js";Pr=import("./agent-E74WVAFR.js").then(t=>{let n=t.runKodaX;if(typeof n!="function")throw new Error("[child-executor] Agent module loaded but `runKodaX` export is missing or not a function. This indicates an API break in packages/coding/src/agent.ts. Check that `export { runKodaX }` is still present.");return qi=n,n}).catch(t=>{if(Pr=void 0,t instanceof Error&&t.message.startsWith("[child-executor]"))throw t;let n=t instanceof Error?t.message:String(t);throw new Error(`[child-executor] Failed to lazy-load agent module (\`${e}\`) for dispatch_child_task. This usually means the @kodax-ai/coding build is broken or out of date. Underlying cause: ${n}`)})}return Pr}i(Fd,"getRunKodaX");var Fw=["You are summarizing your own just-completed child-agent report for a parent workflow.","Do not use tools. Do not continue investigation. Produce only the digest."].join(`
190
+ `),jw=["Create a short user-facing digest of your previous report for the parent workflow.","Return only 2-4 bullet lines.","Each bullet must be concrete: a finding, decision, risk, evidence pointer, unresolved question, or next action.","Use the same natural language as the user request or your report.","Do not include a title, table, generic preamble, or workflow handoff markers."].join(`
191
+ `),Uw=4,jd=1e4,qw=45e3,Bw=40;function Nr(e){let t={};return e.parentOptions.repoIntelligenceMode!==void 0&&(t.repoIntelligenceMode=e.parentOptions.repoIntelligenceMode),e.parentOptions.repoIntelligenceTrace!==void 0&&(t.repoIntelligenceTrace=e.parentOptions.repoIntelligenceTrace),t}i(Nr,"inheritRepoIntelligenceContext");async function Wi(e,t,n){if(e.length===0)return Dd;let r=e.filter(f=>f.readOnly),o=e.filter(f=>!f.readOnly),s=db(o,n.parentRole,n.parentHarness),a=[...r,...s];if(a.length===0)return Dd;let c=[],l=[],d=n.onProgress??(()=>{});d(`Starting ${a.length} child tasks in parallel`);let u=await ia({bundles:a,runOne:i(f=>f.readOnly?Qw(f,t,n):tb(f,t,n),"runOne"),maxParallel:n.maxParallel,abortSignal:n.abortSignal,onProgress:i((f,m)=>{f.kind==="start"?d(`[${m.completedCount}/${m.totalCount}] Running: ${f.bundle.id}`):f.kind==="item-done"&&d(`[${m.completedCount}/${m.totalCount}] Done: ${f.bundle.id} \u2192 ${f.result.status}`)},"onProgress")});for(let f of u.results)f.status==="fulfilled"?c.push(f.value):c.push(xt(f.bundle,`[Crash] ${f.reason.message}`,"failed"));for(let f of u.cancelled)l.push(f.id);return lb(a,c,l)}i(Wi,"executeChildAgents");function Ww(e){let t=JSON.parse(e);if(typeof t!="object"||t===null||!("path"in t))throw new Error("worktree_create returned an invalid payload");let n=t.path;if(typeof n!="string"||n.length===0)throw new Error("worktree_create returned an invalid path");return n}i(Ww,"readWorktreePath");async function Ud(e,t){if(e.isolation!=="worktree")return{ctx:t};let n=await On({description:`workflow-${e.id}`,...t.workflowWorktreeBaseDir?{base_dir:t.workflowWorktreeBaseDir}:{}},t),r=Ww(n);return{ctx:{...t,gitRoot:r,executionCwd:r},worktreePath:r}}i(Ud,"prepareChildIsolationScope");function qd(e,t){return t.worktreePath?[`[Workflow worktree: ${t.worktreePath}]`,e].join(`
192
+ `):e}i(qd,"annotateWorktreeSummary");async function Md(e,t){if(e.worktreePath)try{await In({action:"remove",worktree_path:e.worktreePath,discard_changes:!1},t);return}catch(n){return`[Workflow worktree cleanup failed: ${n instanceof Error?n.message:String(n)}]`}}i(Md,"cleanupChildIsolationScope");function Hw(e,t){return t?{...e,summary:`${e.summary}
193
+ ${t}`}:e}i(Hw,"appendCleanupWarning");async function Bd(e,t,n){let r;try{r=await n()}catch(s){throw await Md(e,t),s}let o=await Md(e,t);return Hw(r,o)}i(Bd,"withChildIsolationCleanup");function Hi(e){let t=e.usage?.totalTokens??e.contextTokenSnapshot?.usage?.totalTokens??e.contextTokenSnapshot?.currentTokens??0;return Number.isFinite(t)&&t>0?t:0}i(Hi,"readChildTokenUsage");function zw(e){let t=e.split(/\r?\n+/).map(n=>n.trim()).filter(n=>n.length>0).filter(n=>!/\[\/?workflow handoff\]/i.test(n)).filter(n=>!/^```/.test(n));if(t.length!==0)return t.slice(0,Uw).join(`
194
+ `)}i(zw,"normalizeWorkflowChildDigest");function Wd(e,t){return e.workflowChild===!0&&e.abortSignal?.aborted!==!0&&t.success===!0&&t.interrupted!==!0&&t.lastText.trim().length>0}i(Wd,"shouldCreateWorkflowChildDigest");function Gw(e){return e.replace(/[\\/]+SKILL\.md$/i,"")}i(Gw,"deriveSkillRootFromSkillFile");function Kw(e,t){return e.split(/\r?\n/).find(r=>r.trim().startsWith(t))?.trim().slice(t.length).trim()||void 0}i(Kw,"extractPrefixedLine");function Pd(e,t,n){let r=e.split(/\r?\n/),o=r.findIndex(a=>a.trim()===t);if(o<0)return[];let s=[];for(let a of r.slice(o+1)){let c=a.trim();if(!c){if(s.length>0)break;continue}if(!c.startsWith("- ")||(s.push(c),s.length>=n))break}return s}i(Pd,"extractListSection");function Xw(e){if(!e)return;let t=Kw(e.expandedContent,"Skill root:")??Gw(e.path),n=Pd(e.expandedContent,"Support roots:",12),r=Pd(e.expandedContent,"Support file inventory:",Bw);return["## Active Skill Resources",`Parent task is using skill "${e.name}". If this child needs skill support files, use these exact paths instead of broad home/workspace searches.`,`- Skill file: ${e.path}`,t?`- Skill root: ${t}`:void 0,n.length>0?"Support roots:":void 0,...n,r.length>0?"Selected support files:":void 0,...r,n.length>0?"If a needed support file is not listed above, combine its relative path with the matching support root.":void 0].filter(s=>!!s).join(`
195
+ `)}i(Xw,"buildActiveSkillResourceBriefing");async function Vw(e,t,n){let r=Cd(e).filter(o=>!t.includes(o)&&!e.includes(`<skill name="${o}"`));if(r.length===0)return[];try{let o=Qn(n);return o.size===0&&await er(n),r.filter(s=>o.has(s))}catch{return[]}}i(Vw,"resolveKnownBareSlashSkillNames");async function Jw(e,t){let n=Ad(e).filter(s=>!e.includes(`<skill name="${s}"`)),r=await Vw(e,n,t),o=Array.from(new Set([...n,...r]));if(o.length!==0)return["## Referenced Skills",`The objective mentions skill reference(s): ${o.map(s=>`/skill:${s}`).join(", ")}.`,"Before acting on those instructions, invoke the `skill` tool for each referenced skill that is not already expanded in this briefing, then follow the returned skill instructions. Do not infer skill-specific rules from the slash token alone."].join(`
196
+ `)}i(Jw,"buildReferencedSkillBriefing");function Hd(e,t,n){return t.workflowDigestMode==="async"&&e.isolation!=="worktree"&&t.onWorkflowChildDigest!==void 0&&Wd(t,n)}i(Hd,"shouldRunWorkflowDigestAsync");async function zi(e){if(!Wd(e.options,e.result))return{totalTokensUsed:0};let t=new AbortController,n=i(()=>t.abort(),"onParentAbort");e.options.abortSignal?.addEventListener("abort",n);let r=setTimeout(()=>t.abort(),e.timeoutMs);try{let o=await e.runFn({provider:e.provider,...e.model?{model:e.model}:{},effort:e.effort??e.options.parentOptions.effort,reasoningMode:e.options.parentOptions.reasoningMode,agentMode:"sa",maxIter:1,abortSignal:t.signal,extensionRuntime:e.options.parentOptions.extensionRuntime,guardrails:e.options.guardrails,session:{initialMessages:e.result.messages},context:{gitRoot:e.scopeCtx.gitRoot,executionCwd:e.scopeCtx.executionCwd??e.scopeCtx.gitRoot,...Nr(e.options),systemPromptOverride:Fw,excludeTools:Ln().map(c=>c.name),currentAgentId:e.bundle.id,parentAgentId:e.scopeCtx.currentAgentId,inheritedChildTaskRegistry:e.scopeCtx.childTaskRegistry}},jw),s=zw(o.lastText),a=Hi(o);return s?{digest:s,totalTokensUsed:a}:{totalTokensUsed:a,attemptFailed:!0}}catch{return{totalTokensUsed:0,attemptFailed:!0}}finally{clearTimeout(r),e.options.abortSignal?.removeEventListener("abort",n)}}i(zi,"createWorkflowChildDigest");function zd(e){zi({...e,timeoutMs:qw}).then(t=>{try{e.options.onWorkflowChildDigest?.({childId:e.bundle.id,...t.digest?{digest:t.digest}:{},...t.attemptFailed?{digestFailed:!0}:{},totalTokensUsed:t.totalTokensUsed})}catch{}})}i(zd,"scheduleWorkflowChildDigest");var Yw=["You are re-formatting your own just-completed report into the JSON a parent workflow requires.","Do not use tools. Do not continue investigation. Output only the JSON block."].join(`
197
+ `),Zw=15e3;async function Gd(e){let t=e.bundle.outputSchema;if(t===void 0)return;let n=Ui(e.result.lastText,t);if(n.ok||e.options.abortSignal?.aborted===!0||e.result.success!==!0||e.result.interrupted===!0)return n.value;let r=new AbortController,o=i(()=>r.abort(),"onParentAbort");e.options.abortSignal?.addEventListener("abort",o);let s=setTimeout(()=>r.abort(),Zw);try{let a=await e.runFn({provider:e.provider,...e.model?{model:e.model}:{},effort:e.effort??e.options.parentOptions.effort,reasoningMode:e.options.parentOptions.reasoningMode,agentMode:"sa",maxIter:1,abortSignal:r.signal,extensionRuntime:e.options.parentOptions.extensionRuntime,guardrails:e.options.guardrails,session:{initialMessages:e.result.messages},context:{gitRoot:e.scopeCtx.gitRoot,executionCwd:e.scopeCtx.executionCwd??e.scopeCtx.gitRoot,...Nr(e.options),systemPromptOverride:Yw,excludeTools:Ln().map(l=>l.name),currentAgentId:e.bundle.id,parentAgentId:e.scopeCtx.currentAgentId,inheritedChildTaskRegistry:e.scopeCtx.childTaskRegistry}},Id(n.errors,t));return Ui(a.lastText,t).value??n.value}catch{return n.value}finally{clearTimeout(s),e.options.abortSignal?.removeEventListener("abort",o)}}i(Gd,"resolveChildStructuredOutput");function Kd(e,t,n){if(!e.specialistName)return{systemPromptOverride:t,excludeTools:n};let r=Me(e.specialistName);if(!r)return{systemPromptOverride:t,excludeTools:n};let o={...r.model?{modelOverride:r.model}:{},...r.provider?{providerOverride:r.provider}:{},...r.effort?{effortOverride:r.effort}:{}},s=typeof r.instructions=="string"?r.instructions:t;if(!r.tools||r.tools.length===0)return{systemPromptOverride:s,excludeTools:n,...o};let a=new Set(r.tools.map(u=>u.name)),c=new Set(n),d=Ln().map(u=>u.name).filter(u=>c.has(u)||!a.has(u));return{systemPromptOverride:s,excludeTools:d,...o}}i(Kd,"resolveSpecialistOverride");function Nd(e){if(e===void 0||e.trim().length===0)return;let t=lt(e);return t==="auto"?void 0:t}i(Nd,"normalizeChildEffort");function Xd(e,t,n){let r=Nd(t),o=Nd(e.effort);if(r!==void 0&&o!==void 0&&o!==r)throw new Error(`specialist "${e.specialistName??"unknown"}" locks effort "${r}", but dispatch requested "${o}". Remove the dispatch effort or match the specialist effort.`);return r??o??n}i(Xd,"resolveChildEffort");async function Qw(e,t,n){let r=await Ud(e,t);return Bd(r,t,()=>eb(e,r,n))}i(Qw,"executeReadChild");async function eb(e,t,n){let r;try{r=await Vd(e,t.ctx,n.maxIterationsPerChild)}catch(p){return xt(e,p instanceof Error?p.message:String(p),"failed",{actualIterations:0,interrupted:!1})}let o=Zd(e.id,n.onProgress,n.planModeBlockCheck,n.snapshotUpdater,n.parentOptions.events,n.workflowCorrelation,n.childActivityName,n.maxIterationsPerChild,!0),{systemPromptOverride:s,excludeTools:a,modelOverride:c,providerOverride:l,effortOverride:d}=Kd(e,Bi,Jd),u=e.provider===void 0&&e.model===void 0&&l===void 0&&c===void 0?Ni(e.modelHint,!0):void 0,f=e.provider??l??u?.provider??n.parentOptions.provider??"anthropic",m=e.model??c??u?.model??n.parentOptions.model,h;try{let p=await Fd(),g=Xd(e,d,n.parentOptions.effort),w=await Di({provider:f,model:m,effort:g,reasoningMode:n.parentOptions.reasoningMode,agentMode:"sa",maxIter:n.maxIterationsPerChild,abortSignal:n.abortSignal,extensionRuntime:n.parentOptions.extensionRuntime,guardrails:n.guardrails,selfManual:t.ctx.selfManual,skillDynamicContext:t.ctx.skillDynamicContext,context:{gitRoot:t.ctx.gitRoot,executionCwd:t.ctx.executionCwd??t.ctx.gitRoot,...Nr(n),systemPromptOverride:s,excludeTools:a,currentAgentId:e.id,parentAgentId:t.ctx.currentAgentId,inheritedChildTaskRegistry:t.ctx.childTaskRegistry,...t.ctx.skillInvocation?{skillInvocation:t.ctx.skillInvocation}:{}},events:o},r,p,{onFallback:i(({fromProvider:x,toProvider:R,reason:A})=>n.onProgress?.(`[fallback] ${e.id}: ${x} \u2192 ${R} (${A})`),"onFallback")}),y=w.messages.filter(x=>x.role==="assistant").length,b=Hi(w),v={runFn:p,result:w,provider:f,...m?{model:m}:{},...g?{effort:g}:{},scopeCtx:t.ctx,bundle:e,options:n},k=Hd(e,n,w),$=k?{totalTokensUsed:0}:await zi({...v,timeoutMs:jd});k&&zd(v);let S=await Gd(v);h=xt(e,qd(w.lastText,t),w.success?"completed":"failed",{actualIterations:y,interrupted:w.interrupted===!0,limitReached:w.limitReached===!0,totalTokensUsed:b+$.totalTokensUsed,sessionId:w.sessionId,artifactPaths:Qd(w),digest:$.digest,digestFailed:$.attemptFailed,digestPending:k,provider:f,model:m,structured:S})}catch(p){h=xt(e,p instanceof Error?p.message:String(p),"failed",{actualIterations:0,interrupted:!1})}finally{Yd(e.id,n.parentOptions.events,n.workflowCorrelation,n.childActivityName)}return h}i(eb,"runReadChildBody");async function tb(e,t,n){let r={...t,backups:new Map},o=await Ud(e,r);return Bd(o,r,()=>nb(e,o,n))}i(tb,"executeWriteChild");async function nb(e,t,n){let r=t.ctx,o;try{o=await Vd(e,r,n.maxIterationsPerChild)}catch(w){return xt(e,w instanceof Error?w.message:String(w),"failed",{actualIterations:0,interrupted:!1})}let s=Zd(e.id,n.onProgress,n.planModeBlockCheck,n.snapshotUpdater,n.parentOptions.events,n.workflowCorrelation,n.childActivityName,n.maxIterationsPerChild,!1),a=ib(r.gitRoot??r.executionCwd??process.cwd()),{systemPromptOverride:c,excludeTools:l,modelOverride:d,providerOverride:u,effortOverride:f}=Kd(e,a,Gi),m=e.provider===void 0&&e.model===void 0&&u===void 0&&d===void 0?Ni(e.modelHint,!1):void 0,h=e.provider??u??m?.provider??n.parentOptions.provider??"anthropic",p=e.model??d??m?.model??n.parentOptions.model,g;try{let w=await Fd(),y=Xd(e,f,n.parentOptions.effort),b=await Di({provider:h,model:p,effort:y,reasoningMode:n.parentOptions.reasoningMode,agentMode:"sa",maxIter:n.maxIterationsPerChild,abortSignal:n.abortSignal,extensionRuntime:n.parentOptions.extensionRuntime,guardrails:n.guardrails,selfManual:r.selfManual,skillDynamicContext:r.skillDynamicContext,context:{gitRoot:r.gitRoot,executionCwd:r.executionCwd??r.gitRoot,...Nr(n),systemPromptOverride:c,excludeTools:l,currentAgentId:e.id,parentAgentId:r.currentAgentId,inheritedChildTaskRegistry:r.childTaskRegistry,...r.skillInvocation?{skillInvocation:r.skillInvocation}:{}},events:s},o,w,{onFallback:i(({fromProvider:A,toProvider:O,reason:P})=>n.onProgress?.(`[fallback] ${e.id}: ${A} \u2192 ${O} (${P})`),"onFallback")}),v=b.messages.filter(A=>A.role==="assistant").length,k=Hi(b),$={runFn:w,result:b,provider:h,...p?{model:p}:{},...y?{effort:y}:{},scopeCtx:r,bundle:e,options:n},S=Hd(e,n,b),x=S?{totalTokensUsed:0}:await zi({...$,timeoutMs:jd});S&&zd($);let R=await Gd($);g=xt(e,qd(b.lastText,t),b.success?"completed":"failed",{actualIterations:v,interrupted:b.interrupted===!0,limitReached:b.limitReached===!0,totalTokensUsed:k+x.totalTokensUsed,sessionId:b.sessionId,artifactPaths:Qd(b),digest:x.digest,digestFailed:x.attemptFailed,digestPending:S,provider:h,model:p,structured:R})}catch(w){g=xt(e,w instanceof Error?w.message:String(w),"failed",{actualIterations:0,interrupted:!1})}finally{Yd(e.id,n.parentOptions.events,n.workflowCorrelation,n.childActivityName)}return g}i(nb,"runWriteChildBody");async function Vd(e,t,n){let r=Z(t),o=t.gitRoot,s=Ld.platform(),a=s==="win32"?"Windows":s==="darwin"?"macOS":s,c=s==="win32"?"Shell defaults: Windows. Use: dir, move, copy, del, type. Avoid Unix-only tools like `head`, `tail`, `rm`, `cp`, `mv`.":"Shell defaults: Unix. Use: ls, mv, cp, rm, cat, head, tail.",l=Xw(t.skillInvocation),d=await Jw(e.objective,o??r),u=["# Child Agent Task","","You are a focused sub-agent executing a specific task in parallel with siblings.",`Complete this task efficiently \u2014 every iteration the parent waits on adds end-to-end latency. You have a hard limit of ${n} iterations.`,"","## Environment",`Working Directory: ${r}`,...e.isolation==="worktree"?["Workflow Isolation: dedicated git worktree requested by the workflow coordinator."]:[],...o&&o!==r?[`Git Root: ${o}`]:[],`Platform: ${a} (${Ld.release()})`,c,"All relative paths in your tool calls (read/write/edit/bash) resolve against the Working Directory above. Do NOT `cd` into invented paths \u2014 the working directory is fixed for the duration of this task, and each `bash` call runs in a fresh subprocess so a `cd` would not persist across calls anyway.","","## Objective",e.objective,...d?["",d]:[],"","## Scope",e.scopeSummary??(e.constraints.join(", ")||"No specific scope constraints."),...l?["",l]:[],"","## Constraints",e.readOnly?"- This is a READ-ONLY task. Do NOT modify any files \u2014 the parent dispatched this child specifically for investigation, and a sibling write-child (or the parent itself) will handle any mutations the findings imply.":"- You may modify files within the scope listed above.","- You CANNOT spawn child agents or call dispatch_child_tasks \u2014 recursion is disabled at the tool layer to keep fan-out bounded.",...e.readOnly?[]:["","## Coordination with peers","Other agents may be working in parallel in this same repository. Before making any file modification, briefly check whether your target path could be touched by a peer (e.g. the coordinator dispatched another sibling whose scope overlaps yours, or the user mentioned a parallel thread). If you cannot confidently rule out a conflict, STOP and report back to the coordinator with what you observed rather than proceeding with the edit. The coordinator will resolve the conflict or hand you an updated scope."],"","## Execution Strategy (use parallel tool calls)","- Open broad: scope-scan turn emits parallel `glob` for structure + `grep` for key patterns + `read` on the obvious entry files, all in one response.","- Iterate narrow: deep-read on files identified by the scope scan, again emitting multiple reads in parallel per turn.","- Synthesize early: stop investigating once the evidence is sufficient to answer the objective. Extra iterations waste tokens and delay the parent's synthesis.","- Signal completion with a text-only response (no tool calls). Any final tool call re-opens the turn and forces another LLM round without giving the parent new information."];if(e.evidenceRefs.length>0){u.push("","## Known Evidence");for(let f of e.evidenceRefs){let m=await ob(f,t);u.push(m)}}return u.push("","## Output Format","When done, provide a concise text summary:","- Key findings (file:line references)","- Severity assessment (if applicable)","- Specific recommendations","Do NOT call any more tools in your final response."),e.outputSchema!==void 0&&u.push("",Od(e.outputSchema)),u.join(`
198
+ `)}i(Vd,"buildChildBriefing");var rb=["file:","diff:","finding:","task_id:"];function PR(e,t,n){for(let r of t??[]){if(!rb.some(o=>r.startsWith(o)))throw new Error(`wf.runAgent("${e}") evidenceRefs entry "${r}" is not a valid evidence reference. Use one of: file:<path>, diff:<path>, finding:<text>, task_id:<id>. To pass another agent's output, use "task_id:" + that agent's result.taskId \u2014 not its name.`);if(r.startsWith("task_id:")){let o=r.slice(8).trim();if(o.length===0)throw new Error(`wf.runAgent("${e}") evidenceRefs contains an empty "task_id:" reference.`);if(n!==void 0&&!n.has(o))throw new Error(`wf.runAgent("${e}") evidenceRefs references unknown workflow task id "${o}". Pass the taskId from a prior result/handle (result.taskId from wf.runAgent, or handle.taskId from wf.spawnAgent) of an agent spawned earlier in this run \u2014 not an agent name or a guessed id.`)}}}i(PR,"assertValidWorkflowEvidenceRefs");async function ob(e,t){if(e.startsWith("file:")){let n=e.slice(5);try{let o=(await Dw.readFile(n,"utf-8")).split(`
184
199
  `).slice(0,200);return`### ${n}
185
200
  \`\`\`
186
201
  ${o.join(`
187
202
  `)}
188
- \`\`\``}catch{return`- ${e} (could not read file)`}}if(e.startsWith("diff:")){let n=e.slice(5);try{let r=Cy("git",["diff","HEAD","--",n],{cwd:t.gitRoot??void 0,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1e4});return r.length>0?`### diff: ${n}
203
+ \`\`\``}catch{return`- ${e} (could not read file)`}}if(e.startsWith("diff:")){let n=e.slice(5);try{let r=Nw("git",["diff","HEAD","--",n],{cwd:t.gitRoot??void 0,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1e4});return r.length>0?`### diff: ${n}
189
204
  \`\`\`diff
190
205
  ${r.slice(0,4e3)}
191
206
  \`\`\``:`- ${e} (no changes)`}catch{return`- ${e} (could not get diff)`}}if(e.startsWith("finding:"))return`- **Known fact**: ${e.slice(8)}`;if(e.startsWith("task_id:")){let n=e.slice(8).trim();if(!n)return"- [evidence_refs error] task_id: prefix is missing the child id (write `task_id:<id>` where <id> is the value returned from a prior dispatch_child_task call)";let r=t.childProgressSnapshots?.get(n);if(!r)return`- task_id:${n} (not found \u2014 child unknown, already cap-pruned, or sync-dispatch mode without snapshot map; verify the id matches a recent dispatch_child_task return)`;if(r.status==="running")return`- task_id:${n} (sibling still running \u2014 its result is not available to you yet; proceed with what you have, or note this dependency in your summary so the coordinator can follow up)`;let o=1e4,s="```",a=r.finalText??"(no final text recorded)",c=a.length>o?`${a.slice(0,o)}
192
207
  [truncated ${a.length-o} chars; full sibling output is not included in this child briefing. Proceed with this excerpt, or note the dependency for the coordinator]`:a;return c.includes(s)&&(c=c.replace(/```/g,"`\u200B`\u200B`")),`### task: ${n} (${r.status})
193
208
  ${s}
194
209
  ${c}
195
- ${s}`}return`- [evidence_refs error] unrecognized prefix in "${e}" \u2014 valid prefixes: file:, diff:, finding:, task_id:`}i(Jy,"resolveEvidenceRef");var $i=["You are a focused sub-agent executing a specific task assigned by a parent agent.","Use the available tools to complete the task fully. Do not gold-plate, but do not leave it half-done.","","## Tool Use \u2014 Prefer Parallel Calls","","When multiple tool calls are independent of each other, emit them all in the SAME response. The execution engine runs non-bash tools concurrently via Promise.all, so serial calls add real wall-clock latency the parent waits on.","","Concrete rules:","- For module exploration or change review, lead with pull-tools (`module_context` / `symbol_context` / `changed_scope` / `changed_diff_bundle`) \u2014 each replaces several read+grep calls so the same investigation finishes in fewer turns.","- For single-file lookup or byte-exact verification, use `glob` + `grep` + targeted `read`.","- When you need multiple independent tool calls (pull-tools, reads, or greps), emit them all in one response. Only serialize when a later call genuinely depends on an earlier result (e.g., you need a file path from grep before you can read it).","- Open broad with a parallel fan-out covering the obvious scope axes, then narrow on follow-up turns. Prefer a few targeted calls over many tiny sequential probes.","","## Peer Communication","","You can send short messages to other in-flight agents in this session with `send_message`:",'- `send_message(to="<peer task_id>", content="\u2026")` \u2014 notify a sibling child that your work overlaps with theirs or that you found something they need to know.','- `send_message(to="worker", content="\u2026")` \u2014 surface a mid-flight finding to your parent Worker (drains when the Worker next yields).','- `send_message(to="*", content="\u2026")` \u2014 broadcast to every sibling plus the parent Worker. Capped at 20 recipients per call.',"","Send a peer message when it would change another agent's plan: a file you both edit, a fact you discovered that changes their scope, a blocker the parent should know about. Do not send routine status pings \u2014 peer chatter that does not change anyone's plan is noise.","",'Forwarding: peer wrappers carry a `seen_by="A,B,\u2026"` attribute listing every agent that has already handled the chain. If you intentionally forward a received peer message, pass that list as the `seen_by` parameter so the tool can reject cycles (forwarding back to a prior sender) and cap chain depth. Omit `seen_by` for fresh sends \u2014 the tool always auto-appends you.',"","## Execution Guidelines","- Focus on the objective described in the user message. Do not deviate.","- Write your final report in the same natural language as the objective you were given, so it reaches the user in their language. Keep code, file paths, and quoted evidence in their source language.","- When you have sufficient evidence, stop investigating and synthesize your findings.","- Your final response MUST be text only \u2014 the parent reads your text directly as the dispatch result, and a final tool call would re-open the turn and force another LLM round without giving the parent new information.","","## Output Format","Respond with a concise report covering:","- Key findings with specific file:line references","- Severity or priority assessment (if applicable)","- Concrete recommendations","","Keep the report focused \u2014 the parent will relay it to the user."].join(`
196
- `);function Yy(e){let t=ml({cwd:e,projectRoot:e}),n=hl(t);return n?[$i,"","Project rules apply to your mutations. Follow them as the parent agent would:",n].join(`
197
- `):$i}i(Yy,"buildWriteSystemPrompt");var Mi=["emit_managed_protocol","dispatch_child_task","task_stop","task_output","ask_user_question","worktree_create","worktree_remove","exit_plan_mode"],yd=[...Mi,"write","edit","multi_edit","insert_after_anchor","undo"],Qy=new Set(Mi),Zy=new Set(yd);function ew(e,t,n){return{...t!==void 0?{workflowCorrelation:t}:{},childAgentId:e,childAgentName:n??e,liveOnly:!0}}i(ew,"childActivityEventMeta");function wd(e,t,n,r){t?.onChildActivityEnd?.(ew(e,n,r))}i(wd,"emitChildActivityEnd");function bd(e,t,n,r,o,s,a,c=200,l=!1){let d=0,u=c,f=0,m=l?Zy:Qy,h=150,p=i((y,b=!1)=>{if(!t)return;let v=Date.now();!b&&v-f<h||(f=v,t(y))},"throttledProgress"),g=i((y,b={})=>{let v=s??y?.workflowCorrelation,k={...v!==void 0?{workflowCorrelation:v}:{},...y?.childAgentId!==void 0?{childAgentId:y.childAgentId}:{childAgentId:e},...y?.childAgentName!==void 0?{childAgentName:y.childAgentName}:{childAgentName:a??e},...y?.parentToolId!==void 0?{parentToolId:y.parentToolId}:{},...b.liveOnly!==void 0?{liveOnly:b.liveOnly}:{}};return k.workflowCorrelation===void 0&&k.childAgentId===void 0&&k.childAgentName===void 0&&k.parentToolId===void 0&&k.liveOnly===void 0?void 0:k},"activityEventMeta"),w=i((y,b={})=>{let k={...g(y,b)??{},...y?.toolId!==void 0?{toolId:y.toolId}:{}};return k.toolId===void 0&&k.workflowCorrelation===void 0&&k.childAgentId===void 0&&k.childAgentName===void 0&&k.parentToolId===void 0&&k.liveOnly===void 0?void 0:k},"toolEventMeta");return{...s?{workflowCorrelation:s}:{},onTextDelta:i((y,b)=>{o?.onTextDelta?.(y,g(b,{liveOnly:!0}))},"onTextDelta"),onThinkingDelta:i((y,b)=>{o?.onThinkingDelta?.(y,g(b,{liveOnly:!0}))},"onThinkingDelta"),onThinkingEnd:i((y,b)=>{o?.onThinkingEnd?.(y,g(b,{liveOnly:!0}))},"onThinkingEnd"),onStreamEnd:i(y=>{o?.onStreamEnd?.(g(y,{liveOnly:!0}))},"onStreamEnd"),onProviderRateLimit:i((y,b,v,k)=>{o?.onProviderRateLimit?.(y,b,v,g(k,{liveOnly:!0}))},"onProviderRateLimit"),onRetryAfter:i((y,b)=>{o?.onRetryAfter?.(y,g(b,{liveOnly:!0}))},"onRetryAfter"),onRetry:i((y,b,v,k)=>{o?.onRetry?.(y,b,v,g(k,{liveOnly:!0}))},"onRetry"),onProviderRecovery:i((y,b)=>{o?.onProviderRecovery?.(y,g(b,{liveOnly:!0}))},"onProviderRecovery"),beforeToolExecute:i(async(y,b,v)=>{if(m.has(y))return`[Tool Error] ${y}: Not available in child agent context.`;if(n){let k=n(y,b);if(k)return`${k} You are a child agent inheriting plan-mode constraints. Complete investigation and return findings as text \u2014 the parent agent will request user approval for any implementation.`}return o?.beforeToolExecute?o.beforeToolExecute(y,b,w(v)):!0},"beforeToolExecute"),onIterationStart:i((y,b)=>{d=y,u=b,r&&r({kind:"iteration",iteration:y,maxIterations:b})},"onIterationStart"),onIterationEnd:i(y=>{o?.onIterationEnd?.({...y,scope:"worker"})},"onIterationEnd"),onToolUseStart:i((y,b)=>{o?.onToolUseStart?.(y,w({...b?.toolId!==void 0?{toolId:b.toolId}:{toolId:y.id},...b?.workflowCorrelation!==void 0?{workflowCorrelation:b.workflowCorrelation}:{}},{liveOnly:!0}));let v=y.input&&typeof y.input=="object"?y.input.path??y.input.pattern??y.input.command??"":"",k=typeof v=="string"?v.slice(0,60):"",C=k?` ${k}`:"";p(`${e} [${d}/${u}] \u2192 ${y.name}${C}`),r&&r({kind:"tool-start",iteration:d,toolName:y.name,inputHint:k,startedAt:Date.now()})},"onToolUseStart"),onToolInputDelta:i((y,b,v)=>{o?.onToolInputDelta?.(y,b,w(v,{liveOnly:!0}))},"onToolInputDelta"),onToolProgress:i((y,b)=>{o?.onToolProgress?.(y,w({...b?.toolId!==void 0?{toolId:b.toolId}:{toolId:y.id},...b?.workflowCorrelation!==void 0?{workflowCorrelation:b.workflowCorrelation}:{}},{liveOnly:!0}))},"onToolProgress"),onToolResult:i((y,b)=>{o?.onToolResult?.(y,w({...b?.toolId!==void 0?{toolId:b.toolId}:{toolId:y.id},...b?.workflowCorrelation!==void 0?{workflowCorrelation:b.workflowCorrelation}:{}},{liveOnly:!0}))},"onToolResult"),...o?.askUser?{askUser:i((y,b)=>o.askUser(y,w(b,{liveOnly:!0})),"askUser")}:{},...o?.askUserMulti?{askUserMulti:i((y,b)=>o.askUserMulti(y,w(b,{liveOnly:!0})),"askUserMulti")}:{},...o?.askUserInput?{askUserInput:i((y,b)=>o.askUserInput(y,w(b,{liveOnly:!0})),"askUserInput")}:{}}}i(bd,"buildChildEvents");function kd(e){let t=new Set(["file_modified","file_created","file_deleted"]);return[...new Set((e.artifactLedger??[]).filter(n=>t.has(n.kind)).map(n=>n.target).filter(n=>n.trim().length>0))]}i(kd,"extractMutationArtifactPaths");function yt(e,t,n,r={}){return{childId:e.id,fanoutClass:e.fanoutClass,status:n,disposition:n==="completed"?"valid":"needs-more-evidence",summary:t,evidenceRefs:e.evidenceRefs,contradictions:[],actualIterations:r.actualIterations,...r.totalTokensUsed!==void 0&&r.totalTokensUsed>0?{totalTokensUsed:r.totalTokensUsed}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.artifactPaths!==void 0&&r.artifactPaths.length>0?{artifactPaths:[...r.artifactPaths]}:{},...r.digest?{digest:r.digest}:{},...r.digestFailed?{digestFailed:!0}:{},...r.digestPending?{digestPending:!0}:{},...r.provider?{provider:r.provider}:{},...r.model?{model:r.model}:{},...r.structured!==void 0?{structured:r.structured}:{},interrupted:r.interrupted,...r.limitReached?{limitReached:!0}:{}}}i(yt,"extractChildResult");function tw(e,t,n){let r=new Map(e.map(l=>[l.id,l])),o=new Map(t.map(l=>[l.childId,l])),s=e.map(l=>o.get(l.id)).filter(l=>l!==void 0&&(l.status==="completed"||l.summary.length>0)).map(l=>({childId:l.childId,objective:r.get(l.childId)?.objective??"",evidence:[l.summary,...l.evidenceRefs],artifacts:l.artifactPaths??[]})),a=[...new Set(t.flatMap(l=>l.artifactPaths??[]))],c=t.reduce((l,d)=>l+(d.totalTokensUsed??0),0);return{results:t,mergedFindings:s,mergedArtifacts:a,totalTokensUsed:c,cancelledChildren:[...n]}}i(tw,"mergeChildResults");function nw(e,t,n){return e.length===0?[]:t!=="worker"?[]:n!=="tool-dispatch"?[]:e}i(nw,"validateWriteBundles");var od={results:[],mergedFindings:[],mergedArtifacts:[],totalTokensUsed:0,cancelledChildren:[]};function vd(e,t){rw(e,199);let n={childId:t.childId,status:"running",startedAt:t.startedAt,iterations:0,maxIterations:t.maxIterations,recentToolCalls:[],parentRole:t.parentRole,readOnly:t.readOnly,specialistName:t.specialistName};return e.set(t.childId,n),n}i(vd,"initChildSnapshot");function _d(e,t,n){if(!e)return;let r=e.get(t);r&&(r.status=n.status,r.endedAt=n.endedAt,n.finalText!==void 0&&(r.finalText=n.finalText))}i(_d,"finalizeChildSnapshot");function xd(e,t,n){if(!e)return;let r=e.get(t);if(!r)return;if(n.kind==="iteration"){r.iterations=n.iteration,r.maxIterations=n.maxIterations;return}let o={iteration:n.iteration,toolName:n.toolName,inputHint:n.inputHint,startedAt:n.startedAt};r.recentToolCalls=[...r.recentToolCalls,o].slice(-20)}i(xd,"applyChildSnapshotEvent");function rw(e,t){if(e.size<=t)return;let n=[...e.values()].sort((o,s)=>o.startedAt-s.startedAt),r=e.size-t;for(let o=0;o<r;o++)e.delete(n[o].childId)}i(rw,"pruneToCapacity");import{randomUUID as Rd}from"node:crypto";var ow="emit_managed_protocol",$C="kodax-task-contract",iw="kodax-task-verdict",OC="kodax-task-scout",IC="kodax-task-handoff";function sw(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}i(sw,"asRecord");function Ed(e){return e.trim().toLowerCase()===ow}i(Ed,"isManagedProtocolToolName");function Sd(e,t){if(!(!e&&!t))return{verdict:t?.verdict?{...e?.verdict??{},...t.verdict}:e?.verdict}}i(Sd,"mergeManagedProtocolPayload");function aw(e){let t=e.trim().toLowerCase();if(!t)return;let r=t.replace(/[`"'()[\]{}<>]+/g,"").replace(/[.:;!?]+$/g,"").replace(/[_\s-]+/g," ").trim().split(/\s+/,1)[0]??"";if(r){if(/^accept(?:ed|s|ing)?$/.test(r)||r==="approve"||r==="approved")return"accept";if(/^revis(?:e|ed|es|ing)?$/.test(r))return"revise";if(/^block(?:ed|ing)?$/.test(r))return"blocked"}}i(aw,"normalizeManagedVerdictStatus");function cw(e){let t=e.trim();if(!t)return;let n=t.replace(/[`"'()[\]{}<>]+/g,"").replace(/[.:;!?]+$/g,"").replace(/[\s-]+/g,"_").trim().toUpperCase();if(n==="H1_EXECUTE_EVAL"||n==="H1")return"H1_EXECUTE_EVAL";if(n==="H2_PLAN_EXECUTE_EVAL"||n==="H2")return"H2_PLAN_EXECUTE_EVAL"}i(cw,"normalizeManagedNextHarness");function lw(e){return Array.isArray(e)?e.map(t=>String(t).trim()).filter(Boolean):typeof e=="string"?e.split(/\r?\n/).map(t=>t.replace(/^-+\s*/,"").trim()).filter(Boolean):[]}i(lw,"normalizeStringListValue");function LC(e,t,n=""){let r=sw(t);if(!r||e!=="evaluator")return;let o=typeof r.status=="string"?aw(r.status):void 0;if(o)return{verdict:{source:"evaluator",status:o,reason:typeof r.reason=="string"&&r.reason.trim()||void 0,followups:lw(r.followup??r.followups),userFacingText:n,userAnswer:typeof r.user_answer=="string"?r.user_answer.trim()||void 0:typeof r.userAnswer=="string"&&r.userAnswer.trim()||void 0,nextHarness:typeof(r.next_harness??r.nextHarness)=="string"?cw(String(r.next_harness??r.nextHarness)):void 0,budgetRequest:typeof(r.budget_request??r.budgetRequest)=="string"&&String(r.budget_request??r.budgetRequest).trim()||void 0}}}i(LC,"coerceManagedProtocolToolPayload");function MC(e){if(e==="evaluator")return iw}i(MC,"getManagedBlockNameForRole");function PC(e,t){return e&&t==="evaluator"?!!e.verdict:!1}i(PC,"hasManagedProtocolForRole");function NC(e,t){return new RegExp(String.raw`\`\`\`${t}\s*[\s\S]*?\`\`\``,"i").test(e)}i(NC,"textContainsManagedBlock");function Je(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}i(Je,"isFiniteNonNegative");function Td(e){return!(!e||!Je(e.inputTokens)||!Je(e.outputTokens)||!Je(e.totalTokens)||e.totalTokens<e.inputTokens||e.totalTokens<e.outputTokens||e.cachedReadTokens!==void 0&&!Je(e.cachedReadTokens)||e.cachedWriteTokens!==void 0&&!Je(e.cachedWriteTokens)||e.thoughtTokens!==void 0&&!Je(e.thoughtTokens))}i(Td,"hasValidTokenUsage");function Ad(e){let t=Fe(e);return{currentTokens:t,baselineEstimatedTokens:t,source:"estimate"}}i(Ad,"createEstimatedContextTokenSnapshot");function dw(e,t){let n=Fe(e);return{currentTokens:t.inputTokens,baselineEstimatedTokens:n,source:"api",usage:t}}i(dw,"createApiContextTokenSnapshot");function WC(e,t){return Td(t)?{currentTokens:t.totalTokens,baselineEstimatedTokens:Fe(e),source:"api",usage:t}:Ad(e)}i(WC,"createCompletedTurnTokenSnapshot");function HC(e,t){return Td(t)?dw(e,t):Ad(e)}i(HC,"createContextTokenSnapshot");function uw(e,t){let n=Fe(e);if(!t||!Je(t.currentTokens)||!Je(t.baselineEstimatedTokens))return n;let r=t.currentTokens+(n-t.baselineEstimatedTokens);return!Number.isFinite(r)||r<0?n:Math.round(r)}i(uw,"resolveContextTokenCount");function Cd(e,t){return{currentTokens:uw(e,t),baselineEstimatedTokens:Fe(e),source:t?.source??"estimate",usage:t?.usage}}i(Cd,"rebaseContextTokenSnapshot");function KC(e,t){let n=Fe(e);return{currentTokens:n,baselineEstimatedTokens:n,source:t?.source??"estimate"}}i(KC,"recomputeContextTokenSnapshot");var Ld=Symbol("KodaXLiveTurnAttributed"),$d=Symbol("KodaXLiveTurnBaseEvents"),Od=16,Id=new Map;function QC(e){let t=e.turnId??`turn_${Rd().replace(/-/g,"").slice(0,Od)}`,n=e.deliveryId??`delivery_${Rd().replace(/-/g,"").slice(0,Od)}`;return{sessionId:e.sessionId,turnId:t,deliveryId:n,deliveryKind:e.deliveryKind??"initial",promptId:e.promptId,nextMeta(){let r=(Id.get(e.sessionId)??0)+1;return Id.set(e.sessionId,r),{sessionId:e.sessionId,seq:r,turnId:t,deliveryId:n,timestamp:new Date().toISOString()}}}}i(QC,"createLiveTurnScope");function fw(e){return e[Ld]===!0}i(fw,"isAttributedEvents");function Md(e){return"current"in e?e.current:e}i(Md,"resolveLiveTurnScope");function W(e,t){return{...t??{},...Md(e).nextMeta()}}i(W,"withActivityMeta");function ce(e,t){return{...t,...Md(e).nextMeta()}}i(ce,"withLiveMeta");function ZC(e,t){let n=fw(e)?e[$d]:e,r={...n,onSessionStart:i(o=>{n.onSessionStart?.(ce(t,o))},"onSessionStart"),onTextDelta:i((o,s)=>{n.onTextDelta?.(o,W(t,s))},"onTextDelta"),onThinkingDelta:i((o,s)=>{n.onThinkingDelta?.(o,W(t,s))},"onThinkingDelta"),onThinkingEnd:i((o,s)=>{n.onThinkingEnd?.(o,W(t,s))},"onThinkingEnd"),onToolUseStart:i((o,s)=>{n.onToolUseStart?.(o,W(t,s))},"onToolUseStart"),onToolInputDelta:i((o,s,a)=>{n.onToolInputDelta?.(o,s,W(t,a))},"onToolInputDelta"),onToolProgress:i((o,s)=>{n.onToolProgress?.(o,W(t,s))},"onToolProgress"),onToolResult:i((o,s)=>{n.onToolResult?.(o,W(t,s))},"onToolResult"),onChildActivityEnd:i(o=>{n.onChildActivityEnd?.(W(t,o))},"onChildActivityEnd"),onStreamEnd:i(o=>{n.onStreamEnd?.(W(t,o))},"onStreamEnd"),onIterationStart:i((o,s,a)=>{n.onIterationStart?.(o,s,W(t,a))},"onIterationStart"),onIterationEnd:i(o=>{n.onIterationEnd?.(ce(t,o))},"onIterationEnd"),onCompactStart:i(o=>{n.onCompactStart?.(W(t,o))},"onCompactStart"),onCompact:i((o,s)=>{n.onCompact?.(o,W(t,s))},"onCompact"),onCompactStats:i(o=>{n.onCompactStats?.(ce(t,o))},"onCompactStats"),onCompactedMessages:i((o,s,a)=>{n.onCompactedMessages?.(o,s,W(t,a))},"onCompactedMessages"),onCompactEnd:i(o=>{n.onCompactEnd?.(W(t,o))},"onCompactEnd"),onMidTurnUserMessages:i((o,s)=>{n.onMidTurnUserMessages?.(o,W(t,s))},"onMidTurnUserMessages"),onRetry:i((o,s,a,c)=>{n.onRetry?.(o,s,a,W(t,c))},"onRetry"),onProviderRateLimit:i((o,s,a,c)=>{n.onProviderRateLimit?.(o,s,a,W(t,c))},"onProviderRateLimit"),onRetryAfter:i((o,s)=>{n.onRetryAfter?.(o,W(t,s))},"onRetryAfter"),onProviderRecovery:i((o,s)=>{n.onProviderRecovery?.(o,W(t,s))},"onProviderRecovery"),onReasoningEffortRejected:i(o=>{n.onReasoningEffortRejected?.(ce(t,o))},"onReasoningEffortRejected"),onRepoIntelligenceTrace:i(o=>{n.onRepoIntelligenceTrace?.(ce(t,o))},"onRepoIntelligenceTrace"),onSidecarMessage:i(o=>{n.onSidecarMessage?.(ce(t,o))},"onSidecarMessage"),onTodoUpdate:i((o,s)=>{n.onTodoUpdate?.(o,W(t,s))},"onTodoUpdate"),onTodoDriftWarning:i(o=>{n.onTodoDriftWarning?.(ce(t,o))},"onTodoDriftWarning"),onManagedTaskStatus:i(o=>{n.onManagedTaskStatus?.(ce(t,o))},"onManagedTaskStatus"),onEffectiveConfig:i(o=>{n.onEffectiveConfig?.(ce(t,o))},"onEffectiveConfig"),onWorkflowProcessEvent:i(o=>{n.onWorkflowProcessEvent?.(ce(t,o))},"onWorkflowProcessEvent"),onWorkflowAgentDigest:i(o=>{n.onWorkflowAgentDigest?.(ce(t,o))},"onWorkflowAgentDigest"),onScoutSuspiciousCompletion:i(o=>{n.onScoutSuspiciousCompletion?.(ce(t,o))},"onScoutSuspiciousCompletion"),onComplete:i(o=>{n.onComplete?.(W(t,o))},"onComplete"),onError:i((o,s)=>{n.onError?.(o,W(t,s))},"onError")};return Object.defineProperty(r,Ld,{value:!0,enumerable:!1}),Object.defineProperty(r,$d,{value:n,enumerable:!1}),r}i(ZC,"withLiveTurnAttribution");function eR(e,t){let n={...t.nextMeta(),deliveryKind:t.deliveryKind,...t.promptId!==void 0?{promptId:t.promptId}:{}};e.onTurnStarted?.(n)}i(eR,"emitTurnStarted");function tR(e,t,n){e.onTurnCompleted?.({...t.nextMeta(),status:n})}i(tR,"emitTurnCompleted");function nR(e,t,n){let r={...t.nextMeta(),error:{name:n.name,message:n.message,...n.stack!==void 0?{stack:n.stack}:{}}};e.onTurnFailed?.(r)}i(nR,"emitTurnFailed");var pw=new Set(["todo_update","todo_list","todo_create","todo_get"]);function rR(e){return!Ed(e)&&!pw.has(e)}i(rR,"isVisibleToolName");function oR(e){return e.hasPendingInputs?.()===!0?!0:Se().has({agentId:void 0,maxPriority:"user",mode:"prompt"})}i(oR,"hasQueuedFollowUp");function iR(e,t){e.onSessionStart?.(t)}i(iR,"emitSessionStart");function sR(e){e.onStreamEnd?.()}i(sR,"emitStreamEnd");function aR(e){e.onComplete?.()}i(aR,"emitComplete");function cR(e,t){e.onError?.(t)}i(cR,"emitError");function Pd(e,t,n,r,o){if(o!==void 0){e.onProviderRateLimit?.(t,n,r,o);return}e.onProviderRateLimit?.(t,n,r)}i(Pd,"emitProviderRateLimit");function lR(e,t,n){e.onIterationStart?.(t+1,n)}i(lR,"emitIterationStart");function dR(e,t){let n=Cd(t.messages,t.snapshotOverride??t.currentSnapshot);return e.onIterationEnd?.({iter:t.iter,maxIter:t.maxIter,tokenCount:n.currentTokens,tokenSource:n.source,usage:n.usage,contextTokenSnapshot:n}),n}i(dR,"emitIterationEnd");var Nd=100*1024,Pi=8e3,mw=2e3,hw=3e4,gw="You are a faithful lossy summarizer. Reply with the summary text only \u2014 no preamble, no closing remarks, no markdown code fences.";function yw(e,t){return["The following content failed to spill to disk and is too large to inline",`into the agent's context. Compress to roughly ${Math.max(mw,Math.floor(t/4))}-${t} characters,`,"PRESERVING VERBATIM:","- All file paths, line numbers, error codes, identifiers","- All explicit findings, decisions, conclusions","- Section headers and list structure","You MAY omit: verbose prose, long examples, code snippets longer than 20 lines.","Reply with the summary ONLY. No preamble, no closing remarks.","","CONTENT:",e].join(`
198
- `)}i(yw,"buildSummarizerUserMessage");var Zt=class extends Error{static{i(this,"BlobSummarizerError")}cause;constructor(t,n){super(t),this.cause=n,this.name="BlobSummarizerError"}};function ww(e){let t=new AbortController,n=[];for(let r of e){if(!r)continue;if(r.aborted){t.abort(r.reason);break}let o=i(()=>t.abort(r.reason),"onAbort");r.addEventListener("abort",o,{once:!0}),n.push(()=>r.removeEventListener("abort",o))}return{signal:t.signal,cleanup:i(()=>{for(let r of n)r()},"cleanup")}}i(ww,"combineAbortSignals");function mR(e){let t=e.timeoutMs??hw;return async(n,r)=>{if(n.length===0)throw new Zt("blob summarizer called with empty content");let o=r?.maxChars??Pi,s=new AbortController,a=setTimeout(()=>s.abort(new Error("summarizer timeout")),t),{signal:c,cleanup:l}=ww([r?.abortSignal,s.signal]),d=[{role:"user",content:yw(n,o)}],u=e.events,f=u?{onRateLimit:i((h,p,g)=>{Pd(u,h,p,g)},"onRateLimit"),onRetryAfter:i(h=>{u.onRetryAfter?.(h)},"onRetryAfter")}:void 0,m=f||e.model?{...f??{},...e.model?{modelOverride:e.model}:{}}:void 0;try{let p=(await e.provider.stream(d,[],gw,void 0,m,c)).textBlocks.map(g=>g.text).join("").trim();if(p.length===0)throw new Zt(`blob summarizer (${e.model??"(default)"}) returned empty text`);return p}catch(h){if(h instanceof Zt)throw h;let p=h instanceof Error?h.message:String(h);throw new Zt(`blob summarizer (${e.model??"(default)"}) failed: ${p}`,h)}finally{clearTimeout(a),l()}}}i(mR,"createBlobSummarizer");var bw=200,Ye="dispatch_child_task",$r=0;function kw(){return $r=$r>=Number.MAX_SAFE_INTEGER?1:$r+1,`child-${Date.now().toString(36)}-${$r.toString(36)}`}i(kw,"createGeneratedChildTaskId");async function Or(e,t,n){let r=await _n(e,t,n);if(!r.spillFailed||t.length<=Nd||!n.summarizeBlob)return r.content;try{let o=await n.summarizeBlob(t,{maxChars:Pi,abortSignal:n.abortSignal});return[`[SPILL FAILED \u2014 original ${N(t.length)} compressed via LLM summarizer; raw content unavailable.`,"Worker: treat this summary as LOSSY. Critical decisions OK; fine-grained detail may be missing.","Re-run upstream tool with narrower scope if you need verbatim source.]","",o].join(`
199
- `)}catch(o){let s=o instanceof Error?o.message:String(o);return console.warn(`[dispatch-child-tasks] LLM summarizer failed for ${e} (${N(t.length)}); inlining full content. Cause: ${s}`),[`[SPILL FAILED AND LLM SUMMARIZER FAILED \u2014 original ${N(t.length)} inlined as last-resort emergency dump.`,`Summarizer cause: ${s}.`,"Worker: this payload may exceed context budget. Treat as authoritative source but expect possible downstream truncation. Re-run upstream tool with narrower scope if you need a clean replay.]","",r.content].join(`
200
- `)}}i(Or,"applyChildSummaryGuardrailWithSummarizer");function vw(e){return process.env.KODAX_ASYNC_DISPATCH==="0"?!1:e.childTaskRegistry!==void 0}i(vw,"shouldUseAsyncDispatch");function Dd(e){let t=e.interrupted?"Child exited via the AbortError silent terminal (CAP-083) \u2014 typically means an upstream abortSignal fired before the child produced any text. Most common upstream causes: provider stream RST, parent-turn cleanup that propagated an abort, or a task_stop call.":"No interrupted flag \u2014 likely the model returned no text in its final assistant turn, or the envelope guardrail dropped all content.";return[`(child task "${e.childId}" completed but produced no observable text output.`,`Diagnostic: status=${e.status??"unknown"} interrupted=${e.interrupted} iterations=${e.iterations??"n/a"} results=${e.resultsCount} mergedFindings=${e.mergedFindingsCount} evidenceRefs=${e.evidenceRefsCount} provider=${e.provider??"?"} model=${e.model??"?"}.`,t,"Treat as inconclusive. Set KODAX_DISPATCH_CHILD_TRACE=1 to capture a JSON trace under `os.tmpdir()/kodax-dispatch-trace/` for the next reproduction.)"].join(`
201
- `)}i(Dd,"buildEmptySummaryFallback");function jd(e){let t=e.resultsCount===0?"silent-drop":(e.iterations??null)===0?"startup-crash":(e.iterations??0)>0?"mid-run-failure":"unknown",n=t==="silent-drop"?`Bundle never reached the child runner \u2014 typically a validation gate dropped it. Check executeChildAgents early-return paths (validateWriteBundles, empty-bundles guard) against parentRole=${e.parentRole??"?"} readOnly=${e.readOnly}.`:t==="startup-crash"?"Child runner errored before any assistant turn \u2014 most often run-substrate CAP-084 (success:false, lastText:'') triggered by a provider stream error on the first LLM call (rate limit / network / auth / context-size 4xx).":t==="mid-run-failure"?`Child runner produced ${e.iterations} assistant turn(s) then errored without retaining text \u2014 typically a mid-stream provider error or a tool-execution failure that left turnState.lastText empty.`:"Failure mode could not be classified \u2014 no childResult and no exception captured.";return[`(child task "${e.childId}" FAILED with no result text.`,`Diagnostic: status=${e.status??"failed"} mode=${t} iterations=${e.iterations??"n/a"} interrupted=${e.interrupted} results=${e.resultsCount} mergedFindings=${e.mergedFindingsCount} readOnly=${e.readOnly} parentRole=${e.parentRole??"?"} provider=${e.provider??"?"} model=${e.model??"?"}.`,n,"Treat as inconclusive \u2014 do NOT invent an infrastructure narrative without evidence. Set KODAX_DISPATCH_CHILD_TRACE=1 for a JSON trace at `os.tmpdir()/kodax-dispatch-trace/` to disambiguate the next reproduction.)"].join(`
202
- `)}i(jd,"buildFailedEmptySummaryFallback");async function Ir(e){if(process.env.KODAX_DISPATCH_CHILD_TRACE==="1")try{let[{tmpdir:t},{join:n},r]=await Promise.all([import("os"),import("path"),import("fs/promises")]),o=n(t(),"kodax-dispatch-trace");await r.mkdir(o,{recursive:!0});let s=new Date().toISOString().replace(/[:.]/g,"-"),a=e.childId.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,80),c=n(o,`${s}_${a}.json`),l=e.result?.results?.[0],d={timestamp:new Date().toISOString(),branch:e.branch,childId:e.childId,durationMs:e.durationMs,provider:e.provider??null,model:e.model??null,bundle:{objective:e.bundle.objective,readOnly:e.bundle.readOnly,scopeSummary:e.bundle.scopeSummary??null,evidenceRefsCount:e.bundle.evidenceRefs.length,constraintsCount:e.bundle.constraints.length,modelHint:e.bundle.modelHint??null,specialistName:e.bundle.specialistName??null},result:e.result===void 0?null:{resultsCount:e.result.results.length,mergedFindingsCount:e.result.mergedFindings.length,cancelledChildrenCount:e.result.cancelledChildren.length,childResult:l===void 0?null:{status:l.status,disposition:l.disposition,summaryLength:l.summary.length,summaryPreview:l.summary.slice(0,200),evidenceRefsCount:l.evidenceRefs.length,contradictionsCount:l.contradictions.length,actualIterations:l.actualIterations??null,interrupted:l.interrupted??null}},rawSummaryLength:e.rawSummary.length,rawSummaryPreview:e.rawSummary.slice(0,400),bannerContentLength:e.bannerContent.length,bannerContentPreview:e.bannerContent.slice(0,400),fallbackApplied:e.fallbackApplied,error:e.error?{message:e.error instanceof Error?e.error.message:String(e.error),name:e.error instanceof Error?e.error.name:"unknown"}:null};await r.writeFile(c,JSON.stringify(d,null,2),{mode:384})}catch{}}i(Ir,"writeDispatchTraceIfEnabled");async function*Fd(e,t){let n=typeof e.id=="string"?e.id.trim():"",r=typeof e.objective=="string"?e.objective.trim():"",o=n||kw();if(!r)return yield{stage:"error",message:`Child "${o}": missing objective`},`[Tool Error] ${Ye}: Missing required parameter: objective`;let s=t.managedProtocolRole,a=(e.read_only??e.readOnly)!==!1,c=Date.now();t.reportToolProgress?.(`[dispatch] start childId=${o} role=${s??"unknown"} readOnly=${a}`);let l="error",d=i(()=>{let T=Date.now()-c;t.reportToolProgress?.(`[dispatch] end childId=${o} status=${l} duration_ms=${T}`)},"emitDispatchEnd"),u=typeof e.model_hint=="string"?e.model_hint.trim():"",f=u==="fast"||u==="balanced"||u==="deep"?u:void 0,h=(typeof e.subagent_type=="string"?e.subagent_type.trim():"")||void 0,p;if(h){let T=Oe(h);if(!T){let x=ae().map(A=>A.name),R=x.length===0?"(none)":x.join(", ");return yield{stage:"error",message:`Child "${o}": specialist "${h}" not registered`},`[Tool Error] ${Ye}: specialist "${h}" not registered. Available: ${R}`}if(!a&&s!=="worker")return`[Tool Error] ${Ye}: specialist "${h}" is a write dispatch (readOnly=false) but current role "${s??"unknown"}" cannot dispatch write children. Only Worker may dispatch write specialists.`;if(T.effort!==void 0&&T.effort.trim().length>0)try{let x=it(T.effort);p=x==="auto"?void 0:x}catch(x){let R=x instanceof Error?x.message:String(x);return`[Tool Error] ${Ye}: specialist "${h}" declares invalid effort "${T.effort}". ${R}`}}let g=typeof e.provider=="string"&&e.provider.trim()?e.provider.trim():void 0,w=typeof e.model=="string"&&e.model.trim()?e.model.trim():void 0,y;if(typeof e.effort=="string"&&e.effort.trim())try{let T=it(e.effort);y=T==="auto"?void 0:T}catch(T){let x=T instanceof Error?T.message:String(T);return`[Tool Error] ${Ye}: invalid effort "${e.effort}". ${x}`}if(p!==void 0&&y!==void 0&&y!==p)return`[Tool Error] ${Ye}: specialist "${h??"unknown"}" locks effort "${p}", but dispatch requested "${y}". Remove the dispatch effort or match the specialist effort.`;let b=p??y,v={id:o,fanoutClass:"evidence-scan",objective:r,readOnly:a,scopeSummary:typeof e.scope_summary=="string"?e.scope_summary:void 0,evidenceRefs:Array.isArray(e.evidence_refs)?e.evidence_refs.filter(T=>typeof T=="string"):[],constraints:Array.isArray(e.constraints)?e.constraints.filter(T=>typeof T=="string"):[],modelHint:f,specialistName:h,...g?{provider:g}:{},...w?{model:w}:{},...b?{effort:b}:{}},k=t.parentAgentConfig,C={maxParallel:1,maxIterationsPerChild:bw,abortSignal:t.abortSignal,parentOptions:{provider:k?.provider,model:k?.model,reasoningMode:k?.reasoningMode,effort:k?.effort,repoIntelligenceMode:k?.repoIntelligenceMode,repoIntelligenceTrace:k?.repoIntelligenceTrace,extensionRuntime:t.extensionRuntime,events:t.parentEvents},parentRole:s??"worker",parentHarness:"tool-dispatch",onProgress:i(T=>{t.reportToolProgress?.(T)},"onProgress"),planModeBlockCheck:t.planModeBlockCheck,guardrails:t.guardrails};if(vw(t)){let T=t.childTaskRegistry;if(!T)return yield{stage:"error",message:`Child "${o}": registry missing`},l="error",d(),`[Tool Error] ${Ye}: childTaskRegistry not available`;if(T.has(o))return yield{stage:"error",message:`Child "${o}": duplicate task_id`},l="error",d(),`[Tool Error] ${Ye}: task_id "${o}" is already in flight. Pick a unique id; the existing child will be reclaimed automatically via the idle-yield wait mechanic (its result will arrive as a <task-completed task_id="${o}"> block in your next user message).`;let x=new AbortController,R=t.abortSignal,A;if(R)if(R.aborted)x.abort(R.reason);else{let $=i(()=>{x.abort(R.reason)},"onParentAbort");R.addEventListener("abort",$,{once:!0}),A=i(()=>{R.removeEventListener("abort",$)},"detachParentAbortListener")}let D=t.childAbortControllers;D?.set(o,x);let P=t.childProgressSnapshots;P&&vd(P,{childId:o,startedAt:Date.now(),maxIterations:C.maxIterationsPerChild,parentRole:C.parentRole,readOnly:v.readOnly,specialistName:v.specialistName});let G={...C,abortSignal:x.signal,snapshotUpdater:P?$=>xd(P,o,$):void 0},E=Date.now(),S="failed",L,U=(async()=>{try{let $=await Oi([v],t,G),F=$.results[0],K=F?.status??"failed",me=$.mergedFindings[0]?.evidence.join(`
203
- `)??"",Ee=F?.summary??"",he,an=!1;K==="completed"?me.trim().length>0?he=me:Ee.trim().length>0?he=Ee:(he=Dd({childId:o,status:K,iterations:F?.actualIterations,interrupted:F?.interrupted===!0,evidenceRefsCount:F?.evidenceRefs.length??0,mergedFindingsCount:$.mergedFindings.length,resultsCount:$.results.length,provider:k?.provider,model:k?.model}),an=!0):Ee.trim().length>0?he=`failed: ${Ee}`:(he=jd({childId:o,status:K,iterations:F?.actualIterations,interrupted:F?.interrupted===!0,resultsCount:$.results.length,mergedFindingsCount:$.mergedFindings.length,readOnly:v.readOnly,parentRole:s,provider:k?.provider,model:k?.model}),an=!0);let js=await Or("child_task_summary",he,t);return cn({taskId:o,summary:js,source:"child_task",status:K==="completed"?"completed":"failed"}),await Ir({childId:o,bundle:v,result:$,rawSummary:he,bannerContent:js,fallbackApplied:an,provider:k?.provider,model:k?.model,durationMs:Date.now()-E,branch:"async-success"}),S=K==="completed"?"completed":"failed",L=he,$}catch($){let F=$ instanceof Error?$.message:String($),K=`crash: ${F.length>0?F:"unknown error (Error.message was empty)"}`,me=await Or("child_task_summary",K,t);throw cn({taskId:o,summary:me,source:"child_task",status:"failed"}),await Ir({childId:o,bundle:v,result:void 0,rawSummary:K,bannerContent:me,fallbackApplied:!1,provider:k?.provider,model:k?.model,error:$,durationMs:Date.now()-E,branch:"async-crash"}),S=$ instanceof Error&&($.name==="AbortError"||$.message.toLowerCase().includes("aborted"))?"aborted":"failed",L=K,$}finally{D?.delete(o),A?.(),_d(P,o,{status:S,finalText:L,endedAt:Date.now()})}})();return Kn(T,o,U),yield{stage:"launched",message:`Child "${o}" launched (async)`},l="launched",d(),`task_id:${o}
204
- Child task "${o}" is running in the background. Do whatever interleaved work is useful (more dispatches, side-reads, drafting). When you have nothing else useful to do, end your turn with one short status sentence and NO tool calls \u2014 the runner will resume you when this child finishes (you will see a <task-completed task_id="${o}">\u2026</task-completed> block in your next user message).`}try{let T=await Oi([v],t,C),x=T.results[0],R=x?.status??"failed";if(l=R,yield{stage:"done",message:`Child "${o}" \u2192 ${R}`},!x||x.status==="failed"){let L=x?.summary&&x.summary.trim().length>0,U,$=!1;L?U=`Child task "${o}" failed: ${x.summary}`:(U=jd({childId:o,status:R,iterations:x?.actualIterations,interrupted:x?.interrupted===!0,resultsCount:T.results.length,mergedFindingsCount:T.mergedFindings.length,readOnly:v.readOnly,parentRole:s,provider:k?.provider,model:k?.model}),$=!0);let F=await Or("child_task_summary",U,t);return await Ir({childId:o,bundle:v,result:T,rawSummary:U,bannerContent:F,fallbackApplied:$,provider:k?.provider,model:k?.model,durationMs:Date.now()-c,branch:"sync"}),F}let A=T.mergedFindings[0],D=A?A.evidence.join(`
205
- `):"",P=x.summary,G,E=!1;D.trim().length>0?G=D:P.trim().length>0?G=P:(G=Dd({childId:o,status:R,iterations:x.actualIterations,interrupted:x.interrupted===!0,evidenceRefsCount:x.evidenceRefs.length,mergedFindingsCount:T.mergedFindings.length,resultsCount:T.results.length,provider:k?.provider,model:k?.model}),E=!0);let S=await Or("child_task_summary",G,t);return await Ir({childId:o,bundle:v,result:T,rawSummary:G,bannerContent:S,fallbackApplied:E,provider:k?.provider,model:k?.model,durationMs:Date.now()-c,branch:"sync"}),S}finally{d()}}i(Fd,"toolDispatchChildTask");var _w={results:[],mergedFindings:[],mergedArtifacts:[],totalTokensUsed:0,cancelledChildren:[]};function Ni(e){if(e.status==="completed"){let n=e.resultText?.trim(),r=e.verificationWarnings??[],o=r.length>0?`Workflow ${e.runId} completed, but ${r.length} agent(s) failed verification (warn-only): ${r.join(", ")}. Review before relying on the result.
206
-
207
- `:"";return n&&n.length>0?`${o}${n}`:`${o}Workflow ${e.runId} completed (no displayable result text was returned).`}let t=e.error??e.resultText??"";return`[Tool Error] Workflow ${e.runId??""} ${e.status??"did not complete"}${t?`: ${t}`:""}`.trim()}i(Ni,"formatWorkflowOutcome");function Ud(e){if(typeof e=="object"&&e!==null&&"name"in e){let t=e.name;if(typeof t=="string"&&t.trim().length>0)return t}return"workflow"}i(Ud,"readManifestName");function xw(e){return e.status==="completed"?"completed":e.status==="cancelled"||e.status==="stopped"?"cancelled":"failed"}i(xw,"workflowTaskResultStatus");async function qd(e,t){let n=t.workflowHost;if(!n)return"[Tool Error] run_workflow is unavailable on this turn. Workflow authoring is enabled in AMAW mode, or in AMA when a workflow host is configured (e.g. via the /workflow command). Use dispatch_child_task for a single sub-task.";let r=e.source;if(typeof r!="string"||r.trim().length===0)return"[Tool Error] run_workflow requires a non-empty `source` string defining `async function run(wf, args) { ... }`.";let o=e.manifest;if(typeof o!="object"||o===null||Array.isArray(o))return"[Tool Error] run_workflow requires a `manifest` object (name, description, phases, readOnly, maxAgents, maxConcurrency, patterns).";let s={manifest:o,source:r,...e.args!==void 0?{args:e.args}:{},...typeof e.resumeFromRunId=="string"&&e.resumeFromRunId.length>0?{resumeFromRunId:e.resumeFromRunId}:{}},a=t.childTaskRegistry;if(a!==void 0&&process.env.KODAX_ASYNC_WORKFLOW!=="0"){let c=new AbortController,l;try{l=await n.startInline({...s,signal:c.signal})}catch(m){return`[Tool Error] run_workflow failed: ${m instanceof Error?m.message:String(m)}`}if(l.kind==="declined")return`Workflow not started: ${l.reason??"the workflow was declined"}`;let d=l.runId,u=l.done;if(a.has(d))return Ni(await u);t.childAbortControllers?.set(d,c),l.getProgress&&t.workflowRunProgress?.set(d,l.getProgress);let f=(async()=>{let m,h="completed";try{let p=await u;h=xw(p),m=Ni(p)}catch(p){h="failed",m=`[Tool Error] Workflow ${d} failed: ${p instanceof Error?p.message:String(p)}`}finally{t.childAbortControllers?.delete(d),t.workflowRunProgress?.delete(d)}return cn({taskId:d,summary:m,source:"workflow",runId:d,status:h,title:Ud(o)}),_w})();return Kn(a,d,f),`task_id:${d}
208
- Workflow "${Ud(o)}" started (run ${d}) and is now running in the background. Do NOT wait for it inline \u2014 its synthesized result will arrive on its own as a <task-completed task_id="${d}"> block in a later message. Idle-yield now (end your turn with no tool calls) if you have nothing else to do, or continue with other useful work; you will be resumed automatically when it finishes. To check how far it has gotten while it runs, call task_output("${d}") \u2014 it reports the current phase and which agents are running. If the goal changes before it finishes, call task_stop("${d}") to stop this run, then run_workflow again with the improved script \u2014 pass resumeFromRunId:"${d}" so the agents that already finished replay from cache and only the changed work re-runs.`}try{let c=await n.runInline(s);return c.kind==="declined"?`Workflow not started: ${c.reason??"the workflow was declined"}`:Ni(c)}catch(c){return`[Tool Error] run_workflow failed: ${c instanceof Error?c.message:String(c)}`}}i(qd,"toolRunWorkflow");var re="send_message",Bd=20,Ew=20,Sw=5,Wd=5,en="worker";function Tw(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}i(Tw,"parseSeenBy");function Aw(e){return e??en}i(Aw,"selfLabel");function Qe(e){return e.replace(/[<>&]/g,t=>t==="<"?"&lt;":t===">"?"&gt;":"&amp;")}i(Qe,"escapeTagBody");function Di(e){return e.length===0?"":` seen_by="${e.map(Qe).join(",")}"`}i(Di,"formatSeenByAttr");function ji(e,t){let n=e.sendMessageTurnCounter;if(!n)return null;let r=e.currentAgentId===void 0?Ew:Sw,o=e.currentAgentId===void 0?"Worker":"child";return n.count+t>r?`[Tool Error] ${re}: per-turn send_message limit reached for this ${o} (${n.count} already sent this turn + ${t} requested > cap ${r}). Wait until the next LLM turn \u2014 peer coordination that needs more than ${r} messages per turn is almost always a storm or a misfire.`:(n.count+=t,null)}i(ji,"chargeTurnCounter");function Cw(e,t,n,r,o,s){let a=n??en;if(s.slice(0,-1).includes(a))return`[Tool Error] ${re}: Cycle detected \u2014 parent "${a}" is already in seen_by (${s.slice(0,-1).join(" \u2192 ")}). Forwarding back to a prior sender would close a loop; the Worker has already handled this chain.`;let c=ji(o,1);if(c)return c;let l=`<child-notification from="${Qe(e)}"${Di(s)}>
209
- ${Qe(t)}
210
- </child-notification>`;return r.enqueue({priority:"background",mode:"task-notification",agentId:n,content:l}),`Message sent to ${n??en}. It will surface as a <child-notification from="${e}"> block when the parent next yields.`}i(Cw,"sendToWorker");function Rw(e,t,n,r,o){let s=n.childTaskRegistry;if(!s)return`[Tool Error] ${re}: Broadcast requires a sibling registry, but none is bound to this context (sync-mode dispatch). Send to a specific task_id or 'worker' instead.`;let a=n.parentAgentId,c=o.slice(0,-1),l=new Set(c),d=[...s.keys()].filter(w=>w!==e&&w!==a&&!l.has(w)),u=a??en,f=e!==void 0&&!l.has(u)&&!l.has(en),m=d.length+(f?1:0);if(m>Bd)return`[Tool Error] ${re}: Broadcast target count ${m} exceeds cap ${Bd}. Narrow the audience by sending to specific task_ids.`;if(m===0)return c.length>0?`[Tool Error] ${re}: Broadcast has zero novel recipients \u2014 every in-flight sibling and the parent are already in seen_by (${c.join(" \u2192 ")}). The chain is exhausted; stop forwarding.`:`[Tool Error] ${re}: Broadcast has zero recipients (no other in-flight siblings, and you have no parent Worker to notify).`;let h=ji(n,m);if(h)return h;let p=e??en,g=`<peer-broadcast from="${Qe(p)}"${Di(o)}>
211
- ${Qe(t)}
212
- </peer-broadcast>`;for(let w of d)r.enqueue({priority:"background",mode:"prompt",agentId:w,content:g});return f&&r.enqueue({priority:"background",mode:"task-notification",agentId:n.parentAgentId,content:g}),`Broadcast sent from ${p} to ${m} target(s) (${d.length} sibling(s)${f?" + parent":""}). Recipients will see the <peer-broadcast> block when they next yield.`}i(Rw,"broadcast");async function Fi(e,t){let n=typeof e.to=="string"?e.to.trim():"",r=typeof e.content=="string"?e.content.trim():"";if(!n)return`[Tool Error] ${re}: Missing required parameter: to (task_id of an in-flight sibling, 'worker' to notify the parent, or '*' to broadcast).`;if(!r)return`[Tool Error] ${re}: Missing required parameter: content (the message body).`;let o=Se(),s=t.currentAgentId,a=Aw(s),l=[...Tw(e.seen_by),a];if(l.length>Wd)return`[Tool Error] ${re}: Forward chain length ${l.length} exceeds cap ${Wd} (chain: ${l.join(" \u2192 ")}). Peer messages are short coordination notes, not cascading forwards \u2014 stop the chain and let the Worker re-plan.`;if(n==="*")return Rw(s,r,t,o,l);if(n==="worker")return s===void 0?`[Tool Error] ${re}: send_message(to='worker') is for children notifying their parent \u2014 you are the Worker (top of the agent tree).`:Cw(s,r,t.parentAgentId,o,t,l);let d=t.childTaskRegistry;if(!d)return`[Tool Error] ${re}: Async dispatch is disabled (no childTaskRegistry on context). Children run synchronously and complete inside their dispatch_child_task call \u2014 there is no in-flight target to steer.`;if(s!==void 0&&n===s)return`[Tool Error] ${re}: Cannot send a message to yourself (to='${n}'). Use task tools to record your own notes; send_message routes between distinct agents.`;let u=l.slice(0,-1);if(u.includes(n))return`[Tool Error] ${re}: Cycle detected \u2014 target "${n}" is already in seen_by (${u.join(" \u2192 ")}). Forwarding back to a prior sender would close a loop.`;let f=s===void 0,m=f?"user":"background",h=f?`<coordinator-instruction>
213
- ${Qe(r)}
214
- </coordinator-instruction>`:`<peer-message from="${Qe(s)}"${Di(l)}>
215
- ${Qe(r)}
216
- </peer-message>`,p=ji(t,1);if(p)return p;let g=zn({to:n,priority:m,mode:"prompt",content:h,registry:d,queue:Se()});return g.ok?f?`Message sent to ${n}. It will be processed at the child's next LLM turn boundary as a <coordinator-instruction> block.`:`Peer message sent to ${n} from ${s}. It will be processed when the peer next yields as a <peer-message from="${s}"> block.`:`[Tool Error] ${re}: Unknown task_id "${g.to}". Verify the task_id matches one returned by dispatch_child_task and that the target has not already completed (completed children are auto-cleaned from the registry).`}i(Fi,"toolSendMessage");var Lr="task_stop";async function Ui(e,t){let n=typeof e.task_id=="string"?e.task_id.trim():"";if(!n)return`[Tool Error] ${Lr}: Missing required parameter: task_id (child task_id from dispatch_child_task)`;let r=typeof e.reason=="string"&&e.reason.trim().length>0?e.reason.trim():void 0,o=t.childAbortControllers;if(!o)return`[Tool Error] ${Lr}: Async dispatch is disabled (no childAbortControllers on context). Children run synchronously and complete inside their dispatch_child_task call \u2014 there is no in-flight target to stop.`;let s=Xs({taskId:n,registry:o,reason:r});if(!s.ok)return s.reason==="unknown-target"?`[Tool Error] ${Lr}: Unknown task_id "${s.taskId}". Verify the task_id matches one returned by dispatch_child_task and that the child has not already completed (completed children are auto-cleaned from the registry).`:`[Tool Error] ${Lr}: Task "${s.taskId}" is already aborted (its first-abort cause is preserved). No additional action needed; the child will surface the cancellation at its next abort check.`;let a=t.childTaskRegistry;if(r&&a){let c=`<coordinator-stop-request>
210
+ ${s}`}return`- [evidence_refs error] unrecognized prefix in "${e}" \u2014 valid prefixes: file:, diff:, finding:, task_id:`}i(ob,"resolveEvidenceRef");var Bi=["You are a focused sub-agent executing a specific task assigned by a parent agent.","Use the available tools to complete the task fully. Do not gold-plate, but do not leave it half-done.","","## Tool Use \u2014 Prefer Parallel Calls","","When multiple tool calls are independent of each other, emit them all in the SAME response. The execution engine runs non-bash tools concurrently via Promise.all, so serial calls add real wall-clock latency the parent waits on.","","Concrete rules:","- For module exploration or change review, lead with pull-tools (`module_context` / `symbol_context` / `changed_scope` / `changed_diff_bundle`) \u2014 each replaces several read+grep calls so the same investigation finishes in fewer turns.","- For single-file lookup or byte-exact verification, use `glob` + `grep` + targeted `read`.","- When you need multiple independent tool calls (pull-tools, reads, or greps), emit them all in one response. Only serialize when a later call genuinely depends on an earlier result (e.g., you need a file path from grep before you can read it).","- Open broad with a parallel fan-out covering the obvious scope axes, then narrow on follow-up turns. Prefer a few targeted calls over many tiny sequential probes.","","## Peer Communication","","You can send short messages to other in-flight agents in this session with `send_message`:",'- `send_message(to="<peer task_id>", content="\u2026")` \u2014 notify a sibling child that your work overlaps with theirs or that you found something they need to know.','- `send_message(to="worker", content="\u2026")` \u2014 surface a mid-flight finding to your parent Worker (drains when the Worker next yields).','- `send_message(to="*", content="\u2026")` \u2014 broadcast to every sibling plus the parent Worker. Capped at 20 recipients per call.',"","Send a peer message when it would change another agent's plan: a file you both edit, a fact you discovered that changes their scope, a blocker the parent should know about. Do not send routine status pings \u2014 peer chatter that does not change anyone's plan is noise.","",'Forwarding: peer wrappers carry a `seen_by="A,B,\u2026"` attribute listing every agent that has already handled the chain. If you intentionally forward a received peer message, pass that list as the `seen_by` parameter so the tool can reject cycles (forwarding back to a prior sender) and cap chain depth. Omit `seen_by` for fresh sends \u2014 the tool always auto-appends you.',"","## Execution Guidelines","- Focus on the objective described in the user message. Do not deviate.","- Write your final report in the same natural language as the objective you were given, so it reaches the user in their language. Keep code, file paths, and quoted evidence in their source language.","- When you have sufficient evidence, stop investigating and synthesize your findings.","- Your final response MUST be text only \u2014 the parent reads your text directly as the dispatch result, and a final tool call would re-open the turn and force another LLM round without giving the parent new information.","","## Output Format","Respond with a concise report covering:","- Key findings with specific file:line references","- Severity or priority assessment (if applicable)","- Concrete recommendations","","Keep the report focused \u2014 the parent will relay it to the user."].join(`
211
+ `);function ib(e){let t=Kl({cwd:e,projectRoot:e}),n=Xl(t);return n?[Bi,"","Project rules apply to your mutations. Follow them as the parent agent would:",n].join(`
212
+ `):Bi}i(ib,"buildWriteSystemPrompt");var Gi=["emit_managed_protocol","dispatch_child_task","task_stop","task_output","ask_user_question","worktree_create","worktree_remove","exit_plan_mode"],Jd=[...Gi,"write","edit","multi_edit","insert_after_anchor","undo"],sb=new Set(Gi),ab=new Set(Jd);function cb(e,t,n){return{...t!==void 0?{workflowCorrelation:t}:{},childAgentId:e,childAgentName:n??e,liveOnly:!0}}i(cb,"childActivityEventMeta");function Yd(e,t,n,r){t?.onChildActivityEnd?.(cb(e,n,r))}i(Yd,"emitChildActivityEnd");function Zd(e,t,n,r,o,s,a,c=200,l=!1){let d=0,u=c,f=0,m=l?ab:sb,h=150,p=i((y,b=!1)=>{if(!t)return;let v=Date.now();!b&&v-f<h||(f=v,t(y))},"throttledProgress"),g=i((y,b={})=>{let v=s??y?.workflowCorrelation,k={...v!==void 0?{workflowCorrelation:v}:{},...y?.childAgentId!==void 0?{childAgentId:y.childAgentId}:{childAgentId:e},...y?.childAgentName!==void 0?{childAgentName:y.childAgentName}:{childAgentName:a??e},...y?.parentToolId!==void 0?{parentToolId:y.parentToolId}:{},...b.liveOnly!==void 0?{liveOnly:b.liveOnly}:{}};return k.workflowCorrelation===void 0&&k.childAgentId===void 0&&k.childAgentName===void 0&&k.parentToolId===void 0&&k.liveOnly===void 0?void 0:k},"activityEventMeta"),w=i((y,b={})=>{let k={...g(y,b)??{},...y?.toolId!==void 0?{toolId:y.toolId}:{}};return k.toolId===void 0&&k.workflowCorrelation===void 0&&k.childAgentId===void 0&&k.childAgentName===void 0&&k.parentToolId===void 0&&k.liveOnly===void 0?void 0:k},"toolEventMeta");return{...s?{workflowCorrelation:s}:{},onTextDelta:i((y,b)=>{o?.onTextDelta?.(y,g(b,{liveOnly:!0}))},"onTextDelta"),onThinkingDelta:i((y,b)=>{o?.onThinkingDelta?.(y,g(b,{liveOnly:!0}))},"onThinkingDelta"),onThinkingEnd:i((y,b)=>{o?.onThinkingEnd?.(y,g(b,{liveOnly:!0}))},"onThinkingEnd"),onStreamEnd:i(y=>{o?.onStreamEnd?.(g(y,{liveOnly:!0}))},"onStreamEnd"),onProviderRateLimit:i((y,b,v,k)=>{o?.onProviderRateLimit?.(y,b,v,g(k,{liveOnly:!0}))},"onProviderRateLimit"),onRetryAfter:i((y,b)=>{o?.onRetryAfter?.(y,g(b,{liveOnly:!0}))},"onRetryAfter"),onRetry:i((y,b,v,k)=>{o?.onRetry?.(y,b,v,g(k,{liveOnly:!0}))},"onRetry"),onProviderRecovery:i((y,b)=>{o?.onProviderRecovery?.(y,g(b,{liveOnly:!0}))},"onProviderRecovery"),beforeToolExecute:i(async(y,b,v)=>{if(m.has(y))return`[Tool Error] ${y}: Not available in child agent context.`;if(n){let k=n(y,b);if(k)return`${k} You are a child agent inheriting plan-mode constraints. Complete investigation and return findings as text \u2014 the parent agent will request user approval for any implementation.`}return o?.beforeToolExecute?o.beforeToolExecute(y,b,w(v)):!0},"beforeToolExecute"),onIterationStart:i((y,b)=>{d=y,u=b,r&&r({kind:"iteration",iteration:y,maxIterations:b})},"onIterationStart"),onIterationEnd:i(y=>{o?.onIterationEnd?.({...y,scope:"worker"})},"onIterationEnd"),onToolUseStart:i((y,b)=>{o?.onToolUseStart?.(y,w({...b?.toolId!==void 0?{toolId:b.toolId}:{toolId:y.id},...b?.workflowCorrelation!==void 0?{workflowCorrelation:b.workflowCorrelation}:{}},{liveOnly:!0}));let v=y.input&&typeof y.input=="object"?y.input.path??y.input.pattern??y.input.command??"":"",k=typeof v=="string"?v.slice(0,60):"",$=k?` ${k}`:"";p(`${e} [${d}/${u}] \u2192 ${y.name}${$}`),r&&r({kind:"tool-start",iteration:d,toolName:y.name,inputHint:k,startedAt:Date.now()})},"onToolUseStart"),onToolInputDelta:i((y,b,v)=>{o?.onToolInputDelta?.(y,b,w(v,{liveOnly:!0}))},"onToolInputDelta"),onToolProgress:i((y,b)=>{o?.onToolProgress?.(y,w({...b?.toolId!==void 0?{toolId:b.toolId}:{toolId:y.id},...b?.workflowCorrelation!==void 0?{workflowCorrelation:b.workflowCorrelation}:{}},{liveOnly:!0}))},"onToolProgress"),onToolResult:i((y,b)=>{o?.onToolResult?.(y,w({...b?.toolId!==void 0?{toolId:b.toolId}:{toolId:y.id},...b?.workflowCorrelation!==void 0?{workflowCorrelation:b.workflowCorrelation}:{}},{liveOnly:!0}))},"onToolResult"),...o?.askUser?{askUser:i((y,b)=>o.askUser(y,w(b,{liveOnly:!0})),"askUser")}:{},...o?.askUserMulti?{askUserMulti:i((y,b)=>o.askUserMulti(y,w(b,{liveOnly:!0})),"askUserMulti")}:{},...o?.askUserInput?{askUserInput:i((y,b)=>o.askUserInput(y,w(b,{liveOnly:!0})),"askUserInput")}:{}}}i(Zd,"buildChildEvents");function Qd(e){let t=new Set(["file_modified","file_created","file_deleted"]);return[...new Set((e.artifactLedger??[]).filter(n=>t.has(n.kind)).map(n=>n.target).filter(n=>n.trim().length>0))]}i(Qd,"extractMutationArtifactPaths");function xt(e,t,n,r={}){return{childId:e.id,fanoutClass:e.fanoutClass,status:n,disposition:n==="completed"?"valid":"needs-more-evidence",summary:t,evidenceRefs:e.evidenceRefs,contradictions:[],actualIterations:r.actualIterations,...r.totalTokensUsed!==void 0&&r.totalTokensUsed>0?{totalTokensUsed:r.totalTokensUsed}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.artifactPaths!==void 0&&r.artifactPaths.length>0?{artifactPaths:[...r.artifactPaths]}:{},...r.digest?{digest:r.digest}:{},...r.digestFailed?{digestFailed:!0}:{},...r.digestPending?{digestPending:!0}:{},...r.provider?{provider:r.provider}:{},...r.model?{model:r.model}:{},...r.structured!==void 0?{structured:r.structured}:{},interrupted:r.interrupted,...r.limitReached?{limitReached:!0}:{}}}i(xt,"extractChildResult");function lb(e,t,n){let r=new Map(e.map(l=>[l.id,l])),o=new Map(t.map(l=>[l.childId,l])),s=e.map(l=>o.get(l.id)).filter(l=>l!==void 0&&(l.status==="completed"||l.summary.length>0)).map(l=>({childId:l.childId,objective:r.get(l.childId)?.objective??"",evidence:[l.summary,...l.evidenceRefs],artifacts:l.artifactPaths??[]})),a=[...new Set(t.flatMap(l=>l.artifactPaths??[]))],c=t.reduce((l,d)=>l+(d.totalTokensUsed??0),0);return{results:t,mergedFindings:s,mergedArtifacts:a,totalTokensUsed:c,cancelledChildren:[...n]}}i(lb,"mergeChildResults");function db(e,t,n){return e.length===0?[]:t!=="worker"?[]:n!=="tool-dispatch"?[]:e}i(db,"validateWriteBundles");var Dd={results:[],mergedFindings:[],mergedArtifacts:[],totalTokensUsed:0,cancelledChildren:[]};function eu(e,t){ub(e,199);let n={childId:t.childId,status:"running",startedAt:t.startedAt,iterations:0,maxIterations:t.maxIterations,recentToolCalls:[],parentRole:t.parentRole,readOnly:t.readOnly,specialistName:t.specialistName};return e.set(t.childId,n),n}i(eu,"initChildSnapshot");function tu(e,t,n){if(!e)return;let r=e.get(t);r&&(r.status=n.status,r.endedAt=n.endedAt,n.finalText!==void 0&&(r.finalText=n.finalText))}i(tu,"finalizeChildSnapshot");function nu(e,t,n){if(!e)return;let r=e.get(t);if(!r)return;if(n.kind==="iteration"){r.iterations=n.iteration,r.maxIterations=n.maxIterations;return}let o={iteration:n.iteration,toolName:n.toolName,inputHint:n.inputHint,startedAt:n.startedAt};r.recentToolCalls=[...r.recentToolCalls,o].slice(-20)}i(nu,"applyChildSnapshotEvent");function ub(e,t){if(e.size<=t)return;let n=[...e.values()].sort((o,s)=>o.startedAt-s.startedAt),r=e.size-t;for(let o=0;o<r;o++)e.delete(n[o].childId)}i(ub,"pruneToCapacity");import{randomUUID as cu}from"node:crypto";var fb="emit_managed_protocol",UR="kodax-task-contract",pb="kodax-task-verdict",qR="kodax-task-scout",BR="kodax-task-handoff";function mb(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}i(mb,"asRecord");function ru(e){return e.trim().toLowerCase()===fb}i(ru,"isManagedProtocolToolName");function ou(e,t){if(!(!e&&!t))return{verdict:t?.verdict?{...e?.verdict??{},...t.verdict}:e?.verdict}}i(ou,"mergeManagedProtocolPayload");function hb(e){let t=e.trim().toLowerCase();if(!t)return;let r=t.replace(/[`"'()[\]{}<>]+/g,"").replace(/[.:;!?]+$/g,"").replace(/[_\s-]+/g," ").trim().split(/\s+/,1)[0]??"";if(r){if(/^accept(?:ed|s|ing)?$/.test(r)||r==="approve"||r==="approved")return"accept";if(/^revis(?:e|ed|es|ing)?$/.test(r))return"revise";if(/^block(?:ed|ing)?$/.test(r))return"blocked"}}i(hb,"normalizeManagedVerdictStatus");function gb(e){let t=e.trim();if(!t)return;let n=t.replace(/[`"'()[\]{}<>]+/g,"").replace(/[.:;!?]+$/g,"").replace(/[\s-]+/g,"_").trim().toUpperCase();if(n==="H1_EXECUTE_EVAL"||n==="H1")return"H1_EXECUTE_EVAL";if(n==="H2_PLAN_EXECUTE_EVAL"||n==="H2")return"H2_PLAN_EXECUTE_EVAL"}i(gb,"normalizeManagedNextHarness");function yb(e){return Array.isArray(e)?e.map(t=>String(t).trim()).filter(Boolean):typeof e=="string"?e.split(/\r?\n/).map(t=>t.replace(/^-+\s*/,"").trim()).filter(Boolean):[]}i(yb,"normalizeStringListValue");function WR(e,t,n=""){let r=mb(t);if(!r||e!=="evaluator")return;let o=typeof r.status=="string"?hb(r.status):void 0;if(o)return{verdict:{source:"evaluator",status:o,reason:typeof r.reason=="string"&&r.reason.trim()||void 0,followups:yb(r.followup??r.followups),userFacingText:n,userAnswer:typeof r.user_answer=="string"?r.user_answer.trim()||void 0:typeof r.userAnswer=="string"&&r.userAnswer.trim()||void 0,nextHarness:typeof(r.next_harness??r.nextHarness)=="string"?gb(String(r.next_harness??r.nextHarness)):void 0,budgetRequest:typeof(r.budget_request??r.budgetRequest)=="string"&&String(r.budget_request??r.budgetRequest).trim()||void 0}}}i(WR,"coerceManagedProtocolToolPayload");function HR(e){if(e==="evaluator")return pb}i(HR,"getManagedBlockNameForRole");function zR(e,t){return e&&t==="evaluator"?!!e.verdict:!1}i(zR,"hasManagedProtocolForRole");function GR(e,t){return new RegExp(String.raw`\`\`\`${t}\s*[\s\S]*?\`\`\``,"i").test(e)}i(GR,"textContainsManagedBlock");function et(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}i(et,"isFiniteNonNegative");function iu(e){return!(!e||!et(e.inputTokens)||!et(e.outputTokens)||!et(e.totalTokens)||e.totalTokens<e.inputTokens||e.totalTokens<e.outputTokens||e.cachedReadTokens!==void 0&&!et(e.cachedReadTokens)||e.cachedWriteTokens!==void 0&&!et(e.cachedWriteTokens)||e.thoughtTokens!==void 0&&!et(e.thoughtTokens))}i(iu,"hasValidTokenUsage");function su(e){let t=Be(e);return{currentTokens:t,baselineEstimatedTokens:t,source:"estimate"}}i(su,"createEstimatedContextTokenSnapshot");function wb(e,t){let n=Be(e);return{currentTokens:t.inputTokens,baselineEstimatedTokens:n,source:"api",usage:t}}i(wb,"createApiContextTokenSnapshot");function JR(e,t){return iu(t)?{currentTokens:t.totalTokens,baselineEstimatedTokens:Be(e),source:"api",usage:t}:su(e)}i(JR,"createCompletedTurnTokenSnapshot");function YR(e,t){return iu(t)?wb(e,t):su(e)}i(YR,"createContextTokenSnapshot");function bb(e,t){let n=Be(e);if(!t||!et(t.currentTokens)||!et(t.baselineEstimatedTokens))return n;let r=t.currentTokens+(n-t.baselineEstimatedTokens);return!Number.isFinite(r)||r<0?n:Math.round(r)}i(bb,"resolveContextTokenCount");function au(e,t){return{currentTokens:bb(e,t),baselineEstimatedTokens:Be(e),source:t?.source??"estimate",usage:t?.usage}}i(au,"rebaseContextTokenSnapshot");function ZR(e,t){let n=Be(e);return{currentTokens:n,baselineEstimatedTokens:n,source:t?.source??"estimate"}}i(ZR,"recomputeContextTokenSnapshot");var fu=Symbol("KodaXLiveTurnAttributed"),lu=Symbol("KodaXLiveTurnBaseEvents"),du=16,uu=new Map;function iO(e){let t=e.turnId??`turn_${cu().replace(/-/g,"").slice(0,du)}`,n=e.deliveryId??`delivery_${cu().replace(/-/g,"").slice(0,du)}`;return{sessionId:e.sessionId,turnId:t,deliveryId:n,deliveryKind:e.deliveryKind??"initial",promptId:e.promptId,nextMeta(){let r=(uu.get(e.sessionId)??0)+1;return uu.set(e.sessionId,r),{sessionId:e.sessionId,seq:r,turnId:t,deliveryId:n,timestamp:new Date().toISOString()}}}}i(iO,"createLiveTurnScope");function kb(e){return e[fu]===!0}i(kb,"isAttributedEvents");function pu(e){return"current"in e?e.current:e}i(pu,"resolveLiveTurnScope");function H(e,t){return{...t??{},...pu(e).nextMeta()}}i(H,"withActivityMeta");function fe(e,t){return{...t,...pu(e).nextMeta()}}i(fe,"withLiveMeta");function sO(e,t){let n=kb(e)?e[lu]:e,r={...n,onSessionStart:i(o=>{n.onSessionStart?.(fe(t,o))},"onSessionStart"),onTextDelta:i((o,s)=>{n.onTextDelta?.(o,H(t,s))},"onTextDelta"),onThinkingDelta:i((o,s)=>{n.onThinkingDelta?.(o,H(t,s))},"onThinkingDelta"),onThinkingEnd:i((o,s)=>{n.onThinkingEnd?.(o,H(t,s))},"onThinkingEnd"),onToolUseStart:i((o,s)=>{n.onToolUseStart?.(o,H(t,s))},"onToolUseStart"),onToolInputDelta:i((o,s,a)=>{n.onToolInputDelta?.(o,s,H(t,a))},"onToolInputDelta"),onToolProgress:i((o,s)=>{n.onToolProgress?.(o,H(t,s))},"onToolProgress"),onToolResult:i((o,s)=>{n.onToolResult?.(o,H(t,s))},"onToolResult"),onChildActivityEnd:i(o=>{n.onChildActivityEnd?.(H(t,o))},"onChildActivityEnd"),onStreamEnd:i(o=>{n.onStreamEnd?.(H(t,o))},"onStreamEnd"),onIterationStart:i((o,s,a)=>{n.onIterationStart?.(o,s,H(t,a))},"onIterationStart"),onIterationEnd:i(o=>{n.onIterationEnd?.(fe(t,o))},"onIterationEnd"),onCompactStart:i(o=>{n.onCompactStart?.(H(t,o))},"onCompactStart"),onCompact:i((o,s)=>{n.onCompact?.(o,H(t,s))},"onCompact"),onCompactStats:i(o=>{n.onCompactStats?.(fe(t,o))},"onCompactStats"),onCompactedMessages:i((o,s,a)=>{n.onCompactedMessages?.(o,s,H(t,a))},"onCompactedMessages"),onCompactEnd:i(o=>{n.onCompactEnd?.(H(t,o))},"onCompactEnd"),onMidTurnUserMessages:i((o,s)=>{n.onMidTurnUserMessages?.(o,H(t,s))},"onMidTurnUserMessages"),onRetry:i((o,s,a,c)=>{n.onRetry?.(o,s,a,H(t,c))},"onRetry"),onProviderRateLimit:i((o,s,a,c)=>{n.onProviderRateLimit?.(o,s,a,H(t,c))},"onProviderRateLimit"),onRetryAfter:i((o,s)=>{n.onRetryAfter?.(o,H(t,s))},"onRetryAfter"),onProviderRecovery:i((o,s)=>{n.onProviderRecovery?.(o,H(t,s))},"onProviderRecovery"),onReasoningEffortRejected:i(o=>{n.onReasoningEffortRejected?.(fe(t,o))},"onReasoningEffortRejected"),onRepoIntelligenceTrace:i(o=>{n.onRepoIntelligenceTrace?.(fe(t,o))},"onRepoIntelligenceTrace"),onSidecarMessage:i(o=>{n.onSidecarMessage?.(fe(t,o))},"onSidecarMessage"),onTodoUpdate:i((o,s)=>{n.onTodoUpdate?.(o,H(t,s))},"onTodoUpdate"),onTodoDriftWarning:i(o=>{n.onTodoDriftWarning?.(fe(t,o))},"onTodoDriftWarning"),onManagedTaskStatus:i(o=>{n.onManagedTaskStatus?.(fe(t,o))},"onManagedTaskStatus"),onEffectiveConfig:i(o=>{n.onEffectiveConfig?.(fe(t,o))},"onEffectiveConfig"),onWorkflowProcessEvent:i(o=>{n.onWorkflowProcessEvent?.(fe(t,o))},"onWorkflowProcessEvent"),onWorkflowAgentDigest:i(o=>{n.onWorkflowAgentDigest?.(fe(t,o))},"onWorkflowAgentDigest"),onScoutSuspiciousCompletion:i(o=>{n.onScoutSuspiciousCompletion?.(fe(t,o))},"onScoutSuspiciousCompletion"),onComplete:i(o=>{n.onComplete?.(H(t,o))},"onComplete"),onError:i((o,s)=>{n.onError?.(o,H(t,s))},"onError")};return Object.defineProperty(r,fu,{value:!0,enumerable:!1}),Object.defineProperty(r,lu,{value:n,enumerable:!1}),r}i(sO,"withLiveTurnAttribution");function aO(e,t){let n={...t.nextMeta(),deliveryKind:t.deliveryKind,...t.promptId!==void 0?{promptId:t.promptId}:{}};e.onTurnStarted?.(n)}i(aO,"emitTurnStarted");function cO(e,t,n){e.onTurnCompleted?.({...t.nextMeta(),status:n})}i(cO,"emitTurnCompleted");function lO(e,t,n){let r={...t.nextMeta(),error:{name:n.name,message:n.message,...n.stack!==void 0?{stack:n.stack}:{}}};e.onTurnFailed?.(r)}i(lO,"emitTurnFailed");var vb=new Set(["todo_update","todo_list","todo_create","todo_get"]);function dO(e){return!ru(e)&&!vb.has(e)}i(dO,"isVisibleToolName");function uO(e){return e.hasPendingInputs?.()===!0?!0:Ce().has({agentId:void 0,maxPriority:"user",mode:"prompt"})}i(uO,"hasQueuedFollowUp");function fO(e,t){e.onSessionStart?.(t)}i(fO,"emitSessionStart");function pO(e){e.onStreamEnd?.()}i(pO,"emitStreamEnd");function mO(e){e.onComplete?.()}i(mO,"emitComplete");function hO(e,t){e.onError?.(t)}i(hO,"emitError");function mu(e,t,n,r,o){if(o!==void 0){e.onProviderRateLimit?.(t,n,r,o);return}e.onProviderRateLimit?.(t,n,r)}i(mu,"emitProviderRateLimit");function gO(e,t,n){e.onIterationStart?.(t+1,n)}i(gO,"emitIterationStart");function yO(e,t){let n=au(t.messages,t.snapshotOverride??t.currentSnapshot);return e.onIterationEnd?.({iter:t.iter,maxIter:t.maxIter,tokenCount:n.currentTokens,tokenSource:n.source,usage:n.usage,contextTokenSnapshot:n}),n}i(yO,"emitIterationEnd");var hu=100*1024,Ki=8e3,_b=2e3,xb=3e4,Eb="You are a faithful lossy summarizer. Reply with the summary text only \u2014 no preamble, no closing remarks, no markdown code fences.";function Sb(e,t){return["The following content failed to spill to disk and is too large to inline",`into the agent's context. Compress to roughly ${Math.max(_b,Math.floor(t/4))}-${t} characters,`,"PRESERVING VERBATIM:","- All file paths, line numbers, error codes, identifiers","- All explicit findings, decisions, conclusions","- Section headers and list structure","You MAY omit: verbose prose, long examples, code snippets longer than 20 lines.","Reply with the summary ONLY. No preamble, no closing remarks.","","CONTENT:",e].join(`
213
+ `)}i(Sb,"buildSummarizerUserMessage");var on=class extends Error{static{i(this,"BlobSummarizerError")}cause;constructor(t,n){super(t),this.cause=n,this.name="BlobSummarizerError"}};function Tb(e){let t=new AbortController,n=[];for(let r of e){if(!r)continue;if(r.aborted){t.abort(r.reason);break}let o=i(()=>t.abort(r.reason),"onAbort");r.addEventListener("abort",o,{once:!0}),n.push(()=>r.removeEventListener("abort",o))}return{signal:t.signal,cleanup:i(()=>{for(let r of n)r()},"cleanup")}}i(Tb,"combineAbortSignals");function vO(e){let t=e.timeoutMs??xb;return async(n,r)=>{if(n.length===0)throw new on("blob summarizer called with empty content");let o=r?.maxChars??Ki,s=new AbortController,a=setTimeout(()=>s.abort(new Error("summarizer timeout")),t),{signal:c,cleanup:l}=Tb([r?.abortSignal,s.signal]),d=[{role:"user",content:Sb(n,o)}],u=e.events,f=u?{onRateLimit:i((h,p,g)=>{mu(u,h,p,g)},"onRateLimit"),onRetryAfter:i(h=>{u.onRetryAfter?.(h)},"onRetryAfter")}:void 0,m=f||e.model?{...f??{},...e.model?{modelOverride:e.model}:{}}:void 0;try{let p=(await e.provider.stream(d,[],Eb,void 0,m,c)).textBlocks.map(g=>g.text).join("").trim();if(p.length===0)throw new on(`blob summarizer (${e.model??"(default)"}) returned empty text`);return p}catch(h){if(h instanceof on)throw h;let p=h instanceof Error?h.message:String(h);throw new on(`blob summarizer (${e.model??"(default)"}) failed: ${p}`,h)}finally{clearTimeout(a),l()}}}i(vO,"createBlobSummarizer");var Ab=200,tt="dispatch_child_task",Dr=0;function Cb(){return Dr=Dr>=Number.MAX_SAFE_INTEGER?1:Dr+1,`child-${Date.now().toString(36)}-${Dr.toString(36)}`}i(Cb,"createGeneratedChildTaskId");async function Fr(e,t,n){let r=await An(e,t,n);if(!r.spillFailed||t.length<=hu||!n.summarizeBlob)return r.content;try{let o=await n.summarizeBlob(t,{maxChars:Ki,abortSignal:n.abortSignal});return[`[SPILL FAILED \u2014 original ${D(t.length)} compressed via LLM summarizer; raw content unavailable.`,"Worker: treat this summary as LOSSY. Critical decisions OK; fine-grained detail may be missing.","Re-run upstream tool with narrower scope if you need verbatim source.]","",o].join(`
214
+ `)}catch(o){let s=o instanceof Error?o.message:String(o);return console.warn(`[dispatch-child-tasks] LLM summarizer failed for ${e} (${D(t.length)}); inlining full content. Cause: ${s}`),[`[SPILL FAILED AND LLM SUMMARIZER FAILED \u2014 original ${D(t.length)} inlined as last-resort emergency dump.`,`Summarizer cause: ${s}.`,"Worker: this payload may exceed context budget. Treat as authoritative source but expect possible downstream truncation. Re-run upstream tool with narrower scope if you need a clean replay.]","",r.content].join(`
215
+ `)}}i(Fr,"applyChildSummaryGuardrailWithSummarizer");function $b(e){return process.env.KODAX_ASYNC_DISPATCH==="0"?!1:e.childTaskRegistry!==void 0}i($b,"shouldUseAsyncDispatch");function gu(e){let t=e.interrupted?"Child exited via the AbortError silent terminal (CAP-083) \u2014 typically means an upstream abortSignal fired before the child produced any text. Most common upstream causes: provider stream RST, parent-turn cleanup that propagated an abort, or a task_stop call.":"No interrupted flag \u2014 likely the model returned no text in its final assistant turn, or the envelope guardrail dropped all content.";return[`(child task "${e.childId}" completed but produced no observable text output.`,`Diagnostic: status=${e.status??"unknown"} interrupted=${e.interrupted} iterations=${e.iterations??"n/a"} results=${e.resultsCount} mergedFindings=${e.mergedFindingsCount} evidenceRefs=${e.evidenceRefsCount} provider=${e.provider??"?"} model=${e.model??"?"}.`,t,"Treat as inconclusive. Set KODAX_DISPATCH_CHILD_TRACE=1 to capture a JSON trace under `os.tmpdir()/kodax-dispatch-trace/` for the next reproduction.)"].join(`
216
+ `)}i(gu,"buildEmptySummaryFallback");function yu(e){let t=e.resultsCount===0?"silent-drop":(e.iterations??null)===0?"startup-crash":(e.iterations??0)>0?"mid-run-failure":"unknown",n=t==="silent-drop"?`Bundle never reached the child runner \u2014 typically a validation gate dropped it. Check executeChildAgents early-return paths (validateWriteBundles, empty-bundles guard) against parentRole=${e.parentRole??"?"} readOnly=${e.readOnly}.`:t==="startup-crash"?"Child runner errored before any assistant turn \u2014 most often run-substrate CAP-084 (success:false, lastText:'') triggered by a provider stream error on the first LLM call (rate limit / network / auth / context-size 4xx).":t==="mid-run-failure"?`Child runner produced ${e.iterations} assistant turn(s) then errored without retaining text \u2014 typically a mid-stream provider error or a tool-execution failure that left turnState.lastText empty.`:"Failure mode could not be classified \u2014 no childResult and no exception captured.";return[`(child task "${e.childId}" FAILED with no result text.`,`Diagnostic: status=${e.status??"failed"} mode=${t} iterations=${e.iterations??"n/a"} interrupted=${e.interrupted} results=${e.resultsCount} mergedFindings=${e.mergedFindingsCount} readOnly=${e.readOnly} parentRole=${e.parentRole??"?"} provider=${e.provider??"?"} model=${e.model??"?"}.`,n,"Treat as inconclusive \u2014 do NOT invent an infrastructure narrative without evidence. Set KODAX_DISPATCH_CHILD_TRACE=1 for a JSON trace at `os.tmpdir()/kodax-dispatch-trace/` to disambiguate the next reproduction.)"].join(`
217
+ `)}i(yu,"buildFailedEmptySummaryFallback");async function jr(e){if(process.env.KODAX_DISPATCH_CHILD_TRACE==="1")try{let[{tmpdir:t},{join:n},r]=await Promise.all([import("os"),import("path"),import("fs/promises")]),o=n(t(),"kodax-dispatch-trace");await r.mkdir(o,{recursive:!0});let s=new Date().toISOString().replace(/[:.]/g,"-"),a=e.childId.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,80),c=n(o,`${s}_${a}.json`),l=e.result?.results?.[0],d={timestamp:new Date().toISOString(),branch:e.branch,childId:e.childId,durationMs:e.durationMs,provider:e.provider??null,model:e.model??null,bundle:{objective:e.bundle.objective,readOnly:e.bundle.readOnly,scopeSummary:e.bundle.scopeSummary??null,evidenceRefsCount:e.bundle.evidenceRefs.length,constraintsCount:e.bundle.constraints.length,modelHint:e.bundle.modelHint??null,specialistName:e.bundle.specialistName??null},result:e.result===void 0?null:{resultsCount:e.result.results.length,mergedFindingsCount:e.result.mergedFindings.length,cancelledChildrenCount:e.result.cancelledChildren.length,childResult:l===void 0?null:{status:l.status,disposition:l.disposition,summaryLength:l.summary.length,summaryPreview:l.summary.slice(0,200),evidenceRefsCount:l.evidenceRefs.length,contradictionsCount:l.contradictions.length,actualIterations:l.actualIterations??null,interrupted:l.interrupted??null}},rawSummaryLength:e.rawSummary.length,rawSummaryPreview:e.rawSummary.slice(0,400),bannerContentLength:e.bannerContent.length,bannerContentPreview:e.bannerContent.slice(0,400),fallbackApplied:e.fallbackApplied,error:e.error?{message:e.error instanceof Error?e.error.message:String(e.error),name:e.error instanceof Error?e.error.name:"unknown"}:null};await r.writeFile(c,JSON.stringify(d,null,2),{mode:384})}catch{}}i(jr,"writeDispatchTraceIfEnabled");async function*wu(e,t){let n=typeof e.id=="string"?e.id.trim():"",r=typeof e.objective=="string"?e.objective.trim():"",o=n||Cb();if(!r)return yield{stage:"error",message:`Child "${o}": missing objective`},`[Tool Error] ${tt}: Missing required parameter: objective`;let s=t.managedProtocolRole,a=(e.read_only??e.readOnly)!==!1,c=Date.now();t.reportToolProgress?.(`[dispatch] start childId=${o} role=${s??"unknown"} readOnly=${a}`);let l="error",d=i(()=>{let S=Date.now()-c;t.reportToolProgress?.(`[dispatch] end childId=${o} status=${l} duration_ms=${S}`)},"emitDispatchEnd"),u=typeof e.model_hint=="string"?e.model_hint.trim():"",f=u==="fast"||u==="balanced"||u==="deep"?u:void 0,h=(typeof e.subagent_type=="string"?e.subagent_type.trim():"")||void 0,p;if(h){let S=Me(h);if(!S){let x=de().map(A=>A.name),R=x.length===0?"(none)":x.join(", ");return yield{stage:"error",message:`Child "${o}": specialist "${h}" not registered`},`[Tool Error] ${tt}: specialist "${h}" not registered. Available: ${R}`}if(!a&&s!=="worker")return`[Tool Error] ${tt}: specialist "${h}" is a write dispatch (readOnly=false) but current role "${s??"unknown"}" cannot dispatch write children. Only Worker may dispatch write specialists.`;if(S.effort!==void 0&&S.effort.trim().length>0)try{let x=lt(S.effort);p=x==="auto"?void 0:x}catch(x){let R=x instanceof Error?x.message:String(x);return`[Tool Error] ${tt}: specialist "${h}" declares invalid effort "${S.effort}". ${R}`}}let g=typeof e.provider=="string"&&e.provider.trim()?e.provider.trim():void 0,w=typeof e.model=="string"&&e.model.trim()?e.model.trim():void 0,y;if(typeof e.effort=="string"&&e.effort.trim())try{let S=lt(e.effort);y=S==="auto"?void 0:S}catch(S){let x=S instanceof Error?S.message:String(S);return`[Tool Error] ${tt}: invalid effort "${e.effort}". ${x}`}if(p!==void 0&&y!==void 0&&y!==p)return`[Tool Error] ${tt}: specialist "${h??"unknown"}" locks effort "${p}", but dispatch requested "${y}". Remove the dispatch effort or match the specialist effort.`;let b=p??y,v={id:o,fanoutClass:"evidence-scan",objective:r,readOnly:a,scopeSummary:typeof e.scope_summary=="string"?e.scope_summary:void 0,evidenceRefs:Array.isArray(e.evidence_refs)?e.evidence_refs.filter(S=>typeof S=="string"):[],constraints:Array.isArray(e.constraints)?e.constraints.filter(S=>typeof S=="string"):[],modelHint:f,specialistName:h,...g?{provider:g}:{},...w?{model:w}:{},...b?{effort:b}:{}},k=t.parentAgentConfig,$={maxParallel:1,maxIterationsPerChild:Ab,abortSignal:t.abortSignal,parentOptions:{provider:k?.provider,model:k?.model,reasoningMode:k?.reasoningMode,effort:k?.effort,repoIntelligenceMode:k?.repoIntelligenceMode,repoIntelligenceTrace:k?.repoIntelligenceTrace,extensionRuntime:t.extensionRuntime,events:t.parentEvents},parentRole:s??"worker",parentHarness:"tool-dispatch",onProgress:i(S=>{t.reportToolProgress?.(S)},"onProgress"),planModeBlockCheck:t.planModeBlockCheck,guardrails:t.guardrails};if($b(t)){let S=t.childTaskRegistry;if(!S)return yield{stage:"error",message:`Child "${o}": registry missing`},l="error",d(),`[Tool Error] ${tt}: childTaskRegistry not available`;if(S.has(o))return yield{stage:"error",message:`Child "${o}": duplicate task_id`},l="error",d(),`[Tool Error] ${tt}: task_id "${o}" is already in flight. Pick a unique id; the existing child will be reclaimed automatically via the idle-yield wait mechanic (its result will arrive as a <task-completed task_id="${o}"> block in your next user message).`;let x=new AbortController,R=t.abortSignal,A;if(R)if(R.aborted)x.abort(R.reason);else{let L=i(()=>{x.abort(R.reason)},"onParentAbort");R.addEventListener("abort",L,{once:!0}),A=i(()=>{R.removeEventListener("abort",L)},"detachParentAbortListener")}let O=t.childAbortControllers;O?.set(o,x);let P=t.childProgressSnapshots;P&&eu(P,{childId:o,startedAt:Date.now(),maxIterations:$.maxIterationsPerChild,parentRole:$.parentRole,readOnly:v.readOnly,specialistName:v.specialistName});let q={...$,abortSignal:x.signal,snapshotUpdater:P?L=>nu(P,o,L):void 0},E=Date.now(),T="failed",C,U=(async()=>{try{let L=await Wi([v],t,q),F=L.results[0],G=F?.status??"failed",ue=L.mergedFindings[0]?.evidence.join(`
218
+ `)??"",Ae=F?.summary??"",we,fn=!1;G==="completed"?ue.trim().length>0?we=ue:Ae.trim().length>0?we=Ae:(we=gu({childId:o,status:G,iterations:F?.actualIterations,interrupted:F?.interrupted===!0,evidenceRefsCount:F?.evidenceRefs.length??0,mergedFindingsCount:L.mergedFindings.length,resultsCount:L.results.length,provider:k?.provider,model:k?.model}),fn=!0):Ae.trim().length>0?we=`failed: ${Ae}`:(we=yu({childId:o,status:G,iterations:F?.actualIterations,interrupted:F?.interrupted===!0,resultsCount:L.results.length,mergedFindingsCount:L.mergedFindings.length,readOnly:v.readOnly,parentRole:s,provider:k?.provider,model:k?.model}),fn=!0);let Js=await Fr("child_task_summary",we,t);return pn({taskId:o,summary:Js,source:"child_task",status:G==="completed"?"completed":"failed"}),await jr({childId:o,bundle:v,result:L,rawSummary:we,bannerContent:Js,fallbackApplied:fn,provider:k?.provider,model:k?.model,durationMs:Date.now()-E,branch:"async-success"}),T=G==="completed"?"completed":"failed",C=we,L}catch(L){let F=L instanceof Error?L.message:String(L),G=`crash: ${F.length>0?F:"unknown error (Error.message was empty)"}`,ue=await Fr("child_task_summary",G,t);throw pn({taskId:o,summary:ue,source:"child_task",status:"failed"}),await jr({childId:o,bundle:v,result:void 0,rawSummary:G,bannerContent:ue,fallbackApplied:!1,provider:k?.provider,model:k?.model,error:L,durationMs:Date.now()-E,branch:"async-crash"}),T=L instanceof Error&&(L.name==="AbortError"||L.message.toLowerCase().includes("aborted"))?"aborted":"failed",C=G,L}finally{O?.delete(o),A?.(),tu(P,o,{status:T,finalText:C,endedAt:Date.now()})}})();return Yn(S,o,U),yield{stage:"launched",message:`Child "${o}" launched (async)`},l="launched",d(),`task_id:${o}
219
+ Child task "${o}" is running in the background. Do whatever interleaved work is useful (more dispatches, side-reads, drafting). When you have nothing else useful to do, end your turn with one short status sentence and NO tool calls \u2014 the runner will resume you when this child finishes (you will see a <task-completed task_id="${o}">\u2026</task-completed> block in your next user message).`}try{let S=await Wi([v],t,$),x=S.results[0],R=x?.status??"failed";if(l=R,yield{stage:"done",message:`Child "${o}" \u2192 ${R}`},!x||x.status==="failed"){let C=x?.summary&&x.summary.trim().length>0,U,L=!1;C?U=`Child task "${o}" failed: ${x.summary}`:(U=yu({childId:o,status:R,iterations:x?.actualIterations,interrupted:x?.interrupted===!0,resultsCount:S.results.length,mergedFindingsCount:S.mergedFindings.length,readOnly:v.readOnly,parentRole:s,provider:k?.provider,model:k?.model}),L=!0);let F=await Fr("child_task_summary",U,t);return await jr({childId:o,bundle:v,result:S,rawSummary:U,bannerContent:F,fallbackApplied:L,provider:k?.provider,model:k?.model,durationMs:Date.now()-c,branch:"sync"}),F}let A=S.mergedFindings[0],O=A?A.evidence.join(`
220
+ `):"",P=x.summary,q,E=!1;O.trim().length>0?q=O:P.trim().length>0?q=P:(q=gu({childId:o,status:R,iterations:x.actualIterations,interrupted:x.interrupted===!0,evidenceRefsCount:x.evidenceRefs.length,mergedFindingsCount:S.mergedFindings.length,resultsCount:S.results.length,provider:k?.provider,model:k?.model}),E=!0);let T=await Fr("child_task_summary",q,t);return await jr({childId:o,bundle:v,result:S,rawSummary:q,bannerContent:T,fallbackApplied:E,provider:k?.provider,model:k?.model,durationMs:Date.now()-c,branch:"sync"}),T}finally{d()}}i(wu,"toolDispatchChildTask");var Rb={results:[],mergedFindings:[],mergedArtifacts:[],totalTokensUsed:0,cancelledChildren:[]};function Xi(e){if(e.status==="completed"){let n=e.resultText?.trim(),r=e.verificationWarnings??[],o=r.length>0?`Workflow ${e.runId} completed, but ${r.length} agent(s) failed verification (warn-only): ${r.join(", ")}. Review before relying on the result.`:"",s=o.length>0?`${o}
221
+
222
+ `:"";return n&&n.length>0?`${s}${n}`:`${s}Workflow ${e.runId} completed (no displayable result text was returned).`}let t=e.error??e.resultText??"";return`[Tool Error] Workflow ${e.runId??""} ${e.status??"did not complete"}${t?`: ${t}`:""}`.trim()}i(Xi,"formatWorkflowOutcome");function bu(e){if(typeof e=="object"&&e!==null&&"name"in e){let t=e.name;if(typeof t=="string"&&t.trim().length>0)return t}return"workflow"}i(bu,"readManifestName");function Ob(e){return e.status==="completed"?"completed":e.status==="cancelled"||e.status==="stopped"?"cancelled":"failed"}i(Ob,"workflowTaskResultStatus");async function ku(e,t){let n=t.workflowHost;if(!n)return"[Tool Error] run_workflow is unavailable on this turn. Workflow authoring is enabled in AMAW mode, or in AMA when a workflow host is configured (e.g. via the /workflow command). Use dispatch_child_task for a single sub-task.";let r=e.source;if(typeof r!="string"||r.trim().length===0)return"[Tool Error] run_workflow requires a non-empty `source` string defining `async function run(wf, args) { ... }`.";let o=e.manifest;if(typeof o!="object"||o===null||Array.isArray(o))return"[Tool Error] run_workflow requires a `manifest` object (name, description, phases, readOnly, maxAgents, maxConcurrency, patterns).";let s={manifest:o,source:r,...e.args!==void 0?{args:e.args}:{},...typeof e.resumeFromRunId=="string"&&e.resumeFromRunId.length>0?{resumeFromRunId:e.resumeFromRunId}:{}},a=t.childTaskRegistry;if(a!==void 0&&process.env.KODAX_ASYNC_WORKFLOW!=="0"){let c=new AbortController,l;try{l=await n.startInline({...s,signal:c.signal})}catch(h){return`[Tool Error] run_workflow failed: ${h instanceof Error?h.message:String(h)}`}if(l.kind==="declined")return`Workflow not started: ${l.reason??"the workflow was declined"}`;let d=l.runId,u=l.done;if(a.has(d))try{return Xi(await u)}catch(h){return`[Tool Error] Workflow ${d} failed: ${h instanceof Error?h.message:String(h)}`}t.childAbortControllers?.set(d,c),l.getProgress&&t.workflowRunProgress?.set(d,l.getProgress);let f=(async()=>{let h,p="completed";try{let g=await u;p=Ob(g),h=Xi(g)}catch(g){p="failed",h=`[Tool Error] Workflow ${d} failed: ${g instanceof Error?g.message:String(g)}`}finally{t.childAbortControllers?.delete(d),t.workflowRunProgress?.delete(d)}return pn({taskId:d,summary:h,source:"workflow",runId:d,status:p,title:bu(o)}),Rb})();return Yn(a,d,f),`task_id:${d}
223
+ Workflow "${bu(o)}" started (run ${d}) and is now running in the background. Do NOT wait for it inline \u2014 its synthesized result will arrive on its own as a <task-completed task_id="${d}"> block in a later message. Idle-yield now (end your turn with no tool calls) if you have nothing else to do, or continue with other useful work; you will be resumed automatically when it finishes. To check how far it has gotten while it runs, call task_output("${d}") \u2014 it reports the current phase and which agents are running. If the goal changes before it finishes, call task_stop("${d}") to stop this run, then run_workflow again with the improved script \u2014 pass resumeFromRunId:"${d}" so the agents that already finished replay from cache and only the changed work re-runs.`}try{let c=await n.runInline(s);return c.kind==="declined"?`Workflow not started: ${c.reason??"the workflow was declined"}`:Xi(c)}catch(c){return`[Tool Error] run_workflow failed: ${c instanceof Error?c.message:String(c)}`}}i(ku,"toolRunWorkflow");var se="send_message",vu=20,Ib=20,Lb=5,_u=5,sn="worker";function Mb(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}i(Mb,"parseSeenBy");function Pb(e){return e??sn}i(Pb,"selfLabel");function nt(e){return e.replace(/[<>&]/g,t=>t==="<"?"&lt;":t===">"?"&gt;":"&amp;")}i(nt,"escapeTagBody");function Vi(e){return e.length===0?"":` seen_by="${e.map(nt).join(",")}"`}i(Vi,"formatSeenByAttr");function Ji(e,t){let n=e.sendMessageTurnCounter;if(!n)return null;let r=e.currentAgentId===void 0?Ib:Lb,o=e.currentAgentId===void 0?"Worker":"child";return n.count+t>r?`[Tool Error] ${se}: per-turn send_message limit reached for this ${o} (${n.count} already sent this turn + ${t} requested > cap ${r}). Wait until the next LLM turn \u2014 peer coordination that needs more than ${r} messages per turn is almost always a storm or a misfire.`:(n.count+=t,null)}i(Ji,"chargeTurnCounter");function Nb(e,t,n,r,o,s){let a=n??sn;if(s.slice(0,-1).includes(a))return`[Tool Error] ${se}: Cycle detected \u2014 parent "${a}" is already in seen_by (${s.slice(0,-1).join(" \u2192 ")}). Forwarding back to a prior sender would close a loop; the Worker has already handled this chain.`;let c=Ji(o,1);if(c)return c;let l=`<child-notification from="${nt(e)}"${Vi(s)}>
224
+ ${nt(t)}
225
+ </child-notification>`;return r.enqueue({priority:"background",mode:"task-notification",agentId:n,content:l}),`Message sent to ${n??sn}. It will surface as a <child-notification from="${e}"> block when the parent next yields.`}i(Nb,"sendToWorker");function Db(e,t,n,r,o){let s=n.childTaskRegistry;if(!s)return`[Tool Error] ${se}: Broadcast requires a sibling registry, but none is bound to this context (sync-mode dispatch). Send to a specific task_id or 'worker' instead.`;let a=n.parentAgentId,c=o.slice(0,-1),l=new Set(c),d=[...s.keys()].filter(w=>w!==e&&w!==a&&!l.has(w)),u=a??sn,f=e!==void 0&&!l.has(u)&&!l.has(sn),m=d.length+(f?1:0);if(m>vu)return`[Tool Error] ${se}: Broadcast target count ${m} exceeds cap ${vu}. Narrow the audience by sending to specific task_ids.`;if(m===0)return c.length>0?`[Tool Error] ${se}: Broadcast has zero novel recipients \u2014 every in-flight sibling and the parent are already in seen_by (${c.join(" \u2192 ")}). The chain is exhausted; stop forwarding.`:`[Tool Error] ${se}: Broadcast has zero recipients (no other in-flight siblings, and you have no parent Worker to notify).`;let h=Ji(n,m);if(h)return h;let p=e??sn,g=`<peer-broadcast from="${nt(p)}"${Vi(o)}>
226
+ ${nt(t)}
227
+ </peer-broadcast>`;for(let w of d)r.enqueue({priority:"background",mode:"prompt",agentId:w,content:g});return f&&r.enqueue({priority:"background",mode:"task-notification",agentId:n.parentAgentId,content:g}),`Broadcast sent from ${p} to ${m} target(s) (${d.length} sibling(s)${f?" + parent":""}). Recipients will see the <peer-broadcast> block when they next yield.`}i(Db,"broadcast");async function Yi(e,t){let n=typeof e.to=="string"?e.to.trim():"",r=typeof e.content=="string"?e.content.trim():"";if(!n)return`[Tool Error] ${se}: Missing required parameter: to (task_id of an in-flight sibling, 'worker' to notify the parent, or '*' to broadcast).`;if(!r)return`[Tool Error] ${se}: Missing required parameter: content (the message body).`;let o=Ce(),s=t.currentAgentId,a=Pb(s),l=[...Mb(e.seen_by),a];if(l.length>_u)return`[Tool Error] ${se}: Forward chain length ${l.length} exceeds cap ${_u} (chain: ${l.join(" \u2192 ")}). Peer messages are short coordination notes, not cascading forwards \u2014 stop the chain and let the Worker re-plan.`;if(n==="*")return Db(s,r,t,o,l);if(n==="worker")return s===void 0?`[Tool Error] ${se}: send_message(to='worker') is for children notifying their parent \u2014 you are the Worker (top of the agent tree).`:Nb(s,r,t.parentAgentId,o,t,l);let d=t.childTaskRegistry;if(!d)return`[Tool Error] ${se}: Async dispatch is disabled (no childTaskRegistry on context). Children run synchronously and complete inside their dispatch_child_task call \u2014 there is no in-flight target to steer.`;if(s!==void 0&&n===s)return`[Tool Error] ${se}: Cannot send a message to yourself (to='${n}'). Use task tools to record your own notes; send_message routes between distinct agents.`;let u=l.slice(0,-1);if(u.includes(n))return`[Tool Error] ${se}: Cycle detected \u2014 target "${n}" is already in seen_by (${u.join(" \u2192 ")}). Forwarding back to a prior sender would close a loop.`;let f=s===void 0,m=f?"user":"background",h=f?`<coordinator-instruction>
228
+ ${nt(r)}
229
+ </coordinator-instruction>`:`<peer-message from="${nt(s)}"${Vi(l)}>
230
+ ${nt(r)}
231
+ </peer-message>`,p=Ji(t,1);if(p)return p;let g=Zn({to:n,priority:m,mode:"prompt",content:h,registry:d,queue:Ce()});return g.ok?f?`Message sent to ${n}. It will be processed at the child's next LLM turn boundary as a <coordinator-instruction> block.`:`Peer message sent to ${n} from ${s}. It will be processed when the peer next yields as a <peer-message from="${s}"> block.`:`[Tool Error] ${se}: Unknown task_id "${g.to}". Verify the task_id matches one returned by dispatch_child_task and that the target has not already completed (completed children are auto-cleaned from the registry).`}i(Yi,"toolSendMessage");var Ur="task_stop";async function Zi(e,t){let n=typeof e.task_id=="string"?e.task_id.trim():"";if(!n)return`[Tool Error] ${Ur}: Missing required parameter: task_id (child task_id from dispatch_child_task)`;let r=typeof e.reason=="string"&&e.reason.trim().length>0?e.reason.trim():void 0,o=t.childAbortControllers;if(!o)return`[Tool Error] ${Ur}: Async dispatch is disabled (no childAbortControllers on context). Children run synchronously and complete inside their dispatch_child_task call \u2014 there is no in-flight target to stop.`;let s=sa({taskId:n,registry:o,reason:r});if(!s.ok)return s.reason==="unknown-target"?`[Tool Error] ${Ur}: Unknown task_id "${s.taskId}". Verify the task_id matches one returned by dispatch_child_task and that the child has not already completed (completed children are auto-cleaned from the registry).`:`[Tool Error] ${Ur}: Task "${s.taskId}" is already aborted (its first-abort cause is preserved). No additional action needed; the child will surface the cancellation at its next abort check.`;let a=t.childTaskRegistry;if(r&&a){let c=`<coordinator-stop-request>
217
232
  Reason: ${r}
218
233
  Finish your current tool call gracefully and emit a final summary.
219
- </coordinator-stop-request>`;zn({to:n,priority:"user",mode:"system-reminder",content:c,registry:a,queue:Se()})}return`task_stop signal sent to ${n}. Child will exit at its next abort check (currently-executing tool completes atomically first).`}i(Ui,"toolTaskStop");var Hd="task_output",$w=3e4,Ow=12e4,Iw=8192;async function Kd(e,t){let n=typeof e.task_id=="string"?e.task_id.trim():"";if(!n)return`[Tool Error] ${Hd}: Missing required parameter: task_id (child task_id from dispatch_child_task)`;let r=e.block,o=typeof r=="boolean"?r:typeof r=="string"?r==="true":!1,s=e.timeout_ms,a=$w;typeof s=="number"&&Number.isFinite(s)&&(a=Math.max(0,Math.min(Ow,Math.floor(s))));let c=t.childProgressSnapshots;if(!c)return`[Tool Error] ${Hd}: Async dispatch is disabled (no childProgressSnapshots on context). Children run synchronously and complete inside their dispatch_child_task call \u2014 there is no in-flight target to query.`;let l="success";if(o){let m=t.childTaskRegistry?.get(n);if(m){let h=new Promise(w=>setTimeout(()=>w("__timeout__"),a)),p=m.then(()=>"__settled__",()=>"__settled__");await Promise.race([p,h])==="__timeout__"&&(l="wait_expired")}}let d=c.get(n);if(!d){let f=t.workflowRunProgress?.get(n)?.();return f?Mw(n,f):Pw(n)}let u=Nw(d,l);return d.status!=="running"&&Lw(n),u}i(Kd,"toolTaskOutput");function Lw(e){let t=`<task-completed task_id="${e}">`;Se().dequeue({agentId:void 0,maxPriority:"background",mode:"task-notification",predicate:i(n=>n.content.startsWith(t),"predicate")})}i(Lw,"drainConsumedTaskNotification");function Mw(e,t){let n=["<retrieval_status>success</retrieval_status>",`<task_id>${Ze(e)}</task_id>`,"<kind>workflow</kind>",`<workflow>${Ze(t.workflowName)}</workflow>`,`<status>${t.status}</status>`];if(t.phase!==void 0){let a=t.phaseIndex!==void 0&&t.phaseTotal!==void 0?`${t.phaseIndex}/${t.phaseTotal} ${t.phase}`:t.phase;n.push(`<phase>${Ze(a)}</phase>`)}let r=t.completedAgents+t.failedAgents+t.stoppedAgents,o=Math.max(t.plannedAgents??0,t.totalSpawned,r),s=`${t.activeAgents.length} running, ${t.completedAgents} completed`+(t.failedAgents>0?`, ${t.failedAgents} failed`:"")+(t.stoppedAgents>0?`, ${t.stoppedAgents} stopped`:"")+(o>0?` (${r}/${o} finished)`:"");return n.push(`<agents>${s}</agents>`),t.activeAgents.length>0&&n.push(`<running_agents>${Ze(t.activeAgents.join(", "))}</running_agents>`),t.elapsedMs!==void 0&&n.push(`<duration_ms>${Math.max(0,Math.floor(t.elapsedMs))}</duration_ms>`),n.push(`<note>Workflow still running \u2014 do NOT wait on it inline; its synthesized result will arrive on its own as a <task-completed task_id="${Ze(e)}"> block when it finishes.</note>`),n.join(`
220
- `)}i(Mw,"renderWorkflowRunProgress");function Pw(e){return["<retrieval_status>not_found</retrieval_status>",`<task_id>${Ze(e)}</task_id>`,`<error>No snapshot for task_id "${Ze(e)}". The task may never have been dispatched, or it settled long enough ago that its snapshot was evicted under the per-runner cap (see CHILD_PROGRESS_SNAPSHOT_CAP).</error>`].join(`
221
- `)}i(Pw,"renderNotFound");function Nw(e,t){let n=Date.now(),r=e.endedAt??n,o=Math.max(0,r-e.startedAt),s=[`<retrieval_status>${t}</retrieval_status>`,`<task_id>${Ze(e.childId)}</task_id>`,`<status>${e.status}</status>`,`<iterations>${e.iterations}/${e.maxIterations}</iterations>`,`<duration_ms>${o}</duration_ms>`];if(t==="wait_expired"&&s.push("<note>The bounded read window expired. The child task has not timed out \u2014 read the `status` field above to decide whether it is still running.</note>"),e.recentToolCalls.length>0){s.push("<recent_tool_calls>");for(let a of e.recentToolCalls)s.push(` ${Dw(a)}`);s.push("</recent_tool_calls>")}else e.status==="running"&&s.push("<recent_tool_calls>(no tool calls yet \u2014 child has not started executing)</recent_tool_calls>");if(e.status!=="running"&&e.finalText!==void 0){let a=jw(e.finalText,Iw),c=e.status==="completed"?"output":"error";s.push(`<${c}>`),s.push(a),s.push(`</${c}>`)}return s.join(`
222
- `)}i(Nw,"renderSnapshot");function Dw(e){let t=e.inputHint?` ${e.inputHint}`:"";return`[iter ${e.iteration}] ${e.toolName}${t}`}i(Dw,"formatBreadcrumb");function jw(e,t){let n=Buffer.from(e,"utf8");if(n.byteLength<=t)return e;let r=n.byteLength-t;for(;r<n.byteLength&&(n[r]&192)===128;)r++;let o=n.subarray(r).toString("utf8");return`[...truncated to last ${t} bytes...]
223
- ${o}`}i(jw,"tailToBytes");function Ze(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}i(Ze,"escapeXmlContent");function zd(){let e="[Tool Error] /goal feature is not wired in this session (no host adapter \u2014 likely an isolated test harness or sync-dispatch context). Goal tools require a REPL session with lineage persistence.";return{readGoal:i(async()=>null,"readGoal"),createGoal:i(async()=>{throw new Error(e)},"createGoal"),requestComplete:i(async()=>({ok:!1,reason:e}),"requestComplete"),requestBlocked:i(async()=>({ok:!1,statusMessage:e,counter:{current:0,required:3}}),"requestBlocked")}}i(zd,"makeDisabledGoalToolsContext");import{randomBytes as Fw}from"node:crypto";function Gd(e){if(!e)return 0;let t=Math.max(0,(e.inputTokens??0)-(e.cachedReadTokens??0)),n=Math.max(0,e.outputTokens??0);return t+n}i(Gd,"goalTokenDelta");function qR(e,t){let n=t-e;return!Number.isFinite(n)||n<=0?0:Math.floor(n/1e3)}i(qR,"turnWallTimeDelta");function Xd(e,t,n){return n===null?!1:e+t>=n}i(Xd,"shouldFlipBudgetLimited");function Uw(e){return`${e}-${Fw(4).toString("hex")}`}i(Uw,"newGoalId");function zR(e,t,n=Date.now()){let r=e.trim();if(r.length===0)throw new Error("Goal objective must be a non-empty string");if(t!==null&&(!Number.isFinite(t)||t<=0))throw new Error(`Goal tokenBudget must be a positive finite number, got ${t}`);return Object.freeze({version:1,id:Uw(n),objective:r,status:"active",tokenBudget:t,tokensUsed:0,timeUsedSeconds:0,blockerTurnCount:0,lastBlockerKind:null,createdAt:n,updatedAt:n})}i(zR,"buildCreatedGoal");function GR(e,t,n,r=Date.now()){if(e.status!=="active")return{nextState:e,budgetLimited:!1};let o=Gd(t),s=Math.max(0,Math.floor(n));if(o===0&&s===0)return{nextState:e,budgetLimited:!1};let a=Xd(e.tokensUsed,o,e.tokenBudget);return{nextState:Object.freeze({...e,tokensUsed:e.tokensUsed+o,timeUsedSeconds:e.timeUsedSeconds+s,status:a?"budget_limited":e.status,updatedAt:r}),budgetLimited:a}}i(GR,"applyAccountingDelta");function XR(e,t=Date.now()){if(e.status!=="active")throw new Error(`Cannot pause goal from status '${e.status}'; only 'active' is pausable.`);return Object.freeze({...e,status:"paused",updatedAt:t})}i(XR,"buildPausedGoal");function VR(e,t=Date.now()){if(e.status!=="paused")throw new Error(`Cannot resume goal from status '${e.status}'; only 'paused' is resumable.`);return Object.freeze({...e,status:"active",updatedAt:t})}i(VR,"buildResumedGoal");function JR(e,t,n,r=Date.now()){if(e.status!=="active")throw new Error(`Cannot mark goal blocked from status '${e.status}'; only 'active' transitions to 'blocked'.`);return Object.freeze({...e,status:"blocked",lastBlockerKind:t,blockerTurnCount:n,updatedAt:r})}i(JR,"buildBlockedGoal");function YR(e,t=Date.now()){if(e.status!=="active")throw new Error(`Cannot mark goal complete from status '${e.status}'; only 'active' transitions to 'complete'.`);return Object.freeze({...e,status:"complete",updatedAt:t})}i(YR,"buildCompleteGoal");function Vd(e){return e===null?!0:typeof e=="number"&&Number.isFinite(e)&&e>0}i(Vd,"isValidTokenBudget");var qw="No goal set for this session. Use `/goal <objective>` (slash command) or call `create_goal` (only when the user or system instructions explicitly request a goal).";function qi(e){return e.goalContext??zd()}i(qi,"getCtx");async function Jd(e,t){let r=await qi(t).readGoal();if(!r)return qw;let o=[`Goal: ${r.objective}`,`Status: ${r.status}`,`Tokens used: ${r.tokensUsed}`];if(r.tokenBudget!==null){let s=Math.max(0,r.tokenBudget-r.tokensUsed);o.push(`Token budget: ${r.tokenBudget} (remaining: ${s})`)}else o.push("Token budget: none");return o.push(`Elapsed: ${r.timeUsedSeconds}s`),r.status==="blocked"&&r.lastBlockerKind&&o.push(`Blocker: ${r.lastBlockerKind}`),o.join(`
224
- `)}i(Jd,"toolGetGoal");async function Yd(e,t){let n=qi(t),r=typeof e.objective=="string"?e.objective.trim():"";if(!r)return"[Tool Error] create_goal: missing required parameter `objective` (a non-empty string describing the long-running goal).";let o=e.token_budget??null,s=o===null?null:Number(o);if(!Vd(s))return"[Tool Error] create_goal: token_budget must be a positive integer or omitted. Set this only when the user explicitly requested a budget.";try{let a=await n.createGoal({objective:r,tokenBudget:s}),c=a.tokenBudget!==null?` (budget: ${a.tokenBudget} tokens)`:"";return`Goal created: "${a.objective}"${c}. The agent will pursue this objective until completion, blocked confirmation, or user clear.`}catch(a){return`[Tool Error] create_goal: ${a instanceof Error?a.message:String(a)}`}}i(Yd,"toolCreateGoal");async function Qd(e,t){let n=qi(t),r=typeof e.status=="string"?e.status.trim():"";if(r!=="complete"&&r!=="blocked")return'[Tool Error] update_goal: status must be exactly "complete" or "blocked". Other status transitions (paused, resumed, cleared, budget_limited) are controlled by the user or the runtime, not this tool.';let o=await n.readGoal();if(!o)return"[Tool Error] update_goal: no active goal to update. Use create_goal first (only when explicitly requested by the user / system).";if(r==="complete"){let c=await n.requestComplete();if(c.ok)return`Goal marked complete: "${o.objective}".`;let l=c.suggestedFix?` Suggested next step: ${c.suggestedFix}`:"";return`[Tool Error] update_goal: completion verifier did not confirm. ${c.reason??"unspecified reason."}${l} Keep working until the objective is genuinely achieved.`}let s=typeof e.blocker_kind=="string"?e.blocker_kind.trim():"";if(!s)return"[Tool Error] update_goal: status=blocked requires a non-empty `blocker_kind` describing what is preventing progress.";let a=await n.requestBlocked(s);return a.ok?`Goal marked blocked: ${a.statusMessage}`:`[Tool Error] update_goal: ${a.statusMessage}`}i(Qd,"toolUpdateGoal");var Rn=3e4,Mr=i(async()=>"ask-user","defaultPolicy"),tn=class extends Error{static{i(this,"CapabilityDeniedError")}toolName;declaredTools;constructor(t,n){super(`Constructed handler attempted to call '${t}' but capabilities.tools only declares [${n.join(", ")||"<empty>"}]`),this.name="CapabilityDeniedError",this.toolName=t,this.declaredTools=n}},et=class extends Error{static{i(this,"ConstructionManifestError")}path;constructor(t,n){super(t),this.name="ConstructionManifestError",this.path=n}};import nt from"path";import kt from"fs/promises";import db from"crypto";function Pr(e){let t=e.indexOf(":");if(t===-1)return e;let n=e.slice(t+1),r=n.indexOf("@");return r===-1?n:n.slice(0,r)}i(Pr,"parseToolNameFromRef");function Bw(e){if(!(!e||e.length===0))return e.map(t=>({name:Pr(t.ref)}))}i(Bw,"refsToTools");function Ww(e){return{name:Pr(e),instructions:""}}i(Ww,"refToHandoffTargetAgent");function Hw(e){if(!(!e||e.length===0))return e.map(t=>({target:Ww(t.target.ref),kind:t.kind,description:t.description}))}i(Hw,"refsToHandoffs");function Kw(e){if(!(!e||e.length===0))return e}i(Kw,"passThroughDeclaredInvariants");function Z(e){let{name:t,content:n}=e,r=Bw(n.tools),o=Hw(n.handoffs),s=Kw(n.declaredInvariants);return{name:t,instructions:n.instructions,...r!==void 0?{tools:r}:{},...o!==void 0?{handoffs:o}:{},...n.reasoning!==void 0?{reasoning:n.reasoning}:{},...n.guardrails!==void 0?{guardrails:n.guardrails.map(c=>({kind:c.kind,name:Pr(c.ref)}))}:{},...n.model!==void 0?{model:n.model}:{},...n.provider!==void 0?{provider:n.provider}:{},...n.effort!==void 0?{effort:n.effort}:{},...n.outputSchema!==void 0?{outputSchema:n.outputSchema}:{},...n.maxBudget!==void 0?{maxBudget:n.maxBudget}:{},...s!==void 0?{declaredInvariants:s}:{}}}i(Z,"buildAdmissionManifest");var zw=3e4;function Gw(e,t){let n=[],r=!1;if(e.expectMatch!==void 0){r=!0;let o;try{o=new RegExp(e.expectMatch)}catch(s){return{caseId:e.id,ok:!1,output:t,error:`expectMatch is not a valid regex: ${s.message}`}}o.test(t)||n.push(`expectMatch ${JSON.stringify(e.expectMatch)} did not match output`)}if(e.expectNotMatch!==void 0){r=!0;let o;try{o=new RegExp(e.expectNotMatch)}catch(s){return{caseId:e.id,ok:!1,output:t,error:`expectNotMatch is not a valid regex: ${s.message}`}}o.test(t)&&n.push(`expectNotMatch ${JSON.stringify(e.expectNotMatch)} unexpectedly matched`)}return e.expectFinalText!==void 0&&(r=!0,t.includes(e.expectFinalText)||n.push(`expectFinalText ${JSON.stringify(e.expectFinalText)} not found in output`)),r?n.length>0?{caseId:e.id,ok:!1,output:t,error:n.join("; ")}:{caseId:e.id,ok:!0,output:t}:{caseId:e.id,ok:!1,output:t,error:"test case has no expectMatch / expectNotMatch / expectFinalText \u2014 at least one is required"}}i(Gw,"gradeCase");async function Xw(e,t,n,r){let o=new AbortController,s=!1,a,c=new Promise((l,d)=>{a=setTimeout(()=>{s=!0,o.abort(),d(new Error("SANDBOX_TIMEOUT"))},r)});try{let l=Y.run(e,t.input,{llm:n,tracer:null,abortSignal:o.signal});l.catch(()=>{});let d=await Promise.race([l,c]);return Gw(t,d.output)}catch(l){return s?{caseId:t.id,ok:!1,error:`timeout after ${r}ms`}:{caseId:t.id,ok:!1,error:l.message}}finally{a&&clearTimeout(a)}}i(Xw,"runOneCase");async function Bi(e,t){let n=e.content.testCases??[];if(n.length===0)return{ok:!0,cases:[]};let r=t.resolvedAgent??Oe(e.name);if(!r)return{ok:!1,cases:n.map(a=>({caseId:a.id,ok:!1,error:`sandbox: agent '${e.name}' not found in resolver and no resolvedAgent override supplied`}))};let o=t.budgetMs??zw,s=[];for(let a of n)s.push(await Xw(r,a,t.llm,o));return{ok:s.every(a=>a.ok),cases:s}}i(Bi,"runSandboxAgentTest");import Ki from"path";import tu from"fs/promises";import{pathToFileURL as Vw}from"url";var Zd=5,eu="__constructedDepth";function Wi(e,t,n={}){let r=e??{},o=new Set(t.tools),s=r[eu]??0,a=Object.create(null);for(let d of o)a[d]=async u=>{if(!o.has(d))throw n.onDenied?.({toolName:d,declaredTools:t.tools}),new tn(d,t.tools);let f=u&&typeof u=="object"&&!Array.isArray(u)?u:{},m=r.planModeBlockCheck;if(m){let y=m(d,f);if(y)return`[Tool Error] ${y} (called from constructed handler \u2014 plan-mode applies transitively).`}let p=tt(d)?.source.kind==="constructed",g=p?s+1:s;if(p&&g>Zd)return`[Tool Error] Constructed tool depth limit (${Zd}) exceeded calling '${d}'. Possible recursive composition (A\u2192B\u2192A); break the cycle or factor through a builtin tool.`;let w={...r,[eu]:g};return Hi(d,f,w)};let c=new Proxy(a,{get(d,u){if(typeof u=="symbol")return Reflect.get(d,u);if(Object.prototype.hasOwnProperty.call(d,u))return d[u];throw n.onDenied?.({toolName:u,declaredTools:t.tools}),new tn(u,t.tools)},set(){throw new Error("Constructed handler attempted to mutate ctx.tools")},deleteProperty(){throw new Error("Constructed handler attempted to delete ctx.tools entries")},has(d,u){return Object.prototype.hasOwnProperty.call(d,u)},ownKeys(d){return Reflect.ownKeys(d)},getPrototypeOf(){return null}});return Object.freeze({...r,tools:c})}i(Wi,"createCtxProxy");var Jw=Ki.join(".kodax","constructed","tools");async function zi(e,t,n,r={}){if(t.kind!=="script"||t.language!=="javascript")throw new Error(`Constructed handler must be { kind: 'script', language: 'javascript' } (got kind='${t.kind}', language='${t.language}'). v0.7.28 does not support TS handlers.`);let o=e.cwd??process.cwd(),s=Ki.resolve(o,Jw,e.name);await tu.mkdir(s,{recursive:!0});let a=Ki.join(s,`${e.version}.js`);await tu.writeFile(a,t.code,"utf8");let l=await import(Vw(a).href);if(typeof l.handler!="function")throw new Error(`Constructed handler '${e.name}@${e.version}' did not export 'handler' as a function. Expected: 'export async function handler(input, ctx) { ... }'`);let d=l.handler,u=r.timeoutMs??3e4,f=`${e.name}@${e.version}`;return i(async(h,p)=>{let g=Wi(p,n,r.ctxProxyOptions),w,y=new Promise((b,v)=>{w=setTimeout(()=>{v(new Error(`Constructed handler '${f}' timed out after ${u}ms`))},u)});try{let b=(async()=>d(h,g))(),v=await Promise.race([b,y]);return typeof v=="string"?v:JSON.stringify(v)}finally{w!==void 0&&clearTimeout(w)}},"wrapped")}i(zi,"loadHandler");import*as I from"typescript";function $n(e){let t=I.createSourceFile("handler.js",e,I.ScriptTarget.ES2022,!0,I.ScriptKind.JS),n=[],r=i(s=>{I.isCallExpression(s)&&I.isIdentifier(s.expression)&&s.expression.text==="eval"&&n.push({rule:"no-eval",message:"Calls to 'eval' are forbidden in constructed handlers."}),(I.isNewExpression(s)||I.isCallExpression(s))&&I.isIdentifier(s.expression)&&s.expression.text==="Function"&&n.push({rule:"no-Function-constructor",message:"Calls to 'Function(...)' / 'new Function(...)' are forbidden (equivalent to eval)."}),I.forEachChild(s,r)},"walk");r(t);let o=Yw(t);return o.ok||n.push({rule:"require-handler-signature",message:o.reason}),{ok:n.length===0,violations:n}}i($n,"runAstRules");function Yw(e){for(let t of e.statements){if(I.isFunctionDeclaration(t)&&t.name?.text==="handler"&&Gi(t,I.SyntaxKind.ExportKeyword))return Gi(t,I.SyntaxKind.AsyncKeyword)?t.parameters.length<2?{ok:!1,reason:"'handler' must accept at least (input, ctx) parameters."}:{ok:!0}:{ok:!1,reason:"'handler' export must be async."};if(I.isVariableStatement(t)&&Gi(t,I.SyntaxKind.ExportKeyword))for(let n of t.declarationList.declarations){if(!I.isIdentifier(n.name)||n.name.text!=="handler")continue;let r=n.initializer;return r?!I.isArrowFunction(r)&&!I.isFunctionExpression(r)?{ok:!1,reason:"'handler' export must be an async function (function declaration / async arrow / async function expression)."}:(r.modifiers??[]).some(s=>s.kind===I.SyntaxKind.AsyncKeyword)?r.parameters.length<2?{ok:!1,reason:"'handler' must accept at least (input, ctx) parameters."}:{ok:!0}:{ok:!1,reason:"'handler' export must be async."}:{ok:!1,reason:"'handler' export must be initialized to a function."}}}return{ok:!1,reason:"Module must export 'handler' as one of: `export async function handler(input, ctx) {...}` / `export const handler = async (input, ctx) => {...}` / `export const handler = async function (input, ctx) {...}`."}}i(Yw,"checkHandlerSignature");function Gi(e,t){return I.canHaveModifiers(e)?!!I.getModifiers(e)?.some(r=>r.kind===t):!1}i(Gi,"hasSyntaxKind");function On(e,t="anthropic"){let n={errors:[],warnings:[]};return t==="anthropic"?Nr(e,n,"$"):n.warnings.push(`No constructed-tool schema validator for provider '${t}'; relying on builtin dispatch path.`),{ok:n.errors.length===0,errors:n.errors,warnings:n.warnings}}i(On,"validateToolSchemaForProvider");function Nr(e,t,n){if(!nu(e)){t.errors.push(`${n}: input_schema must be a JSON object.`);return}n==="$"&&(e.type!=="object"&&t.errors.push(`${n}.type: Anthropic requires top-level input_schema.type === 'object' (got ${ru(e.type)}).`),"properties"in e||t.errors.push(`${n}.properties: Anthropic requires top-level input_schema.properties (object).`)),"$ref"in e&&t.errors.push(`${n}: $ref is not supported by Anthropic input_schema (no schema resolver). Inline the referenced shape.`);for(let r of["oneOf","anyOf","allOf"])r in e&&t.warnings.push(`${n}.${r}: Anthropic support for '${r}' is partial. Test with the target model before relying on it.`);if("required"in e){let r=e.required;(!Array.isArray(r)||r.some(o=>typeof o!="string"))&&t.errors.push(`${n}.required: must be an array of strings (got ${ru(r)}).`)}if(nu(e.properties)){let r=e.properties;for(let[o,s]of Object.entries(r))Nr(s,t,`${n}.properties.${o}`)}if("items"in e){let r=e.items;Array.isArray(r)?r.forEach((o,s)=>{Nr(o,t,`${n}.items[${s}]`)}):r!==void 0&&Nr(r,t,`${n}.items`)}}i(Nr,"validateAnthropic");function nu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(nu,"isPlainObject");function ru(e){if(typeof e=="string")return JSON.stringify(e);if(e===void 0)return"undefined";try{return JSON.stringify(e)}catch{return String(e)}}i(ru,"formatLiteral");function ou(e){let t=e.capabilities.tools.length>0?e.capabilities.tools.map(r=>`'${r}'`).join(", "):"<none>";return`You are KodaX reviewing a tool handler that another KodaX agent just generated. The handler will run in the host process with no JS-level sandbox; the only safety net at runtime is the capability whitelist below.${e.artifactRef?`
234
+ </coordinator-stop-request>`;Zn({to:n,priority:"user",mode:"system-reminder",content:c,registry:a,queue:Ce()})}return`task_stop signal sent to ${n}. Child will exit at its next abort check (currently-executing tool completes atomically first).`}i(Zi,"toolTaskStop");var xu="task_output",Fb=3e4,jb=12e4,Ub=8192;async function Eu(e,t){let n=typeof e.task_id=="string"?e.task_id.trim():"";if(!n)return`[Tool Error] ${xu}: Missing required parameter: task_id (child task_id from dispatch_child_task)`;let r=e.block,o=typeof r=="boolean"?r:typeof r=="string"?r==="true":!1,s=e.timeout_ms,a=Fb;typeof s=="number"&&Number.isFinite(s)&&(a=Math.max(0,Math.min(jb,Math.floor(s))));let c=t.childProgressSnapshots;if(!c)return`[Tool Error] ${xu}: Async dispatch is disabled (no childProgressSnapshots on context). Children run synchronously and complete inside their dispatch_child_task call \u2014 there is no in-flight target to query.`;let l="success";if(o){let m=t.childTaskRegistry?.get(n);if(m){let h=new Promise(w=>setTimeout(()=>w("__timeout__"),a)),p=m.then(()=>"__settled__",()=>"__settled__");await Promise.race([p,h])==="__timeout__"&&(l="wait_expired")}}let d=c.get(n);if(!d){let f=t.workflowRunProgress?.get(n)?.();return f?Bb(n,f):Wb(n)}let u=Hb(d,l);return d.status!=="running"&&qb(n),u}i(Eu,"toolTaskOutput");function qb(e){let t=`<task-completed task_id="${e}">`;Ce().dequeue({agentId:void 0,maxPriority:"background",mode:"task-notification",predicate:i(n=>n.content.startsWith(t),"predicate")})}i(qb,"drainConsumedTaskNotification");function Bb(e,t){let n=["<retrieval_status>success</retrieval_status>",`<task_id>${rt(e)}</task_id>`,"<kind>workflow</kind>",`<workflow>${rt(t.workflowName)}</workflow>`,`<status>${t.status}</status>`];if(t.phase!==void 0){let a=t.phaseIndex!==void 0&&t.phaseTotal!==void 0?`${t.phaseIndex}/${t.phaseTotal} ${t.phase}`:t.phase;n.push(`<phase>${rt(a)}</phase>`)}let r=t.completedAgents+t.failedAgents+t.stoppedAgents,o=Math.max(t.plannedAgents??0,t.totalSpawned,r),s=`${t.activeAgents.length} running, ${t.completedAgents} completed`+(t.failedAgents>0?`, ${t.failedAgents} failed`:"")+(t.stoppedAgents>0?`, ${t.stoppedAgents} stopped`:"")+(o>0?` (${r}/${o} finished)`:"");return n.push(`<agents>${s}</agents>`),t.activeAgents.length>0&&n.push(`<running_agents>${rt(t.activeAgents.join(", "))}</running_agents>`),t.elapsedMs!==void 0&&n.push(`<duration_ms>${Math.max(0,Math.floor(t.elapsedMs))}</duration_ms>`),n.push(`<note>Workflow still running \u2014 do NOT wait on it inline; its synthesized result will arrive on its own as a <task-completed task_id="${rt(e)}"> block when it finishes.</note>`),n.join(`
235
+ `)}i(Bb,"renderWorkflowRunProgress");function Wb(e){return["<retrieval_status>not_found</retrieval_status>",`<task_id>${rt(e)}</task_id>`,`<error>No snapshot for task_id "${rt(e)}". The task may never have been dispatched, or it settled long enough ago that its snapshot was evicted under the per-runner cap (see CHILD_PROGRESS_SNAPSHOT_CAP).</error>`].join(`
236
+ `)}i(Wb,"renderNotFound");function Hb(e,t){let n=Date.now(),r=e.endedAt??n,o=Math.max(0,r-e.startedAt),s=[`<retrieval_status>${t}</retrieval_status>`,`<task_id>${rt(e.childId)}</task_id>`,`<status>${e.status}</status>`,`<iterations>${e.iterations}/${e.maxIterations}</iterations>`,`<duration_ms>${o}</duration_ms>`];if(t==="wait_expired"&&s.push("<note>The bounded read window expired. The child task has not timed out \u2014 read the `status` field above to decide whether it is still running.</note>"),e.recentToolCalls.length>0){s.push("<recent_tool_calls>");for(let a of e.recentToolCalls)s.push(` ${zb(a)}`);s.push("</recent_tool_calls>")}else e.status==="running"&&s.push("<recent_tool_calls>(no tool calls yet \u2014 child has not started executing)</recent_tool_calls>");if(e.status!=="running"&&e.finalText!==void 0){let a=Gb(e.finalText,Ub),c=e.status==="completed"?"output":"error";s.push(`<${c}>`),s.push(a),s.push(`</${c}>`)}return s.join(`
237
+ `)}i(Hb,"renderSnapshot");function zb(e){let t=e.inputHint?` ${e.inputHint}`:"";return`[iter ${e.iteration}] ${e.toolName}${t}`}i(zb,"formatBreadcrumb");function Gb(e,t){let n=Buffer.from(e,"utf8");if(n.byteLength<=t)return e;let r=n.byteLength-t;for(;r<n.byteLength&&(n[r]&192)===128;)r++;let o=n.subarray(r).toString("utf8");return`[...truncated to last ${t} bytes...]
238
+ ${o}`}i(Gb,"tailToBytes");function rt(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}i(rt,"escapeXmlContent");function Su(){let e="[Tool Error] /goal feature is not wired in this session (no host adapter \u2014 likely an isolated test harness or sync-dispatch context). Goal tools require a REPL session with lineage persistence.";return{readGoal:i(async()=>null,"readGoal"),createGoal:i(async()=>{throw new Error(e)},"createGoal"),requestComplete:i(async()=>({ok:!1,reason:e}),"requestComplete"),requestBlocked:i(async()=>({ok:!1,statusMessage:e,counter:{current:0,required:3}}),"requestBlocked")}}i(Su,"makeDisabledGoalToolsContext");import{randomBytes as Kb}from"node:crypto";function Tu(e){if(!e)return 0;let t=Math.max(0,(e.inputTokens??0)-(e.cachedReadTokens??0)),n=Math.max(0,e.outputTokens??0);return t+n}i(Tu,"goalTokenDelta");function XO(e,t){let n=t-e;return!Number.isFinite(n)||n<=0?0:Math.floor(n/1e3)}i(XO,"turnWallTimeDelta");function Au(e,t,n){return n===null?!1:e+t>=n}i(Au,"shouldFlipBudgetLimited");function Xb(e){return`${e}-${Kb(4).toString("hex")}`}i(Xb,"newGoalId");function QO(e,t,n=Date.now()){let r=e.trim();if(r.length===0)throw new Error("Goal objective must be a non-empty string");if(t!==null&&(!Number.isFinite(t)||t<=0))throw new Error(`Goal tokenBudget must be a positive finite number, got ${t}`);return Object.freeze({version:1,id:Xb(n),objective:r,status:"active",tokenBudget:t,tokensUsed:0,timeUsedSeconds:0,blockerTurnCount:0,lastBlockerKind:null,createdAt:n,updatedAt:n})}i(QO,"buildCreatedGoal");function eI(e,t,n,r=Date.now()){if(e.status!=="active")return{nextState:e,budgetLimited:!1};let o=Tu(t),s=Math.max(0,Math.floor(n));if(o===0&&s===0)return{nextState:e,budgetLimited:!1};let a=Au(e.tokensUsed,o,e.tokenBudget);return{nextState:Object.freeze({...e,tokensUsed:e.tokensUsed+o,timeUsedSeconds:e.timeUsedSeconds+s,status:a?"budget_limited":e.status,updatedAt:r}),budgetLimited:a}}i(eI,"applyAccountingDelta");function tI(e,t=Date.now()){if(e.status!=="active")throw new Error(`Cannot pause goal from status '${e.status}'; only 'active' is pausable.`);return Object.freeze({...e,status:"paused",updatedAt:t})}i(tI,"buildPausedGoal");function nI(e,t=Date.now()){if(e.status!=="paused")throw new Error(`Cannot resume goal from status '${e.status}'; only 'paused' is resumable.`);return Object.freeze({...e,status:"active",updatedAt:t})}i(nI,"buildResumedGoal");function rI(e,t,n,r=Date.now()){if(e.status!=="active")throw new Error(`Cannot mark goal blocked from status '${e.status}'; only 'active' transitions to 'blocked'.`);return Object.freeze({...e,status:"blocked",lastBlockerKind:t,blockerTurnCount:n,updatedAt:r})}i(rI,"buildBlockedGoal");function oI(e,t=Date.now()){if(e.status!=="active")throw new Error(`Cannot mark goal complete from status '${e.status}'; only 'active' transitions to 'complete'.`);return Object.freeze({...e,status:"complete",updatedAt:t})}i(oI,"buildCompleteGoal");function Cu(e){return e===null?!0:typeof e=="number"&&Number.isFinite(e)&&e>0}i(Cu,"isValidTokenBudget");var Vb="No goal set for this session. Use `/goal <objective>` (slash command) or call `create_goal` (only when the user or system instructions explicitly request a goal).";function Qi(e){return e.goalContext??Su()}i(Qi,"getCtx");async function $u(e,t){let r=await Qi(t).readGoal();if(!r)return Vb;let o=[`Goal: ${r.objective}`,`Status: ${r.status}`,`Tokens used: ${r.tokensUsed}`];if(r.tokenBudget!==null){let s=Math.max(0,r.tokenBudget-r.tokensUsed);o.push(`Token budget: ${r.tokenBudget} (remaining: ${s})`)}else o.push("Token budget: none");return o.push(`Elapsed: ${r.timeUsedSeconds}s`),r.status==="blocked"&&r.lastBlockerKind&&o.push(`Blocker: ${r.lastBlockerKind}`),o.join(`
239
+ `)}i($u,"toolGetGoal");async function Ru(e,t){let n=Qi(t),r=typeof e.objective=="string"?e.objective.trim():"";if(!r)return"[Tool Error] create_goal: missing required parameter `objective` (a non-empty string describing the long-running goal).";let o=e.token_budget??null,s=o===null?null:Number(o);if(!Cu(s))return"[Tool Error] create_goal: token_budget must be a positive integer or omitted. Set this only when the user explicitly requested a budget.";try{let a=await n.createGoal({objective:r,tokenBudget:s}),c=a.tokenBudget!==null?` (budget: ${a.tokenBudget} tokens)`:"";return`Goal created: "${a.objective}"${c}. The agent will pursue this objective until completion, blocked confirmation, or user clear.`}catch(a){return`[Tool Error] create_goal: ${a instanceof Error?a.message:String(a)}`}}i(Ru,"toolCreateGoal");async function Ou(e,t){let n=Qi(t),r=typeof e.status=="string"?e.status.trim():"";if(r!=="complete"&&r!=="blocked")return'[Tool Error] update_goal: status must be exactly "complete" or "blocked". Other status transitions (paused, resumed, cleared, budget_limited) are controlled by the user or the runtime, not this tool.';let o=await n.readGoal();if(!o)return"[Tool Error] update_goal: no active goal to update. Use create_goal first (only when explicitly requested by the user / system).";if(r==="complete"){let c=await n.requestComplete();if(c.ok)return`Goal marked complete: "${o.objective}".`;let l=c.suggestedFix?` Suggested next step: ${c.suggestedFix}`:"";return`[Tool Error] update_goal: completion verifier did not confirm. ${c.reason??"unspecified reason."}${l} Keep working until the objective is genuinely achieved.`}let s=typeof e.blocker_kind=="string"?e.blocker_kind.trim():"";if(!s)return"[Tool Error] update_goal: status=blocked requires a non-empty `blocker_kind` describing what is preventing progress.";let a=await n.requestBlocked(s);return a.ok?`Goal marked blocked: ${a.statusMessage}`:`[Tool Error] update_goal: ${a.statusMessage}`}i(Ou,"toolUpdateGoal");var Mn=3e4,qr=i(async()=>"ask-user","defaultPolicy"),an=class extends Error{static{i(this,"CapabilityDeniedError")}toolName;declaredTools;constructor(t,n){super(`Constructed handler attempted to call '${t}' but capabilities.tools only declares [${n.join(", ")||"<empty>"}]`),this.name="CapabilityDeniedError",this.toolName=t,this.declaredTools=n}},ot=class extends Error{static{i(this,"ConstructionManifestError")}path;constructor(t,n){super(t),this.name="ConstructionManifestError",this.path=n}};import st from"path";import Tt from"fs/promises";import wk from"crypto";function Br(e){let t=e.indexOf(":");if(t===-1)return e;let n=e.slice(t+1),r=n.indexOf("@");return r===-1?n:n.slice(0,r)}i(Br,"parseToolNameFromRef");function Jb(e){if(!(!e||e.length===0))return e.map(t=>({name:Br(t.ref)}))}i(Jb,"refsToTools");function Yb(e){return{name:Br(e),instructions:""}}i(Yb,"refToHandoffTargetAgent");function Zb(e){if(!(!e||e.length===0))return e.map(t=>({target:Yb(t.target.ref),kind:t.kind,description:t.description}))}i(Zb,"refsToHandoffs");function Qb(e){if(!(!e||e.length===0))return e}i(Qb,"passThroughDeclaredInvariants");function te(e){let{name:t,content:n}=e,r=Jb(n.tools),o=Zb(n.handoffs),s=Qb(n.declaredInvariants);return{name:t,instructions:n.instructions,...r!==void 0?{tools:r}:{},...o!==void 0?{handoffs:o}:{},...n.reasoning!==void 0?{reasoning:n.reasoning}:{},...n.guardrails!==void 0?{guardrails:n.guardrails.map(c=>({kind:c.kind,name:Br(c.ref)}))}:{},...n.model!==void 0?{model:n.model}:{},...n.provider!==void 0?{provider:n.provider}:{},...n.effort!==void 0?{effort:n.effort}:{},...n.outputSchema!==void 0?{outputSchema:n.outputSchema}:{},...n.maxBudget!==void 0?{maxBudget:n.maxBudget}:{},...s!==void 0?{declaredInvariants:s}:{}}}i(te,"buildAdmissionManifest");var ek=3e4;function tk(e,t){let n=[],r=!1;if(e.expectMatch!==void 0){r=!0;let o;try{o=new RegExp(e.expectMatch)}catch(s){return{caseId:e.id,ok:!1,output:t,error:`expectMatch is not a valid regex: ${s.message}`}}o.test(t)||n.push(`expectMatch ${JSON.stringify(e.expectMatch)} did not match output`)}if(e.expectNotMatch!==void 0){r=!0;let o;try{o=new RegExp(e.expectNotMatch)}catch(s){return{caseId:e.id,ok:!1,output:t,error:`expectNotMatch is not a valid regex: ${s.message}`}}o.test(t)&&n.push(`expectNotMatch ${JSON.stringify(e.expectNotMatch)} unexpectedly matched`)}return e.expectFinalText!==void 0&&(r=!0,t.includes(e.expectFinalText)||n.push(`expectFinalText ${JSON.stringify(e.expectFinalText)} not found in output`)),r?n.length>0?{caseId:e.id,ok:!1,output:t,error:n.join("; ")}:{caseId:e.id,ok:!0,output:t}:{caseId:e.id,ok:!1,output:t,error:"test case has no expectMatch / expectNotMatch / expectFinalText \u2014 at least one is required"}}i(tk,"gradeCase");async function nk(e,t,n,r){let o=new AbortController,s=!1,a,c=new Promise((l,d)=>{a=setTimeout(()=>{s=!0,o.abort(),d(new Error("SANDBOX_TIMEOUT"))},r)});try{let l=Y.run(e,t.input,{llm:n,tracer:null,abortSignal:o.signal});l.catch(()=>{});let d=await Promise.race([l,c]);return tk(t,d.output)}catch(l){return s?{caseId:t.id,ok:!1,error:`timeout after ${r}ms`}:{caseId:t.id,ok:!1,error:l.message}}finally{a&&clearTimeout(a)}}i(nk,"runOneCase");async function es(e,t){let n=e.content.testCases??[];if(n.length===0)return{ok:!0,cases:[]};let r=t.resolvedAgent??Me(e.name);if(!r)return{ok:!1,cases:n.map(a=>({caseId:a.id,ok:!1,error:`sandbox: agent '${e.name}' not found in resolver and no resolvedAgent override supplied`}))};let o=t.budgetMs??ek,s=[];for(let a of n)s.push(await nk(r,a,t.llm,o));return{ok:s.every(a=>a.ok),cases:s}}i(es,"runSandboxAgentTest");import rs from"path";import Mu from"fs/promises";import{pathToFileURL as rk}from"url";var Iu=5,Lu="__constructedDepth";function ts(e,t,n={}){let r=e??{},o=new Set(t.tools),s=r[Lu]??0,a=Object.create(null);for(let d of o)a[d]=async u=>{if(!o.has(d))throw n.onDenied?.({toolName:d,declaredTools:t.tools}),new an(d,t.tools);let f=u&&typeof u=="object"&&!Array.isArray(u)?u:{},m=r.planModeBlockCheck;if(m){let y=m(d,f);if(y)return`[Tool Error] ${y} (called from constructed handler \u2014 plan-mode applies transitively).`}let p=it(d)?.source.kind==="constructed",g=p?s+1:s;if(p&&g>Iu)return`[Tool Error] Constructed tool depth limit (${Iu}) exceeded calling '${d}'. Possible recursive composition (A\u2192B\u2192A); break the cycle or factor through a builtin tool.`;let w={...r,[Lu]:g};return ns(d,f,w)};let c=new Proxy(a,{get(d,u){if(typeof u=="symbol")return Reflect.get(d,u);if(Object.prototype.hasOwnProperty.call(d,u))return d[u];throw n.onDenied?.({toolName:u,declaredTools:t.tools}),new an(u,t.tools)},set(){throw new Error("Constructed handler attempted to mutate ctx.tools")},deleteProperty(){throw new Error("Constructed handler attempted to delete ctx.tools entries")},has(d,u){return Object.prototype.hasOwnProperty.call(d,u)},ownKeys(d){return Reflect.ownKeys(d)},getPrototypeOf(){return null}});return Object.freeze({...r,tools:c})}i(ts,"createCtxProxy");var ok=rs.join(".kodax","constructed","tools");async function os(e,t,n,r={}){if(t.kind!=="script"||t.language!=="javascript")throw new Error(`Constructed handler must be { kind: 'script', language: 'javascript' } (got kind='${t.kind}', language='${t.language}'). v0.7.28 does not support TS handlers.`);let o=e.cwd??process.cwd(),s=rs.resolve(o,ok,e.name);await Mu.mkdir(s,{recursive:!0});let a=rs.join(s,`${e.version}.js`);await Mu.writeFile(a,t.code,"utf8");let l=await import(rk(a).href);if(typeof l.handler!="function")throw new Error(`Constructed handler '${e.name}@${e.version}' did not export 'handler' as a function. Expected: 'export async function handler(input, ctx) { ... }'`);let d=l.handler,u=r.timeoutMs??3e4,f=`${e.name}@${e.version}`;return i(async(h,p)=>{let g=ts(p,n,r.ctxProxyOptions),w,y=new Promise((b,v)=>{w=setTimeout(()=>{v(new Error(`Constructed handler '${f}' timed out after ${u}ms`))},u)});try{let b=(async()=>d(h,g))(),v=await Promise.race([b,y]);return typeof v=="string"?v:JSON.stringify(v)}finally{w!==void 0&&clearTimeout(w)}},"wrapped")}i(os,"loadHandler");import*as M from"typescript";function Pn(e){let t=M.createSourceFile("handler.js",e,M.ScriptTarget.ES2022,!0,M.ScriptKind.JS),n=[],r=i(s=>{M.isCallExpression(s)&&M.isIdentifier(s.expression)&&s.expression.text==="eval"&&n.push({rule:"no-eval",message:"Calls to 'eval' are forbidden in constructed handlers."}),(M.isNewExpression(s)||M.isCallExpression(s))&&M.isIdentifier(s.expression)&&s.expression.text==="Function"&&n.push({rule:"no-Function-constructor",message:"Calls to 'Function(...)' / 'new Function(...)' are forbidden (equivalent to eval)."}),M.forEachChild(s,r)},"walk");r(t);let o=ik(t);return o.ok||n.push({rule:"require-handler-signature",message:o.reason}),{ok:n.length===0,violations:n}}i(Pn,"runAstRules");function ik(e){for(let t of e.statements){if(M.isFunctionDeclaration(t)&&t.name?.text==="handler"&&is(t,M.SyntaxKind.ExportKeyword))return is(t,M.SyntaxKind.AsyncKeyword)?t.parameters.length<2?{ok:!1,reason:"'handler' must accept at least (input, ctx) parameters."}:{ok:!0}:{ok:!1,reason:"'handler' export must be async."};if(M.isVariableStatement(t)&&is(t,M.SyntaxKind.ExportKeyword))for(let n of t.declarationList.declarations){if(!M.isIdentifier(n.name)||n.name.text!=="handler")continue;let r=n.initializer;return r?!M.isArrowFunction(r)&&!M.isFunctionExpression(r)?{ok:!1,reason:"'handler' export must be an async function (function declaration / async arrow / async function expression)."}:(r.modifiers??[]).some(s=>s.kind===M.SyntaxKind.AsyncKeyword)?r.parameters.length<2?{ok:!1,reason:"'handler' must accept at least (input, ctx) parameters."}:{ok:!0}:{ok:!1,reason:"'handler' export must be async."}:{ok:!1,reason:"'handler' export must be initialized to a function."}}}return{ok:!1,reason:"Module must export 'handler' as one of: `export async function handler(input, ctx) {...}` / `export const handler = async (input, ctx) => {...}` / `export const handler = async function (input, ctx) {...}`."}}i(ik,"checkHandlerSignature");function is(e,t){return M.canHaveModifiers(e)?!!M.getModifiers(e)?.some(r=>r.kind===t):!1}i(is,"hasSyntaxKind");function Nn(e,t="anthropic"){let n={errors:[],warnings:[]};return t==="anthropic"?Wr(e,n,"$"):n.warnings.push(`No constructed-tool schema validator for provider '${t}'; relying on builtin dispatch path.`),{ok:n.errors.length===0,errors:n.errors,warnings:n.warnings}}i(Nn,"validateToolSchemaForProvider");function Wr(e,t,n){if(!Pu(e)){t.errors.push(`${n}: input_schema must be a JSON object.`);return}n==="$"&&(e.type!=="object"&&t.errors.push(`${n}.type: Anthropic requires top-level input_schema.type === 'object' (got ${Nu(e.type)}).`),"properties"in e||t.errors.push(`${n}.properties: Anthropic requires top-level input_schema.properties (object).`)),"$ref"in e&&t.errors.push(`${n}: $ref is not supported by Anthropic input_schema (no schema resolver). Inline the referenced shape.`);for(let r of["oneOf","anyOf","allOf"])r in e&&t.warnings.push(`${n}.${r}: Anthropic support for '${r}' is partial. Test with the target model before relying on it.`);if("required"in e){let r=e.required;(!Array.isArray(r)||r.some(o=>typeof o!="string"))&&t.errors.push(`${n}.required: must be an array of strings (got ${Nu(r)}).`)}if(Pu(e.properties)){let r=e.properties;for(let[o,s]of Object.entries(r))Wr(s,t,`${n}.properties.${o}`)}if("items"in e){let r=e.items;Array.isArray(r)?r.forEach((o,s)=>{Wr(o,t,`${n}.items[${s}]`)}):r!==void 0&&Wr(r,t,`${n}.items`)}}i(Wr,"validateAnthropic");function Pu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Pu,"isPlainObject");function Nu(e){if(typeof e=="string")return JSON.stringify(e);if(e===void 0)return"undefined";try{return JSON.stringify(e)}catch{return String(e)}}i(Nu,"formatLiteral");function Du(e){let t=e.capabilities.tools.length>0?e.capabilities.tools.map(r=>`'${r}'`).join(", "):"<none>";return`You are KodaX reviewing a tool handler that another KodaX agent just generated. The handler will run in the host process with no JS-level sandbox; the only safety net at runtime is the capability whitelist below.${e.artifactRef?`
225
240
  Artifact: ${e.artifactRef}
226
241
  `:""}
227
242
  Declared capabilities (the only builtin tools the handler may invoke through ctx.tools.<name>):
@@ -247,9 +262,9 @@ Handler source:
247
262
  \`\`\`javascript
248
263
  ${e.handlerCode}
249
264
  \`\`\`
250
- `}i(ou,"buildLlmReviewPrompt");function iu(e){let t=Qw(e);if(!t)throw new Error("LLM review output did not contain a JSON object.");let n=t.verdict;if(n!=="safe"&&n!=="suspicious"&&n!=="dangerous")throw new Error(`LLM review output had invalid verdict '${String(n)}'; expected 'safe' | 'suspicious' | 'dangerous'.`);let r=t.concerns,o=Array.isArray(r)?r.filter(c=>typeof c=="string"):[],s=t.suggested_capabilities,a=Array.isArray(s)?s.filter(c=>typeof c=="string"):[];return{verdict:n,concerns:o,suggestedCapabilities:a,raw:e}}i(iu,"parseLlmReviewVerdict");async function Vi(e,t){let n=ou(e),r=await t(n);return iu(r)}i(Vi,"runLlmReview");function Qw(e){let t=e.trim();if(t.startsWith("{")){let c=Xi(t);if(c!==void 0)return c}let n=/```(?:json)?\s*([\s\S]*?)\s*```/i.exec(t);if(n){let c=Xi(n[1].trim());if(c!==void 0)return c}let r=t.indexOf("{");if(r===-1)return;let o=0,s=!1,a=!1;for(let c=r;c<t.length;c+=1){let l=t[c];if(a){a=!1;continue}if(l==="\\"){a=!0;continue}if(l==='"'){s=!s;continue}if(!s&&(l==="{"&&(o+=1),l==="}"&&(o-=1,o===0))){let d=t.slice(r,c+1),u=Xi(d);return u!==void 0?u:void 0}}}i(Qw,"extractJsonObject");function Xi(e){try{let t=JSON.parse(e);return t&&typeof t=="object"?t:void 0}catch{return}}i(Xi,"tryParseJson");import Dr from"path";import Ji from"fs/promises";import Zw from"crypto";var su=Dr.join(".kodax","constructed","_audit.jsonl");async function Ie(e,t={}){let n=t.cwd??process.cwd(),r=Dr.resolve(n,su);await Ji.mkdir(Dr.dirname(r),{recursive:!0});let o=JSON.stringify(e)+`
251
- `;await Ji.appendFile(r,o,"utf8")}i(Ie,"appendAuditEntry");async function eb(e={}){let t=e.cwd??process.cwd(),n=Dr.resolve(t,su),r;try{r=await Ji.readFile(n,"utf8")}catch(c){if(c.code==="ENOENT")return[];throw c}let o=e.agentName,s=e.events?new Set(e.events):void 0,a=[];for(let c of r.split(`
252
- `)){let l=c.trim();if(l.length===0)continue;let d;try{d=JSON.parse(l)}catch{console.warn(`[ConstructionRuntime] Skipping malformed audit line: ${l.slice(0,80)}\u2026`);continue}o!==void 0&&d.agentName!==o||s!==void 0&&!s.has(d.event)||a.push(d)}return a}i(eb,"readAuditEntries");function wt(e,t){let n=JSON.stringify({prev:e,next:t},tb);return Zw.createHash("sha256").update(n).digest("hex")}i(wt,"computeDiffHash");function tb(e,t){if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t,r={};for(let o of Object.keys(n).sort())r[o]=n[o];return r}return t}i(tb,"sortedReplacer");import au from"path";import Yi from"fs/promises";var Qi=3,nb="_self_modify.json";function cu(e,t){return au.resolve(e,".kodax","constructed","agents",t,nb)}i(cu,"budgetPath");async function bt(e,t={}){let n=t.cwd??process.cwd(),r=cu(n,e);try{let o=await Yi.readFile(r,"utf8"),s=JSON.parse(o),a=typeof s.count=="number"?s.count:0;return{name:e,limit:Qi,count:Math.max(0,a),lastModifiedAt:s.lastModifiedAt}}catch(o){if(o.code==="ENOENT")return{name:e,limit:Qi,count:0};throw o}}i(bt,"readBudget");function nn(e){return Math.max(0,e.limit-e.count)}i(nn,"remaining");async function lu(e,t={}){let n=t.cwd??process.cwd(),r=await bt(e,{cwd:n}),o={name:e,limit:r.limit,count:r.count+1,lastModifiedAt:new Date().toISOString()};return await du(n,o),o}i(lu,"consumeBudget");async function rb(e,t={}){let n=t.cwd??process.cwd(),r=await bt(e,{cwd:n}),o={name:e,limit:r.limit,count:0,lastModifiedAt:new Date().toISOString()};return await du(n,o),o}i(rb,"resetBudget");async function du(e,t){let n=cu(e,t.name);await Yi.mkdir(au.dirname(n),{recursive:!0});let r={name:t.name,count:t.count,...t.lastModifiedAt?{lastModifiedAt:t.lastModifiedAt}:{}};await Yi.writeFile(n,JSON.stringify(r,null,2),"utf8")}i(du,"persist");import uu from"path";import Zi from"fs/promises";var ob="_self_modify_disabled.json";function fu(e,t){return uu.resolve(e,".kodax","constructed","agents",t,ob)}i(fu,"disablePath");async function In(e,t={}){let n=t.cwd??process.cwd(),r=fu(n,e);try{let o=await Zi.readFile(r,"utf8"),s;try{s=JSON.parse(o)}catch{return console.warn(`[ConstructionRuntime] Treating malformed disable marker at ${r} as disabled (fail-safe).`),{name:e,disabled:!0}}return{name:e,disabled:!0,disabledAt:typeof s.disabledAt=="string"?s.disabledAt:void 0,user:typeof s.user=="string"?s.user:void 0}}catch(o){if(o.code==="ENOENT")return{name:e,disabled:!1};throw o}}i(In,"readDisableState");async function ib(e,t={}){let n=t.cwd??process.cwd(),r=fu(n,e);await Zi.mkdir(uu.dirname(r),{recursive:!0});let o={name:e,disabled:!0,disabledAt:new Date().toISOString(),...t.user?{user:t.user}:{}};return await Zi.writeFile(r,JSON.stringify(o,null,2),"utf8"),o}i(ib,"disableSelfModify");function sb(e){let t=JSON.stringify(e.prev,null,2),n=JSON.stringify(e.next,null,2);return`You are KodaX reviewing a self-modify proposal a constructed agent has submitted for itself. The agent named '${e.agentName}' (active version ${e.fromVersion}) is proposing to replace its own manifest with a new version ${e.toVersion}.
265
+ `}i(Du,"buildLlmReviewPrompt");function Fu(e){let t=sk(e);if(!t)throw new Error("LLM review output did not contain a JSON object.");let n=t.verdict;if(n!=="safe"&&n!=="suspicious"&&n!=="dangerous")throw new Error(`LLM review output had invalid verdict '${String(n)}'; expected 'safe' | 'suspicious' | 'dangerous'.`);let r=t.concerns,o=Array.isArray(r)?r.filter(c=>typeof c=="string"):[],s=t.suggested_capabilities,a=Array.isArray(s)?s.filter(c=>typeof c=="string"):[];return{verdict:n,concerns:o,suggestedCapabilities:a,raw:e}}i(Fu,"parseLlmReviewVerdict");async function as(e,t){let n=Du(e),r=await t(n);return Fu(r)}i(as,"runLlmReview");function sk(e){let t=e.trim();if(t.startsWith("{")){let c=ss(t);if(c!==void 0)return c}let n=/```(?:json)?\s*([\s\S]*?)\s*```/i.exec(t);if(n){let c=ss(n[1].trim());if(c!==void 0)return c}let r=t.indexOf("{");if(r===-1)return;let o=0,s=!1,a=!1;for(let c=r;c<t.length;c+=1){let l=t[c];if(a){a=!1;continue}if(l==="\\"){a=!0;continue}if(l==='"'){s=!s;continue}if(!s&&(l==="{"&&(o+=1),l==="}"&&(o-=1,o===0))){let d=t.slice(r,c+1),u=ss(d);return u!==void 0?u:void 0}}}i(sk,"extractJsonObject");function ss(e){try{let t=JSON.parse(e);return t&&typeof t=="object"?t:void 0}catch{return}}i(ss,"tryParseJson");import Hr from"path";import cs from"fs/promises";import ak from"crypto";var ju=Hr.join(".kodax","constructed","_audit.jsonl");async function Pe(e,t={}){let n=t.cwd??process.cwd(),r=Hr.resolve(n,ju);await cs.mkdir(Hr.dirname(r),{recursive:!0});let o=JSON.stringify(e)+`
266
+ `;await cs.appendFile(r,o,"utf8")}i(Pe,"appendAuditEntry");async function ck(e={}){let t=e.cwd??process.cwd(),n=Hr.resolve(t,ju),r;try{r=await cs.readFile(n,"utf8")}catch(c){if(c.code==="ENOENT")return[];throw c}let o=e.agentName,s=e.events?new Set(e.events):void 0,a=[];for(let c of r.split(`
267
+ `)){let l=c.trim();if(l.length===0)continue;let d;try{d=JSON.parse(l)}catch{console.warn(`[ConstructionRuntime] Skipping malformed audit line: ${l.slice(0,80)}\u2026`);continue}o!==void 0&&d.agentName!==o||s!==void 0&&!s.has(d.event)||a.push(d)}return a}i(ck,"readAuditEntries");function Et(e,t){let n=JSON.stringify({prev:e,next:t},lk);return ak.createHash("sha256").update(n).digest("hex")}i(Et,"computeDiffHash");function lk(e,t){if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t,r={};for(let o of Object.keys(n).sort())r[o]=n[o];return r}return t}i(lk,"sortedReplacer");import Uu from"path";import ls from"fs/promises";var ds=3,dk="_self_modify.json";function qu(e,t){return Uu.resolve(e,".kodax","constructed","agents",t,dk)}i(qu,"budgetPath");async function St(e,t={}){let n=t.cwd??process.cwd(),r=qu(n,e);try{let o=await ls.readFile(r,"utf8"),s=JSON.parse(o),a=typeof s.count=="number"?s.count:0;return{name:e,limit:ds,count:Math.max(0,a),lastModifiedAt:s.lastModifiedAt}}catch(o){if(o.code==="ENOENT")return{name:e,limit:ds,count:0};throw o}}i(St,"readBudget");function cn(e){return Math.max(0,e.limit-e.count)}i(cn,"remaining");async function Bu(e,t={}){let n=t.cwd??process.cwd(),r=await St(e,{cwd:n}),o={name:e,limit:r.limit,count:r.count+1,lastModifiedAt:new Date().toISOString()};return await Wu(n,o),o}i(Bu,"consumeBudget");async function uk(e,t={}){let n=t.cwd??process.cwd(),r=await St(e,{cwd:n}),o={name:e,limit:r.limit,count:0,lastModifiedAt:new Date().toISOString()};return await Wu(n,o),o}i(uk,"resetBudget");async function Wu(e,t){let n=qu(e,t.name);await ls.mkdir(Uu.dirname(n),{recursive:!0});let r={name:t.name,count:t.count,...t.lastModifiedAt?{lastModifiedAt:t.lastModifiedAt}:{}};await ls.writeFile(n,JSON.stringify(r,null,2),"utf8")}i(Wu,"persist");import Hu from"path";import us from"fs/promises";var fk="_self_modify_disabled.json";function zu(e,t){return Hu.resolve(e,".kodax","constructed","agents",t,fk)}i(zu,"disablePath");async function Dn(e,t={}){let n=t.cwd??process.cwd(),r=zu(n,e);try{let o=await us.readFile(r,"utf8"),s;try{s=JSON.parse(o)}catch{return console.warn(`[ConstructionRuntime] Treating malformed disable marker at ${r} as disabled (fail-safe).`),{name:e,disabled:!0}}return{name:e,disabled:!0,disabledAt:typeof s.disabledAt=="string"?s.disabledAt:void 0,user:typeof s.user=="string"?s.user:void 0}}catch(o){if(o.code==="ENOENT")return{name:e,disabled:!1};throw o}}i(Dn,"readDisableState");async function pk(e,t={}){let n=t.cwd??process.cwd(),r=zu(n,e);await us.mkdir(Hu.dirname(r),{recursive:!0});let o={name:e,disabled:!0,disabledAt:new Date().toISOString(),...t.user?{user:t.user}:{}};return await us.writeFile(r,JSON.stringify(o,null,2),"utf8"),o}i(pk,"disableSelfModify");function mk(e){let t=JSON.stringify(e.prev,null,2),n=JSON.stringify(e.next,null,2);return`You are KodaX reviewing a self-modify proposal a constructed agent has submitted for itself. The agent named '${e.agentName}' (active version ${e.fromVersion}) is proposing to replace its own manifest with a new version ${e.toVersion}.
253
268
 
254
269
  Your role is to summarise the change for the human operator who will approve or reject it. You are NOT making the decision \u2014 produce a faithful description of what changed and flag anything that looks suspicious. The operator sees the full prev/next manifests too.
255
270
 
@@ -277,50 +292,50 @@ Proposed manifest (${e.toVersion}):
277
292
  \`\`\`json
278
293
  ${n}
279
294
  \`\`\`
280
- `}i(sb,"buildSelfModifyDiffPrompt");function ab(e){let t={summary:"LLM summary unavailable \u2014 review the raw manifest diff carefully before approving.",severity:"major",flaggedConcerns:["LLM reviewer did not return a parseable summary."],raw:e},n=lb(e);if(!n)return t;let r;try{r=JSON.parse(n)}catch{return t}let o=typeof r.summary=="string"?r.summary:void 0,s=cb(r.severity)?r.severity:void 0,a=Array.isArray(r.flaggedConcerns)?r.flaggedConcerns.filter(c=>typeof c=="string"):void 0;return!o||!s||!a?t:{summary:o,severity:s,flaggedConcerns:a,raw:e}}i(ab,"parseSelfModifyDiffSummary");function cb(e){return e==="minor"||e==="moderate"||e==="major"}i(cb,"isSeverity");function lb(e){let t=e.indexOf("{");if(t===-1)return;let n=0,r=!1,o=!1;for(let s=t;s<e.length;s+=1){let a=e[s];if(r){o?o=!1:a==="\\"?o=!0:a==='"'&&(r=!1);continue}if(a==='"'){r=!0;continue}if(a==="{")n+=1;else if(a==="}"&&(n-=1,n===0))return e.slice(t,s+1)}}i(lb,"extractFirstJsonObject");async function pu(e,t){let n=sb(e),r;try{r=await t(n)}catch(o){return{summary:`LLM summary unavailable \u2014 reviewer threw: ${o.message}`,severity:"major",flaggedConcerns:["LLM reviewer call failed."]}}return ab(r)}i(pu,"runSelfModifyDiffSummary");var ts=nt.join(".kodax","constructed");function rt(e,t){if(typeof e!="string"||e.length===0||e.length>128)throw new et(`Invalid ${t}: must be a non-empty string \u2264 128 chars (got ${typeof e=="string"?`length=${e.length}`:typeof e}).`);if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(e)||e.includes(".."))throw new et(`Invalid ${t} ${JSON.stringify(e)}: must match [A-Za-z0-9][A-Za-z0-9._-]* with no '..' sequences. Reserved separator/control characters and parent-traversal segments are rejected.`)}i(rt,"assertSafeIdentifier");function ns(e){return db.createHash("sha256").update(JSON.stringify(e)).digest("hex")}i(ns,"computeContentHash");var rs=["tool","agent"],j={cwd:process.cwd(),policy:Mr},ot=new Map;function ub(e){j={cwd:e.cwd??j.cwd,policy:e.policy??j.policy,llmReviewer:e.llmReviewer??j.llmReviewer,selfModifyAskUser:e.selfModifyAskUser??j.selfModifyAskUser}}i(ub,"configureRuntime");function os(){return j.cwd}i(os,"getRuntimeCwd");function fb(){for(let e of ot.values())e();ot.clear(),es(),j={cwd:process.cwd(),policy:Mr,llmReviewer:void 0,selfModifyAskUser:void 0}}i(fb,"_resetRuntimeForTesting");async function vt(e){rt(e.name,"artifact.name"),rt(e.version,"artifact.version");let t=as(e);try{let r=await kt.readFile(t,"utf8"),o=JSON.parse(r);throw new et(`Cannot stage '${e.name}@${e.version}': a manifest already exists at this version (status='${o.status}'). Constructed artifacts are version-immutable \u2014 bump the semver to publish a new variant. Re-staging the same version would silently shadow the cached ESM module, even after revoke.`,t)}catch(r){if(r instanceof et||r.code!=="ENOENT")throw r}let n={...e,status:"staged",createdAt:e.createdAt||Date.now(),testedAt:void 0,activatedAt:void 0,revokedAt:void 0,contentHash:void 0};return await rn(n),{artifact:n,stagedAt:Date.now()}}i(vt,"stage");async function Ln(e,t={}){let{artifact:n}=e;return n.kind==="tool"?pb(n,t):n.kind==="agent"?mb(n,t):{ok:!1,errors:[`Unsupported artifact kind '${n.kind??"<missing>"}'. Runtime understands: ${rs.join(", ")}.`]}}i(Ln,"test");async function pb(e,t){let n=[],r=[];if(e.content.handler.language!=="javascript"&&n.push(`Handler language must be 'javascript' (got '${e.content.handler.language}').`),!Array.isArray(e.content.capabilities.tools))n.push("capabilities.tools must be an array of strings.");else for(let c of e.content.capabilities.tools)if(typeof c!="string"||c.trim().length===0){n.push(`capabilities.tools entry must be a non-empty string (got: ${JSON.stringify(c)}).`);break}if(n.length>0)return{ok:!1,errors:n};let o=$n(e.content.handler.code);if(!o.ok){for(let c of o.violations)n.push(`[${c.rule}] ${c.message}`);return{ok:!1,errors:n}}let s=On(e.content.inputSchema,t.provider??"anthropic");for(let c of s.warnings)r.push(c);if(!s.ok){for(let c of s.errors)n.push(`[schema] ${c}`);return{ok:!1,errors:n,warnings:r}}if(t.llmReviewer){let c;try{c=await Vi({handlerCode:e.content.handler.code,capabilities:e.content.capabilities,artifactRef:`${e.name}@${e.version}`},t.llmReviewer)}catch(l){return n.push(`LLM review failed to produce a verdict: ${l.message}`),{ok:!1,errors:n,warnings:r}}if(c.verdict==="dangerous"){n.push("LLM review verdict='dangerous'.");for(let l of c.concerns)n.push(`[review] ${l}`);return{ok:!1,errors:n,warnings:r}}if(c.verdict==="suspicious"){r.push("LLM review verdict='suspicious' \u2014 policy gate will see these concerns:");for(let l of c.concerns)r.push(`[review] ${l}`)}}let a={...e,testedAt:Date.now()};return await rn(a),r.length>0?{ok:!0,warnings:r}:{ok:!0}}i(pb,"testToolArtifact");async function mb(e,t){let n=[],r=[];if((typeof e.content.instructions!="string"||e.content.instructions.length===0)&&n.push("agent.content.instructions must be a non-empty string."),e.content.tools!==void 0)if(!Array.isArray(e.content.tools))n.push("agent.content.tools, when present, must be an array of ToolRef objects.");else for(let l=0;l<e.content.tools.length;l+=1){let d=e.content.tools[l]?.ref;if(typeof d!="string"||d.length===0){n.push(`agent.content.tools[${l}].ref must be a non-empty string.`);break}}if(n.length>0)return{ok:!1,errors:n};let o=Z({name:e.name,content:e.content}),s=await Y.admit(o,{activatedAgents:await ls(),stagedAgents:await ds(e.name)});if(!s.ok)return n.push(`[admission] ${s.reason} (retryable=${s.retryable})`),{ok:!1,errors:n};for(let l of s.clampNotes)r.push(`[admission] ${l}`);if((e.content.testCases??[]).length>0&&t.sandboxLlm){let l={name:o.name,instructions:o.instructions,...o.tools?{tools:o.tools}:{},...o.handoffs?{handoffs:o.handoffs}:{},...o.reasoning?{reasoning:o.reasoning}:{}},d=await Bi(e,{llm:t.sandboxLlm,budgetMs:t.sandboxBudgetMs,resolvedAgent:l});for(let u of d.cases)u.ok||n.push(`[sandbox:${u.caseId}] ${u.error??"failed"}`);if(!d.ok)return{ok:!1,errors:n,warnings:r}}let c={...e,testedAt:Date.now()};return await rn(c),r.length>0?{ok:!0,warnings:r}:{ok:!0}}i(mb,"testAgentArtifact");async function Mn(e){let t=e.artifact;rt(t.name,"artifact.name"),rt(t.version,"artifact.version");let n=await cs(t.name,t.version);if(!n)throw new Error(`Cannot activate '${t.name}@${t.version}': artifact not found on disk. Stage and test it first.`);if(n.status==="revoked")throw new Error(`Cannot activate '${n.name}@${n.version}': artifact is revoked. Revoked artifacts are terminal; bump the version and re-stage.`);if(!n.testedAt)throw new Error(`Cannot activate '${n.name}@${n.version}': artifact has not passed test(). Call test_tool first \u2014 activation must follow the AST/schema/LLM-review chain so the policy gate is not the only line of defense.`);let r;if(n.kind==="agent"){let c=Z({name:n.name,content:n.content}),l=await Y.admit(c,{activatedAgents:await ls(),stagedAgents:await ds(n.name)});if(!l.ok)throw new Error(`Cannot activate '${n.name}@${n.version}': re-admission at activate-time failed. ${l.reason} (retryable=${l.retryable}). This indicates the persisted manifest changed between test_agent and activate_agent \u2014 re-stage with a fresh version.`);r=l.handle}let o=await hb(n);if(o){await gb({next:n,prev:o,admittedHandle:r});return}let s=await j.policy(n);if(s==="reject")throw new Error(`Construction policy rejected '${n.name}@${n.version}'.`);if(s==="ask-user")throw new Error(`Construction policy returned 'ask-user' for '${n.name}@${n.version}', but the current surface has no interactive UI bound. Activation must originate from a session whose policy can prompt the user (e.g. the Ink REPL).`);await is(n,{admittedHandle:r});let a={...n,status:"active",activatedAt:Date.now(),contentHash:ns(n.content)};await rn(a)}i(Mn,"activate");async function hb(e){return e.kind!=="agent"||!e.sourceAgent||e.sourceAgent!==e.name?void 0:(await Fr(j.cwd,"agent")).find(n=>n.kind==="agent"&&n.name===e.name&&n.status==="active"&&n.version!==e.version)}i(hb,"detectSelfModify");async function gb(e){let{next:t,prev:n}=e;if(t.kind!=="agent")throw new Error(`runSelfModifyActivation: expected kind='agent', got '${t.kind}'.`);let r=j.llmReviewer?await pu({agentName:t.name,fromVersion:n.version,toVersion:t.version,prev:n.content,next:t.content},j.llmReviewer):{summary:"No LLM reviewer configured \u2014 review the raw manifest diff before approving.",severity:"major",flaggedConcerns:["No LLM reviewer wired into the runtime; summary skipped."]};if((await In(t.name,{cwd:j.cwd})).disabled)throw await Ie({ts:new Date().toISOString(),event:"self_modify_rejected",agentName:t.name,toVersion:t.version,fromVersion:n.version,diffHash:wt(n.content,t.content),rejectRule:"self-modify-disabled",rejectReason:"Self-modify is disabled for this agent; the disable marker was found at activate time."},{cwd:j.cwd}),new Error(`Self-modify is disabled for '${t.name}'. The activate request is rejected; bump version + author a separately-named agent if a different posture is required.`);let s=await bt(t.name,{cwd:j.cwd}),a=nn(s);if(a<=0)throw await Ie({ts:new Date().toISOString(),event:"self_modify_rejected",agentName:t.name,toVersion:t.version,fromVersion:n.version,diffHash:wt(n.content,t.content),budgetRemaining:0,rejectRule:"budget-exhausted",rejectReason:"Modification budget was exhausted between stage and activate."},{cwd:j.cwd}),new Error(`Cannot activate self-modify of '${t.name}@${t.version}': budget exhausted between stage and activate. Run 'kodax constructed reset-self-modify-budget ${t.name}' to unlock.`);if(!j.selfModifyAskUser)throw new Error(`Self-modify activation of '${t.name}@${t.version}' requires an interactive surface that wires \`selfModifyAskUser\` via configureRuntime. The current surface has none \u2014 activation rejected.`);let c=await j.selfModifyAskUser({agentName:t.name,fromVersion:n.version,toVersion:t.version,prevContent:n.content,nextContent:t.content,llmSummary:r,budgetRemaining:a,budgetLimit:s.limit}),l=wt(n.content,t.content);if(c==="reject")throw await Ie({ts:new Date().toISOString(),event:"self_modify_rejected",agentName:t.name,toVersion:t.version,fromVersion:n.version,diffHash:l,llmSummary:r.summary,severity:r.severity,flaggedConcerns:r.flaggedConcerns,policyVerdict:"reject",budgetRemaining:a,rejectRule:"user-rejected",rejectReason:"User rejected the self-modify proposal at the activate gate."},{cwd:j.cwd}),new Error(`User rejected self-modify of '${t.name}@${t.version}'.`);let d=await lu(t.name,{cwd:j.cwd});await is(t,{admittedHandle:e.admittedHandle,deferred:!0});let u={...t,status:"active",activatedAt:Date.now(),contentHash:ns(t.content)};await rn(u),await Ie({ts:new Date().toISOString(),event:"self_modify_activated",agentName:t.name,toVersion:t.version,fromVersion:n.version,diffHash:l,llmSummary:r.summary,severity:r.severity,flaggedConcerns:r.flaggedConcerns,policyVerdict:"force-ask-user",budgetRemaining:nn(d)},{cwd:j.cwd})}i(gb,"runSelfModifyActivation");async function is(e,t={}){if(e.kind==="tool")return yb(e);if(e.kind==="agent")return wb(e,t);let n=e;throw new Error(`registerActiveArtifact: unknown artifact kind '${n.kind}'`)}i(is,"registerActiveArtifact");async function yb(e){let t=await zi({name:e.name,version:e.version,cwd:j.cwd},e.content.handler,e.content.capabilities,{timeoutMs:e.content.timeoutMs}),n={name:e.name,description:e.content.description,input_schema:e.content.inputSchema,handler:t,sideEffect:"mutates-state",toClassifierInput:i(s=>En(e.name,s),"toClassifierInput")},r=ot.get(jr(e));r&&r();let o=on(n,{source:{kind:"constructed",id:`constructed:${e.name}@${e.version}`,label:e.name,version:e.version,manifestPath:as(e)}});ot.set(jr(e),o)}i(yb,"registerActiveToolArtifact");async function wb(e,t={}){let n=ot.get(jr(e));n&&n();let r,o;if(t.admittedHandle)r=t.admittedHandle.invariantBindings,o=t.admittedHandle.manifest;else{let c=Z({name:e.name,content:e.content}),l=await Y.admit(c,{activatedAgents:await ls(),stagedAgents:await ds(e.name)});l.ok&&(r=l.handle.invariantBindings,o=l.handle.manifest)}let a=de(e,r&&o?{bindings:r,manifest:o}:{},{deferred:t.deferred??!1});ot.set(jr(e),a)}i(wb,"registerActiveAgentArtifact");async function bb(){let t=(await Fr(j.cwd)).filter(s=>s.status==="active"),n=0,r=0,o=0;for(let s of t){if(s.contentHash&&ns(s.content)!==s.contentHash){o+=1,console.warn(`[ConstructionRuntime] Refusing to rehydrate ${s.name}@${s.version}: contentHash mismatch (manifest was edited after activation). Re-stage and re-activate to re-approve.`);continue}try{await is(s),n+=1}catch(a){r+=1,console.warn(`[ConstructionRuntime] Failed to rehydrate ${s.name}@${s.version}: ${a.message}`)}}return{loaded:n,failed:r,tampered:o}}i(bb,"rehydrateActiveArtifacts");async function ss(e,t){rt(e,"name"),rt(t,"version");let n=`${e}@${t}`,r=ot.get(n);r&&(r(),ot.delete(n));let o=await cs(e,t);if(o){let s={...o,status:"revoked",revokedAt:Date.now()};await rn(s)}}i(ss,"revoke");async function _t(e){return Fr(j.cwd,e)}i(_t,"list");function as(e){return nt.resolve(j.cwd,ts,`${e.kind}s`,e.name,`${e.version}.json`)}i(as,"manifestPath");function jr(e){return`${e.name}@${e.version}`}i(jr,"activeKey");async function rn(e){let t=as(e);await kt.mkdir(nt.dirname(t),{recursive:!0}),await kt.writeFile(t,JSON.stringify(e,null,2),"utf8")}i(rn,"persistArtifact");async function xt(e,t){return rt(e,"name"),rt(t,"version"),cs(e,t)}i(xt,"readArtifact");async function cs(e,t){for(let n of rs){let r=nt.resolve(j.cwd,ts,`${n}s`,e,`${t}.json`);try{let o=await kt.readFile(r,"utf8");return JSON.parse(o)}catch(o){if(o.code==="ENOENT")continue;throw o}}}i(cs,"readArtifactByVersion");async function Fr(e,t){let n=nt.resolve(e,ts),r=[],o=t?[t]:rs;for(let s of o){let a=nt.join(n,`${s}s`),c;try{c=await kt.readdir(a)}catch(l){if(l.code==="ENOENT")continue;throw l}for(let l of c){let d=nt.join(a,l),u;try{u=await kt.readdir(d)}catch{continue}for(let f of u){if(!f.endsWith(".json")||f.startsWith("_"))continue;let m=nt.join(d,f);try{let h=await kt.readFile(m,"utf8"),p=JSON.parse(h);typeof p.name=="string"&&typeof p.version=="string"&&typeof p.kind=="string"&&typeof p.status=="string"?r.push(p):console.warn(`[ConstructionRuntime] Skipping malformed manifest at ${m} \u2014 missing required fields.`)}catch(h){console.warn(`[ConstructionRuntime] Skipping unreadable manifest at ${m}: ${h.message}`)}}}}return r}i(Fr,"loadAllArtifacts");async function ls(){let e=new Map;for(let t of ae())e.set(t.name,t);return e}i(ls,"buildActivatedAgentsMap");async function ds(e){let t=new Map,n=await Fr(j.cwd,"agent");for(let r of n){if(r.status!=="staged"||r.kind!=="agent"||e&&r.name===e)continue;let o=r.content.handoffs?.map(s=>{let a=s.target.ref,c=a.indexOf(":"),l=c===-1?a:a.slice(c+1),d=l.indexOf("@");return{target:{name:d===-1?l:l.slice(0,d),instructions:""},kind:s.kind}})??[];t.set(r.name,{name:r.name,instructions:"",handoffs:o})}return t}i(ds,"buildStagedAgentsMap");function kb(){let e=[];for(let t of Le())for(let n of Et(t))n.source.kind==="constructed"&&e.push(n);return e}i(kb,"listConstructed");function vb(e,t){return Et(e).find(n=>n.source.kind==="constructed"&&n.source.version===t)}i(vb,"findByVersion");function _b(){let e=[];for(let t of Le())e.push(...Et(t));return e}i(_b,"listAll");import{readdir as xb,readFile as Eb,stat as Sb}from"node:fs/promises";import{join as Pn}from"node:path";var hu="agents",gu=".kodax/agents";async function Tb(e={}){let t=Pn(e.configHome??st(),hu),n=Pn(e.cwd??process.cwd(),gu),r=[],o=0;for(let[s,a]of[[t,"markdown:user"],[n,"markdown:project"]]){let c=await yu(s);for(let l of c){let d=await Ab(l,a);d.ok?o+=1:d.reason!==null&&r.push({path:l,reason:d.reason})}}return{loaded:o,failed:r}}i(Tb,"loadAgentsFromMarkdown");async function yu(e){try{let t=await xb(e),n=[];for(let r of t){if(!r.endsWith(".md"))continue;let o=Pn(e,r);try{(await Sb(o)).isFile()&&n.push(o)}catch{}}return n}catch{return[]}}i(yu,"listMarkdownFiles");async function Ab(e,t){let n=await wu(e);if(n.kind==="silent-skip")return{ok:!1,reason:null};if(n.kind==="fail")return{ok:!1,reason:n.reason};let{name:r,description:o,instructions:s,toolNames:a,model:c,effort:l}=n.parsed,d=a?.map(g=>({ref:g.includes(":")?g:`builtin:${g}`})),u={instructions:s,description:o,...d!==void 0?{tools:d}:{},...c!==void 0?{model:c}:{},...l!==void 0?{effort:l}:{}},f=Z({name:r,content:u}),m=new Map(ae().map(g=>[g.name,g])),h=await Y.admit(f,{activatedAgents:m});if(!h.ok)return{ok:!1,reason:`admission rejected: ${h.reason}`};let p={kind:"agent",name:r,version:"0.0.0-markdown",content:u,status:"active",createdAt:Date.now(),testedAt:Date.now(),activatedAt:Date.now()};return de(p,{bindings:h.handle.invariantBindings,manifest:h.handle.manifest,source:t}),{ok:!0}}i(Ab,"loadOneAgentFile");async function Cb(e={}){let t=Pn(e.configHome??st(),hu),n=Pn(e.cwd??process.cwd(),gu),r=[],o=new Map;for(let[s,a]of[[t,"markdown:user"],[n,"markdown:project"]]){let c=await yu(s);for(let l of c){let d=await wu(l);d.kind==="ok"?o.set(d.parsed.name,{name:d.parsed.name,description:d.parsed.description,source:a,path:l,...d.parsed.toolNames!==void 0?{tools:d.parsed.toolNames}:{},...d.parsed.model!==void 0?{model:d.parsed.model}:{},...d.parsed.effort!==void 0?{effort:d.parsed.effort}:{}}):d.kind==="fail"&&r.push({path:l,reason:d.reason})}}return{agents:Array.from(o.values()),failed:r}}i(Cb,"discoverMarkdownAgents");async function wu(e){let t;try{t=await Eb(e,"utf8")}catch(p){return{kind:"fail",reason:`read failed: ${mu(p)}`}}let[n,r]=Ys(t);if(!n)return{kind:"silent-skip"};let o=n.name;if(typeof o!="string"||o.trim().length===0)return{kind:"silent-skip"};let s=o.trim(),a=n.description;if(typeof a!="string"||a.trim().length===0)return{kind:"fail",reason:`frontmatter "description" is required (got ${typeof a})`};let c=a.trim(),l=r.trim();if(l.length===0)return{kind:"fail",reason:"markdown body (instructions) is empty"};let d=Rb(n.tools),u=n.model,f=typeof u=="string"&&u.trim().length>0?u.trim():void 0,m=n.effort,h;if(typeof m=="string"&&m.trim().length>0)try{h=it(m)}catch(p){return{kind:"fail",reason:`frontmatter "effort" is invalid: ${mu(p)}`}}return{kind:"ok",parsed:{name:s,description:c,instructions:l,...d!==void 0?{toolNames:d}:{},...f!==void 0?{model:f}:{},...h!==void 0?{effort:h}:{}}}}i(wu,"parseMarkdownAgentFile");function Rb(e){if(e==null)return;let t=[];if(Array.isArray(e))t=e.map(n=>String(n).trim()).filter(n=>n.length>0);else if(typeof e=="string")t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);else return;if(t.length!==0)return t}i(Rb,"parseToolNamesField");function mu(e){return e instanceof Error?e.message:String(e)}i(mu,"errMsg");var Ur="repo-explorer",$b=80,bu=["read","glob","grep","code_search","semantic_lookup","repo_overview","changed_scope","changed_diff","changed_diff_bundle","module_context","symbol_context","process_context","impact_estimate","relationship_scan","cyclic_dependencies","lsp_definition","lsp_hover","lsp_references","lsp_document_symbols","lsp_workspace_symbols","lsp_implementation","lsp_prepare_call_hierarchy","lsp_incoming_calls","lsp_outgoing_calls"];function Ob(e){return e.map(t=>({ref:`builtin:${t}`}))}i(Ob,"builtinToolRefs");function ku(){return{description:"Read-only repository exploration specialist for architecture, dependencies, call graphs, and change impact.",instructions:["You are repo-explorer, a read-only repository exploration specialist.","","Mission:","- Build a concise map of unfamiliar code, ownership boundaries, dependencies, entry points, call relationships, and change impact.","- Answer with file:line evidence when available. Prefer structured repo/LSP tools before broad raw file reading.","","Tool strategy:","- For upstream/downstream, callers/callees, impact, or Chinese \\u4e0a\\u4e0b\\u6e38/\\u8c03\\u7528\\u94fe/\\u5f71\\u54cd\\u9762 questions, start with relationship_scan.","- Use module_context before reading 3 or more files in one module.","- Use symbol_context for named symbols; use lsp_* tools when you have an exact file position.","- Use changed_scope and changed_diff_bundle for review/change-audit scope.","- Use read/grep/glob only after structured tools narrow the target or when exact code text is required.","","Constraints:","- Stay read-only. Do not edit files, run shell commands, change git state, or ask the user questions.","- Stop when the evidence is sufficient; extra exploration delays the parent agent.","","Output:","- Summarize the repository map, key relationships, gaps/uncertainty, and next best drill-down handles.","- Keep the final answer compact enough for the parent agent to synthesize directly."].join(`
281
- `),tools:Ob(bu),maxBudget:$b}}i(ku,"buildRepoExplorerAgentContent");function vu(e=Date.now()){return{kind:"agent",name:Ur,version:"0.7.57-builtin",content:ku(),status:"active",createdAt:e,testedAt:e,activatedAt:e}}i(vu,"buildRepoExplorerAgentArtifact");async function Ib(){if(Oe(Ur))return!1;let e=vu(),t=Z({name:e.name,content:e.content}),n=new Map(ae().map(o=>[o.name,o])),r=await Y.admit(t,{activatedAgents:n});if(!r.ok)throw new Error(`built-in ${Ur} admission rejected: ${r.reason}`);return de(e,{bindings:r.handle.invariantBindings,manifest:r.handle.manifest,source:"built-in"}),!0}i(Ib,"ensureBuiltinRepoExplorerAgent");var Nn=class extends Error{static{i(this,"RollbackError")}code;constructor(t,n){super(n),this.name="RollbackError",this.code=t}};async function Lb(e){let n=(await _t("agent")).filter(c=>c.kind==="agent"&&c.name===e&&c.status==="active"&&typeof c.activatedAt=="number").sort((c,l)=>(l.activatedAt??0)-(c.activatedAt??0));if(n.length===0)throw new Nn("no-current-active",`No active version of '${e}' on disk \u2014 nothing to roll back from.`);if(n.length===1)throw new Nn("no-rollback-target",`Only one active version of '${e}' (${n[0].version}) \u2014 no prior version to roll back to. Bump version + stage to author further changes.`);let r=n[0],o=n[1],s=Z({name:o.name,content:o.content}),a=await Y.admit(s,{activatedAgents:Mb(e),stagedAgents:new Map});if(!a.ok)throw new Nn("admission-failed",`Rollback target ${o.name}@${o.version} no longer admits: ${a.reason}.`);return await ss(r.name,r.version),de(o,{bindings:a.handle.invariantBindings,manifest:a.handle.manifest}),{agentName:e,fromVersion:r.version,toVersion:o.version,fromActivatedAt:r.activatedAt,toActivatedAt:o.activatedAt}}i(Lb,"rollbackSelfModify");function Mb(e){let t=new Map;for(let n of ae())n.name!==e&&t.set(n.name,n);return t}i(Mb,"snapshotActivatedAgentsExcept");var _u=["scaffold_tool","validate_tool","stage_construction","test_tool","activate_tool"],Db=new Set(_u);function xu(e){return Db.has(e)}i(xu,"isConstructionToolName");function jb(e,t){return t?[...e]:e.filter(n=>!xu(n))}i(jb,"filterConstructionToolNames");function St(e,t){let n=e[t];if(typeof n!="string"||n.trim().length===0)throw new Error(`'${t}' is required and must be a non-empty string.`);return n.trim()}i(St,"readRequiredString");function Eu(e){try{return JSON.parse(e)}catch(t){throw new Error(`artifact_json failed to parse as JSON: ${t.message}`)}}i(Eu,"parseArtifactJson");function Su(e){if(!e||typeof e!="object")throw new Error("artifact must be a JSON object.");let t=e;if(t.kind!=="tool")throw new Error(`artifact.kind must be 'tool' (got ${JSON.stringify(t.kind)}).`);if(typeof t.name!="string"||t.name.trim()==="")throw new Error("artifact.name must be a non-empty string.");if(typeof t.version!="string"||t.version.trim()==="")throw new Error("artifact.version must be a non-empty string (semver recommended).");if(!t.content||typeof t.content!="object")throw new Error("artifact.content must be an object.");let n=t.content;if(typeof n.description!="string")throw new Error("artifact.content.description must be a string.");if(!n.inputSchema||typeof n.inputSchema!="object")throw new Error("artifact.content.inputSchema must be an object.");if(!n.capabilities||typeof n.capabilities!="object")throw new Error("artifact.content.capabilities must be an object with a tools array.");let r=n.handler;if(!r||r.kind!=="script"||r.language!=="javascript")throw new Error("artifact.content.handler must be { kind: 'script', language: 'javascript', code }.");if(typeof r.code!="string"||r.code.trim()==="")throw new Error("artifact.content.handler.code must be a non-empty JavaScript source string.");return e}i(Su,"asConstructionArtifact");function us(e){let t=[];if(t.push(`ok=${e.ok?"true":"false"}`),e.errors&&e.errors.length>0){t.push("errors:");for(let n of e.errors)t.push(` - ${n}`)}if(e.warnings&&e.warnings.length>0){t.push("warnings:");for(let n of e.warnings)t.push(` - ${n}`)}return t.join(`
282
- `)}i(us,"renderTestResult");var Fb=`export async function handler(input, ctx) {
295
+ `}i(mk,"buildSelfModifyDiffPrompt");function hk(e){let t={summary:"LLM summary unavailable \u2014 review the raw manifest diff carefully before approving.",severity:"major",flaggedConcerns:["LLM reviewer did not return a parseable summary."],raw:e},n=yk(e);if(!n)return t;let r;try{r=JSON.parse(n)}catch{return t}let o=typeof r.summary=="string"?r.summary:void 0,s=gk(r.severity)?r.severity:void 0,a=Array.isArray(r.flaggedConcerns)?r.flaggedConcerns.filter(c=>typeof c=="string"):void 0;return!o||!s||!a?t:{summary:o,severity:s,flaggedConcerns:a,raw:e}}i(hk,"parseSelfModifyDiffSummary");function gk(e){return e==="minor"||e==="moderate"||e==="major"}i(gk,"isSeverity");function yk(e){let t=e.indexOf("{");if(t===-1)return;let n=0,r=!1,o=!1;for(let s=t;s<e.length;s+=1){let a=e[s];if(r){o?o=!1:a==="\\"?o=!0:a==='"'&&(r=!1);continue}if(a==='"'){r=!0;continue}if(a==="{")n+=1;else if(a==="}"&&(n-=1,n===0))return e.slice(t,s+1)}}i(yk,"extractFirstJsonObject");async function Gu(e,t){let n=mk(e),r;try{r=await t(n)}catch(o){return{summary:`LLM summary unavailable \u2014 reviewer threw: ${o.message}`,severity:"major",flaggedConcerns:["LLM reviewer call failed."]}}return hk(r)}i(Gu,"runSelfModifyDiffSummary");var ps=st.join(".kodax","constructed");function at(e,t){if(typeof e!="string"||e.length===0||e.length>128)throw new ot(`Invalid ${t}: must be a non-empty string \u2264 128 chars (got ${typeof e=="string"?`length=${e.length}`:typeof e}).`);if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(e)||e.includes(".."))throw new ot(`Invalid ${t} ${JSON.stringify(e)}: must match [A-Za-z0-9][A-Za-z0-9._-]* with no '..' sequences. Reserved separator/control characters and parent-traversal segments are rejected.`)}i(at,"assertSafeIdentifier");function ms(e){return wk.createHash("sha256").update(JSON.stringify(e)).digest("hex")}i(ms,"computeContentHash");var hs=["tool","agent"],j={cwd:process.cwd(),policy:qr},ct=new Map;function bk(e){j={cwd:e.cwd??j.cwd,policy:e.policy??j.policy,llmReviewer:e.llmReviewer??j.llmReviewer,selfModifyAskUser:e.selfModifyAskUser??j.selfModifyAskUser}}i(bk,"configureRuntime");function gs(){return j.cwd}i(gs,"getRuntimeCwd");function kk(){for(let e of ct.values())e();ct.clear(),fs(),j={cwd:process.cwd(),policy:qr,llmReviewer:void 0,selfModifyAskUser:void 0}}i(kk,"_resetRuntimeForTesting");async function At(e){at(e.name,"artifact.name"),at(e.version,"artifact.version");let t=bs(e);try{let r=await Tt.readFile(t,"utf8"),o=JSON.parse(r);throw new ot(`Cannot stage '${e.name}@${e.version}': a manifest already exists at this version (status='${o.status}'). Constructed artifacts are version-immutable \u2014 bump the semver to publish a new variant. Re-staging the same version would silently shadow the cached ESM module, even after revoke.`,t)}catch(r){if(r instanceof ot||r.code!=="ENOENT")throw r}let n={...e,status:"staged",createdAt:e.createdAt||Date.now(),testedAt:void 0,activatedAt:void 0,revokedAt:void 0,contentHash:void 0};return await ln(n),{artifact:n,stagedAt:Date.now()}}i(At,"stage");async function Fn(e,t={}){let{artifact:n}=e;return n.kind==="tool"?vk(n,t):n.kind==="agent"?_k(n,t):{ok:!1,errors:[`Unsupported artifact kind '${n.kind??"<missing>"}'. Runtime understands: ${hs.join(", ")}.`]}}i(Fn,"test");async function vk(e,t){let n=[],r=[];if(e.content.handler.language!=="javascript"&&n.push(`Handler language must be 'javascript' (got '${e.content.handler.language}').`),!Array.isArray(e.content.capabilities.tools))n.push("capabilities.tools must be an array of strings.");else for(let c of e.content.capabilities.tools)if(typeof c!="string"||c.trim().length===0){n.push(`capabilities.tools entry must be a non-empty string (got: ${JSON.stringify(c)}).`);break}if(n.length>0)return{ok:!1,errors:n};let o=Pn(e.content.handler.code);if(!o.ok){for(let c of o.violations)n.push(`[${c.rule}] ${c.message}`);return{ok:!1,errors:n}}let s=Nn(e.content.inputSchema,t.provider??"anthropic");for(let c of s.warnings)r.push(c);if(!s.ok){for(let c of s.errors)n.push(`[schema] ${c}`);return{ok:!1,errors:n,warnings:r}}if(t.llmReviewer){let c;try{c=await as({handlerCode:e.content.handler.code,capabilities:e.content.capabilities,artifactRef:`${e.name}@${e.version}`},t.llmReviewer)}catch(l){return n.push(`LLM review failed to produce a verdict: ${l.message}`),{ok:!1,errors:n,warnings:r}}if(c.verdict==="dangerous"){n.push("LLM review verdict='dangerous'.");for(let l of c.concerns)n.push(`[review] ${l}`);return{ok:!1,errors:n,warnings:r}}if(c.verdict==="suspicious"){r.push("LLM review verdict='suspicious' \u2014 policy gate will see these concerns:");for(let l of c.concerns)r.push(`[review] ${l}`)}}let a={...e,testedAt:Date.now()};return await ln(a),r.length>0?{ok:!0,warnings:r}:{ok:!0}}i(vk,"testToolArtifact");async function _k(e,t){let n=[],r=[];if((typeof e.content.instructions!="string"||e.content.instructions.length===0)&&n.push("agent.content.instructions must be a non-empty string."),e.content.tools!==void 0)if(!Array.isArray(e.content.tools))n.push("agent.content.tools, when present, must be an array of ToolRef objects.");else for(let l=0;l<e.content.tools.length;l+=1){let d=e.content.tools[l]?.ref;if(typeof d!="string"||d.length===0){n.push(`agent.content.tools[${l}].ref must be a non-empty string.`);break}}if(n.length>0)return{ok:!1,errors:n};let o=te({name:e.name,content:e.content}),s=await Y.admit(o,{activatedAgents:await vs(),stagedAgents:await _s(e.name)});if(!s.ok)return n.push(`[admission] ${s.reason} (retryable=${s.retryable})`),{ok:!1,errors:n};for(let l of s.clampNotes)r.push(`[admission] ${l}`);if((e.content.testCases??[]).length>0&&t.sandboxLlm){let l={name:o.name,instructions:o.instructions,...o.tools?{tools:o.tools}:{},...o.handoffs?{handoffs:o.handoffs}:{},...o.reasoning?{reasoning:o.reasoning}:{}},d=await es(e,{llm:t.sandboxLlm,budgetMs:t.sandboxBudgetMs,resolvedAgent:l});for(let u of d.cases)u.ok||n.push(`[sandbox:${u.caseId}] ${u.error??"failed"}`);if(!d.ok)return{ok:!1,errors:n,warnings:r}}let c={...e,testedAt:Date.now()};return await ln(c),r.length>0?{ok:!0,warnings:r}:{ok:!0}}i(_k,"testAgentArtifact");async function jn(e){let t=e.artifact;at(t.name,"artifact.name"),at(t.version,"artifact.version");let n=await ks(t.name,t.version);if(!n)throw new Error(`Cannot activate '${t.name}@${t.version}': artifact not found on disk. Stage and test it first.`);if(n.status==="revoked")throw new Error(`Cannot activate '${n.name}@${n.version}': artifact is revoked. Revoked artifacts are terminal; bump the version and re-stage.`);if(!n.testedAt)throw new Error(`Cannot activate '${n.name}@${n.version}': artifact has not passed test(). Call test_tool first \u2014 activation must follow the AST/schema/LLM-review chain so the policy gate is not the only line of defense.`);let r;if(n.kind==="agent"){let c=te({name:n.name,content:n.content}),l=await Y.admit(c,{activatedAgents:await vs(),stagedAgents:await _s(n.name)});if(!l.ok)throw new Error(`Cannot activate '${n.name}@${n.version}': re-admission at activate-time failed. ${l.reason} (retryable=${l.retryable}). This indicates the persisted manifest changed between test_agent and activate_agent \u2014 re-stage with a fresh version.`);r=l.handle}let o=await xk(n);if(o){await Ek({next:n,prev:o,admittedHandle:r});return}let s=await j.policy(n);if(s==="reject")throw new Error(`Construction policy rejected '${n.name}@${n.version}'.`);if(s==="ask-user")throw new Error(`Construction policy returned 'ask-user' for '${n.name}@${n.version}', but the current surface has no interactive UI bound. Activation must originate from a session whose policy can prompt the user (e.g. the Ink REPL).`);await ys(n,{admittedHandle:r});let a={...n,status:"active",activatedAt:Date.now(),contentHash:ms(n.content)};await ln(a)}i(jn,"activate");async function xk(e){return e.kind!=="agent"||!e.sourceAgent||e.sourceAgent!==e.name?void 0:(await Gr(j.cwd,"agent")).find(n=>n.kind==="agent"&&n.name===e.name&&n.status==="active"&&n.version!==e.version)}i(xk,"detectSelfModify");async function Ek(e){let{next:t,prev:n}=e;if(t.kind!=="agent")throw new Error(`runSelfModifyActivation: expected kind='agent', got '${t.kind}'.`);let r=j.llmReviewer?await Gu({agentName:t.name,fromVersion:n.version,toVersion:t.version,prev:n.content,next:t.content},j.llmReviewer):{summary:"No LLM reviewer configured \u2014 review the raw manifest diff before approving.",severity:"major",flaggedConcerns:["No LLM reviewer wired into the runtime; summary skipped."]};if((await Dn(t.name,{cwd:j.cwd})).disabled)throw await Pe({ts:new Date().toISOString(),event:"self_modify_rejected",agentName:t.name,toVersion:t.version,fromVersion:n.version,diffHash:Et(n.content,t.content),rejectRule:"self-modify-disabled",rejectReason:"Self-modify is disabled for this agent; the disable marker was found at activate time."},{cwd:j.cwd}),new Error(`Self-modify is disabled for '${t.name}'. The activate request is rejected; bump version + author a separately-named agent if a different posture is required.`);let s=await St(t.name,{cwd:j.cwd}),a=cn(s);if(a<=0)throw await Pe({ts:new Date().toISOString(),event:"self_modify_rejected",agentName:t.name,toVersion:t.version,fromVersion:n.version,diffHash:Et(n.content,t.content),budgetRemaining:0,rejectRule:"budget-exhausted",rejectReason:"Modification budget was exhausted between stage and activate."},{cwd:j.cwd}),new Error(`Cannot activate self-modify of '${t.name}@${t.version}': budget exhausted between stage and activate. Run 'kodax constructed reset-self-modify-budget ${t.name}' to unlock.`);if(!j.selfModifyAskUser)throw new Error(`Self-modify activation of '${t.name}@${t.version}' requires an interactive surface that wires \`selfModifyAskUser\` via configureRuntime. The current surface has none \u2014 activation rejected.`);let c=await j.selfModifyAskUser({agentName:t.name,fromVersion:n.version,toVersion:t.version,prevContent:n.content,nextContent:t.content,llmSummary:r,budgetRemaining:a,budgetLimit:s.limit}),l=Et(n.content,t.content);if(c==="reject")throw await Pe({ts:new Date().toISOString(),event:"self_modify_rejected",agentName:t.name,toVersion:t.version,fromVersion:n.version,diffHash:l,llmSummary:r.summary,severity:r.severity,flaggedConcerns:r.flaggedConcerns,policyVerdict:"reject",budgetRemaining:a,rejectRule:"user-rejected",rejectReason:"User rejected the self-modify proposal at the activate gate."},{cwd:j.cwd}),new Error(`User rejected self-modify of '${t.name}@${t.version}'.`);let d=await Bu(t.name,{cwd:j.cwd});await ys(t,{admittedHandle:e.admittedHandle,deferred:!0});let u={...t,status:"active",activatedAt:Date.now(),contentHash:ms(t.content)};await ln(u),await Pe({ts:new Date().toISOString(),event:"self_modify_activated",agentName:t.name,toVersion:t.version,fromVersion:n.version,diffHash:l,llmSummary:r.summary,severity:r.severity,flaggedConcerns:r.flaggedConcerns,policyVerdict:"force-ask-user",budgetRemaining:cn(d)},{cwd:j.cwd})}i(Ek,"runSelfModifyActivation");async function ys(e,t={}){if(e.kind==="tool")return Sk(e);if(e.kind==="agent")return Tk(e,t);let n=e;throw new Error(`registerActiveArtifact: unknown artifact kind '${n.kind}'`)}i(ys,"registerActiveArtifact");async function Sk(e){let t=await os({name:e.name,version:e.version,cwd:j.cwd},e.content.handler,e.content.capabilities,{timeoutMs:e.content.timeoutMs}),n={name:e.name,description:e.content.description,input_schema:e.content.inputSchema,handler:t,sideEffect:"mutates-state",toClassifierInput:i(s=>$n(e.name,s),"toClassifierInput")},r=ct.get(zr(e));r&&r();let o=dn(n,{source:{kind:"constructed",id:`constructed:${e.name}@${e.version}`,label:e.name,version:e.version,manifestPath:bs(e)}});ct.set(zr(e),o)}i(Sk,"registerActiveToolArtifact");async function Tk(e,t={}){let n=ct.get(zr(e));n&&n();let r,o;if(t.admittedHandle)r=t.admittedHandle.invariantBindings,o=t.admittedHandle.manifest;else{let c=te({name:e.name,content:e.content}),l=await Y.admit(c,{activatedAgents:await vs(),stagedAgents:await _s(e.name)});l.ok&&(r=l.handle.invariantBindings,o=l.handle.manifest)}let a=me(e,r&&o?{bindings:r,manifest:o}:{},{deferred:t.deferred??!1});ct.set(zr(e),a)}i(Tk,"registerActiveAgentArtifact");async function Ak(){let t=(await Gr(j.cwd)).filter(s=>s.status==="active"),n=0,r=0,o=0;for(let s of t){if(s.contentHash&&ms(s.content)!==s.contentHash){o+=1,console.warn(`[ConstructionRuntime] Refusing to rehydrate ${s.name}@${s.version}: contentHash mismatch (manifest was edited after activation). Re-stage and re-activate to re-approve.`);continue}try{await ys(s),n+=1}catch(a){r+=1,console.warn(`[ConstructionRuntime] Failed to rehydrate ${s.name}@${s.version}: ${a.message}`)}}return{loaded:n,failed:r,tampered:o}}i(Ak,"rehydrateActiveArtifacts");async function ws(e,t){at(e,"name"),at(t,"version");let n=`${e}@${t}`,r=ct.get(n);r&&(r(),ct.delete(n));let o=await ks(e,t);if(o){let s={...o,status:"revoked",revokedAt:Date.now()};await ln(s)}}i(ws,"revoke");async function Ct(e){return Gr(j.cwd,e)}i(Ct,"list");function bs(e){return st.resolve(j.cwd,ps,`${e.kind}s`,e.name,`${e.version}.json`)}i(bs,"manifestPath");function zr(e){return`${e.name}@${e.version}`}i(zr,"activeKey");async function ln(e){let t=bs(e);await Tt.mkdir(st.dirname(t),{recursive:!0}),await Tt.writeFile(t,JSON.stringify(e,null,2),"utf8")}i(ln,"persistArtifact");async function $t(e,t){return at(e,"name"),at(t,"version"),ks(e,t)}i($t,"readArtifact");async function ks(e,t){for(let n of hs){let r=st.resolve(j.cwd,ps,`${n}s`,e,`${t}.json`);try{let o=await Tt.readFile(r,"utf8");return JSON.parse(o)}catch(o){if(o.code==="ENOENT")continue;throw o}}}i(ks,"readArtifactByVersion");async function Gr(e,t){let n=st.resolve(e,ps),r=[],o=t?[t]:hs;for(let s of o){let a=st.join(n,`${s}s`),c;try{c=await Tt.readdir(a)}catch(l){if(l.code==="ENOENT")continue;throw l}for(let l of c){let d=st.join(a,l),u;try{u=await Tt.readdir(d)}catch{continue}for(let f of u){if(!f.endsWith(".json")||f.startsWith("_"))continue;let m=st.join(d,f);try{let h=await Tt.readFile(m,"utf8"),p=JSON.parse(h);typeof p.name=="string"&&typeof p.version=="string"&&typeof p.kind=="string"&&typeof p.status=="string"?r.push(p):console.warn(`[ConstructionRuntime] Skipping malformed manifest at ${m} \u2014 missing required fields.`)}catch(h){console.warn(`[ConstructionRuntime] Skipping unreadable manifest at ${m}: ${h.message}`)}}}}return r}i(Gr,"loadAllArtifacts");async function vs(){let e=new Map;for(let t of de())e.set(t.name,t);return e}i(vs,"buildActivatedAgentsMap");async function _s(e){let t=new Map,n=await Gr(j.cwd,"agent");for(let r of n){if(r.status!=="staged"||r.kind!=="agent"||e&&r.name===e)continue;let o=r.content.handoffs?.map(s=>{let a=s.target.ref,c=a.indexOf(":"),l=c===-1?a:a.slice(c+1),d=l.indexOf("@");return{target:{name:d===-1?l:l.slice(0,d),instructions:""},kind:s.kind}})??[];t.set(r.name,{name:r.name,instructions:"",handoffs:o})}return t}i(_s,"buildStagedAgentsMap");function Ck(){let e=[];for(let t of Ne())for(let n of Rt(t))n.source.kind==="constructed"&&e.push(n);return e}i(Ck,"listConstructed");function $k(e,t){return Rt(e).find(n=>n.source.kind==="constructed"&&n.source.version===t)}i($k,"findByVersion");function Rk(){let e=[];for(let t of Ne())e.push(...Rt(t));return e}i(Rk,"listAll");import{readdir as Ok,readFile as Ik,stat as Lk}from"node:fs/promises";import{join as Un}from"node:path";var Xu="agents",Vu=".kodax/agents";async function Mk(e={}){let t=Un(e.configHome??dt(),Xu),n=Un(e.cwd??process.cwd(),Vu),r=[],o=0;for(let[s,a]of[[t,"markdown:user"],[n,"markdown:project"]]){let c=await Ju(s);for(let l of c){let d=await Pk(l,a);d.ok?o+=1:d.reason!==null&&r.push({path:l,reason:d.reason})}}return{loaded:o,failed:r}}i(Mk,"loadAgentsFromMarkdown");async function Ju(e){try{let t=await Ok(e),n=[];for(let r of t){if(!r.endsWith(".md"))continue;let o=Un(e,r);try{(await Lk(o)).isFile()&&n.push(o)}catch{}}return n}catch{return[]}}i(Ju,"listMarkdownFiles");async function Pk(e,t){let n=await Yu(e);if(n.kind==="silent-skip")return{ok:!1,reason:null};if(n.kind==="fail")return{ok:!1,reason:n.reason};let{name:r,description:o,instructions:s,toolNames:a,model:c,effort:l}=n.parsed,d=a?.map(g=>({ref:g.includes(":")?g:`builtin:${g}`})),u={instructions:s,description:o,...d!==void 0?{tools:d}:{},...c!==void 0?{model:c}:{},...l!==void 0?{effort:l}:{}},f=te({name:r,content:u}),m=new Map(de().map(g=>[g.name,g])),h=await Y.admit(f,{activatedAgents:m});if(!h.ok)return{ok:!1,reason:`admission rejected: ${h.reason}`};let p={kind:"agent",name:r,version:"0.0.0-markdown",content:u,status:"active",createdAt:Date.now(),testedAt:Date.now(),activatedAt:Date.now()};return me(p,{bindings:h.handle.invariantBindings,manifest:h.handle.manifest,source:t}),{ok:!0}}i(Pk,"loadOneAgentFile");async function Nk(e={}){let t=Un(e.configHome??dt(),Xu),n=Un(e.cwd??process.cwd(),Vu),r=[],o=new Map;for(let[s,a]of[[t,"markdown:user"],[n,"markdown:project"]]){let c=await Ju(s);for(let l of c){let d=await Yu(l);d.kind==="ok"?o.set(d.parsed.name,{name:d.parsed.name,description:d.parsed.description,source:a,path:l,...d.parsed.toolNames!==void 0?{tools:d.parsed.toolNames}:{},...d.parsed.model!==void 0?{model:d.parsed.model}:{},...d.parsed.effort!==void 0?{effort:d.parsed.effort}:{}}):d.kind==="fail"&&r.push({path:l,reason:d.reason})}}return{agents:Array.from(o.values()),failed:r}}i(Nk,"discoverMarkdownAgents");async function Yu(e){let t;try{t=await Ik(e,"utf8")}catch(p){return{kind:"fail",reason:`read failed: ${Ku(p)}`}}let[n,r]=la(t);if(!n)return{kind:"silent-skip"};let o=n.name;if(typeof o!="string"||o.trim().length===0)return{kind:"silent-skip"};let s=o.trim(),a=n.description;if(typeof a!="string"||a.trim().length===0)return{kind:"fail",reason:`frontmatter "description" is required (got ${typeof a})`};let c=a.trim(),l=r.trim();if(l.length===0)return{kind:"fail",reason:"markdown body (instructions) is empty"};let d=Dk(n.tools),u=n.model,f=typeof u=="string"&&u.trim().length>0?u.trim():void 0,m=n.effort,h;if(typeof m=="string"&&m.trim().length>0)try{h=lt(m)}catch(p){return{kind:"fail",reason:`frontmatter "effort" is invalid: ${Ku(p)}`}}return{kind:"ok",parsed:{name:s,description:c,instructions:l,...d!==void 0?{toolNames:d}:{},...f!==void 0?{model:f}:{},...h!==void 0?{effort:h}:{}}}}i(Yu,"parseMarkdownAgentFile");function Dk(e){if(e==null)return;let t=[];if(Array.isArray(e))t=e.map(n=>String(n).trim()).filter(n=>n.length>0);else if(typeof e=="string")t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);else return;if(t.length!==0)return t}i(Dk,"parseToolNamesField");function Ku(e){return e instanceof Error?e.message:String(e)}i(Ku,"errMsg");var Kr="repo-explorer",Fk=80,Zu=["read","glob","grep","code_search","semantic_lookup","repo_overview","changed_scope","changed_diff","changed_diff_bundle","module_context","symbol_context","process_context","impact_estimate","relationship_scan","cyclic_dependencies","lsp_definition","lsp_hover","lsp_references","lsp_document_symbols","lsp_workspace_symbols","lsp_implementation","lsp_prepare_call_hierarchy","lsp_incoming_calls","lsp_outgoing_calls"];function jk(e){return e.map(t=>({ref:`builtin:${t}`}))}i(jk,"builtinToolRefs");function Qu(){return{description:"Read-only repository exploration specialist for architecture, dependencies, call graphs, and change impact.",instructions:["You are repo-explorer, a read-only repository exploration specialist.","","Mission:","- Build a concise map of unfamiliar code, ownership boundaries, dependencies, entry points, call relationships, and change impact.","- Answer with file:line evidence when available. Prefer structured repo/LSP tools before broad raw file reading.","","Tool strategy:","- For upstream/downstream, callers/callees, impact, or Chinese \\u4e0a\\u4e0b\\u6e38/\\u8c03\\u7528\\u94fe/\\u5f71\\u54cd\\u9762 questions, start with relationship_scan.","- Use module_context before reading 3 or more files in one module.","- Use symbol_context for named symbols; use lsp_* tools when you have an exact file position.","- Use changed_scope and changed_diff_bundle for review/change-audit scope.","- Use read/grep/glob only after structured tools narrow the target or when exact code text is required.","","Constraints:","- Stay read-only. Do not edit files, run shell commands, change git state, or ask the user questions.","- Stop when the evidence is sufficient; extra exploration delays the parent agent.","","Output:","- Summarize the repository map, key relationships, gaps/uncertainty, and next best drill-down handles.","- Keep the final answer compact enough for the parent agent to synthesize directly."].join(`
296
+ `),tools:jk(Zu),maxBudget:Fk}}i(Qu,"buildRepoExplorerAgentContent");function ef(e=Date.now()){return{kind:"agent",name:Kr,version:"0.7.57-builtin",content:Qu(),status:"active",createdAt:e,testedAt:e,activatedAt:e}}i(ef,"buildRepoExplorerAgentArtifact");async function Uk(){if(Me(Kr))return!1;let e=ef(),t=te({name:e.name,content:e.content}),n=new Map(de().map(o=>[o.name,o])),r=await Y.admit(t,{activatedAgents:n});if(!r.ok)throw new Error(`built-in ${Kr} admission rejected: ${r.reason}`);return me(e,{bindings:r.handle.invariantBindings,manifest:r.handle.manifest,source:"built-in"}),!0}i(Uk,"ensureBuiltinRepoExplorerAgent");var qn=class extends Error{static{i(this,"RollbackError")}code;constructor(t,n){super(n),this.name="RollbackError",this.code=t}};async function qk(e){let n=(await Ct("agent")).filter(c=>c.kind==="agent"&&c.name===e&&c.status==="active"&&typeof c.activatedAt=="number").sort((c,l)=>(l.activatedAt??0)-(c.activatedAt??0));if(n.length===0)throw new qn("no-current-active",`No active version of '${e}' on disk \u2014 nothing to roll back from.`);if(n.length===1)throw new qn("no-rollback-target",`Only one active version of '${e}' (${n[0].version}) \u2014 no prior version to roll back to. Bump version + stage to author further changes.`);let r=n[0],o=n[1],s=te({name:o.name,content:o.content}),a=await Y.admit(s,{activatedAgents:Bk(e),stagedAgents:new Map});if(!a.ok)throw new qn("admission-failed",`Rollback target ${o.name}@${o.version} no longer admits: ${a.reason}.`);return await ws(r.name,r.version),me(o,{bindings:a.handle.invariantBindings,manifest:a.handle.manifest}),{agentName:e,fromVersion:r.version,toVersion:o.version,fromActivatedAt:r.activatedAt,toActivatedAt:o.activatedAt}}i(qk,"rollbackSelfModify");function Bk(e){let t=new Map;for(let n of de())n.name!==e&&t.set(n.name,n);return t}i(Bk,"snapshotActivatedAgentsExcept");var tf=["scaffold_tool","validate_tool","stage_construction","test_tool","activate_tool"],zk=new Set(tf);function nf(e){return zk.has(e)}i(nf,"isConstructionToolName");function Gk(e,t){return t?[...e]:e.filter(n=>!nf(n))}i(Gk,"filterConstructionToolNames");function Ot(e,t){let n=e[t];if(typeof n!="string"||n.trim().length===0)throw new Error(`'${t}' is required and must be a non-empty string.`);return n.trim()}i(Ot,"readRequiredString");function rf(e){try{return JSON.parse(e)}catch(t){throw new Error(`artifact_json failed to parse as JSON: ${t.message}`)}}i(rf,"parseArtifactJson");function of(e){if(!e||typeof e!="object")throw new Error("artifact must be a JSON object.");let t=e;if(t.kind!=="tool")throw new Error(`artifact.kind must be 'tool' (got ${JSON.stringify(t.kind)}).`);if(typeof t.name!="string"||t.name.trim()==="")throw new Error("artifact.name must be a non-empty string.");if(typeof t.version!="string"||t.version.trim()==="")throw new Error("artifact.version must be a non-empty string (semver recommended).");if(!t.content||typeof t.content!="object")throw new Error("artifact.content must be an object.");let n=t.content;if(typeof n.description!="string")throw new Error("artifact.content.description must be a string.");if(!n.inputSchema||typeof n.inputSchema!="object")throw new Error("artifact.content.inputSchema must be an object.");if(!n.capabilities||typeof n.capabilities!="object")throw new Error("artifact.content.capabilities must be an object with a tools array.");let r=n.handler;if(!r||r.kind!=="script"||r.language!=="javascript")throw new Error("artifact.content.handler must be { kind: 'script', language: 'javascript', code }.");if(typeof r.code!="string"||r.code.trim()==="")throw new Error("artifact.content.handler.code must be a non-empty JavaScript source string.");return e}i(of,"asConstructionArtifact");function xs(e){let t=[];if(t.push(`ok=${e.ok?"true":"false"}`),e.errors&&e.errors.length>0){t.push("errors:");for(let n of e.errors)t.push(` - ${n}`)}if(e.warnings&&e.warnings.length>0){t.push("warnings:");for(let n of e.warnings)t.push(` - ${n}`)}return t.join(`
297
+ `)}i(xs,"renderTestResult");var Kk=`export async function handler(input, ctx) {
283
298
  // TODO: implement using only declared capabilities (ctx.tools.<name>).
284
299
  // Return a string. Throw on unrecoverable input. The runtime applies
285
300
  // a timeout (default 30s) and rejects calls to undeclared tools.
286
301
  return JSON.stringify({ note: 'scaffold \u2014 replace this body', input });
287
302
  }
288
- `;async function fs(e,t){try{let n=St(e,"name"),r=_(e,"version")??"0.1.0",o=_(e,"description")??"TODO: short tool description.",s=e.capabilities,a=(()=>{if(!s)return{tools:[]};if(typeof s!="object")throw new Error("capabilities must be an object with a tools[] array.");let l=s.tools;if(l===void 0)return{tools:[]};if(!Array.isArray(l)||l.some(d=>typeof d!="string"))throw new Error("capabilities.tools must be an array of builtin tool names (strings).");return{tools:l}})(),c={kind:"tool",name:n,version:r,status:"staged",createdAt:Date.now(),content:{description:o,inputSchema:{type:"object",properties:{}},capabilities:a,handler:{kind:"script",language:"javascript",code:Fb},timeoutMs:3e4}};return["Scaffolded artifact JSON (fill TODO sections, then call validate_tool):","",JSON.stringify(c,null,2)].join(`
289
- `)}catch(n){return`[Tool Error] scaffold_tool: ${n.message}`}}i(fs,"toolScaffoldTool");async function ps(e,t){try{let n=St(e,"artifact_json"),r=_(e,"provider")??"anthropic",o;try{o=Su(Eu(n))}catch(u){return`[Tool Error] validate_tool: ${u.message}`}let s=[],a=[];if(o.kind!=="tool")return s.push(`validate_tool only inspects tool artifacts (got kind='${o.kind}'). Use validate_agent for agent artifacts (FEATURE_089).`),us({ok:!1,errors:s});let c=o.content.capabilities.tools;if(!Array.isArray(c))s.push("capabilities.tools must be an array of strings.");else for(let u of c)if(typeof u!="string"||u.trim()===""){s.push(`capabilities.tools entry must be a non-empty string (got: ${JSON.stringify(u)}).`);break}let l=$n(o.content.handler.code);if(!l.ok)for(let u of l.violations)s.push(`[${u.rule}] ${u.message}`);let d=On(o.content.inputSchema,r);for(let u of d.warnings)a.push(`[schema] ${u}`);if(!d.ok)for(let u of d.errors)s.push(`[schema] ${u}`);return us({ok:s.length===0,errors:s.length>0?s:void 0,warnings:a.length>0?a:void 0})}catch(n){return`[Tool Error] validate_tool: ${n.message}`}}i(ps,"toolValidateTool");async function ms(e,t){try{let n=St(e,"artifact_json"),r=Su(Eu(n)),o=await vt(r);return[`staged: ${o.artifact.name}@${o.artifact.version}`,`status=${o.artifact.status}`,"Next: call test_tool with name and version."].join(`
290
- `)}catch(n){return`[Tool Error] stage_construction: ${n.message}`}}i(ms,"toolStageConstruction");async function hs(e,t){try{let n=St(e,"name"),r=St(e,"version"),o=_(e,"provider"),s=await xt(n,r);if(!s)return`[Tool Error] test_tool: no staged artifact found for ${n}@${r}.`;if(s.status==="revoked")return`[Tool Error] test_tool: artifact ${n}@${r} is revoked. Bump the version and re-stage.`;let a={artifact:s,stagedAt:Date.now()},c=await Ln(a,o?{provider:o}:void 0);return us(c)}catch(n){return`[Tool Error] test_tool: ${n.message}`}}i(hs,"toolTestTool");async function gs(e,t){try{let n=St(e,"name"),r=St(e,"version"),o=await xt(n,r);if(!o)return`[Tool Error] activate_tool: no artifact found for ${n}@${r}. Stage and test it first.`;if(o.status==="revoked")return`[Tool Error] activate_tool: ${n}@${r} is revoked. Bump the version and re-stage.`;let s={artifact:o,stagedAt:Date.now()};return await Mn(s),[`activated: ${n}@${r}`,`The handler is now registered in TOOL_REGISTRY and callable as '${n}'.`].join(`
291
- `)}catch(n){return`[Tool Error] activate_tool: ${n.message}`}}i(gs,"toolActivateTool");var Tu={quick:0,balanced:1,deep:2};function Au(e){if(e.prevKind!=="agent"||e.nextKind!=="agent")return{ok:!1,rule:"kind-invalid",reason:`Self-modify only supports kind='agent' (prev='${e.prevKind}', next='${e.nextKind}'). Tool artifacts cannot self-modify; bump version via stage_tool instead.`};if(e.prevName!==e.nextName)return{ok:!1,rule:"name-changed",reason:`Self-modify must keep the same name (prev='${e.prevName}', next='${e.nextName}'). Use stage_agent to publish a differently-named agent.`};if(e.isDisabled)return{ok:!1,rule:"self-modify-disabled",reason:`Self-modify has been permanently disabled for agent '${e.prevName}' via 'kodax constructed disable-self-modify'. To author a different agent with similar capabilities, stage a separately-named manifest via stage_agent_construction.`};if(e.budgetRemaining<=0)return{ok:!1,rule:"budget-exhausted",reason:`Modification budget for '${e.prevName}' is exhausted. Run 'kodax constructed reset-self-modify-budget ${e.prevName}' to unlock further self-modifications.`};let t=Ub(e.prev.guardrails,e.next.guardrails);if(!t.ok)return t;let n=qb(e.next,e.userReasoningCeiling);return n.ok?{ok:!0}:n}i(Au,"validateSelfModify");function Ub(e,t){if(!e||e.length===0)return{ok:!0};let n=new Set((t??[]).map(o=>ys(o))),r=[];for(let o of e)n.has(ys(o))||r.push(ys(o));return r.length>0?{ok:!1,rule:"guardrail-ratchet",reason:`Guardrail ratchet violated \u2014 self-modify cannot remove existing guardrails. Missing in proposed manifest: ${r.join(", ")}. Add the missing guardrail(s) back, or stage a separately-named agent if a different safety posture is required.`}:{ok:!0}}i(Ub,"checkGuardrailRatchet");function ys(e){return`${e.kind}:${e.ref}`}i(ys,"guardrailKey");function qb(e,t){if(t===void 0)return{ok:!0};let n=e.reasoning?.max;return n===void 0?{ok:!0}:Tu[n]>Tu[t]?{ok:!1,rule:"reasoning-ceiling",reason:`Proposed reasoning.max='${n}' exceeds the configured user ceiling '${t}'. Lower the requested max or have the user raise the ceiling.`}:{ok:!0}}i(qb,"checkReasoningCeiling");var Me="stage_self_modify";function Bb(e,t){let n=e[t];if(typeof n!="string"||n.trim().length===0)throw new Error(`'${t}' is required and must be a non-empty string.`);return n.trim()}i(Bb,"readRequiredString");function Wb(e){try{return JSON.parse(e)}catch(t){throw new Error(`artifact_json failed to parse as JSON: ${t.message}`)}}i(Wb,"parseArtifactJson");function Hb(e){if(!e||typeof e!="object")throw new Error("artifact must be a JSON object.");let t=e;if(t.kind!=="agent")throw new Error(`artifact.kind must be 'agent' (got ${JSON.stringify(t.kind)}).`);if(typeof t.name!="string"||t.name.trim()==="")throw new Error("artifact.name must be a non-empty string.");if(typeof t.version!="string"||t.version.trim()==="")throw new Error("artifact.version must be a non-empty string (semver recommended).");if(!t.content||typeof t.content!="object")throw new Error("artifact.content must be an object.");let n=t.content;if(typeof n.instructions!="string"||n.instructions.trim().length===0)throw new Error("artifact.content.instructions must be a non-empty string.");return e}i(Hb,"asAgentArtifact");async function Kb(e){return(await _t("agent")).find(n=>n.kind==="agent"&&n.name===e&&n.status==="active")}i(Kb,"findActiveAgentArtifact");async function Cu(e,t){try{let n=Bb(e,"artifact_json"),r=Hb(Wb(n));if(typeof r.sourceAgent!="string"||r.sourceAgent.length===0)return[`[Tool Error] ${Me}:`,"artifact.sourceAgent is required for self-modify and must equal artifact.name (the agent claiming the modification)."].join(" ");if(r.sourceAgent!==r.name)return[`[Tool Error] ${Me}:`,`artifact.sourceAgent='${r.sourceAgent}' does not match artifact.name='${r.name}'.`,"Self-modify only allows an agent to publish a new version of itself.","To create a different agent, use stage_agent_construction."].join(" ");let o=await Kb(r.name);if(!o)return[`[Tool Error] ${Me}:`,`no active version of '${r.name}' on disk.`,"Self-modify requires an existing active manifest \u2014 use stage_agent_construction for first-time staging."].join(" ");let s=os(),[a,c]=await Promise.all([bt(r.name,{cwd:s}),In(r.name,{cwd:s})]),l=nn(a),d=Au({prev:o.content,next:r.content,prevName:o.name,nextName:r.name,prevKind:o.kind,nextKind:r.kind,budgetRemaining:l,isDisabled:c.disabled});if(!d.ok)return await Ie({ts:new Date().toISOString(),event:"self_modify_rejected",agentName:r.name,toVersion:r.version,fromVersion:o.version,diffHash:wt(o.content,r.content),budgetRemaining:l,rejectRule:d.rule,rejectReason:d.reason},{cwd:s}),[`[Tool Error] ${Me}: rule='${d.rule}'`,d.reason].join(" \u2014 ");let u=await vt(r);return await Ie({ts:new Date().toISOString(),event:"self_modify_staged",agentName:r.name,toVersion:r.version,fromVersion:o.version,diffHash:wt(o.content,r.content),budgetRemaining:l},{cwd:s}),[`staged self-modify: ${u.artifact.name} ${o.version} \u2192 ${u.artifact.version}`,`status=${u.artifact.status} budgetRemaining=${l}/${a.limit}`,"Next: call test_agent with name and version. Activation will require user approval (force-ask-user)."].join(`
292
- `)}catch(n){return`[Tool Error] ${Me}: ${n.message}`}}i(Cu,"toolStageSelfModify");var ws=["scaffold_agent","validate_agent","stage_agent_construction","test_agent","activate_agent"],yI=new Set(ws),zb=new Set([...ws,Me]);function Gb(e,t){return t?[...e]:e.filter(n=>!zb.has(n))}i(Gb,"filterAgentConstructionToolNames");function Tt(e,t){let n=e[t];if(typeof n!="string"||n.trim().length===0)throw new Error(`'${t}' is required and must be a non-empty string.`);return n.trim()}i(Tt,"readRequiredString");function Ru(e){try{return JSON.parse(e)}catch(t){throw new Error(`artifact_json failed to parse as JSON: ${t.message}`)}}i(Ru,"parseArtifactJson");function $u(e){if(!e||typeof e!="object")throw new Error("artifact must be a JSON object.");let t=e;if(t.kind!=="agent")throw new Error(`artifact.kind must be 'agent' (got ${JSON.stringify(t.kind)}).`);if(typeof t.name!="string"||t.name.trim()==="")throw new Error("artifact.name must be a non-empty string.");if(typeof t.version!="string"||t.version.trim()==="")throw new Error("artifact.version must be a non-empty string (semver recommended).");if(!t.content||typeof t.content!="object")throw new Error("artifact.content must be an object.");let n=t.content;if(typeof n.instructions!="string"||n.instructions.trim().length===0)throw new Error("artifact.content.instructions must be a non-empty string.");return e}i($u,"asAgentArtifact");function Ou(e){let t=[];if(t.push(`ok=${e.ok?"true":"false"}`),e.errors&&e.errors.length>0){t.push("errors:");for(let n of e.errors)t.push(` - ${n}`)}if(e.warnings&&e.warnings.length>0){t.push("warnings:");for(let n of e.warnings)t.push(` - ${n}`)}return t.join(`
293
- `)}i(Ou,"renderTestResult");async function Iu(e,t){try{let n=Tt(e,"name"),r=_(e,"version")??"0.1.0",o=_(e,"description")??"TODO: short summary of what this agent does and when to invoke it.",s={kind:"agent",name:n,version:r,status:"staged",createdAt:Date.now(),content:{instructions:`${o}
303
+ `;async function Es(e,t){try{let n=Ot(e,"name"),r=_(e,"version")??"0.1.0",o=_(e,"description")??"TODO: short tool description.",s=e.capabilities,a=(()=>{if(!s)return{tools:[]};if(typeof s!="object")throw new Error("capabilities must be an object with a tools[] array.");let l=s.tools;if(l===void 0)return{tools:[]};if(!Array.isArray(l)||l.some(d=>typeof d!="string"))throw new Error("capabilities.tools must be an array of builtin tool names (strings).");return{tools:l}})(),c={kind:"tool",name:n,version:r,status:"staged",createdAt:Date.now(),content:{description:o,inputSchema:{type:"object",properties:{}},capabilities:a,handler:{kind:"script",language:"javascript",code:Kk},timeoutMs:3e4}};return["Scaffolded artifact JSON (fill TODO sections, then call validate_tool):","",JSON.stringify(c,null,2)].join(`
304
+ `)}catch(n){return`[Tool Error] scaffold_tool: ${n.message}`}}i(Es,"toolScaffoldTool");async function Ss(e,t){try{let n=Ot(e,"artifact_json"),r=_(e,"provider")??"anthropic",o;try{o=of(rf(n))}catch(u){return`[Tool Error] validate_tool: ${u.message}`}let s=[],a=[];if(o.kind!=="tool")return s.push(`validate_tool only inspects tool artifacts (got kind='${o.kind}'). Use validate_agent for agent artifacts (FEATURE_089).`),xs({ok:!1,errors:s});let c=o.content.capabilities.tools;if(!Array.isArray(c))s.push("capabilities.tools must be an array of strings.");else for(let u of c)if(typeof u!="string"||u.trim()===""){s.push(`capabilities.tools entry must be a non-empty string (got: ${JSON.stringify(u)}).`);break}let l=Pn(o.content.handler.code);if(!l.ok)for(let u of l.violations)s.push(`[${u.rule}] ${u.message}`);let d=Nn(o.content.inputSchema,r);for(let u of d.warnings)a.push(`[schema] ${u}`);if(!d.ok)for(let u of d.errors)s.push(`[schema] ${u}`);return xs({ok:s.length===0,errors:s.length>0?s:void 0,warnings:a.length>0?a:void 0})}catch(n){return`[Tool Error] validate_tool: ${n.message}`}}i(Ss,"toolValidateTool");async function Ts(e,t){try{let n=Ot(e,"artifact_json"),r=of(rf(n)),o=await At(r);return[`staged: ${o.artifact.name}@${o.artifact.version}`,`status=${o.artifact.status}`,"Next: call test_tool with name and version."].join(`
305
+ `)}catch(n){return`[Tool Error] stage_construction: ${n.message}`}}i(Ts,"toolStageConstruction");async function As(e,t){try{let n=Ot(e,"name"),r=Ot(e,"version"),o=_(e,"provider"),s=await $t(n,r);if(!s)return`[Tool Error] test_tool: no staged artifact found for ${n}@${r}.`;if(s.status==="revoked")return`[Tool Error] test_tool: artifact ${n}@${r} is revoked. Bump the version and re-stage.`;let a={artifact:s,stagedAt:Date.now()},c=await Fn(a,o?{provider:o}:void 0);return xs(c)}catch(n){return`[Tool Error] test_tool: ${n.message}`}}i(As,"toolTestTool");async function Cs(e,t){try{let n=Ot(e,"name"),r=Ot(e,"version"),o=await $t(n,r);if(!o)return`[Tool Error] activate_tool: no artifact found for ${n}@${r}. Stage and test it first.`;if(o.status==="revoked")return`[Tool Error] activate_tool: ${n}@${r} is revoked. Bump the version and re-stage.`;let s={artifact:o,stagedAt:Date.now()};return await jn(s),[`activated: ${n}@${r}`,`The handler is now registered in TOOL_REGISTRY and callable as '${n}'.`].join(`
306
+ `)}catch(n){return`[Tool Error] activate_tool: ${n.message}`}}i(Cs,"toolActivateTool");var sf={quick:0,balanced:1,deep:2};function af(e){if(e.prevKind!=="agent"||e.nextKind!=="agent")return{ok:!1,rule:"kind-invalid",reason:`Self-modify only supports kind='agent' (prev='${e.prevKind}', next='${e.nextKind}'). Tool artifacts cannot self-modify; bump version via stage_tool instead.`};if(e.prevName!==e.nextName)return{ok:!1,rule:"name-changed",reason:`Self-modify must keep the same name (prev='${e.prevName}', next='${e.nextName}'). Use stage_agent to publish a differently-named agent.`};if(e.isDisabled)return{ok:!1,rule:"self-modify-disabled",reason:`Self-modify has been permanently disabled for agent '${e.prevName}' via 'kodax constructed disable-self-modify'. To author a different agent with similar capabilities, stage a separately-named manifest via stage_agent_construction.`};if(e.budgetRemaining<=0)return{ok:!1,rule:"budget-exhausted",reason:`Modification budget for '${e.prevName}' is exhausted. Run 'kodax constructed reset-self-modify-budget ${e.prevName}' to unlock further self-modifications.`};let t=Xk(e.prev.guardrails,e.next.guardrails);if(!t.ok)return t;let n=Vk(e.next,e.userReasoningCeiling);return n.ok?{ok:!0}:n}i(af,"validateSelfModify");function Xk(e,t){if(!e||e.length===0)return{ok:!0};let n=new Set((t??[]).map(o=>$s(o))),r=[];for(let o of e)n.has($s(o))||r.push($s(o));return r.length>0?{ok:!1,rule:"guardrail-ratchet",reason:`Guardrail ratchet violated \u2014 self-modify cannot remove existing guardrails. Missing in proposed manifest: ${r.join(", ")}. Add the missing guardrail(s) back, or stage a separately-named agent if a different safety posture is required.`}:{ok:!0}}i(Xk,"checkGuardrailRatchet");function $s(e){return`${e.kind}:${e.ref}`}i($s,"guardrailKey");function Vk(e,t){if(t===void 0)return{ok:!0};let n=e.reasoning?.max;return n===void 0?{ok:!0}:sf[n]>sf[t]?{ok:!1,rule:"reasoning-ceiling",reason:`Proposed reasoning.max='${n}' exceeds the configured user ceiling '${t}'. Lower the requested max or have the user raise the ceiling.`}:{ok:!0}}i(Vk,"checkReasoningCeiling");var De="stage_self_modify";function Jk(e,t){let n=e[t];if(typeof n!="string"||n.trim().length===0)throw new Error(`'${t}' is required and must be a non-empty string.`);return n.trim()}i(Jk,"readRequiredString");function Yk(e){try{return JSON.parse(e)}catch(t){throw new Error(`artifact_json failed to parse as JSON: ${t.message}`)}}i(Yk,"parseArtifactJson");function Zk(e){if(!e||typeof e!="object")throw new Error("artifact must be a JSON object.");let t=e;if(t.kind!=="agent")throw new Error(`artifact.kind must be 'agent' (got ${JSON.stringify(t.kind)}).`);if(typeof t.name!="string"||t.name.trim()==="")throw new Error("artifact.name must be a non-empty string.");if(typeof t.version!="string"||t.version.trim()==="")throw new Error("artifact.version must be a non-empty string (semver recommended).");if(!t.content||typeof t.content!="object")throw new Error("artifact.content must be an object.");let n=t.content;if(typeof n.instructions!="string"||n.instructions.trim().length===0)throw new Error("artifact.content.instructions must be a non-empty string.");return e}i(Zk,"asAgentArtifact");async function Qk(e){return(await Ct("agent")).find(n=>n.kind==="agent"&&n.name===e&&n.status==="active")}i(Qk,"findActiveAgentArtifact");async function cf(e,t){try{let n=Jk(e,"artifact_json"),r=Zk(Yk(n));if(typeof r.sourceAgent!="string"||r.sourceAgent.length===0)return[`[Tool Error] ${De}:`,"artifact.sourceAgent is required for self-modify and must equal artifact.name (the agent claiming the modification)."].join(" ");if(r.sourceAgent!==r.name)return[`[Tool Error] ${De}:`,`artifact.sourceAgent='${r.sourceAgent}' does not match artifact.name='${r.name}'.`,"Self-modify only allows an agent to publish a new version of itself.","To create a different agent, use stage_agent_construction."].join(" ");let o=await Qk(r.name);if(!o)return[`[Tool Error] ${De}:`,`no active version of '${r.name}' on disk.`,"Self-modify requires an existing active manifest \u2014 use stage_agent_construction for first-time staging."].join(" ");let s=gs(),[a,c]=await Promise.all([St(r.name,{cwd:s}),Dn(r.name,{cwd:s})]),l=cn(a),d=af({prev:o.content,next:r.content,prevName:o.name,nextName:r.name,prevKind:o.kind,nextKind:r.kind,budgetRemaining:l,isDisabled:c.disabled});if(!d.ok)return await Pe({ts:new Date().toISOString(),event:"self_modify_rejected",agentName:r.name,toVersion:r.version,fromVersion:o.version,diffHash:Et(o.content,r.content),budgetRemaining:l,rejectRule:d.rule,rejectReason:d.reason},{cwd:s}),[`[Tool Error] ${De}: rule='${d.rule}'`,d.reason].join(" \u2014 ");let u=await At(r);return await Pe({ts:new Date().toISOString(),event:"self_modify_staged",agentName:r.name,toVersion:r.version,fromVersion:o.version,diffHash:Et(o.content,r.content),budgetRemaining:l},{cwd:s}),[`staged self-modify: ${u.artifact.name} ${o.version} \u2192 ${u.artifact.version}`,`status=${u.artifact.status} budgetRemaining=${l}/${a.limit}`,"Next: call test_agent with name and version. Activation will require user approval (force-ask-user)."].join(`
307
+ `)}catch(n){return`[Tool Error] ${De}: ${n.message}`}}i(cf,"toolStageSelfModify");var Rs=["scaffold_agent","validate_agent","stage_agent_construction","test_agent","activate_agent"],EL=new Set(Rs),ev=new Set([...Rs,De]);function tv(e,t){return t?[...e]:e.filter(n=>!ev.has(n))}i(tv,"filterAgentConstructionToolNames");function It(e,t){let n=e[t];if(typeof n!="string"||n.trim().length===0)throw new Error(`'${t}' is required and must be a non-empty string.`);return n.trim()}i(It,"readRequiredString");function lf(e){try{return JSON.parse(e)}catch(t){throw new Error(`artifact_json failed to parse as JSON: ${t.message}`)}}i(lf,"parseArtifactJson");function df(e){if(!e||typeof e!="object")throw new Error("artifact must be a JSON object.");let t=e;if(t.kind!=="agent")throw new Error(`artifact.kind must be 'agent' (got ${JSON.stringify(t.kind)}).`);if(typeof t.name!="string"||t.name.trim()==="")throw new Error("artifact.name must be a non-empty string.");if(typeof t.version!="string"||t.version.trim()==="")throw new Error("artifact.version must be a non-empty string (semver recommended).");if(!t.content||typeof t.content!="object")throw new Error("artifact.content must be an object.");let n=t.content;if(typeof n.instructions!="string"||n.instructions.trim().length===0)throw new Error("artifact.content.instructions must be a non-empty string.");return e}i(df,"asAgentArtifact");function uf(e){let t=[];if(t.push(`ok=${e.ok?"true":"false"}`),e.errors&&e.errors.length>0){t.push("errors:");for(let n of e.errors)t.push(` - ${n}`)}if(e.warnings&&e.warnings.length>0){t.push("warnings:");for(let n of e.warnings)t.push(` - ${n}`)}return t.join(`
308
+ `)}i(uf,"renderTestResult");async function ff(e,t){try{let n=It(e,"name"),r=_(e,"version")??"0.1.0",o=_(e,"description")??"TODO: short summary of what this agent does and when to invoke it.",s={kind:"agent",name:n,version:r,status:"staged",createdAt:Date.now(),content:{instructions:`${o}
294
309
 
295
310
  TODO: replace with the agent's full operating instructions.`,tools:[],reasoning:{default:"balanced",max:"deep",escalateOnRevise:!1}}};return["Scaffolded agent manifest (fill TODO sections, then call validate_agent):","","Manifest schema notes:"," - instructions: string (required) \u2014 the agent's system-prompt body.",' - tools: ToolRef[] \u2014 refs like { ref: "builtin:read" } or { ref: "constructed:foo@1.0.0" }.',' - handoffs: AgentHandoffRef[] \u2014 { target: { ref }, kind: "continuation"|"as-tool" }.'," - reasoning: { default, max?, escalateOnRevise? } \u2014 same shape as Layer A AgentReasoningProfile.",' - guardrails: GuardrailRef[] \u2014 { kind: "input"|"output"|"tool", ref }.'," - maxBudget: number \u2014 clamped against systemCap.maxBudget at admission.",' - declaredInvariants: string[] \u2014 voluntary invariants (e.g. ["harnessSelectionTiming"]).'," - testCases: AgentTestCase[] \u2014 { id, input, expectMatch?|expectNotMatch?|expectFinalText? }.","",JSON.stringify(s,null,2)].join(`
296
- `)}catch(n){return`[Tool Error] scaffold_agent: ${n.message}`}}i(Iu,"toolScaffoldAgent");async function Lu(e,t){try{let n=Tt(e,"artifact_json"),r;try{r=$u(Ru(n))}catch(l){return`[Tool Error] validate_agent: ${l.message}`}if(Ws().length===0)return["[Tool Error] validate_agent: invariant registry is empty.","Call registerCodingInvariants() (from @kodax-ai/coding) before invoking validate_agent \u2014","the REPL surface bootstraps this at startup; non-REPL contexts must register explicitly."].join(" ");let o=Z({name:r.name,content:r.content}),s=await Y.admit(o),a=[],c=[];if(!s.ok)a.push(`[admission] ${s.reason} (retryable=${s.retryable})`);else for(let l of s.clampNotes)c.push(`[admission] ${l}`);return Ou({ok:a.length===0,errors:a.length>0?a:void 0,warnings:c.length>0?c:void 0})}catch(n){return`[Tool Error] validate_agent: ${n.message}`}}i(Lu,"toolValidateAgent");async function Mu(e,t){try{let n=Tt(e,"artifact_json"),r=$u(Ru(n)),o=(await _t("agent")).find(a=>a.kind==="agent"&&a.name===r.name&&a.status==="active");if(o)return["[Tool Error] stage_agent_construction:",`'${r.name}' already has an active manifest (${o.version}).`,"Modifying an existing constructed agent must go through stage_self_modify so the FEATURE_090 hard checks (guardrail ratchet, budget, force-ask-user) apply.","Pick a different name to create a separate agent."].join(" ");let s=await vt(r);return[`staged: ${s.artifact.name}@${s.artifact.version} (kind=agent)`,`status=${s.artifact.status}`,"Next: call test_agent with name and version."].join(`
297
- `)}catch(n){return`[Tool Error] stage_agent_construction: ${n.message}`}}i(Mu,"toolStageAgentConstruction");async function Pu(e,t){try{let n=Tt(e,"name"),r=Tt(e,"version"),o=await xt(n,r);if(!o)return`[Tool Error] test_agent: no staged artifact found for ${n}@${r}.`;if(o.kind!=="agent")return`[Tool Error] test_agent: ${n}@${r} has kind='${o.kind}', expected 'agent'. Use test_tool for tool artifacts.`;if(o.status==="revoked")return`[Tool Error] test_agent: ${n}@${r} is revoked. Bump the version and re-stage.`;let s={artifact:o,stagedAt:Date.now()},a=await Ln(s);return Ou(a)}catch(n){return`[Tool Error] test_agent: ${n.message}`}}i(Pu,"toolTestAgent");async function Nu(e,t){try{let n=Tt(e,"name"),r=Tt(e,"version"),o=await xt(n,r);if(!o)return`[Tool Error] activate_agent: no artifact found for ${n}@${r}. Stage and test it first.`;if(o.kind!=="agent")return`[Tool Error] activate_agent: ${n}@${r} has kind='${o.kind}', expected 'agent'. Use activate_tool for tool artifacts.`;if(o.status==="revoked")return`[Tool Error] activate_agent: ${n}@${r} is revoked. Bump the version and re-stage.`;let s={artifact:o,stagedAt:Date.now()};return await Mn(s),[`activated: ${n}@${r} (kind=agent)`,"Resolver now exposes the agent at this name; subsequent Runner.run calls can resolve it."].join(`
298
- `)}catch(n){return`[Tool Error] activate_agent: ${n.message}`}}i(Nu,"toolActivateAgent");var qr=Object.freeze({web_search:'Discover web content when no specific URL is known \u2014 call `tool_search("web_search")` for full schema.',web_fetch:'Fetch a specific remote URL (HTML\u2192markdown, cached) \u2014 call `tool_search("web_fetch")` for full schema (includes GitHub-URL gh-CLI guidance).',code_search:'Ranked text search across the repo with noise filtering \u2014 call `tool_search("code_search")` for selection heuristics vs grep / symbol_context.',semantic_lookup:'Symbol-/module-/process-aware semantic queries against repo intelligence \u2014 call `tool_search("semantic_lookup")` for full schema and selection rules.',mcp_search:'Search active MCP capabilities by query / server / kind \u2014 call `tool_search("mcp_search")` for full schema.',mcp_describe:'Describe a specific MCP capability by id (JSON schema + trust) \u2014 call `tool_search("mcp_describe")` for full schema.',mcp_call:'Invoke an MCP tool capability \u2014 can MUTATE remote state. Call `tool_search("mcp_call")` for the full safety contract.',mcp_read_resource:'Read an MCP resource (no mutation) \u2014 call `tool_search("mcp_read_resource")` for full schema.',mcp_get_prompt:'Retrieve an MCP prompt template \u2014 call `tool_search("mcp_get_prompt")` for full schema.',repo_overview:'Workspace structure snapshot \u2014 call ONCE at session start; `tool_search("repo_overview")` for full schema.',changed_scope:'List files / areas changed in current git diff \u2014 canonical review entry. `tool_search("changed_scope")` for full schema.',module_context:'Compact module capsule (deps, entries, symbols, tests) \u2014 call `tool_search("module_context")` for full schema and selection rules vs symbol_context.',symbol_context:'Definition + callers/callees for one symbol \u2014 call `tool_search("symbol_context")` for full schema and selection rules.',process_context:'Static execution/process trace from an entry \u2014 call `tool_search("process_context")` for full schema.',impact_estimate:'Blast radius estimate BEFORE a rename or refactor \u2014 call `tool_search("impact_estimate")` for full schema (replaces guessing impact from grep).',get_goal:'Read the current /goal status (objective / tokens / budget / elapsed) \u2014 call `tool_search("get_goal")` for full schema. Available when a goal is set.',create_goal:'Create a persistent /goal \u2014 only when explicitly requested by the user or system instructions. Call `tool_search("create_goal")` for full schema and discipline rules.',update_goal:'Mark the current /goal complete or blocked \u2014 runtime-verified (sidecar + 3-turn rule). Call `tool_search("update_goal")` for full schema.'});function Uu(e){return e in qr}i(Uu,"isDeferredTool");var ks=new WeakMap;function qu(e,t){let n=ks.get(e);n||(n=new Set,ks.set(e,n)),n.add(t)}i(qu,"unlockDeferredToolForContext");function n0(e){let t=ks.get(e);return t?new Set(t):new Set}i(n0,"getUnlockedDeferredTools");var ak=5,Bu=15;function ck(e){let t=e.trim();if(t.startsWith("select:"))return{mode:"select",names:t.slice(7).split(/[,\s]+/).map(c=>c.trim()).filter(c=>c.length>0),required:[],loose:[]};let n=t.split(/\s+/).filter(s=>s.length>0),r=[],o=[];for(let s of n)s.startsWith("+")&&s.length>1?r.push(s.slice(1).toLowerCase()):o.push(s.toLowerCase());return{mode:"keyword",names:[],required:r,loose:o}}i(ck,"parseQuery");function lk(e,t,n,r){let o=`${e.toLowerCase()} ${t.toLowerCase()}`;for(let a of n)if(!o.includes(a))return null;let s=0;for(let a of r)o.includes(a)&&s++;return s}i(lk,"scoreToolForKeywords");function dk(e){let t=[],n=new Set;for(let r of e)n.has(r)||(n.add(r),(Uu(r)||Dn(r))&&t.push(r));return t}i(dk,"resolveSelectNames");function uk(e,t,n){let r=[];for(let[o,s]of Object.entries(qr)){let a=lk(o,s,e,t);a!==null&&(a===0&&t.length>0||r.push({name:o,score:a}))}return r.sort((o,s)=>s.score-o.score),r.slice(0,n).map(o=>o.name)}i(uk,"searchKeywords");function fk(e){let t={description:e.description,name:e.name,parameters:e.input_schema};return`<function>${JSON.stringify(t)}</function>`}i(fk,"formatToolAsFunctionBlock");function pk(e,t,n){if(e.length===0)return"No tools matched the query. Available deferred tools: "+Object.keys(qr).join(", ")+". Use query form `select:NAME` to fetch a specific schema.";let r=[];for(let o of e){let s=Dn(o);if(!s){r.push(`<!-- ${o}: not registered (skipped) -->`);continue}qu(t,o),r.push(fk(ba(s,n)))}return r.join(`
299
- `)}i(pk,"buildResult");var mk=i(async(e,t)=>{let n=e,r=typeof n.query=="string"?n.query:"";if(r.length===0)return"tool_search: `query` is required. Forms: `select:NAME[,NAME...]` for exact lookup, or keyword search (`+required loose terms`).";let o=typeof n.max_results=="number"&&n.max_results>0?Math.min(Math.floor(n.max_results),Bu):ak,s=ck(r),a=s.mode==="select"?dk(s.names).slice(0,Bu):uk(s.required,s.loose,o);return pk(a,t,t.selfManual?.productName)},"toolSearchHandler"),Wu={name:"tool_search",description:["Fetch full schema definitions for tools whose rich descriptions are deferred behind compact search hints.","The deferred catalog includes mcp_*, web_*, repo-intel (module_context / symbol_context / impact_estimate / process_context / changed_scope / repo_overview / semantic_lookup / code_search), and goal tools (get_goal / create_goal / update_goal).","Use `tool_search` when a hint suggests a tool fits the task and you need the full schema (parameter shape, when-to-prefer-X, behavioral contracts) before invoking.",'Query forms: `select:ToolName` (exact, recommended) or keyword search like `"+module exploration"` (require keyword) / `"refactor impact"` (loose match, ranked).',"On the SA path, resolving a deferred tool unlocks its full description for later tool lists in the same context. On AMA/AMAW managed paths, the tool list is static, so the `tool_search` result itself is the durable teaching surface."].join(" "),input_schema:{type:"object",properties:{query:{type:"string",description:"Either `select:ToolName[,ToolName...]` for exact lookup, or keyword search (`+keyword required loose terms`)."},max_results:{type:"number",description:"Maximum number of results to return (default 5, capped at 15). Ignored in `select:` mode."}},required:["query"]},handler:mk,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")};import ue from"path";import{pathToFileURL as Ju}from"url";import{execFile as hk}from"child_process";import{promisify as gk}from"util";var yk=gk(hk),wk=3e4,bk=1e4;async function Hu(e,t={}){let n=t.timeout??wk,r=t.shell??(process.platform==="win32"?"powershell":"bash"),o=r==="powershell"?["-Command",e]:["-c",e],s={PATH:process.env.PATH??"",HOME:process.env.HOME??process.env.USERPROFILE??"",LANG:process.env.LANG??"",TERM:process.env.TERM??"",...process.platform==="win32"?{SYSTEMROOT:process.env.SYSTEMROOT??"",COMSPEC:process.env.COMSPEC??"",PATHEXT:process.env.PATHEXT??""}:{},...t.env};try{let{stdout:a,stderr:c}=await yk(r,o,{timeout:n,cwd:t.cwd,env:s});return{exitCode:0,stdout:a.trim(),stderr:c.trim()}}catch(a){let c=a&&typeof a=="object"&&"code"in a&&typeof a.code=="number"?a.code:1,l=a&&typeof a=="object"&&"stdout"in a?String(a.stdout??"").trim():"",d=a&&typeof a=="object"&&"stderr"in a?String(a.stderr??"").trim():a instanceof Error?a.message:String(a);return{exitCode:c,stdout:l,stderr:d}}}i(Hu,"exec");async function Ku(e,t,n={}){let r=n.timeout??bk,o=new AbortController,s=setTimeout(()=>o.abort(),r);try{let a=await fetch(e,{method:n.method??"POST",headers:{"Content-Type":"application/json",...n.headers},body:JSON.stringify(t),signal:o.signal});clearTimeout(s);let c=await a.text().catch(()=>{});return{ok:a.ok,status:a.status,body:c}}catch(a){return clearTimeout(s),{ok:!1,status:0,body:a instanceof Error?a.message:String(a)}}}i(Ku,"webhook");import ke from"path";import{access as kk,readdir as vk,realpath as _k,stat as xs}from"fs/promises";import{constants as xk}from"fs";var zu=new Set([".js",".mjs",".cjs",".ts",".mts",".cts"]),Br=["extension.mjs","extension.js","extension.cjs","extension.mts","extension.ts","extension.cts","index.mjs","index.js","index.cjs","index.mts","index.ts","index.cts"];function Es(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}i(Es,"isMissingPathError");async function Gu(e){try{return(await xs(e)).isFile()?(await kk(e,xk.R_OK),!0):!1}catch(t){if(Es(t))return!1;throw t}}i(Gu,"isReadableFile");function jn(e){return zu.has(ke.extname(e).toLowerCase())}i(jn,"isSupportedExtensionModulePath");function Ek(e=st()){return ke.join(e,"extensions")}i(Ek,"getDefaultExtensionDirectory");async function Ss(e){let t=ke.resolve(e),n=await xs(t);if(n.isFile()){if(!jn(t))throw new Error(`Unsupported extension module "${t}". Expected one of: ${[...zu].join(", ")}.`);return t}if(!n.isDirectory())throw new Error(`Extension path "${t}" must be a file or directory.`);for(let r of Br){let o=ke.join(t,r);if(await Gu(o))return o}throw new Error(`Extension directory "${t}" must contain one of: ${Br.join(", ")}.`)}i(Ss,"resolveExtensionEntrypoint");async function Xu(e){for(let t of Br){let n=ke.join(e,t);if(await Gu(n))return n}}i(Xu,"tryResolveDirectoryEntrypoint");async function Sk(e){try{let t=await xs(e);return t.isFile()?jn(e)?ke.resolve(e):void 0:t.isDirectory()?Xu(e):void 0}catch(t){if(Es(t))return;throw t}}i(Sk,"tryResolveDiscoveredEntrypoint");async function Tk(e){try{return await _k(e)}catch(t){return ke.resolve(e)}}i(Tk,"canonicalEntrypointIdentity");async function _s(e){let t=e.trim();try{return await Tk(await Ss(t))}catch(n){return ke.resolve(t)}}i(_s,"getExtensionEntrypointIdentity");async function Vu(e){let t=[],n=new Set;for(let r of e){let o=r.trim();if(!o)continue;let s=await _s(o);n.has(s)||(n.add(s),t.push(o))}return t}i(Vu,"dedupeExtensionPathsByEntrypoint");async function w0(e,t){let n=new Set;for(let s of t){let a=s.trim();a&&n.add(await _s(a))}let r=[],o=new Set;for(let s of e){let a=s.trim();if(!a)continue;let c=await _s(a);n.has(c)||o.has(c)||(o.add(c),r.push(a))}return r}i(w0,"excludeExtensionPathsByEntrypoint");function vs(e,t,n){return{path:e,reason:t,message:n}}i(vs,"skippedEntry");async function Ak(e){let t=ke.resolve(e),n;try{n=await vk(t,{withFileTypes:!0})}catch(s){if(Es(s))return{paths:[],skipped:[]};throw s}let r=[],o=[];for(let s of n.sort((a,c)=>a.name.localeCompare(c.name))){let a=ke.join(t,s.name);if(s.isFile()){jn(a)?r.push(a):o.push(vs(a,"unsupported_module","File extension is not supported for KodaX runtime extensions."));continue}if(s.isDirectory()){let c=await Xu(a);c?r.push(c):o.push(vs(a,"missing_entrypoint",`Directory does not contain one of: ${Br.join(", ")}.`));continue}if(s.isSymbolicLink()){let c=await Sk(a);c?r.push(c):o.push(vs(a,"unsupported_target","Symlink target is not a supported extension file or package directory."))}}return{paths:r,skipped:o}}i(Ak,"discoverExtensionsInDirectoryDetailed");async function Ck(e){return(await Ak(e)).paths}i(Ck,"discoverExtensionsInDirectory");async function b0(){return Ck(Ek())}i(b0,"discoverDefaultExtensions");import{tsImport as Rk}from"tsx/esm/api";function $k(e){let t=ue.basename(e),n=ue.parse(t).name;return n==="extension"||n==="index"?ue.basename(ue.dirname(e)):t}i($k,"getExtensionLabel");var At=null,Ct=null;function Ok(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.emit=="function"&&typeof t.runHook=="function"}i(Ok,"isActiveExtensionExecutionRuntime");function Ik(e){let t=[];for(let n of e){let r=n.trim();!r||t.includes(r)||t.push(r)}return t}i(Ik,"dedupeStrings");function Yu(e){return typeof e=="string"?{role:"user",content:e}:e}i(Yu,"normalizeQueuedMessage");function Lk(e){let t={};return e.provider?.trim()&&(t.provider=e.provider.trim()),e.model?.trim()&&(t.model=e.model.trim()),t}i(Lk,"normalizeModelSelection");function sn(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return!0;if(Array.isArray(e))return e.every(sn);if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(sn)}i(sn,"isJsonValue");var Ts=class{static{i(this,"KodaXExtensionRuntime")}capabilityProviders=new Map;commands=new Map;eventHandlers=new Map;hookHandlers=new Map;loadedExtensions=new Map;failures=[];runtimeDisposables=[];runtimeLogger;config;runtimeController;nextRecordId=0;boundController=null;defaultActiveTools;defaultModelSelection={};defaultThinkingLevel;constructor(t={}){this.config=t.config??{},this.runtimeLogger={debug:i((...n)=>console.debug("[kodax:extension]",...n),"debug"),info:i((...n)=>console.info("[kodax:extension]",...n),"info"),warn:i((...n)=>console.warn("[kodax:extension]",...n),"warn"),error:i((...n)=>console.error("[kodax:extension]",...n),"error")},this.runtimeController=this.createRuntimeControllerProxy()}activate(){return At=this,this}getDefaults(){return{activeTools:this.defaultActiveTools===void 0?void 0:[...this.defaultActiveTools],modelSelection:{...this.defaultModelSelection},thinkingLevel:this.defaultThinkingLevel}}bindController(t){let n=this.boundController;return this.boundController=t,()=>{this.boundController=n}}async dispose(){for(let t of Array.from(this.loadedExtensions.values()).reverse())await t.disposeAll();this.loadedExtensions.clear();for(let t of this.runtimeDisposables.reverse())await t();this.runtimeDisposables.length=0,this.failures.length=0,this.boundController=null,At===this&&(At=null),Ct===this&&(Ct=null)}async loadExtensions(t,n={}){let r=await Vu(t);for(let o of r)try{await this.loadExtension(o,{loadSource:n.loadSource,stage:n.stage??"load"})}catch(s){if(!n.continueOnError)throw s;this.runtimeLogger.warn(`Failed to load extension "${o}" during ${n.stage??"load"}:`,s instanceof Error?s.message:String(s))}}async loadExtension(t,n={}){let r=ue.resolve(t);try{r=await Ss(r);let o=this.loadedExtensions.get(r),s=n.loadSource??o?.loadSource??"api",a=await this.importExtensionModule(r),c=a.default,l=c&&typeof c=="object"&&"default"in c?c.default:void 0,d=c&&typeof c=="object"&&"activate"in c?c.activate:void 0,u=typeof c=="function"?c:typeof l=="function"?l:typeof a.activate=="function"?a.activate:typeof d=="function"?d:void 0;if(!u)throw new Error(`Extension "${r}" must export a default function or named activate() function.`);try{let f=[],m=this.createExtensionApi(r,f,s),h={path:r,label:$k(r),loadSource:s,disposeAll:i(async()=>{for(let p of f.reverse())await p()},"disposeAll")};try{let p=await u(m);typeof p=="function"&&f.push(p)}catch(p){throw await h.disposeAll(),p}if(o)try{await o.disposeAll()}catch(p){throw await h.disposeAll(),p}this.loadedExtensions.set(r,h)}catch(f){throw f}}catch(o){throw this.recordFailure(n.stage??(this.loadedExtensions.has(r)?"reload":"load"),r,this.createExtensionSource(r,n.loadSource??this.loadedExtensions.get(r)?.loadSource??"api"),o),o}}async reloadExtensions(t={continueOnError:!0}){let n=Array.from(this.loadedExtensions.keys());for(let r of n)try{await this.loadExtension(r,{loadSource:this.loadedExtensions.get(r)?.loadSource,stage:"reload"})}catch(o){if(!t.continueOnError)throw o;this.runtimeLogger.warn(`Failed to reload extension "${r}":`,o instanceof Error?o.message:String(o))}}listCapabilityProviders(){return Array.from(this.capabilityProviders.values()).map(t=>t[t.length-1]?.value).filter(t=>t!==void 0)}registerCapabilityProvider(t,n={}){let r=n.source??this.createRuntimeSource(`runtime:capability:${t.id}`,t.id),o=this.registerRecord(this.capabilityProviders,t.id,t,r,this.runtimeDisposables);return t.dispose&&this.runtimeDisposables.push(()=>t.dispose?.()),o}registerTool(t,n={}){let r=n.source??{kind:"extension",id:`runtime:tool:${t.name}`,label:t.name},o=on(t,{source:r});return this.runtimeDisposables.push(o),o}registerHook(t,n,r={}){let o=r.source??this.createRuntimeSource(`runtime:hook:${String(t)}`,String(t)),s=this.registerHookHandler(t,n,o);return this.runtimeDisposables.push(s),s}on(t,n,r={}){let o=r.source??this.createRuntimeSource(`runtime:event:${String(t)}`,String(t)),s=this.registerEventHandler(t,n,o);return this.runtimeDisposables.push(s),s}listCommands(){return Array.from(this.commands.values()).map(t=>t[t.length-1]?.value).filter(t=>t!==void 0)}getCommand(t){let n=t.trim().toLowerCase();if(n)return this.listCommands().find(r=>r.name.trim().toLowerCase()===n||(r.aliases??[]).some(o=>o.trim().toLowerCase()===n))}getDiagnostics(){let t=Array.from(this.capabilityProviders.entries()).map(([a,c])=>{let l=c[c.length-1];if(l)return{id:a,kinds:[...l.value.kinds],source:{...l.source},metadata:l.value.getDiagnostics?.()}}).filter(a=>a!==void 0).sort((a,c)=>a.id.localeCompare(c.id)),n=Array.from(this.commands.entries()).map(([a,c])=>{let l=c[c.length-1];if(l)return{name:a,aliases:l.value.aliases,description:l.value.description,usage:l.value.usage,metadata:l.value.metadata,source:{...l.source}}}).filter(a=>a!==void 0).sort((a,c)=>a.name.localeCompare(c.name)),r=Le().map(a=>{let c=Et(a),l=c[c.length-1];if(l)return{name:l.name,description:l.description,requiredParams:[...l.requiredParams],source:{...l.source},shadowedSources:c.slice(0,-1).map(d=>({...d.source}))}}).filter(a=>a!==void 0).sort((a,c)=>a.name.localeCompare(c.name)),o=Array.from(this.loadedExtensions.values()).map(a=>{let c=this.boundController?Object.keys(this.boundController.getSessionStateSnapshot(this.createExtensionSource(a.path,a.loadSource).id)).sort((d,u)=>d.localeCompare(u)):void 0,l=this.boundController?this.boundController.listSessionRecords(this.createExtensionSource(a.path,a.loadSource).id).reduce((d,u)=>(d[u.type]=(d[u.type]??0)+1,d),{}):void 0;return{path:a.path,label:a.label,loadSource:a.loadSource,sessionStateKeys:c&&c.length>0?c:void 0,sessionRecordCounts:l&&Object.keys(l).length>0?l:void 0}}).sort((a,c)=>a.path.localeCompare(c.path)),s=Array.from(this.hookHandlers.entries()).flatMap(([a,c])=>c.map((l,d)=>({hook:a,order:d+1,source:{...l.source}}))).sort((a,c)=>{let l=a.hook.localeCompare(c.hook);return l!==0?l:a.order-c.order});return{loadedExtensions:o,capabilityProviders:t,commands:n,tools:r,hooks:s,failures:this.failures.map(a=>({...a,source:{...a.source}})),defaults:this.getDefaults()}}getCapabilityProvider(t){let n=this.capabilityProviders.get(t);if(!(!n||n.length===0))return n[n.length-1]?.value}async searchCapabilities(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o)throw new Error(`Unknown capability provider: ${t}`);return o.search?(await this.emit("capability:search",{providerId:t,query:n,kind:r.kind,limit:r.limit}),o.search(n,r)):[]}async describeCapability(t,n){let r=this.getCapabilityProvider(t);if(!r)throw new Error(`Unknown capability provider: ${t}`);return await this.emit("capability:describe",{providerId:t,capabilityId:n}),r.describe?.(n)}async executeCapability(t,n,r){let o=this.getCapabilityProvider(t);if(!o?.execute)throw new Error(`Capability provider "${t}" does not implement execute().`);return await this.emit("capability:invoke",{providerId:t,capabilityId:n,kind:"tool"}),o.execute(n,r)}async readCapability(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o?.read)throw new Error(`Capability provider "${t}" does not implement read().`);return await this.emit("capability:invoke",{providerId:t,capabilityId:n,kind:"resource"}),o.read(n,r)}async getCapabilityPrompt(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o?.getPrompt)throw new Error(`Capability provider "${t}" does not implement getPrompt().`);return await this.emit("capability:invoke",{providerId:t,capabilityId:n,kind:"prompt"}),o.getPrompt(n,r)}async getCapabilityPromptContext(t){let n=this.getCapabilityProvider(t);if(n?.getPromptContext)return n.getPromptContext()}async refreshCapabilityProviders(t){if(t){let n=this.getCapabilityProvider(t);if(!n)throw new Error(`Unknown capability provider: ${t}`);await this.emit("capability:refresh",{providerId:t}),await n.refresh?.();return}for(let n of this.listCapabilityProviders())await this.emit("capability:refresh",{providerId:n.id}),await n.refresh?.()}async hydrateSession(t){let n=this.hookHandlers.get("session:hydrate");if(!n||n.length===0)return;let r=this.boundController;if(!r)throw new Error("Session hydration requires an active KodaX session binding.");for(let o of n)try{let s=o.source,a=i((c,l)=>{let d=new Error(l);this.recordFailure("persistence",c,s,d),this.runtimeLogger.warn(l)},"warnPersistence");await o.value({sessionId:t,getState:i(c=>r.getSessionState(s.id,c),"getState"),setState:i((c,l)=>{if(l!==void 0&&!sn(l)){a(`sessionState:${c}`,`Ignoring non-JSON session state for "${s.label}" key "${c}".`);return}r.setSessionState(s.id,c,l)},"setState"),listRecords:i(c=>r.listSessionRecords(s.id,c),"listRecords"),appendRecord:i((c,l,d)=>{let u=c.trim();if(!u){a("sessionRecord",`Ignoring session record with an empty type for "${s.label}".`);return}if(l!==void 0&&!sn(l)){a(`sessionRecord:${u}`,`Ignoring non-JSON session record "${u}" for "${s.label}".`);return}return r.appendSessionRecord(s.id,u,l,d)},"appendRecord"),clearRecords:i(c=>r.clearSessionRecords(s.id,c),"clearRecords")})}catch(s){this.recordFailure("hook","session:hydrate",o.source,s),this.runtimeLogger.warn('Extension hook failed for "session:hydrate":',s instanceof Error?s.message:String(s))}}async emit(t,n){let r=this.eventHandlers.get(t);if(!(!r||r.length===0))for(let o of r)try{await o.value(n)}catch(s){this.recordFailure("event",t,o.source,s),this.runtimeLogger.warn(`Extension event handler failed for "${t}":`,s instanceof Error?s.message:String(s))}}async runHook(t,n){let r=this.hookHandlers.get(t);if(!(!r||r.length===0))for(let o of r)try{let s=await o.value(n);if(s!==void 0)return s}catch(s){this.recordFailure("hook",t,o.source,s),this.runtimeLogger.warn(`Extension hook failed for "${t}":`,s instanceof Error?s.message:String(s))}}createExtensionSource(t,n="api"){return{kind:"extension",id:`${n}:extension:${t}`,label:ue.basename(t),path:t}}createRuntimeSource(t,n){return{kind:"runtime",id:t,label:n}}recordFailure(t,n,r,o){this.failures.push({stage:t,target:n,message:o instanceof Error?o.message:String(o),occurredAt:new Date().toISOString(),source:{...r}}),this.failures.length>50&&this.failures.shift()}createExtensionApi(t,n,r="api"){let o=this.createLogger(t),s=this.createExtensionSource(t,r);return{registerTool:i(a=>{let c=on(a,{source:s});return n.push(c),c},"registerTool"),getTool:i(a=>tt(a),"getTool"),getBuiltinTool:i(a=>bs(a),"getBuiltinTool"),registerModelProvider:i(a=>{let c=qs(a.name,a.factory);return n.push(c),c},"registerModelProvider"),registerCapabilityProvider:i(a=>{let c=this.registerRecord(this.capabilityProviders,a.id,a,s,n);return a.dispose&&n.push(()=>a.dispose?.()),c},"registerCapabilityProvider"),registerCommand:i(a=>this.registerRecord(this.commands,a.name,a,s,n),"registerCommand"),registerSkillPath:i(a=>{let c=ue.isAbsolute(a)?a:ue.resolve(ue.dirname(t),a),l=Js(c);return n.push(l),l},"registerSkillPath"),registerAgent:i(async(a,c)=>{let l=Z({name:a,content:c}),d=new Map(ae().map(h=>[h.name,h])),u=await Y.admit(l,{activatedAgents:d});if(!u.ok)throw new Error(`[extension:${s.id}] registerAgent("${a}") rejected by admission: ${u.reason}`);let f={kind:"agent",name:a,version:"0.0.0-extension",content:c,status:"active",createdAt:Date.now(),testedAt:Date.now(),activatedAt:Date.now()},m=de(f,{bindings:u.handle.invariantBindings,manifest:u.handle.manifest,source:"extension"});return n.push(m),m},"registerAgent"),on:i((a,c)=>{let l=this.registerEventHandler(a,c,s);return n.push(l),l},"on"),hook:i((a,c)=>{let l=this.registerHookHandler(a,c,s);return n.push(l),l},"hook"),logger:o,config:this.config,runtime:this.createExtensionApiRuntimeController(s,o,n),persistence:Zs(s.id),exec:Hu,webhook:Ku}}createLogger(t){let n=ue.basename(t);return{debug:i((...r)=>console.debug(`[kodax:extension:${n}]`,...r),"debug"),info:i((...r)=>console.info(`[kodax:extension:${n}]`,...r),"info"),warn:i((...r)=>console.warn(`[kodax:extension:${n}]`,...r),"warn"),error:i((...r)=>console.error(`[kodax:extension:${n}]`,...r),"error")}}createRuntimeControllerProxy(){return{queueUserMessage:i(t=>{let n=this.boundController;if(!n)throw new Error("No active KodaX session is bound to the extension runtime.");n.queueUserMessage(Yu(t))},"queueUserMessage"),getSessionState:i((t,n)=>this.boundController?.getSessionState(t,n),"getSessionState"),setSessionState:i((t,n,r)=>{let o=this.boundController;if(!o)throw new Error("Session state is only available while a KodaX session is active.");o.setSessionState(t,n,r)},"setSessionState"),getSessionStateSnapshot:i(t=>this.boundController?this.boundController.getSessionStateSnapshot(t):{},"getSessionStateSnapshot"),appendSessionRecord:i((t,n,r,o)=>{let s=this.boundController;if(!s)throw new Error("Session records are only available while a KodaX session is active.");return s.appendSessionRecord(t,n,r,o)},"appendSessionRecord"),listSessionRecords:i((t,n)=>this.boundController?this.boundController.listSessionRecords(t,n):[],"listSessionRecords"),clearSessionRecords:i((t,n)=>{let r=this.boundController;if(!r)throw new Error("Session records are only available while a KodaX session is active.");return r.clearSessionRecords(t,n)},"clearSessionRecords"),getActiveTools:i(()=>this.boundController?this.boundController.getActiveTools():this.defaultActiveTools===void 0?Le():[...this.defaultActiveTools],"getActiveTools"),setActiveTools:i(t=>{let n=Ik(t);if(this.boundController){this.boundController.setActiveTools(n);return}this.defaultActiveTools=n},"setActiveTools"),getModelSelection:i(()=>this.boundController?this.boundController.getModelSelection():{...this.defaultModelSelection},"getModelSelection"),setModelSelection:i(t=>{let n=Lk(t);if(this.boundController){this.boundController.setModelSelection(n);return}this.defaultModelSelection=n},"setModelSelection"),getThinkingLevel:i(()=>this.boundController?.getThinkingLevel()??this.defaultThinkingLevel,"getThinkingLevel"),setThinkingLevel:i(t=>{if(this.boundController){this.boundController.setThinkingLevel(t);return}this.defaultThinkingLevel=t},"setThinkingLevel")}}createExtensionApiRuntimeController(t,n,r){let o=!1,s,a=!1,c={},l=!1,d,u=i(()=>{o||this.boundController||(o=!0,s=this.defaultActiveTools===void 0?void 0:[...this.defaultActiveTools],r.push(()=>{this.defaultActiveTools=s===void 0?void 0:[...s]}))},"captureActiveToolsRestore"),f=i(()=>{a||this.boundController||(a=!0,c={...this.defaultModelSelection},r.push(()=>{this.defaultModelSelection={...c}}))},"captureModelSelectionRestore"),m=i(()=>{l||this.boundController||(l=!0,d=this.defaultThinkingLevel,r.push(()=>{this.defaultThinkingLevel=d}))},"captureThinkingLevelRestore"),h=i((p,g)=>{let w=new Error(g);this.recordFailure("persistence",p,t,w),n.warn(g)},"recordPersistenceFailure");return{queueUserMessage:i(p=>this.runtimeController.queueUserMessage(Yu(p)),"queueUserMessage"),getSessionState:i(p=>this.runtimeController.getSessionState(t.id,p),"getSessionState"),setSessionState:i((p,g)=>{if(g!==void 0&&!sn(g)){h(`sessionState:${p}`,`Ignoring non-JSON session state for "${t.label}" key "${p}".`);return}this.runtimeController.setSessionState(t.id,p,g)},"setSessionState"),appendSessionRecord:i((p,g,w)=>{let y=p.trim();if(!y){h("sessionRecord",`Ignoring session record with an empty type for "${t.label}".`);return}if(g!==void 0&&!sn(g)){h(`sessionRecord:${y}`,`Ignoring non-JSON session record "${y}" for "${t.label}".`);return}return this.runtimeController.appendSessionRecord(t.id,y,g,w)},"appendSessionRecord"),listSessionRecords:i(p=>this.runtimeController.listSessionRecords(t.id,p),"listSessionRecords"),clearSessionRecords:i(p=>this.runtimeController.clearSessionRecords(t.id,p),"clearSessionRecords"),getActiveTools:i(()=>this.runtimeController.getActiveTools(),"getActiveTools"),setActiveTools:i(p=>{u(),this.runtimeController.setActiveTools(p)},"setActiveTools"),getModelSelection:i(()=>this.runtimeController.getModelSelection(),"getModelSelection"),setModelSelection:i(p=>{f(),this.runtimeController.setModelSelection(p)},"setModelSelection"),getThinkingLevel:i(()=>this.runtimeController.getThinkingLevel(),"getThinkingLevel"),setThinkingLevel:i(p=>{m(),this.runtimeController.setThinkingLevel(p)},"setThinkingLevel")}}registerRecord(t,n,r,o,s){let a=`runtime:${++this.nextRecordId}`,c=t.get(n)??[];t.set(n,[...c,{id:a,value:r,source:o}]);let l=i(()=>{let u=(t.get(n)??[]).filter(f=>f.id!==a);u.length===0?t.delete(n):t.set(n,u)},"dispose");return s.push(l),l}registerEventHandler(t,n,r){let o=`runtime:${++this.nextRecordId}`,s=this.eventHandlers.get(t)??[];return s.push({id:o,value:n,source:r}),this.eventHandlers.set(t,s),()=>{let a=this.eventHandlers.get(t);if(!a)return;let c=a.filter(l=>l.id!==o);if(c.length===0){this.eventHandlers.delete(t);return}this.eventHandlers.set(t,c)}}registerHookHandler(t,n,r){let o=`runtime:${++this.nextRecordId}`,s=this.hookHandlers.get(t)??[];return s.push({id:o,value:n,source:r}),this.hookHandlers.set(t,s),()=>{let a=this.hookHandlers.get(t);if(!a)return;let c=a.filter(l=>l.id!==o);if(c.length===0){this.hookHandlers.delete(t);return}this.hookHandlers.set(t,c)}}async unloadExtension(t){let n=this.loadedExtensions.get(t);n&&(await n.disposeAll(),this.loadedExtensions.delete(t))}async importExtensionModule(t){let n=ue.extname(t).toLowerCase();if(!jn(t))throw new Error(`Unsupported extension module "${t}". FEATURE_034 currently loads .js/.mjs/.cjs/.ts/.mts/.cts files.`);if([".js",".mjs",".cjs"].includes(n)){let r=new URL(Ju(t).href);return r.searchParams.set("kodax_ext_reload",`${Date.now()}:${Math.random()}`),import(r.href)}if([".ts",".mts",".cts"].includes(n))return Rk(Ju(t).href,{parentURL:import.meta.url});throw new Error(`Unsupported extension module "${t}". FEATURE_034 currently loads .js/.mjs/.cjs/.ts/.mts/.cts files.`)}},As=class{static{i(this,"CombinedExtensionRuntime")}primary;secondary;constructor(t,n){this.primary=t,this.secondary=n}getDefaults(){let t=this.primary.getDefaults(),n=this.secondary.getDefaults();return{activeTools:t.activeTools??n.activeTools,modelSelection:{...n.modelSelection,...t.modelSelection},thinkingLevel:t.thinkingLevel??n.thinkingLevel}}bindController(t){let n=[this.secondary.bindController(t),this.primary.bindController(t)];return()=>{for(let r of n.reverse())r()}}async hydrateSession(t){await this.secondary.hydrateSession(t),await this.primary.hydrateSession(t)}async runHook(t,n){let r=await this.secondary.runHook(t,n);return r!==void 0?r:this.primary.runHook(t,n)}async emit(t,n){await this.secondary.emit(t,n),await this.primary.emit(t,n)}async searchCapabilities(t,n,r={}){let o=[],s;for(let a of[this.primary,this.secondary])try{o.push(...await a.searchCapabilities(t,n,r))}catch(c){if(!this.shouldTryNextCapabilityRuntime(c,t))throw c;s??=c}if(o.length===0&&s)throw s;return typeof r.limit=="number"?o.slice(0,r.limit):o}describeCapability(t,n){return this.firstCapabilityResult(t,[()=>this.primary.describeCapability(t,n),()=>this.secondary.describeCapability(t,n)])}executeCapability(t,n,r){return this.firstCapabilityResult(t,[()=>this.primary.executeCapability(t,n,r),()=>this.secondary.executeCapability(t,n,r)])}readCapability(t,n,r={}){return this.firstCapabilityResult(t,[()=>this.primary.readCapability(t,n,r),()=>this.secondary.readCapability(t,n,r)])}getCapabilityPrompt(t,n,r={}){return this.firstCapabilityResult(t,[()=>this.primary.getCapabilityPrompt(t,n,r),()=>this.secondary.getCapabilityPrompt(t,n,r)])}async getCapabilityPromptContext(t){return(await Promise.all([this.secondary.getCapabilityPromptContext(t),this.primary.getCapabilityPromptContext(t)])).filter(o=>typeof o=="string"&&o.trim().length>0).join(`
311
+ `)}catch(n){return`[Tool Error] scaffold_agent: ${n.message}`}}i(ff,"toolScaffoldAgent");async function pf(e,t){try{let n=It(e,"artifact_json"),r;try{r=df(lf(n))}catch(l){return`[Tool Error] validate_agent: ${l.message}`}if(ta().length===0)return["[Tool Error] validate_agent: invariant registry is empty.","Call registerCodingInvariants() (from @kodax-ai/coding) before invoking validate_agent \u2014","the REPL surface bootstraps this at startup; non-REPL contexts must register explicitly."].join(" ");let o=te({name:r.name,content:r.content}),s=await Y.admit(o),a=[],c=[];if(!s.ok)a.push(`[admission] ${s.reason} (retryable=${s.retryable})`);else for(let l of s.clampNotes)c.push(`[admission] ${l}`);return uf({ok:a.length===0,errors:a.length>0?a:void 0,warnings:c.length>0?c:void 0})}catch(n){return`[Tool Error] validate_agent: ${n.message}`}}i(pf,"toolValidateAgent");async function mf(e,t){try{let n=It(e,"artifact_json"),r=df(lf(n)),o=(await Ct("agent")).find(a=>a.kind==="agent"&&a.name===r.name&&a.status==="active");if(o)return["[Tool Error] stage_agent_construction:",`'${r.name}' already has an active manifest (${o.version}).`,"Modifying an existing constructed agent must go through stage_self_modify so the FEATURE_090 hard checks (guardrail ratchet, budget, force-ask-user) apply.","Pick a different name to create a separate agent."].join(" ");let s=await At(r);return[`staged: ${s.artifact.name}@${s.artifact.version} (kind=agent)`,`status=${s.artifact.status}`,"Next: call test_agent with name and version."].join(`
312
+ `)}catch(n){return`[Tool Error] stage_agent_construction: ${n.message}`}}i(mf,"toolStageAgentConstruction");async function hf(e,t){try{let n=It(e,"name"),r=It(e,"version"),o=await $t(n,r);if(!o)return`[Tool Error] test_agent: no staged artifact found for ${n}@${r}.`;if(o.kind!=="agent")return`[Tool Error] test_agent: ${n}@${r} has kind='${o.kind}', expected 'agent'. Use test_tool for tool artifacts.`;if(o.status==="revoked")return`[Tool Error] test_agent: ${n}@${r} is revoked. Bump the version and re-stage.`;let s={artifact:o,stagedAt:Date.now()},a=await Fn(s);return uf(a)}catch(n){return`[Tool Error] test_agent: ${n.message}`}}i(hf,"toolTestAgent");async function gf(e,t){try{let n=It(e,"name"),r=It(e,"version"),o=await $t(n,r);if(!o)return`[Tool Error] activate_agent: no artifact found for ${n}@${r}. Stage and test it first.`;if(o.kind!=="agent")return`[Tool Error] activate_agent: ${n}@${r} has kind='${o.kind}', expected 'agent'. Use activate_tool for tool artifacts.`;if(o.status==="revoked")return`[Tool Error] activate_agent: ${n}@${r} is revoked. Bump the version and re-stage.`;let s={artifact:o,stagedAt:Date.now()};return await jn(s),[`activated: ${n}@${r} (kind=agent)`,"Resolver now exposes the agent at this name; subsequent Runner.run calls can resolve it."].join(`
313
+ `)}catch(n){return`[Tool Error] activate_agent: ${n.message}`}}i(gf,"toolActivateAgent");var Xr=Object.freeze({web_search:'Discover web content when no specific URL is known \u2014 call `tool_search("web_search")` for full schema.',web_fetch:'Fetch a specific remote URL (HTML\u2192markdown, cached) \u2014 call `tool_search("web_fetch")` for full schema (includes GitHub-URL gh-CLI guidance).',code_search:'Ranked text search across the repo with noise filtering \u2014 call `tool_search("code_search")` for selection heuristics vs grep / symbol_context.',semantic_lookup:'Symbol-/module-/process-aware semantic queries against repo intelligence \u2014 call `tool_search("semantic_lookup")` for full schema and selection rules.',mcp_search:'Search active MCP capabilities by query / server / kind \u2014 call `tool_search("mcp_search")` for full schema.',mcp_describe:'Describe a specific MCP capability by id (JSON schema + trust) \u2014 call `tool_search("mcp_describe")` for full schema.',mcp_call:'Invoke an MCP tool capability \u2014 can MUTATE remote state. Call `tool_search("mcp_call")` for the full safety contract.',mcp_read_resource:'Read an MCP resource (no mutation) \u2014 call `tool_search("mcp_read_resource")` for full schema.',mcp_get_prompt:'Retrieve an MCP prompt template \u2014 call `tool_search("mcp_get_prompt")` for full schema.',repo_overview:'Workspace structure snapshot \u2014 call ONCE at session start; `tool_search("repo_overview")` for full schema.',changed_scope:'List files / areas changed in current git diff \u2014 canonical review entry. `tool_search("changed_scope")` for full schema.',module_context:'Compact module capsule (deps, entries, symbols, tests) \u2014 call `tool_search("module_context")` for full schema and selection rules vs symbol_context.',symbol_context:'Definition + callers/callees for one symbol \u2014 call `tool_search("symbol_context")` for full schema and selection rules.',process_context:'Static execution/process trace from an entry \u2014 call `tool_search("process_context")` for full schema.',impact_estimate:'Blast radius estimate BEFORE a rename or refactor \u2014 call `tool_search("impact_estimate")` for full schema (replaces guessing impact from grep).',get_goal:'Read the current /goal status (objective / tokens / budget / elapsed) \u2014 call `tool_search("get_goal")` for full schema. Available when a goal is set.',create_goal:'Create a persistent /goal \u2014 only when explicitly requested by the user or system instructions. Call `tool_search("create_goal")` for full schema and discipline rules.',update_goal:'Mark the current /goal complete or blocked \u2014 runtime-verified (sidecar + 3-turn rule). Call `tool_search("update_goal")` for full schema.'});function kf(e){return e in Xr}i(kf,"isDeferredTool");var Is=new WeakMap;function vf(e,t){let n=Is.get(e);n||(n=new Set,Is.set(e,n)),n.add(t)}i(vf,"unlockDeferredToolForContext");function lM(e){let t=Is.get(e);return t?new Set(t):new Set}i(lM,"getUnlockedDeferredTools");var hv=5,_f=15;function gv(e){let t=e.trim();if(t.startsWith("select:"))return{mode:"select",names:t.slice(7).split(/[,\s]+/).map(c=>c.trim()).filter(c=>c.length>0),required:[],loose:[]};let n=t.split(/\s+/).filter(s=>s.length>0),r=[],o=[];for(let s of n)s.startsWith("+")&&s.length>1?r.push(s.slice(1).toLowerCase()):o.push(s.toLowerCase());return{mode:"keyword",names:[],required:r,loose:o}}i(gv,"parseQuery");function yv(e,t,n,r){let o=`${e.toLowerCase()} ${t.toLowerCase()}`;for(let a of n)if(!o.includes(a))return null;let s=0;for(let a of r)o.includes(a)&&s++;return s}i(yv,"scoreToolForKeywords");function wv(e){let t=[],n=new Set;for(let r of e)n.has(r)||(n.add(r),(kf(r)||Bn(r))&&t.push(r));return t}i(wv,"resolveSelectNames");function bv(e,t,n){let r=[];for(let[o,s]of Object.entries(Xr)){let a=yv(o,s,e,t);a!==null&&(a===0&&t.length>0||r.push({name:o,score:a}))}return r.sort((o,s)=>s.score-o.score),r.slice(0,n).map(o=>o.name)}i(bv,"searchKeywords");function kv(e){let t={description:e.description,name:e.name,parameters:e.input_schema};return`<function>${JSON.stringify(t)}</function>`}i(kv,"formatToolAsFunctionBlock");function vv(e,t,n){if(e.length===0)return"No tools matched the query. Available deferred tools: "+Object.keys(Xr).join(", ")+". Use query form `select:NAME` to fetch a specific schema.";let r=[];for(let o of e){let s=Bn(o);if(!s){r.push(`<!-- ${o}: not registered (skipped) -->`);continue}vf(t,o),r.push(kv(Oa(s,n)))}return r.join(`
314
+ `)}i(vv,"buildResult");var _v=i(async(e,t)=>{let n=e,r=typeof n.query=="string"?n.query:"";if(r.length===0)return"tool_search: `query` is required. Forms: `select:NAME[,NAME...]` for exact lookup, or keyword search (`+required loose terms`).";let o=typeof n.max_results=="number"&&n.max_results>0?Math.min(Math.floor(n.max_results),_f):hv,s=gv(r),a=s.mode==="select"?wv(s.names).slice(0,_f):bv(s.required,s.loose,o);return vv(a,t,t.selfManual?.productName)},"toolSearchHandler"),xf={name:"tool_search",description:["Fetch full schema definitions for tools whose rich descriptions are deferred behind compact search hints.","The deferred catalog includes mcp_*, web_*, repo-intel (module_context / symbol_context / impact_estimate / process_context / changed_scope / repo_overview / semantic_lookup / code_search), and goal tools (get_goal / create_goal / update_goal).","Use `tool_search` when a hint suggests a tool fits the task and you need the full schema (parameter shape, when-to-prefer-X, behavioral contracts) before invoking.",'Query forms: `select:ToolName` (exact, recommended) or keyword search like `"+module exploration"` (require keyword) / `"refactor impact"` (loose match, ranked).',"On the SA path, resolving a deferred tool unlocks its full description for later tool lists in the same context. On AMA/AMAW managed paths, the tool list is static, so the `tool_search` result itself is the durable teaching surface."].join(" "),input_schema:{type:"object",properties:{query:{type:"string",description:"Either `select:ToolName[,ToolName...]` for exact lookup, or keyword search (`+keyword required loose terms`)."},max_results:{type:"number",description:"Maximum number of results to return (default 5, capped at 15). Ignored in `select:` mode."}},required:["query"]},handler:_v,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")};import he from"path";import{pathToFileURL as Rf}from"url";import{execFile as xv}from"child_process";import{promisify as Ev}from"util";var Sv=Ev(xv),Tv=3e4,Av=1e4;async function Ef(e,t={}){let n=t.timeout??Tv,r=t.shell??(process.platform==="win32"?"powershell":"bash"),o=r==="powershell"?["-Command",e]:["-c",e],s={PATH:process.env.PATH??"",HOME:process.env.HOME??process.env.USERPROFILE??"",LANG:process.env.LANG??"",TERM:process.env.TERM??"",...process.platform==="win32"?{SYSTEMROOT:process.env.SYSTEMROOT??"",COMSPEC:process.env.COMSPEC??"",PATHEXT:process.env.PATHEXT??""}:{},...t.env};try{let{stdout:a,stderr:c}=await Sv(r,o,{timeout:n,cwd:t.cwd,env:s});return{exitCode:0,stdout:a.trim(),stderr:c.trim()}}catch(a){let c=a&&typeof a=="object"&&"code"in a&&typeof a.code=="number"?a.code:1,l=a&&typeof a=="object"&&"stdout"in a?String(a.stdout??"").trim():"",d=a&&typeof a=="object"&&"stderr"in a?String(a.stderr??"").trim():a instanceof Error?a.message:String(a);return{exitCode:c,stdout:l,stderr:d}}}i(Ef,"exec");async function Sf(e,t,n={}){let r=n.timeout??Av,o=new AbortController,s=setTimeout(()=>o.abort(),r);try{let a=await fetch(e,{method:n.method??"POST",headers:{"Content-Type":"application/json",...n.headers},body:JSON.stringify(t),signal:o.signal});clearTimeout(s);let c=await a.text().catch(()=>{});return{ok:a.ok,status:a.status,body:c}}catch(a){return clearTimeout(s),{ok:!1,status:0,body:a instanceof Error?a.message:String(a)}}}i(Sf,"webhook");import xe from"path";import{access as Cv,readdir as $v,realpath as Rv,stat as Ps}from"fs/promises";import{constants as Ov}from"fs";var Tf=new Set([".js",".mjs",".cjs",".ts",".mts",".cts"]),Vr=["extension.mjs","extension.js","extension.cjs","extension.mts","extension.ts","extension.cts","index.mjs","index.js","index.cjs","index.mts","index.ts","index.cts"];function Ns(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}i(Ns,"isMissingPathError");async function Af(e){try{return(await Ps(e)).isFile()?(await Cv(e,Ov.R_OK),!0):!1}catch(t){if(Ns(t))return!1;throw t}}i(Af,"isReadableFile");function Wn(e){return Tf.has(xe.extname(e).toLowerCase())}i(Wn,"isSupportedExtensionModulePath");function Iv(e=dt()){return xe.join(e,"extensions")}i(Iv,"getDefaultExtensionDirectory");async function Ds(e){let t=xe.resolve(e),n=await Ps(t);if(n.isFile()){if(!Wn(t))throw new Error(`Unsupported extension module "${t}". Expected one of: ${[...Tf].join(", ")}.`);return t}if(!n.isDirectory())throw new Error(`Extension path "${t}" must be a file or directory.`);for(let r of Vr){let o=xe.join(t,r);if(await Af(o))return o}throw new Error(`Extension directory "${t}" must contain one of: ${Vr.join(", ")}.`)}i(Ds,"resolveExtensionEntrypoint");async function Cf(e){for(let t of Vr){let n=xe.join(e,t);if(await Af(n))return n}}i(Cf,"tryResolveDirectoryEntrypoint");async function Lv(e){try{let t=await Ps(e);return t.isFile()?Wn(e)?xe.resolve(e):void 0:t.isDirectory()?Cf(e):void 0}catch(t){if(Ns(t))return;throw t}}i(Lv,"tryResolveDiscoveredEntrypoint");async function Mv(e){try{return await Rv(e)}catch(t){return xe.resolve(e)}}i(Mv,"canonicalEntrypointIdentity");async function Ms(e){let t=e.trim();try{return await Mv(await Ds(t))}catch(n){return xe.resolve(t)}}i(Ms,"getExtensionEntrypointIdentity");async function $f(e){let t=[],n=new Set;for(let r of e){let o=r.trim();if(!o)continue;let s=await Ms(o);n.has(s)||(n.add(s),t.push(o))}return t}i($f,"dedupeExtensionPathsByEntrypoint");async function SM(e,t){let n=new Set;for(let s of t){let a=s.trim();a&&n.add(await Ms(a))}let r=[],o=new Set;for(let s of e){let a=s.trim();if(!a)continue;let c=await Ms(a);n.has(c)||o.has(c)||(o.add(c),r.push(a))}return r}i(SM,"excludeExtensionPathsByEntrypoint");function Ls(e,t,n){return{path:e,reason:t,message:n}}i(Ls,"skippedEntry");async function Pv(e){let t=xe.resolve(e),n;try{n=await $v(t,{withFileTypes:!0})}catch(s){if(Ns(s))return{paths:[],skipped:[]};throw s}let r=[],o=[];for(let s of n.sort((a,c)=>a.name.localeCompare(c.name))){let a=xe.join(t,s.name);if(s.isFile()){Wn(a)?r.push(a):o.push(Ls(a,"unsupported_module","File extension is not supported for KodaX runtime extensions."));continue}if(s.isDirectory()){let c=await Cf(a);c?r.push(c):o.push(Ls(a,"missing_entrypoint",`Directory does not contain one of: ${Vr.join(", ")}.`));continue}if(s.isSymbolicLink()){let c=await Lv(a);c?r.push(c):o.push(Ls(a,"unsupported_target","Symlink target is not a supported extension file or package directory."))}}return{paths:r,skipped:o}}i(Pv,"discoverExtensionsInDirectoryDetailed");async function Nv(e){return(await Pv(e)).paths}i(Nv,"discoverExtensionsInDirectory");async function TM(){return Nv(Iv())}i(TM,"discoverDefaultExtensions");import{tsImport as Dv}from"tsx/esm/api";function Fv(e){let t=he.basename(e),n=he.parse(t).name;return n==="extension"||n==="index"?he.basename(he.dirname(e)):t}i(Fv,"getExtensionLabel");var Lt=null,Mt=null;function jv(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.emit=="function"&&typeof t.runHook=="function"}i(jv,"isActiveExtensionExecutionRuntime");function Uv(e){let t=[];for(let n of e){let r=n.trim();!r||t.includes(r)||t.push(r)}return t}i(Uv,"dedupeStrings");function Of(e){return typeof e=="string"?{role:"user",content:e}:e}i(Of,"normalizeQueuedMessage");function qv(e){let t={};return e.provider?.trim()&&(t.provider=e.provider.trim()),e.model?.trim()&&(t.model=e.model.trim()),t}i(qv,"normalizeModelSelection");function un(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return!0;if(Array.isArray(e))return e.every(un);if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(un)}i(un,"isJsonValue");var Fs=class{static{i(this,"KodaXExtensionRuntime")}capabilityProviders=new Map;commands=new Map;eventHandlers=new Map;hookHandlers=new Map;loadedExtensions=new Map;failures=[];runtimeDisposables=[];runtimeLogger;config;runtimeController;nextRecordId=0;boundController=null;defaultActiveTools;defaultModelSelection={};defaultThinkingLevel;constructor(t={}){this.config=t.config??{},this.runtimeLogger={debug:i((...n)=>console.debug("[kodax:extension]",...n),"debug"),info:i((...n)=>console.info("[kodax:extension]",...n),"info"),warn:i((...n)=>console.warn("[kodax:extension]",...n),"warn"),error:i((...n)=>console.error("[kodax:extension]",...n),"error")},this.runtimeController=this.createRuntimeControllerProxy()}activate(){return Lt=this,this}getDefaults(){return{activeTools:this.defaultActiveTools===void 0?void 0:[...this.defaultActiveTools],modelSelection:{...this.defaultModelSelection},thinkingLevel:this.defaultThinkingLevel}}bindController(t){let n=this.boundController;return this.boundController=t,()=>{this.boundController=n}}async dispose(){for(let t of Array.from(this.loadedExtensions.values()).reverse())await t.disposeAll();this.loadedExtensions.clear();for(let t of this.runtimeDisposables.reverse())await t();this.runtimeDisposables.length=0,this.failures.length=0,this.boundController=null,Lt===this&&(Lt=null),Mt===this&&(Mt=null)}async loadExtensions(t,n={}){let r=await $f(t);for(let o of r)try{await this.loadExtension(o,{loadSource:n.loadSource,stage:n.stage??"load"})}catch(s){if(!n.continueOnError)throw s;this.runtimeLogger.warn(`Failed to load extension "${o}" during ${n.stage??"load"}:`,s instanceof Error?s.message:String(s))}}async loadExtension(t,n={}){let r=he.resolve(t);try{r=await Ds(r);let o=this.loadedExtensions.get(r),s=n.loadSource??o?.loadSource??"api",a=await this.importExtensionModule(r),c=a.default,l=c&&typeof c=="object"&&"default"in c?c.default:void 0,d=c&&typeof c=="object"&&"activate"in c?c.activate:void 0,u=typeof c=="function"?c:typeof l=="function"?l:typeof a.activate=="function"?a.activate:typeof d=="function"?d:void 0;if(!u)throw new Error(`Extension "${r}" must export a default function or named activate() function.`);try{let f=[],m=this.createExtensionApi(r,f,s),h={path:r,label:Fv(r),loadSource:s,disposeAll:i(async()=>{for(let p of f.reverse())await p()},"disposeAll")};try{let p=await u(m);typeof p=="function"&&f.push(p)}catch(p){throw await h.disposeAll(),p}if(o)try{await o.disposeAll()}catch(p){throw await h.disposeAll(),p}this.loadedExtensions.set(r,h)}catch(f){throw f}}catch(o){throw this.recordFailure(n.stage??(this.loadedExtensions.has(r)?"reload":"load"),r,this.createExtensionSource(r,n.loadSource??this.loadedExtensions.get(r)?.loadSource??"api"),o),o}}async reloadExtensions(t={continueOnError:!0}){let n=Array.from(this.loadedExtensions.keys());for(let r of n)try{await this.loadExtension(r,{loadSource:this.loadedExtensions.get(r)?.loadSource,stage:"reload"})}catch(o){if(!t.continueOnError)throw o;this.runtimeLogger.warn(`Failed to reload extension "${r}":`,o instanceof Error?o.message:String(o))}}listCapabilityProviders(){return Array.from(this.capabilityProviders.values()).map(t=>t[t.length-1]?.value).filter(t=>t!==void 0)}registerCapabilityProvider(t,n={}){let r=n.source??this.createRuntimeSource(`runtime:capability:${t.id}`,t.id),o=this.registerRecord(this.capabilityProviders,t.id,t,r,this.runtimeDisposables);return t.dispose&&this.runtimeDisposables.push(()=>t.dispose?.()),o}registerTool(t,n={}){let r=n.source??{kind:"extension",id:`runtime:tool:${t.name}`,label:t.name},o=dn(t,{source:r});return this.runtimeDisposables.push(o),o}registerHook(t,n,r={}){let o=r.source??this.createRuntimeSource(`runtime:hook:${String(t)}`,String(t)),s=this.registerHookHandler(t,n,o);return this.runtimeDisposables.push(s),s}on(t,n,r={}){let o=r.source??this.createRuntimeSource(`runtime:event:${String(t)}`,String(t)),s=this.registerEventHandler(t,n,o);return this.runtimeDisposables.push(s),s}listCommands(){return Array.from(this.commands.values()).map(t=>t[t.length-1]?.value).filter(t=>t!==void 0)}getCommand(t){let n=t.trim().toLowerCase();if(n)return this.listCommands().find(r=>r.name.trim().toLowerCase()===n||(r.aliases??[]).some(o=>o.trim().toLowerCase()===n))}getDiagnostics(){let t=Array.from(this.capabilityProviders.entries()).map(([a,c])=>{let l=c[c.length-1];if(l)return{id:a,kinds:[...l.value.kinds],source:{...l.source},metadata:l.value.getDiagnostics?.()}}).filter(a=>a!==void 0).sort((a,c)=>a.id.localeCompare(c.id)),n=Array.from(this.commands.entries()).map(([a,c])=>{let l=c[c.length-1];if(l)return{name:a,aliases:l.value.aliases,description:l.value.description,usage:l.value.usage,metadata:l.value.metadata,source:{...l.source}}}).filter(a=>a!==void 0).sort((a,c)=>a.name.localeCompare(c.name)),r=Ne().map(a=>{let c=Rt(a),l=c[c.length-1];if(l)return{name:l.name,description:l.description,requiredParams:[...l.requiredParams],source:{...l.source},shadowedSources:c.slice(0,-1).map(d=>({...d.source}))}}).filter(a=>a!==void 0).sort((a,c)=>a.name.localeCompare(c.name)),o=Array.from(this.loadedExtensions.values()).map(a=>{let c=this.boundController?Object.keys(this.boundController.getSessionStateSnapshot(this.createExtensionSource(a.path,a.loadSource).id)).sort((d,u)=>d.localeCompare(u)):void 0,l=this.boundController?this.boundController.listSessionRecords(this.createExtensionSource(a.path,a.loadSource).id).reduce((d,u)=>(d[u.type]=(d[u.type]??0)+1,d),{}):void 0;return{path:a.path,label:a.label,loadSource:a.loadSource,sessionStateKeys:c&&c.length>0?c:void 0,sessionRecordCounts:l&&Object.keys(l).length>0?l:void 0}}).sort((a,c)=>a.path.localeCompare(c.path)),s=Array.from(this.hookHandlers.entries()).flatMap(([a,c])=>c.map((l,d)=>({hook:a,order:d+1,source:{...l.source}}))).sort((a,c)=>{let l=a.hook.localeCompare(c.hook);return l!==0?l:a.order-c.order});return{loadedExtensions:o,capabilityProviders:t,commands:n,tools:r,hooks:s,failures:this.failures.map(a=>({...a,source:{...a.source}})),defaults:this.getDefaults()}}getCapabilityProvider(t){let n=this.capabilityProviders.get(t);if(!(!n||n.length===0))return n[n.length-1]?.value}async searchCapabilities(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o)throw new Error(`Unknown capability provider: ${t}`);return o.search?(await this.emit("capability:search",{providerId:t,query:n,kind:r.kind,limit:r.limit}),o.search(n,r)):[]}async describeCapability(t,n){let r=this.getCapabilityProvider(t);if(!r)throw new Error(`Unknown capability provider: ${t}`);return await this.emit("capability:describe",{providerId:t,capabilityId:n}),r.describe?.(n)}async executeCapability(t,n,r){let o=this.getCapabilityProvider(t);if(!o?.execute)throw new Error(`Capability provider "${t}" does not implement execute().`);return await this.emit("capability:invoke",{providerId:t,capabilityId:n,kind:"tool"}),o.execute(n,r)}async readCapability(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o?.read)throw new Error(`Capability provider "${t}" does not implement read().`);return await this.emit("capability:invoke",{providerId:t,capabilityId:n,kind:"resource"}),o.read(n,r)}async getCapabilityPrompt(t,n,r={}){let o=this.getCapabilityProvider(t);if(!o?.getPrompt)throw new Error(`Capability provider "${t}" does not implement getPrompt().`);return await this.emit("capability:invoke",{providerId:t,capabilityId:n,kind:"prompt"}),o.getPrompt(n,r)}async getCapabilityPromptContext(t){let n=this.getCapabilityProvider(t);if(n?.getPromptContext)return n.getPromptContext()}async refreshCapabilityProviders(t){if(t){let n=this.getCapabilityProvider(t);if(!n)throw new Error(`Unknown capability provider: ${t}`);await this.emit("capability:refresh",{providerId:t}),await n.refresh?.();return}for(let n of this.listCapabilityProviders())await this.emit("capability:refresh",{providerId:n.id}),await n.refresh?.()}async hydrateSession(t){let n=this.hookHandlers.get("session:hydrate");if(!n||n.length===0)return;let r=this.boundController;if(!r)throw new Error("Session hydration requires an active KodaX session binding.");for(let o of n)try{let s=o.source,a=i((c,l)=>{let d=new Error(l);this.recordFailure("persistence",c,s,d),this.runtimeLogger.warn(l)},"warnPersistence");await o.value({sessionId:t,getState:i(c=>r.getSessionState(s.id,c),"getState"),setState:i((c,l)=>{if(l!==void 0&&!un(l)){a(`sessionState:${c}`,`Ignoring non-JSON session state for "${s.label}" key "${c}".`);return}r.setSessionState(s.id,c,l)},"setState"),listRecords:i(c=>r.listSessionRecords(s.id,c),"listRecords"),appendRecord:i((c,l,d)=>{let u=c.trim();if(!u){a("sessionRecord",`Ignoring session record with an empty type for "${s.label}".`);return}if(l!==void 0&&!un(l)){a(`sessionRecord:${u}`,`Ignoring non-JSON session record "${u}" for "${s.label}".`);return}return r.appendSessionRecord(s.id,u,l,d)},"appendRecord"),clearRecords:i(c=>r.clearSessionRecords(s.id,c),"clearRecords")})}catch(s){this.recordFailure("hook","session:hydrate",o.source,s),this.runtimeLogger.warn('Extension hook failed for "session:hydrate":',s instanceof Error?s.message:String(s))}}async emit(t,n){let r=this.eventHandlers.get(t);if(!(!r||r.length===0))for(let o of r)try{await o.value(n)}catch(s){this.recordFailure("event",t,o.source,s),this.runtimeLogger.warn(`Extension event handler failed for "${t}":`,s instanceof Error?s.message:String(s))}}async runHook(t,n){let r=this.hookHandlers.get(t);if(!(!r||r.length===0))for(let o of r)try{let s=await o.value(n);if(s!==void 0)return s}catch(s){this.recordFailure("hook",t,o.source,s),this.runtimeLogger.warn(`Extension hook failed for "${t}":`,s instanceof Error?s.message:String(s))}}createExtensionSource(t,n="api"){return{kind:"extension",id:`${n}:extension:${t}`,label:he.basename(t),path:t}}createRuntimeSource(t,n){return{kind:"runtime",id:t,label:n}}recordFailure(t,n,r,o){this.failures.push({stage:t,target:n,message:o instanceof Error?o.message:String(o),occurredAt:new Date().toISOString(),source:{...r}}),this.failures.length>50&&this.failures.shift()}createExtensionApi(t,n,r="api"){let o=this.createLogger(t),s=this.createExtensionSource(t,r);return{registerTool:i(a=>{let c=dn(a,{source:s});return n.push(c),c},"registerTool"),getTool:i(a=>it(a),"getTool"),getBuiltinTool:i(a=>Os(a),"getBuiltinTool"),registerModelProvider:i(a=>{let c=Qs(a.name,a.factory);return n.push(c),c},"registerModelProvider"),registerCapabilityProvider:i(a=>{let c=this.registerRecord(this.capabilityProviders,a.id,a,s,n);return a.dispose&&n.push(()=>a.dispose?.()),c},"registerCapabilityProvider"),registerCommand:i(a=>this.registerRecord(this.commands,a.name,a,s,n),"registerCommand"),registerSkillPath:i(a=>{let c=he.isAbsolute(a)?a:he.resolve(he.dirname(t),a),l=ca(c);return n.push(l),l},"registerSkillPath"),registerAgent:i(async(a,c)=>{let l=te({name:a,content:c}),d=new Map(de().map(h=>[h.name,h])),u=await Y.admit(l,{activatedAgents:d});if(!u.ok)throw new Error(`[extension:${s.id}] registerAgent("${a}") rejected by admission: ${u.reason}`);let f={kind:"agent",name:a,version:"0.0.0-extension",content:c,status:"active",createdAt:Date.now(),testedAt:Date.now(),activatedAt:Date.now()},m=me(f,{bindings:u.handle.invariantBindings,manifest:u.handle.manifest,source:"extension"});return n.push(m),m},"registerAgent"),on:i((a,c)=>{let l=this.registerEventHandler(a,c,s);return n.push(l),l},"on"),hook:i((a,c)=>{let l=this.registerHookHandler(a,c,s);return n.push(l),l},"hook"),logger:o,config:this.config,runtime:this.createExtensionApiRuntimeController(s,o,n),persistence:ua(s.id),exec:Ef,webhook:Sf}}createLogger(t){let n=he.basename(t);return{debug:i((...r)=>console.debug(`[kodax:extension:${n}]`,...r),"debug"),info:i((...r)=>console.info(`[kodax:extension:${n}]`,...r),"info"),warn:i((...r)=>console.warn(`[kodax:extension:${n}]`,...r),"warn"),error:i((...r)=>console.error(`[kodax:extension:${n}]`,...r),"error")}}createRuntimeControllerProxy(){return{queueUserMessage:i(t=>{let n=this.boundController;if(!n)throw new Error("No active KodaX session is bound to the extension runtime.");n.queueUserMessage(Of(t))},"queueUserMessage"),getSessionState:i((t,n)=>this.boundController?.getSessionState(t,n),"getSessionState"),setSessionState:i((t,n,r)=>{let o=this.boundController;if(!o)throw new Error("Session state is only available while a KodaX session is active.");o.setSessionState(t,n,r)},"setSessionState"),getSessionStateSnapshot:i(t=>this.boundController?this.boundController.getSessionStateSnapshot(t):{},"getSessionStateSnapshot"),appendSessionRecord:i((t,n,r,o)=>{let s=this.boundController;if(!s)throw new Error("Session records are only available while a KodaX session is active.");return s.appendSessionRecord(t,n,r,o)},"appendSessionRecord"),listSessionRecords:i((t,n)=>this.boundController?this.boundController.listSessionRecords(t,n):[],"listSessionRecords"),clearSessionRecords:i((t,n)=>{let r=this.boundController;if(!r)throw new Error("Session records are only available while a KodaX session is active.");return r.clearSessionRecords(t,n)},"clearSessionRecords"),getActiveTools:i(()=>this.boundController?this.boundController.getActiveTools():this.defaultActiveTools===void 0?Ne():[...this.defaultActiveTools],"getActiveTools"),setActiveTools:i(t=>{let n=Uv(t);if(this.boundController){this.boundController.setActiveTools(n);return}this.defaultActiveTools=n},"setActiveTools"),getModelSelection:i(()=>this.boundController?this.boundController.getModelSelection():{...this.defaultModelSelection},"getModelSelection"),setModelSelection:i(t=>{let n=qv(t);if(this.boundController){this.boundController.setModelSelection(n);return}this.defaultModelSelection=n},"setModelSelection"),getThinkingLevel:i(()=>this.boundController?.getThinkingLevel()??this.defaultThinkingLevel,"getThinkingLevel"),setThinkingLevel:i(t=>{if(this.boundController){this.boundController.setThinkingLevel(t);return}this.defaultThinkingLevel=t},"setThinkingLevel")}}createExtensionApiRuntimeController(t,n,r){let o=!1,s,a=!1,c={},l=!1,d,u=i(()=>{o||this.boundController||(o=!0,s=this.defaultActiveTools===void 0?void 0:[...this.defaultActiveTools],r.push(()=>{this.defaultActiveTools=s===void 0?void 0:[...s]}))},"captureActiveToolsRestore"),f=i(()=>{a||this.boundController||(a=!0,c={...this.defaultModelSelection},r.push(()=>{this.defaultModelSelection={...c}}))},"captureModelSelectionRestore"),m=i(()=>{l||this.boundController||(l=!0,d=this.defaultThinkingLevel,r.push(()=>{this.defaultThinkingLevel=d}))},"captureThinkingLevelRestore"),h=i((p,g)=>{let w=new Error(g);this.recordFailure("persistence",p,t,w),n.warn(g)},"recordPersistenceFailure");return{queueUserMessage:i(p=>this.runtimeController.queueUserMessage(Of(p)),"queueUserMessage"),getSessionState:i(p=>this.runtimeController.getSessionState(t.id,p),"getSessionState"),setSessionState:i((p,g)=>{if(g!==void 0&&!un(g)){h(`sessionState:${p}`,`Ignoring non-JSON session state for "${t.label}" key "${p}".`);return}this.runtimeController.setSessionState(t.id,p,g)},"setSessionState"),appendSessionRecord:i((p,g,w)=>{let y=p.trim();if(!y){h("sessionRecord",`Ignoring session record with an empty type for "${t.label}".`);return}if(g!==void 0&&!un(g)){h(`sessionRecord:${y}`,`Ignoring non-JSON session record "${y}" for "${t.label}".`);return}return this.runtimeController.appendSessionRecord(t.id,y,g,w)},"appendSessionRecord"),listSessionRecords:i(p=>this.runtimeController.listSessionRecords(t.id,p),"listSessionRecords"),clearSessionRecords:i(p=>this.runtimeController.clearSessionRecords(t.id,p),"clearSessionRecords"),getActiveTools:i(()=>this.runtimeController.getActiveTools(),"getActiveTools"),setActiveTools:i(p=>{u(),this.runtimeController.setActiveTools(p)},"setActiveTools"),getModelSelection:i(()=>this.runtimeController.getModelSelection(),"getModelSelection"),setModelSelection:i(p=>{f(),this.runtimeController.setModelSelection(p)},"setModelSelection"),getThinkingLevel:i(()=>this.runtimeController.getThinkingLevel(),"getThinkingLevel"),setThinkingLevel:i(p=>{m(),this.runtimeController.setThinkingLevel(p)},"setThinkingLevel")}}registerRecord(t,n,r,o,s){let a=`runtime:${++this.nextRecordId}`,c=t.get(n)??[];t.set(n,[...c,{id:a,value:r,source:o}]);let l=i(()=>{let u=(t.get(n)??[]).filter(f=>f.id!==a);u.length===0?t.delete(n):t.set(n,u)},"dispose");return s.push(l),l}registerEventHandler(t,n,r){let o=`runtime:${++this.nextRecordId}`,s=this.eventHandlers.get(t)??[];return s.push({id:o,value:n,source:r}),this.eventHandlers.set(t,s),()=>{let a=this.eventHandlers.get(t);if(!a)return;let c=a.filter(l=>l.id!==o);if(c.length===0){this.eventHandlers.delete(t);return}this.eventHandlers.set(t,c)}}registerHookHandler(t,n,r){let o=`runtime:${++this.nextRecordId}`,s=this.hookHandlers.get(t)??[];return s.push({id:o,value:n,source:r}),this.hookHandlers.set(t,s),()=>{let a=this.hookHandlers.get(t);if(!a)return;let c=a.filter(l=>l.id!==o);if(c.length===0){this.hookHandlers.delete(t);return}this.hookHandlers.set(t,c)}}async unloadExtension(t){let n=this.loadedExtensions.get(t);n&&(await n.disposeAll(),this.loadedExtensions.delete(t))}async importExtensionModule(t){let n=he.extname(t).toLowerCase();if(!Wn(t))throw new Error(`Unsupported extension module "${t}". FEATURE_034 currently loads .js/.mjs/.cjs/.ts/.mts/.cts files.`);if([".js",".mjs",".cjs"].includes(n)){let r=new URL(Rf(t).href);return r.searchParams.set("kodax_ext_reload",`${Date.now()}:${Math.random()}`),import(r.href)}if([".ts",".mts",".cts"].includes(n))return Dv(Rf(t).href,{parentURL:import.meta.url});throw new Error(`Unsupported extension module "${t}". FEATURE_034 currently loads .js/.mjs/.cjs/.ts/.mts/.cts files.`)}},js=class{static{i(this,"CombinedExtensionRuntime")}primary;secondary;constructor(t,n){this.primary=t,this.secondary=n}getDefaults(){let t=this.primary.getDefaults(),n=this.secondary.getDefaults();return{activeTools:t.activeTools??n.activeTools,modelSelection:{...n.modelSelection,...t.modelSelection},thinkingLevel:t.thinkingLevel??n.thinkingLevel}}bindController(t){let n=[this.secondary.bindController(t),this.primary.bindController(t)];return()=>{for(let r of n.reverse())r()}}async hydrateSession(t){await this.secondary.hydrateSession(t),await this.primary.hydrateSession(t)}async runHook(t,n){let r=await this.secondary.runHook(t,n);return r!==void 0?r:this.primary.runHook(t,n)}async emit(t,n){await this.secondary.emit(t,n),await this.primary.emit(t,n)}async searchCapabilities(t,n,r={}){let o=[],s;for(let a of[this.primary,this.secondary])try{o.push(...await a.searchCapabilities(t,n,r))}catch(c){if(!this.shouldTryNextCapabilityRuntime(c,t))throw c;s??=c}if(o.length===0&&s)throw s;return typeof r.limit=="number"?o.slice(0,r.limit):o}describeCapability(t,n){return this.firstCapabilityResult(t,[()=>this.primary.describeCapability(t,n),()=>this.secondary.describeCapability(t,n)])}executeCapability(t,n,r){return this.firstCapabilityResult(t,[()=>this.primary.executeCapability(t,n,r),()=>this.secondary.executeCapability(t,n,r)])}readCapability(t,n,r={}){return this.firstCapabilityResult(t,[()=>this.primary.readCapability(t,n,r),()=>this.secondary.readCapability(t,n,r)])}getCapabilityPrompt(t,n,r={}){return this.firstCapabilityResult(t,[()=>this.primary.getCapabilityPrompt(t,n,r),()=>this.secondary.getCapabilityPrompt(t,n,r)])}async getCapabilityPromptContext(t){return(await Promise.all([this.secondary.getCapabilityPromptContext(t),this.primary.getCapabilityPromptContext(t)])).filter(o=>typeof o=="string"&&o.trim().length>0).join(`
300
315
 
301
- `)||void 0}async refreshCapabilityProviders(t){let n=!1,r;for(let o of[this.primary,this.secondary])try{await o.refreshCapabilityProviders(t),n=!0}catch(s){if(r??=s,!t||!this.shouldTryNextCapabilityRuntime(s,t))throw s}if(!n&&r)throw r}getDiagnostics(){let t=this.primary.getDiagnostics(),n=this.secondary.getDiagnostics();return{loadedExtensions:[...n.loadedExtensions,...t.loadedExtensions].sort((r,o)=>r.path.localeCompare(o.path)),capabilityProviders:[...n.capabilityProviders,...t.capabilityProviders].sort((r,o)=>r.id.localeCompare(o.id)),commands:[...n.commands,...t.commands].sort((r,o)=>r.name.localeCompare(o.name)),tools:this.dedupeToolDiagnostics([...n.tools,...t.tools]),hooks:[...n.hooks,...t.hooks].sort((r,o)=>r.hook.localeCompare(o.hook)||r.order-o.order),failures:[...n.failures,...t.failures],defaults:this.getDefaults()}}async firstCapabilityResult(t,n){let r;for(let o of n)try{return await o()}catch(s){if(r??=s,!this.shouldTryNextCapabilityRuntime(s,t))throw s}throw r}shouldTryNextCapabilityRuntime(t,n){return t instanceof Error?t.message==="Unknown capability provider: "+n||t.message.startsWith('Capability provider "'+n+'" does not implement ')||n==="mcp"&&t.message.startsWith("Unknown MCP server:"):!1}dedupeToolDiagnostics(t){let n=new Set,r=[];for(let o of t){let s=`${o.name}\0${o.source.kind}\0${o.source.id}`;n.has(s)||(n.add(s),r.push(o))}return r.sort((o,s)=>o.name.localeCompare(s.name))}};function L0(e,t){return new As(e,t)}i(L0,"combineExtensionRuntimes");function M0(e={}){return new Ts(e)}i(M0,"createExtensionRuntime");function P0(e){At=e}i(P0,"setActiveExtensionRuntime");function N0(){return At}i(N0,"getActiveExtensionRuntime");function D0(e){let t=Ct;return Ct=Ok(e)?e:null,()=>{Ct=t}}i(D0,"bindActiveExtensionExecutionRuntime");async function Fn(e,t){await(Ct??At)?.emit(e,t)}i(Fn,"emitActiveExtensionEvent");async function Wr(e,t){return(Ct??At)?.runHook(e,t)}i(Wr,"runActiveExtensionHook");var Mk=new Set(["in_progress","completed","failed","skipped","cancelled","deleted"]),ef=new Set(["build","test","lint"]),Pk=new Set(["init","update"]),Un=new Set(["completed","skipped","cancelled"]),Qu=3,Zu="All plan-list items are now in a terminal state (completed / skipped / cancelled). Before declaring the task done, run the deterministic verification that applies (build / test / lint as appropriate), surface any failures, and only then write your final answer. If you have already verified within this run, ignore this reminder. NEVER mention this reminder to the user.";function M(e){return JSON.stringify(e)}i(M,"jsonResult");function Nk(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Nk,"isPlainObject");function Dk(e,t){let n=[];return e.subject!==t.subject&&n.push("subject"),e.description!==t.description&&n.push("description"),e.status!==t.status&&n.push("status"),e.activeForm!==t.activeForm&&n.push("activeForm"),e.note!==t.note&&n.push("note"),e.evaluator!==t.evaluator&&n.push("evaluator"),e.metadata!==t.metadata&&n.push("metadata"),Object.freeze(n)}i(Dk,"changedFieldsOf");function jk(e,t){if(!Array.isArray(e.items))return M({ok:!1,reason:"Invalid op:'init' payload: `items` must be an array of {id, content, activeForm?} objects (>= 1 entry)."});let n=e.items;if(n.length===0)return M({ok:!1,reason:"Invalid op:'init' payload: `items` array must contain >= 1 entry. Use op:'update' (or pass a non-empty list) instead of an empty init."});let r=new Set,o=[];for(let s=0;s<n.length;s++){let a=n[s];if(a==null||typeof a!="object")return M({ok:!1,reason:`Invalid op:'init' items[${s}]: must be an object {id, subject, description?, activeForm?}.`});let{id:c,subject:l,description:d,activeForm:u,evaluator:f}=a;if(typeof c!="string"||c.length===0)return M({ok:!1,reason:`Invalid op:'init' items[${s}].id: must be a non-empty string.`});if(r.has(c))return M({ok:!1,reason:`Invalid op:'init' items[${s}].id: duplicate id ${JSON.stringify(c)}. Each item id must be unique within the list.`});if(r.add(c),typeof l!="string"||l.length===0)return M({ok:!1,reason:`Invalid op:'init' items[${s}].subject: must be a non-empty string (brief imperative title shown in the plan-list row).`});if(d!==void 0&&typeof d!="string")return M({ok:!1,reason:`Invalid op:'init' items[${s}].description: when provided, must be a string (fuller context / work instructions; multi-line OK).`});if(u!==void 0&&typeof u!="string")return M({ok:!1,reason:`Invalid op:'init' items[${s}].activeForm: when provided, must be a string (present-continuous form, e.g. "Running tests").`});if(f!==void 0&&(typeof f!="string"||!ef.has(f)))return M({ok:!1,reason:`Invalid op:'init' items[${s}].evaluator: when provided, must be one of 'build' | 'test' | 'lint'. Got ${JSON.stringify(f)}.`});o.push({id:c,subject:l,...typeof d=="string"?{description:d}:{},...typeof u=="string"?{activeForm:u}:{},...typeof f=="string"?{evaluator:f}:{}})}return t.todoStore.init(o),M({ok:!0,count:o.length})}i(jk,"executeInitOp");async function tf(e,t){let{op:n,id:r,status:o,note:s,activeForm:a,subject:c,description:l,evaluator:d,metadata:u}=e;if(!t.todoStore)return M({ok:!1,reason:"todo_update is not active in this run (no plan list was seeded). You may continue working without calling todo_update."});let f=n===void 0?"update":n;if(typeof f!="string"||!Pk.has(f))return M({ok:!1,reason:`Invalid op: ${JSON.stringify(n)}. Allowed: 'init' | 'update' (omit for default 'update').`});if(f==="init")return jk(e,t);if(typeof r!="string"||r.length===0)return M({ok:!1,reason:"Missing or invalid required parameter: id (non-empty string)."});if(o!==void 0&&(typeof o!="string"||!Mk.has(o)))return M({ok:!1,reason:`Invalid status: ${JSON.stringify(o)}. Allowed: in_progress | completed | failed | skipped | cancelled | deleted.`});if(o===void 0&&c===void 0&&l===void 0&&a===void 0&&s===void 0&&d===void 0&&u===void 0)return M({ok:!1,reason:"Empty op:'update' payload. Supply at least one of: status, subject, description, activeForm, note, evaluator, metadata."});if(!t.todoStore.has(r)){let g=t.todoStore.allIds(),w=g.length===0?"no todos currently exist":g.join(", ");return M({ok:!1,reason:`Unknown todo id: ${JSON.stringify(r)}. Current valid ids: ${w}. Please retry with one of the valid ids, or skip this update.`})}if(o==="deleted"){let g=t.todoStore.getAll().find(b=>b.id===r);if(!t.todoStore.remove(r)||!g)return M({ok:!1,reason:`Failed to delete ${JSON.stringify(r)}.`});await Fn("todo:deleted",{id:r,item:g,source:"tool"});let y=t.todoStore.getAll();return y.length>=Qu&&y.every(b=>Un.has(b.status))&&!Un.has(g.status)?M({ok:!0,reminder:Zu}):M({ok:!0})}if(s!==void 0&&typeof s!="string")return M({ok:!1,reason:"Invalid note: when provided, must be a string."});if(a!==void 0&&typeof a!="string")return M({ok:!1,reason:'Invalid activeForm: when provided, must be a string (present-continuous, e.g. "Running tests").'});if(c!==void 0&&(typeof c!="string"||c.length===0))return M({ok:!1,reason:"Invalid subject: when provided, must be a non-empty string (brief imperative title for the plan-list row)."});if(l!==void 0&&typeof l!="string")return M({ok:!1,reason:"Invalid description: when provided, must be a string (fuller context; pass empty string to clear)."});if(d!==void 0&&(typeof d!="string"||!ef.has(d)))return M({ok:!1,reason:`Invalid evaluator: when provided, must be one of 'build' | 'test' | 'lint'. Got ${JSON.stringify(d)}.`});if(u!=null&&!Nk(u))return M({ok:!1,reason:"Invalid metadata: when provided, must be a plain object or null (to clear)."});let m=t.todoStore.getAll().find(g=>g.id===r);if(!m)return M({ok:!1,reason:`Failed to read ${JSON.stringify(r)} before patch.`});if(o==="completed"&&m.status!=="completed"){let g=await Wr("todo:before-complete",{id:r,item:m});if(typeof g=="string")return M({ok:!1,reason:g});if(g===!1)return M({ok:!1,reason:"blocked-by-hook"})}t.todoStore.patch(r,{...o!==void 0?{status:o}:{},...c!==void 0?{subject:c}:{},...l!==void 0?{description:l}:{},...a!==void 0?{activeForm:a}:{},...s!==void 0?{note:s}:{},...d!==void 0?{evaluator:d}:{},...u!==void 0?{metadata:u}:{}});let h=t.todoStore.getAll().find(g=>g.id===r);if(h){let g=Dk(m,h);g.length>0&&await Fn("todo:updated",{id:r,before:m,after:h,changedFields:g,source:"tool"})}let p=t.todoStore.getAll();return p.length>=Qu&&p.every(w=>Un.has(w.status))&&!(t.todoStore.getAll().filter(y=>y.id!==r).every(y=>Un.has(y.status))&&Un.has(m.status))?M({ok:!0,reminder:Zu}):M({ok:!0})}i(tf,"toolTodoUpdate");function Fk(e){return{id:e.id,subject:e.subject,status:e.status,...e.description?{description:e.description}:{},...e.activeForm?{activeForm:e.activeForm}:{},...e.note?{note:e.note}:{}}}i(Fk,"toDTO");function nf(e){return JSON.stringify(e)}i(nf,"jsonResult");async function rf(e,t){if(!t.todoStore)return nf({ok:!1,reason:"todo_list is not active in this run (no plan list infrastructure is wired). Either no managed task is active, or the runtime did not provide a todo store. You may continue working without querying the plan list."});let n=t.todoStore.getAll().map(Fk);return nf({ok:!0,count:n.length,items:n})}i(rf,"toolTodoList");var Uk=new Set(["build","test","lint"]);function Pe(e){return JSON.stringify(e)}i(Pe,"jsonResult");function qk(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(qk,"isPlainObject");async function of(e,t){let{subject:n,description:r,activeForm:o,evaluator:s,metadata:a}=e;if(!t.todoStore)return Pe({ok:!1,reason:"todo_create is not active in this run (no plan list was seeded). You may continue working without calling todo_create."});if(typeof n!="string"||n.length===0)return Pe({ok:!1,reason:'Missing or invalid required parameter: subject (non-empty string). Provide a brief imperative title for the plan-list row, e.g. "Audit handleAuth callers".'});if(r!==void 0&&typeof r!="string")return Pe({ok:!1,reason:"Invalid description: when provided, must be a string (fuller context / work instructions; multi-line OK)."});if(o!==void 0&&typeof o!="string")return Pe({ok:!1,reason:'Invalid activeForm: when provided, must be a string (present-continuous form, e.g. "Running tests").'});if(s!==void 0&&(typeof s!="string"||!Uk.has(s)))return Pe({ok:!1,reason:`Invalid evaluator: when provided, must be one of 'build' | 'test' | 'lint'. Got ${JSON.stringify(s)}.`});if(a!==void 0&&!qk(a))return Pe({ok:!1,reason:"Invalid metadata: when provided, must be a plain object."});let c={subject:n,...typeof r=="string"?{description:r}:{},...typeof o=="string"?{activeForm:o}:{},...typeof s=="string"?{evaluator:s}:{},...a!==void 0?{metadata:a}:{}},l=await Wr("todo:before-create",{seed:c});if(typeof l=="string")return Pe({ok:!1,reason:l});if(l===!1)return Pe({ok:!1,reason:"blocked-by-hook"});let d=t.todoStore.add(c),f=t.todoStore.getAll().find(m=>m.id===d);return f&&await Fn("todo:created",{id:d,item:f,source:"tool"}),Pe({ok:!0,id:d})}i(of,"toolTodoCreate");function Bk(e){return{id:e.id,subject:e.subject,status:e.status,...e.description?{description:e.description}:{},...e.activeForm?{activeForm:e.activeForm}:{},...e.note?{note:e.note}:{},...e.evaluator?{evaluator:e.evaluator}:{},...e.metadata?{metadata:e.metadata}:{}}}i(Bk,"toDTO");function Hr(e){return JSON.stringify(e)}i(Hr,"jsonResult");async function sf(e,t){let{id:n}=e;if(!t.todoStore)return Hr({ok:!1,reason:"todo_get is not active in this run (no plan list infrastructure is wired). Either no managed task is active, or the runtime did not provide a todo store. You may continue working without querying the plan list."});if(typeof n!="string"||n.length===0)return Hr({ok:!1,reason:"Missing or invalid required parameter: id (non-empty string)."});let r=t.todoStore.getAll().find(o=>o.id===n);if(!r){let o=t.todoStore.allIds(),s=o.length===0?"no todos currently exist":o.join(", ");return Hr({ok:!1,reason:`Unknown todo id: ${JSON.stringify(n)}. Current valid ids: ${s}. Call todo_list to see the full plan, or retry with one of the valid ids.`})}return Hr({ok:!0,item:Bk(r)})}i(sf,"toolTodoGet");function Cs(e){if(typeof e!="string"||e.length===0)return"<no-artifact>";try{let t=JSON.parse(e),n=typeof t?.name=="string"?t.name:"<no-name>",r=typeof t?.version=="string"?t.version:"<no-version>";return`${n}@${r}`}catch{return"<unparseable>"}}i(Cs,"stageArtifactPreview");function Wk(e,t){if(!e)return xr("<no-server>","<no-tool>",t);try{let{serverId:n,kind:r,name:o}=Vs(ye(e));return xr(n,`${r}:${o}`,t)}catch{return xr(e,"<invalid-id>",t)}}i(Wk,"mcpCapabilityPreview");var zL="When you would otherwise fan several of these out and then synthesize or cross-check their results into one answer (comparing several codebases, reviewing a diff from multiple angles, fanning many files out and ranking what comes back), prefer run_workflow instead: one call gives you a bounded parallel/pipeline, per-child structured output, and same-session resume that dispatch_child_task does not.",fe=[{name:"read",description:["Read a file from the local filesystem with bounded output.","- Text files: returns line-numbered content. Large files are capped per call; use offset/limit to continue in smaller slices.",'- Image files (PNG, JPG, JPEG, GIF, WEBP): returns the image as inline vision content. The model is multimodal \u2014 when an image is delivered through this tool, you can see the picture directly in your next turn. Describe what you see; do NOT claim binary files are unsupported \u2014 the tool decodes the image bytes into vision content for the model, so refusing as "binary file" skips a valid read and frustrates the user.',"- For pasted/attached images already inlined in the user message, you already perceive them via native vision \u2014 no `read` call is needed. Use `read` on an image path only when the file is on disk and not yet in the conversation (e.g., a fresh path the user mentioned in text without attaching).","- PDF files (.pdf): do not use this tool for PDF content. If the `read_pdf` tool is available, call `read_pdf` directly with the PDF path; it extracts page-marked text and can OCR scanned pages when configured. If `read_pdf` is unavailable, tell the user to enable/install the read_pdf extension."].join(`
302
- `),input_schema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file"},offset:{type:"number",description:"Line number to start from (text files only)"},limit:{type:"number",description:"Number of lines to read (text files only)"}},required:["path"]},handler:so,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"kodax_manual",description:uo(),input_schema:{type:"object",properties:{topic:{type:"string",description:'A manual topic id (e.g. "providers", "config", "agents", "extensions", "doctor"). Unknown topics return the index.'},query:{type:"string",description:"A free-text question when you do not know the topic id (English or Chinese)."}},required:[]},handler:wl,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"skill",description:["Invoke a discovered skill by name. Returns the skill's expanded content (variables resolved) as the tool_result so you can follow its instructions in your next turn.",`- Use this whenever a skill listed in your "Available Skills" matches the user's request. The BLOCKING REQUIREMENT in the skills section binds on THIS tool, not on read.`,"- DO NOT call `read` on a `SKILL.md` path to load a skill \u2014 skill loading is `skill`'s job; `read` is for plain files.",'- `args` is an optional free-form string the skill resolver can substitute into its template (e.g. `args: "123"` for `/review-pr 123`). Most skills ignore it.'].join(`
303
- `),input_schema:{type:"object",properties:{skill:{type:"string",description:'The skill name (e.g. "commit", "review-pr"). Leading slash is tolerated.'},args:{type:"string",description:"Optional arguments forwarded to the skill resolver."}},required:["skill"]},handler:bl,sideEffect:"mutates-state",toClassifierInput:i(()=>"","toClassifierInput")},{name:"write",description:'Write content to a file on the local filesystem. Large diffs may be summarized in the tool result.\n\n## When to Use This Tool\n\n- Creating a NEW file the user explicitly asked for.\n- Performing a complete rewrite of an existing file the user explicitly requested.\n- Writing a structural skeleton with placeholder markers (e.g. `<!-- SECTION_A -->` or `// === SECTION_A ===`), then filling each section with `edit` / `multi_edit`. This pattern streams reliably for files too large to write in one pass.\n\n## When NOT to Use This Tool\n\n- Modifying an existing file \u2014 call `edit` (single change) or `multi_edit` (multiple independent changes) instead. `edit` sends only the diff and avoids output-token pressure and mid-stream truncation on large files.\n- Generating a known-content file through `bash` heredocs (`cat > file <<EOF`), `echo > file`, PowerShell `Set-Content` / `Out-File`, or python/node heredoc. Shell redirection bypasses mutation tracking, loses diff visibility to downstream verification, and recurses the same streaming limit onto the generator script itself.\n- Switching to `python` / `bash` scripts to "avoid encoding problems". `write` calls Node `fs.writeFile(path, content, "utf-8")` \u2014 content goes directly from your tool_use input to disk WITHOUT passing through any shell. UTF-8 (Chinese / emoji / etc.) works correctly by default; routing through a shell adds encoding surface area rather than removing it.\n\n## Recovery\n\nIf a `write` failed mid-stream, retry with a smaller skeleton, then `edit` each section.',input_schema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file"},content:{type:"string",description:"The content to write"}},required:["path","content"]},handler:po,sideEffect:"mutates-fs",toClassifierInput:i(e=>{let t=e,n=typeof t?.content=="string"?t.content.length:0;return`Write ${t?.path??"<unknown>"} (${n} bytes)`},"toClassifierInput")},{name:"edit",description:'Replace exact (or normalized) text in an existing file. The most efficient way to modify a file \u2014 only the diff is sent.\n\n## When to Use This Tool\n\n- Modifying an existing file with one targeted text change.\n- Renaming a single occurrence; use `replace_all: true` only when every match in the file should change.\n- Filling in one placeholder produced by a prior `write(path, skeleton)`.\n\n## When NOT to Use This Tool\n\n- Without first calling `read` on the file in this conversation \u2014 your `old_string` will almost certainly be wrong and the edit will fail with "old_string not found", costing a retry round-trip more expensive than the initial read.\n- For multiple independent edits to the same file \u2014 call `multi_edit` instead, which batches N edits atomically in one tool call.\n- As a recovery from a failed `edit` by rewriting the whole file via `write` \u2014 that discards the partial-edit context and re-streams the entire file, which is exactly what `edit` was designed to avoid. Instead retry with a smaller unique snippet, or use `insert_after_anchor`.',input_schema:{type:"object",properties:{path:{type:"string",description:"The file to edit"},old_string:{type:"string",description:"The text to replace"},new_string:{type:"string",description:"The replacement text"},replace_all:{type:"boolean",description:"Replace all occurrences"}},required:["path","old_string","new_string"]},handler:ho,sideEffect:"mutates-fs",toClassifierInput:i(e=>{let t=e;return`Edit ${t?.path??"<unknown>"}${t?.replace_all?" [replace_all]":""}`},"toClassifierInput")},{name:"multi_edit",description:'Apply multiple exact-text replacements to a single file in ONE atomic tool call.\n\n## When to Use This Tool\n\n- Several independent edits to the same file \u2014 especially when filling in a skeleton you just created with `write`.\n- Bulk renames within one file (use `replace_all: true` per edit).\n- Refactors that touch multiple spots in one file and should land all-or-nothing.\n\n## When NOT to Use This Tool\n\n- For a single change \u2014 call `edit` directly; the extra wrapping is unnecessary overhead.\n- Without first calling `read` on the file in this conversation \u2014 your first failing `old_string` aborts the ENTIRE batch, so you pay for all the edits in tokens but land none of them.\n- When later edits need to reference text an earlier edit overlaps \u2014 edits compose sequentially (each sees the result of the previous), so once `edits[k]` rewrites a region, text inside that region is no longer a valid anchor for `edits[k+1..]`. Either shrink the earlier edit to preserve the anchor, or merge them into one edit.\n\n## Atomicity\n\nThe whole batch is atomic: if any single `old_string` fails to match, NO edits are written to disk and you get back an index pointing at the failing edit. Each `edits[i]` has the same semantics as one `edit` call \u2014 exact-match first, then safe-normalized anchor fallback; `replace_all: true` per edit for bulk renames.\n\n## Uniqueness\n\nEach `old_string` must be unique in the WHOLE current file, not just in the window you last read. A short snippet from a narrow `read` (single line, 6-line window, common phrase) is the #1 cause of "matched N places" errors. Widen the anchor with a nearby unique landmark (heading, function signature, distinctive comment, or a multi-line block), or set `replace_all: true` if every occurrence should change.\n\n## Typical Pattern\n\n(1) `write(path, skeleton_with_<!-- SECTION_A -->_placeholders)`; (2) `multi_edit(path, [{SECTION_A, realA}, {SECTION_B, realB}, ...])` \u2014 one batched call.',input_schema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file"},edits:{type:"array",description:"Sequence of edit operations to apply in order",items:{type:"object",properties:{old_string:{type:"string",description:"The text to replace (matched exactly, then via normalized fallback)"},new_string:{type:"string",description:"The replacement text"},replace_all:{type:"boolean",description:"When true, replace every occurrence of old_string (defaults to false)"}},required:["old_string","new_string"]}}},required:["path","edits"]},handler:La,sideEffect:"mutates-fs",toClassifierInput:i(e=>{let t=e,n=Array.isArray(t?.edits)?t.edits.length:0;return`MultiEdit ${t?.path??"<unknown>"}: ${n} edits`},"toClassifierInput")},{name:"insert_after_anchor",description:"Insert content after a unique anchor without rewriting the whole file. Prefer this for appending new sections to existing docs or configs.",input_schema:{type:"object",properties:{path:{type:"string",description:"The file to update"},anchor:{type:"string",description:"A unique heading or nearby marker to insert after"},content:{type:"string",description:"The content to insert after the anchor"}},required:["path","anchor","content"]},handler:go,sideEffect:"mutates-fs",toClassifierInput:i(e=>{let t=e,n=typeof t?.anchor=="string"?t.anchor.slice(0,40):"<no-anchor>";return`InsertAfterAnchor ${t?.path??"<unknown>"} after "${n}"`},"toClassifierInput")},{name:"bash",description:"Execute a shell command. Use `run_in_background` for long-running commands. Large output may be truncated to the most relevant tail.\n\n## When to Use This Tool\n\n- Tests, builds, lint, type-checking, package managers.\n- Git operations (status, diff, log, blame, commit, push).\n- Process inspection / management (ps, kill, top).\n- File system queries not covered by dedicated tools \u2014 `grep` and `glob` have dedicated tools, but `find` / `du` / `df` etc. go through bash.\n- Computed or templated multi-file generation \u2014 e.g. generating 50 similar test fixtures from a template script.\n\n## When NOT to Use This Tool\n\n- Producing a SINGLE file whose content you already have \u2014 call `write` or `edit` instead. Shell redirection (`cat > file <<EOF`, `echo ... >`, PowerShell `Set-Content` / `Out-File`, python/node heredoc) bypasses the mutation tracker, loses diff visibility to downstream verification, and re-encounters the same streaming limit on the generator script itself.\n- Reproducing a hand-written file you already have in memory \u2014 write it directly with `write`. Use a shell script ONLY when the output is computed (loops, templating over many files, data transformation of an input you are reading).",input_schema:{type:"object",properties:{command:{type:"string",description:"The command to execute"},description:{type:"string",description:"Clear, concise description of what this command does"},timeout:{type:"number",description:"Timeout in seconds"},run_in_background:{type:"boolean",description:"Run command in background. Returns immediately with output file path. Use read tool to check output later."}},required:["command"]},handler:wo,sideEffect:"mutates-shell",toClassifierInput:i(e=>{let t=e;return`Bash: ${typeof t?.command=="string"?t.command:"<no-command>"}`},"toClassifierInput")},{name:"glob",description:"Find files matching a pattern.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"The glob pattern"},path:{type:"string",description:"Directory to search"}},required:["pattern"]},handler:bo,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"grep",description:"Search for a regex pattern in file contents. Supports context lines, multiline matching, file type filtering, and pagination.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"The regex pattern to search for in file contents"},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}")'},type:{type:"string",description:"File type to search (e.g. js, ts, py, go, rust, java). More efficient than glob for standard types."},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:'Output mode. "content" shows matching lines (default), "files_with_matches" shows file paths only, "count" shows match counts.'},ignore_case:{type:"boolean",description:"Case insensitive search (default false)"},"-i":{type:"boolean",description:"Alias for ignore_case"},"-A":{type:"number",description:'Number of lines to show after each match. Requires output_mode "content".'},"-B":{type:"number",description:'Number of lines to show before each match. Requires output_mode "content".'},"-C":{type:"number",description:"Alias for context"},context:{type:"number",description:'Number of lines to show before and after each match. Requires output_mode "content".'},multiline:{type:"boolean",description:"Enable multiline mode where . matches newlines and patterns can span lines. Default: false."},head_limit:{type:"number",description:"Limit output to first N entries. Defaults to 250. Pass 0 for unlimited."},offset:{type:"number",description:"Skip first N entries before applying head_limit. Defaults to 0."}},required:["pattern"]},handler:mn,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"dispatch_child_task",description:"Execute a single child agent for an independent sub-task. The child runs its own multi-turn investigation loop and returns findings. Call multiple times in parallel for concurrent sub-tasks \u2014 each call appears as a separate tool with its own status in the transcript.",input_schema:{type:"object",properties:{id:{type:"string",description:"Unique child task identifier"},objective:{type:"string",description:"Detailed multi-step goal for this child agent"},readOnly:{type:"boolean",description:"true (default): child can only read files. false: child may edit files (Generator/Worker only); use for non-conflicting file-level edits across modules."},scope_summary:{type:"string",description:'Optional scope hint (e.g. "packages/llm/src/")'},evidence_refs:{type:"array",items:{type:"string"},description:`Optional known evidence. Prefixed strings: "file:path" inlines the first 200 lines of a working-tree file, "diff:path" inlines the git diff against HEAD, "finding:text" transcribes a fact you already know, "task_id:<child_id>" forwards a completed sibling child's output verbatim \u2014 use this after dispatching one child whose findings feed the next so the new child sees the sibling's full report without you re-narrating it. An unknown prefix is surfaced as an error in the next dispatch tool_result so you can correct it.`},constraints:{type:"array",items:{type:"string"},description:"Optional constraints"},model_hint:{type:"string",enum:["fast","balanced","deep"],description:`Optional hint for routing this child to a tier-appropriate model. "fast" for short focused lookups (reading a handful of files, a simple grep); "balanced" (default; same as omit) for normal subtasks; "deep" for heavy reasoning (multi-file analysis, complex audit). Routing is currently a no-op (every child runs on the parent's model); a future routing feature will activate the hint. Mark "fast" only for trivial focused lookups; mark "deep" only for multi-file research or analytical synthesis; when in doubt, omit.`},subagent_type:{type:"string",description:"When the task matches a registered specialist (e.g., db-reviewer for SQL changes, e2e-runner for browser tests), dispatch as that specialist instead of a generic child."},provider:{type:"string",description:"Optional. Run this child on a specific provider instead of inheriting yours. Use when you deliberately want a different model family \u2014 e.g. a second independent review of the same change by a different family, to catch blind spots a single family would share. Omit to inherit your provider (the default). An unconfigured provider falls back to yours."},model:{type:"string",description:"Optional. Specific model id for this child, paired with `provider`. Omit to inherit your model."},effort:{type:"string",description:"Optional. Reasoning effort for this child (for example off, low, medium, high, xhigh, max). Omit or use auto to inherit the parent/default effort. If subagent_type names a specialist with a declared effort, that specialist effort is locked and a different dispatch effort is rejected. Unsupported values are rejected by the selected provider/model."}},required:["objective"]},handler:Fd,sideEffect:"mutates-state",toClassifierInput:i(e=>{let t=e,n=typeof t?.objective=="string"?t.objective.slice(0,200):"<no-objective>";return`Dispatch(${t?.readOnly===!1?"mutating":"readonly"}): ${n}`},"toClassifierInput")},{name:"run_workflow",description:`Author and run a multi-agent workflow inline: you write a small JavaScript orchestration script that runs as child agents under the workflow runtime. run_workflow is ASYNCHRONOUS \u2014 the call returns immediately with a task_id and the workflow runs in the background; its synthesized result arrives later as a <task-completed task_id=\u2026> block, so after calling it you idle-yield (end your turn with no tool calls) or do other work rather than waiting inline, exactly like dispatch_child_task. Reach for this when independent agents working in parallel and then cross-checking each other beat a single linear pass \u2014 comparing several codebases or options, reviewing a diff from multiple independent angles and adversarially verifying each finding, or fanning many files out and synthesizing what they return; common single-phase shapes are understand (parallel readers over subsystems), design (a judge panel of approaches), review (find then verify each), research (a multi-angle sweep), and migrate (discover the sites, then transform each). First investigate with your own tools (read / grep / glob) to find the real files, the actual sub-problems, and the shape of the data; then bake those concrete findings into the child prompts \u2014 exact paths, the specific dimensions to compare, a real outputSchema. Write those child prompts in the same natural language as the user's request, so each child's report and the synthesized result come back in that language. A script that only says "investigate X" and re-delegates all the scouting to its children produces shallow, duplicated work, because each child starts from nothing; the value of the workflow is that its children start from what you already discovered. The run(wf, args) body coordinates agents through wf only: wf.runAgent({name, prompt, readOnly, phase?, modelHint?, outputSchema?}) returns the child's result, or null if it failed or was stopped (so you can .filter(Boolean) instead of guarding every call); modelHint is a tier \u2014 'deep' for an agent that needs a stronger model, 'fast' for a cheap read-only pass \u2014 not a concrete model name; the operator maps tiers to real models, and an unconfigured tier just inherits your model, and with outputSchema \u2014 a JSON-Schema subset of type/enum/required/properties/items/additionalProperties \u2014 the parsed validated object comes back on result.structured, so read your declared fields off result.structured (e.g. result.structured.findings) and never off the top-level result, which is undefined for those fields and yields an empty report; wf.parallel([thunks]) runs thunks concurrently and nulls any that fail rather than rejecting; wf.pipeline(items, stage1, stage2) streams each item through the stages without waiting for the slowest and is the default for staged work \u2014 reach for wf.parallel as a barrier only when a stage genuinely needs every prior result before it can start, such as a dedup or merge across all of them; wf.synthesize({inputs, rubric}) folds results into one; wf.workflow(name, args) runs a saved or built-in workflow as a sub-step; a shared phase tag groups agents in the progress view. Patterns worth composing (these are examples, not a fixed menu): adversarially verify a finding by spawning a few independent agents that each attack it from a distinct failure-mode angle, keeping it only if the majority cannot refute it; run a judge panel by generating several independent attempts from different angles and synthesizing from the strongest; loop until dry by spawning finders until a couple of rounds surface nothing new rather than stopping at a fixed count; sweep multi-modally by pointing agents at one target through different routes (by file, by symbol, by test) so a single blind spot does not sink the search; end with a completeness critic that asks what is still missing. Reach for more than one of these in a single script when the task has more than one shape, and name every pattern you use in manifest.patterns \u2014 chaining them is the norm, not the exception. A review or audit, for instance, combines fan-out-and-synthesize with adversarial-verification as pipeline(findings, find, verify): fan independent reviewers out to surface findings, then pipe each finding straight into an independent verifier that tries to refute it, keeping only the ones it cannot dismiss and ending with .filter(Boolean); weaving verification in this way is what lets you skip a separate re-audit pass afterward. Research that must be exhaustive chains loop-until-done with a completeness critic; a design task chains generate-and-filter with a tournament judge. Declare each pattern the script actually uses, e.g. ['fan-out-and-synthesize', 'adversarial-verification']. Match the effort to the request: a quick 'find any bugs' wants a few finders and one check, while 'thoroughly audit this' wants a larger pool and several independent verifiers before synthesis. If you bound coverage \u2014 top-N, no retry, sampling \u2014 say so in the result, because a silent cap reads as covered-everything when it was not. Prefer dispatch_child_task for a single focused sub-task \u2014 a whole workflow's coordination overhead is wasted on one agent \u2014 and just read files yourself for a quick lookup.`,input_schema:{type:"object",properties:{manifest:{type:"object",description:"Workflow metadata. Set readOnly false only if child agents must write files. patterns names the shapes the script uses (one or more of: classify-and-act, fan-out-and-synthesize, adversarial-verification, generate-and-filter, tournament, loop-until-done).",properties:{name:{type:"string"},description:{type:"string"},phases:{type:"array",items:{type:"string"},description:"Ordered phase names for progress display."},readOnly:{type:"boolean"},maxAgents:{type:"number",description:"Lifetime cap on total child agents across the run."},maxConcurrency:{type:"number",description:"Max simultaneously in-flight child agents."},patterns:{type:"array",items:{type:"string"}},plannedAgents:{type:"number"}},required:["name","description","phases","readOnly","maxAgents","maxConcurrency","patterns"]},source:{type:"string",description:"JavaScript module body defining `async function run(wf, args) { ... }`. Coordinate child agents only through `wf`; the script gets no fs/network/shell and may not use import/require. Return displayable final text (for example `{ synthesis }`)."},args:{type:"object",description:"Optional initial arguments passed to run(wf, args)."},resumeFromRunId:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]*$",description:"Optional run id of a prior run of THIS workflow to resume from. Re-submit the same script (edited or not) with the prior run id: unchanged agent calls return their cached results instantly and only the changed/new calls re-run. Scripts must be deterministic for this \u2014 Date.now()/Math.random() are disabled."}},required:["manifest","source"]},handler:qd,sideEffect:"mutates-state",toClassifierInput:i(e=>{let t=e,n=t?.manifest?.name??t?.manifest?.description??"<workflow>";return`RunWorkflow: ${String(n).slice(0,160)}`},"toClassifierInput")},{name:"send_message",description:`Route a short message to another in-flight agent in this session. Worker \u2192 child appends a <coordinator-instruction> at user priority (drained next tool boundary). Child \u2192 child peer appends a <peer-message from=\u2026> at background priority (drained when the peer next yields). Child \u2192 parent Worker uses to="worker" and appends a <child-notification from=\u2026>. Broadcast to="*" fans the message out to every other in-flight sibling plus the parent Worker, framed as <peer-broadcast from=\u2026>. Use sparingly \u2014 most children should not need mid-flight steering, and peer chatter is for coordination notes that change another agent's plan, not status updates.`,input_schema:{type:"object",properties:{to:{type:"string",description:'One of: an in-flight task_id from a prior dispatch_child_task call (single addressed send), the literal "worker" (notify the parent Worker; only valid when the sender is a child), or "*" (broadcast to all other in-flight siblings plus the parent Worker, capped at 20 recipients). Self-targeted sends are rejected.'},content:{type:"string",description:"Message body. Will be wrapped in the framing tag matching the routing branch (<coordinator-instruction>, <peer-message from=\u2026>, <child-notification from=\u2026>, or <peer-broadcast from=\u2026>) before the recipient sees it."},seen_by:{type:"array",items:{type:"string"},description:'Optional chain of agents that have already handled this message \u2014 only relevant when you are forwarding a peer message you received. The incoming wrapper carries a seen_by="A,B,\u2026" attribute; copy that list into this parameter so the tool can detect cycles (forwarding back to a prior sender is rejected) and cap chain depth. Omit entirely for fresh sends; the tool always auto-appends you to the chain before enqueue.'}},required:["to","content"]},handler:Fi,sideEffect:"mutates-state",toClassifierInput:i(e=>{let t=e,n=typeof t?.to=="string"?t.to:"<no-to>",r=typeof t?.content=="string"?t.content.slice(0,120):"<no-content>";return`SendMessage(${n}): ${r}`},"toClassifierInput")},{name:"task_stop",description:"Request graceful exit of a specific in-flight child task launched via dispatch_child_task. The child finishes its current tool call atomically (no hard kill \u2014 a 90s npm test won't be interrupted), sees an optional <coordinator-stop-request> message explaining why, then emits a final summary. Use when: child went off-scope (e.g. started writing files when launched read-only), user cancelled the parent task that justified the child, or child is pathologically slow with no progress signal. Coordinator-only: child agents cannot call this tool.",input_schema:{type:"object",properties:{task_id:{type:"string",description:"Target child task_id (from a prior dispatch_child_task call). Completed children are auto-cleaned and become invalid targets."},reason:{type:"string",description:"Optional explanation. When provided, the child receives a <coordinator-stop-request> system-reminder with this reason BEFORE the abort fires, so it can frame its final summary accordingly. Omitting the reason still aborts the child; only the explanation is skipped."}},required:["task_id"]},handler:Ui,sideEffect:"mutates-state",planModeAllowed:!0,toClassifierInput:i(e=>{let t=e,n=typeof t?.task_id=="string"?t.task_id:"<no-task_id>",r=typeof t?.reason=="string"?t.reason.slice(0,80):"";return`TaskStop(${n})${r?": "+r:""}`},"toClassifierInput")},{name:"task_output",description:"Peek at the current state of a child task launched via dispatch_child_task. Returns a structured snapshot (status, iteration count, recent tool-call breadcrumbs, and final text once the child settles). Normal Worker usage is task_output({task_id}) with block omitted/false for a status snapshot. If block:true is used, timeout_ms is only a bounded read-window cap; retrieval_status=wait_expired with status=running means the child is still running, not timed out or failed. Prefer idle-yield (end the turn text-only) for normal waits. Coordinator-only: child agents cannot call this tool. Completed children's snapshots remain queryable for the lifetime of the parent runner; very old snapshots may be evicted under a per-runner cap.",input_schema:{type:"object",properties:{task_id:{type:"string",description:"Target child task_id (from a prior dispatch_child_task call). Returns retrieval_status=not_found if the task was never dispatched or its snapshot has been evicted."},block:{type:"boolean",description:"Optional compatibility knob. When false or omitted (normal Worker usage), return the current snapshot immediately. When true, wait only within a bounded read window (up to timeout_ms) before returning the snapshot; wait expiry is not child failure. Idle-yield (end turn text-only) is the canonical wait."},timeout_ms:{type:"number",description:"Max bounded read-window time in milliseconds when block:true. Default 30000 (30s), max 120000 (120s). Ignored when block:false. If the read window expires, returns the current snapshot with retrieval_status=wait_expired; this is not a child task timeout."}},required:["task_id"]},handler:Kd,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(e=>{let t=e,n=typeof t?.task_id=="string"?t.task_id:"<no-task_id>",r=t?.block===!0?" (block)":"";return`TaskOutput(${n})${r}`},"toClassifierInput")},{name:"web_search",description:'Search the web for discovery-oriented results with explicit trust and freshness signaling. Use this for "discover what is out there" queries when you do not yet have a specific URL \u2014 researching a library before integrating it, finding canonical docs for an API, identifying current best-practice patterns. Output includes provenance + trust signals; when relaying answers to the user, cite sources back in markdown link format (`[title](url)`). Pair with `web_fetch` to follow up on a specific result. Search results are geographically scoped (US-based) and freshness metadata reflects when each source was last indexed, not the moment of your query \u2014 interpret "current X" with that caveat. For finding code or documentation INSIDE the repo, prefer `grep` / `code_search` / `semantic_lookup` \u2014 those operate on the local checkout and do not consume network turns.',input_schema:{type:"object",properties:{query:{type:"string",description:"Search query to run"},limit:{type:"number",description:"Maximum number of search results to return"},provider_id:{type:"string",description:"Optional extension capability provider id for provider-backed search"}},required:["query"]},handler:li,sideEffect:"reads-network",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"web_fetch",description:'Fetch a specific remote source by URL and return bounded text with provenance and trust hints. The handler converts HTML to markdown and caches each unique URL for a short window so repeated reads within the same task are free. If the response is a redirect (3xx), the tool stops and reports the new target URL \u2014 re-issue `web_fetch` against that new URL rather than chasing the redirect manually, so the cache + provenance line up with what the user actually sees. For GitHub URLs specifically (`github.com/...` / `raw.githubusercontent.com/...`), prefer `bash` with the `gh` CLI when available \u2014 `gh api` / `gh pr view` / `gh issue view` are faster, return structured output, and avoid markdown-conversion artifacts; using `web_fetch` on a github.com URL when `gh` would work is the most common "tool waste" pattern in this surface. Despite the `mutates-network` side-effect classification (some providers route POST requests through this surface), the LLM-facing semantics are read-only. Use `web_search` first when you do not yet have a specific URL.',input_schema:{type:"object",properties:{url:{type:"string",description:"Remote URL to fetch"},provider_id:{type:"string",description:"Optional extension capability provider id for provider-backed fetch"},capability_id:{type:"string",description:"Optional provider capability id for provider-backed fetch"}}},handler:di,sideEffect:"mutates-network",toClassifierInput:i(e=>{let t=e;return`WebFetch ${typeof t?.url=="string"?t.url:"<no-url>"}`},"toClassifierInput")},{name:"code_search",description:'Search local repository code with lower-noise output than ad hoc shell grep. Returns ranked matches with file:line refs and surrounding context, filtered by repo-aware heuristics (skips minified bundles, generated artifacts, lockfiles by default). Prefer `code_search` over `grep` for "find symbol X" / "where is this string used" investigations spanning the whole repo \u2014 the noise reduction saves token budget on the result side. Prefer raw `grep` when you need exact byte-level matching (regex anchors, character classes, multiline patterns) or when scoping is already narrow (a known single file or small subdirectory). For symbol-level intelligence (callers, callees, imports), use `symbol_context` instead \u2014 it pre-resolves the relationships that a text search would only hint at.',input_schema:{type:"object",properties:{query:{type:"string",description:"String query to search for"},path:{type:"string",description:"Optional file or directory scope for the search"},limit:{type:"number",description:"Maximum number of matches to return"},case_sensitive:{type:"boolean",description:"Whether the query should be matched case-sensitively"},provider_id:{type:"string",description:"Optional extension capability provider id for provider-backed code search"}},required:["query"]},handler:fi,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"semantic_lookup",description:'Search repository intelligence for symbol-, module-, or process-aware semantic matches. "Repository intelligence" here is a pre-indexed structural view of the codebase (symbol definitions, module boundaries, process flows); `semantic_lookup` queries that index rather than scanning raw text. Use it when the question is structural ("what does symbol X relate to", "which module owns concept Y", "what flow does entry Z drive") rather than textual. The `kind` parameter narrows the lookup category (`symbol` / `module` / `process` / `auto`); `target_path` scopes to a subtree. `refresh: true` rebuilds the underlying index \u2014 expensive \u2014 so only set it when you have reason to believe the index is stale (e.g., right after a large bulk edit). For exact text match prefer `grep`; for ranked text search prefer `code_search`; to read a file directly prefer `read`.',input_schema:{type:"object",properties:{query:{type:"string",description:"Semantic query to resolve inside repository intelligence"},kind:{type:"string",enum:["auto","symbol","module","process"],description:"Optional semantic lookup category"},target_path:{type:"string",description:"Optional path hint to scope the semantic lookup"},limit:{type:"number",description:"Maximum number of semantic matches to return"},refresh:{type:"boolean",description:"When true, refresh repository intelligence before searching"}},required:["query"]},handler:pi,sideEffect:"readonly",toClassifierInput:i(e=>En("semantic_lookup",e),"toClassifierInput")},{name:"mcp_search",description:"Search active MCP tools, resources, and prompts through the shared capability runtime. The KodaX MCP surface is a meta-tool layer: capabilities live on remote MCP servers, and `mcp_search` is the discovery entry point. Returns capability ids in the exact `mcp:<server-id>:<kind>:<capability-name>` format, for example `mcp:git-nexus:tool:list_branches`. Copy the Locator/ID from `mcp_search` exactly, including the `mcp:` prefix; do not rebuild or shorten it. Batch-call `mcp_describe` on the ids you actually plan to use rather than describing every result \u2014 describing capabilities you will not call wastes a turn. The `kind` filter (`tool` / `resource` / `prompt`) narrows the family: tools are the only family that can mutate remote state via `mcp_call`; resources are reads via `mcp_read_resource`; prompts are templates via `mcp_get_prompt`. The `server` filter scopes to a specific MCP server when multiple are connected.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search query. Omit or pass an empty string to browse active MCP catalogs."},server:{type:"string",description:"Optional MCP server id filter"},kind:{type:"string",enum:["tool","resource","prompt"],description:"Optional MCP capability family filter"},limit:{type:"number",description:"Maximum number of search results to return"}}},handler:wi,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"mcp_describe",description:"Describe a specific MCP capability by id, including its full JSON Schema, trust tier, and provenance. Use this when `mcp_search` returned a candidate id and you need to see the exact parameter shape before invoking it. `mcp_describe` is a pure read against the MCP server catalog \u2014 safe to call freely, but redundant: only describe capabilities you actually plan to call. The schema returned is the source of truth for `mcp_call.args` / `mcp_get_prompt.args` shape; do not guess argument names from the capability id alone.",input_schema:{type:"object",properties:{id:{type:"string",description:"MCP capability id from mcp_search"}},required:["id"]},handler:bi,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"mcp_call",description:"Invoke an MCP tool capability by id with structured arguments. This is the ONLY side-effecting MCP entry point \u2014 the underlying capability can mutate remote state (file writes, database updates, API calls). Treat each `mcp_call` with the same care as a `bash` command against an unfamiliar shell: confirm the capability is what you intend by `mcp_describe` first when uncertain. The `id` must be the exact `mcp:<server-id>:tool:<tool-name>` id from `mcp_search`, for example `mcp:git-nexus:tool:list_branches`; copy it exactly, including the `mcp:` prefix. `args` must match the JSON Schema returned by `mcp_describe`. For pure reads use `mcp_read_resource` (no mutation) or `mcp_get_prompt` (template retrieval) instead \u2014 `mcp_call` is overkill when the goal is just reading.",input_schema:{type:"object",properties:{id:{type:"string",description:"MCP tool capability id from mcp_search"},args:{type:"object",description:"Structured arguments for the MCP tool call"}},required:["id"]},handler:ki,sideEffect:"mutates-network",toClassifierInput:i(e=>{let t=e,n=typeof t?.id=="string"?t.id:"<no-id>";return Wk(n,t?.args??{})},"toClassifierInput")},{name:"mcp_read_resource",description:'Read an MCP resource capability by id. Resources are server-published read-only data sources \u2014 file contents, query results, config snapshots \u2014 and `mcp_read_resource` retrieves them without invoking remote code. Unlike `mcp_call`, this entry point cannot mutate remote state, so it is safe to use during plan-mode preview. The `id` must be the exact `mcp:<server-id>:resource:<resource-name>` id from `mcp_search` (with `kind="resource"` filter); copy it exactly, including the `mcp:` prefix. Use `mcp_call` instead when the capability is registered as a tool (mutation-capable), and `mcp_get_prompt` when it is a templated prompt.',input_schema:{type:"object",properties:{id:{type:"string",description:"MCP resource capability id from mcp_search"}},required:["id"]},handler:vi,sideEffect:"reads-network",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"mcp_get_prompt",description:'Retrieve an MCP prompt capability by id, expanding any template arguments. Prompts are server-published reusable text templates (system prompt snippets, structured query templates, task framings); `mcp_get_prompt` returns the expanded text after substituting `args`. Read-only with respect to remote state \u2014 the server resolves the template but does not run code. The `id` must be the exact `mcp:<server-id>:prompt:<prompt-name>` id from `mcp_search` (with `kind="prompt"` filter); copy it exactly, including the `mcp:` prefix. `args` must match the prompt template variables (which `mcp_describe` will list).',input_schema:{type:"object",properties:{id:{type:"string",description:"MCP prompt capability id from mcp_search"},args:{type:"object",description:"Optional arguments for the MCP prompt"}},required:["id"]},handler:_i,sideEffect:"reads-network",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"worktree_create",description:"Create a new git worktree with an isolated branch for safe agent work.",input_schema:{type:"object",properties:{branch_name:{type:"string",description:"Optional explicit branch name"},description:{type:"string",description:"Optional description to auto-generate branch name from"}}},handler:Tn,sideEffect:"mutates-fs",toClassifierInput:i(e=>{let t=e;return`WorktreeCreate ${typeof t?.branch_name=="string"?t.branch_name:typeof t?.description=="string"?`<auto from "${t.description.slice(0,40)}">`:"<auto>"}`},"toClassifierInput")},{name:"worktree_remove",description:"Remove a git worktree and optionally its branch.",input_schema:{type:"object",properties:{action:{type:"string",enum:["keep","remove"],description:"Whether to keep or remove the worktree directory and branch"},worktree_path:{type:"string",description:"Absolute path to the worktree directory"},discard_changes:{type:"boolean",description:"If true, bypass safety checks for uncommitted changes or local commits"}},required:["action","worktree_path"]},handler:An,sideEffect:"mutates-fs",toClassifierInput:i(e=>{let t=e,n=t?.discard_changes?" [discard_changes]":"";return`WorktreeRemove ${t?.action??"<no-action>"} ${t?.worktree_path??"<no-path>"}${n}`},"toClassifierInput")},{name:"undo",description:"Revert the last file modification.",input_schema:{type:"object",properties:{}},handler:ko,sideEffect:"mutates-fs",toClassifierInput:i(()=>"Undo: revert last file modification","toClassifierInput")},{name:"ask_user_question",description:'Ask the user a question. Supports single-select (default), multi-select, or free-text input. When you have multiple independent questions, use the "questions" array \u2014 each question is presented separately with its own options. Do NOT combine multiple questions into a single question string, because combining forces the user to mentally disambiguate option combinations themselves, which usually breaks the option-button UI.',input_schema:{type:"object",properties:{question:{type:"string",description:'The question to ask the user. Use this for a single question. For multiple independent questions, use the "questions" array instead.'},questions:{type:"array",description:'Multiple independent questions (1-4). Each question is presented separately with its own options. Use this instead of combining multiple questions into a single "question" string. Takes precedence over "question"+"options" when provided.',items:{type:"object",properties:{question:{type:"string",description:"The question text"},header:{type:"string",description:'Short label (max 12 chars) shown in progress indicator, e.g. "\u73AF\u5883" or "Deploy"'},options:{type:"array",description:"Available options for this question.",items:{type:"object",properties:{label:{type:"string",description:"Display label for this option"},description:{type:"string",description:"Optional description of this option"},value:{type:"string",description:"Optional value to return (defaults to label)"}},required:["label"]}},multi_select:{type:"boolean",description:"Allow multiple selections for this question. Returns an array of the selected values."},min_selections:{type:"integer",description:"Minimum number of options the user must select. Only applies when multi_select is true."},max_selections:{type:"integer",description:"Maximum number of options the user may select. Only applies when multi_select is true."}},required:["question","options"]},minItems:1,maxItems:4},kind:{type:"string",enum:["select","input"],description:'Interaction kind. "select" (default) shows options for the user to pick from. "input" shows a free-text prompt for the user to type anything. Use "input" when the user needs to provide an open-ended answer (e.g. step combinations like "1,3,5", version numbers, custom text).'},options:{type:"array",description:'Available options for the user to choose from. Required for kind="select", ignored for kind="input".',items:{type:"object",properties:{label:{type:"string",description:"Display label for this option"},description:{type:"string",description:"Optional description of this option"},value:{type:"string",description:"Optional value to return (defaults to label)"}},required:["label"]}},multi_select:{type:"boolean",description:'Allow the user to select multiple options (space to toggle, enter to confirm). Only applies to kind="select". Returns an array of the selected values.'},min_selections:{type:"integer",description:"Minimum number of options the user must select. Only applies when multi_select is true."},max_selections:{type:"integer",description:"Maximum number of options the user may select. Only applies when multi_select is true."},default:{type:"string",description:"Optional default choice (for select) or default text (for input)"}},required:["question"]},handler:vo,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"get_goal",description:"Read the current goal for this session, including status, budget, token and elapsed-time usage, and remaining token budget.",input_schema:{type:"object",properties:{}},handler:Jd,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"create_goal",description:"Create a goal only when explicitly requested by the user or system/developer instructions; do not infer goals from ordinary tasks. Set token_budget only when an explicit token budget is requested. Fails if a goal exists; use update_goal only for status changes.",input_schema:{type:"object",properties:{objective:{type:"string",description:"The long-running objective the agent should pursue across turns. A clear, concrete sentence describing the target end-state."},token_budget:{type:"number",description:"Optional positive integer token budget for the entire goal. Omit when the user did not request a budget."}},required:["objective"]},handler:Yd,sideEffect:"mutates-state",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"update_goal",description:`Mark the current goal complete or blocked.
316
+ `)||void 0}async refreshCapabilityProviders(t){let n=!1,r;for(let o of[this.primary,this.secondary])try{await o.refreshCapabilityProviders(t),n=!0}catch(s){if(r??=s,!t||!this.shouldTryNextCapabilityRuntime(s,t))throw s}if(!n&&r)throw r}getDiagnostics(){let t=this.primary.getDiagnostics(),n=this.secondary.getDiagnostics();return{loadedExtensions:[...n.loadedExtensions,...t.loadedExtensions].sort((r,o)=>r.path.localeCompare(o.path)),capabilityProviders:[...n.capabilityProviders,...t.capabilityProviders].sort((r,o)=>r.id.localeCompare(o.id)),commands:[...n.commands,...t.commands].sort((r,o)=>r.name.localeCompare(o.name)),tools:this.dedupeToolDiagnostics([...n.tools,...t.tools]),hooks:[...n.hooks,...t.hooks].sort((r,o)=>r.hook.localeCompare(o.hook)||r.order-o.order),failures:[...n.failures,...t.failures],defaults:this.getDefaults()}}async firstCapabilityResult(t,n){let r;for(let o of n)try{return await o()}catch(s){if(r??=s,!this.shouldTryNextCapabilityRuntime(s,t))throw s}throw r}shouldTryNextCapabilityRuntime(t,n){return t instanceof Error?t.message==="Unknown capability provider: "+n||t.message.startsWith('Capability provider "'+n+'" does not implement ')||n==="mcp"&&t.message.startsWith("Unknown MCP server:"):!1}dedupeToolDiagnostics(t){let n=new Set,r=[];for(let o of t){let s=`${o.name}\0${o.source.kind}\0${o.source.id}`;n.has(s)||(n.add(s),r.push(o))}return r.sort((o,s)=>o.name.localeCompare(s.name))}};function UM(e,t){return new js(e,t)}i(UM,"combineExtensionRuntimes");function qM(e={}){return new Fs(e)}i(qM,"createExtensionRuntime");function BM(e){Lt=e}i(BM,"setActiveExtensionRuntime");function WM(){return Lt}i(WM,"getActiveExtensionRuntime");function HM(e){let t=Mt;return Mt=jv(e)?e:null,()=>{Mt=t}}i(HM,"bindActiveExtensionExecutionRuntime");async function Hn(e,t){await(Mt??Lt)?.emit(e,t)}i(Hn,"emitActiveExtensionEvent");async function Jr(e,t){return(Mt??Lt)?.runHook(e,t)}i(Jr,"runActiveExtensionHook");var Bv=new Set(["in_progress","completed","failed","skipped","cancelled","deleted"]),Mf=new Set(["build","test","lint"]),Wv=new Set(["init","update"]),zn=new Set(["completed","skipped","cancelled"]),If=3,Lf="All plan-list items are now in a terminal state (completed / skipped / cancelled). Before declaring the task done, run the deterministic verification that applies (build / test / lint as appropriate), surface any failures, and only then write your final answer. If you have already verified within this run, ignore this reminder. NEVER mention this reminder to the user.";function N(e){return JSON.stringify(e)}i(N,"jsonResult");function Hv(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Hv,"isPlainObject");function zv(e,t){let n=[];return e.subject!==t.subject&&n.push("subject"),e.description!==t.description&&n.push("description"),e.status!==t.status&&n.push("status"),e.activeForm!==t.activeForm&&n.push("activeForm"),e.note!==t.note&&n.push("note"),e.evaluator!==t.evaluator&&n.push("evaluator"),e.metadata!==t.metadata&&n.push("metadata"),Object.freeze(n)}i(zv,"changedFieldsOf");function Gv(e,t){if(!Array.isArray(e.items))return N({ok:!1,reason:"Invalid op:'init' payload: `items` must be an array of {id, content, activeForm?} objects (>= 1 entry)."});let n=e.items;if(n.length===0)return N({ok:!1,reason:"Invalid op:'init' payload: `items` array must contain >= 1 entry. Use op:'update' (or pass a non-empty list) instead of an empty init."});let r=new Set,o=[];for(let s=0;s<n.length;s++){let a=n[s];if(a==null||typeof a!="object")return N({ok:!1,reason:`Invalid op:'init' items[${s}]: must be an object {id, subject, description?, activeForm?}.`});let{id:c,subject:l,description:d,activeForm:u,evaluator:f}=a;if(typeof c!="string"||c.length===0)return N({ok:!1,reason:`Invalid op:'init' items[${s}].id: must be a non-empty string.`});if(r.has(c))return N({ok:!1,reason:`Invalid op:'init' items[${s}].id: duplicate id ${JSON.stringify(c)}. Each item id must be unique within the list.`});if(r.add(c),typeof l!="string"||l.length===0)return N({ok:!1,reason:`Invalid op:'init' items[${s}].subject: must be a non-empty string (brief imperative title shown in the plan-list row).`});if(d!==void 0&&typeof d!="string")return N({ok:!1,reason:`Invalid op:'init' items[${s}].description: when provided, must be a string (fuller context / work instructions; multi-line OK).`});if(u!==void 0&&typeof u!="string")return N({ok:!1,reason:`Invalid op:'init' items[${s}].activeForm: when provided, must be a string (present-continuous form, e.g. "Running tests").`});if(f!==void 0&&(typeof f!="string"||!Mf.has(f)))return N({ok:!1,reason:`Invalid op:'init' items[${s}].evaluator: when provided, must be one of 'build' | 'test' | 'lint'. Got ${JSON.stringify(f)}.`});o.push({id:c,subject:l,...typeof d=="string"?{description:d}:{},...typeof u=="string"?{activeForm:u}:{},...typeof f=="string"?{evaluator:f}:{}})}return t.todoStore.init(o),N({ok:!0,count:o.length})}i(Gv,"executeInitOp");async function Pf(e,t){let{op:n,id:r,status:o,note:s,activeForm:a,subject:c,description:l,evaluator:d,metadata:u}=e;if(!t.todoStore)return N({ok:!1,reason:"todo_update is not active in this run (no plan list was seeded). You may continue working without calling todo_update."});let f=n===void 0?"update":n;if(typeof f!="string"||!Wv.has(f))return N({ok:!1,reason:`Invalid op: ${JSON.stringify(n)}. Allowed: 'init' | 'update' (omit for default 'update').`});if(f==="init")return Gv(e,t);if(typeof r!="string"||r.length===0)return N({ok:!1,reason:"Missing or invalid required parameter: id (non-empty string)."});if(o!==void 0&&(typeof o!="string"||!Bv.has(o)))return N({ok:!1,reason:`Invalid status: ${JSON.stringify(o)}. Allowed: in_progress | completed | failed | skipped | cancelled | deleted.`});if(o===void 0&&c===void 0&&l===void 0&&a===void 0&&s===void 0&&d===void 0&&u===void 0)return N({ok:!1,reason:"Empty op:'update' payload. Supply at least one of: status, subject, description, activeForm, note, evaluator, metadata."});if(!t.todoStore.has(r)){let g=t.todoStore.allIds(),w=g.length===0?"no todos currently exist":g.join(", ");return N({ok:!1,reason:`Unknown todo id: ${JSON.stringify(r)}. Current valid ids: ${w}. Please retry with one of the valid ids, or skip this update.`})}if(o==="deleted"){let g=t.todoStore.getAll().find(b=>b.id===r);if(!t.todoStore.remove(r)||!g)return N({ok:!1,reason:`Failed to delete ${JSON.stringify(r)}.`});await Hn("todo:deleted",{id:r,item:g,source:"tool"});let y=t.todoStore.getAll();return y.length>=If&&y.every(b=>zn.has(b.status))&&!zn.has(g.status)?N({ok:!0,reminder:Lf}):N({ok:!0})}if(s!==void 0&&typeof s!="string")return N({ok:!1,reason:"Invalid note: when provided, must be a string."});if(a!==void 0&&typeof a!="string")return N({ok:!1,reason:'Invalid activeForm: when provided, must be a string (present-continuous, e.g. "Running tests").'});if(c!==void 0&&(typeof c!="string"||c.length===0))return N({ok:!1,reason:"Invalid subject: when provided, must be a non-empty string (brief imperative title for the plan-list row)."});if(l!==void 0&&typeof l!="string")return N({ok:!1,reason:"Invalid description: when provided, must be a string (fuller context; pass empty string to clear)."});if(d!==void 0&&(typeof d!="string"||!Mf.has(d)))return N({ok:!1,reason:`Invalid evaluator: when provided, must be one of 'build' | 'test' | 'lint'. Got ${JSON.stringify(d)}.`});if(u!=null&&!Hv(u))return N({ok:!1,reason:"Invalid metadata: when provided, must be a plain object or null (to clear)."});let m=t.todoStore.getAll().find(g=>g.id===r);if(!m)return N({ok:!1,reason:`Failed to read ${JSON.stringify(r)} before patch.`});if(o==="completed"&&m.status!=="completed"){let g=await Jr("todo:before-complete",{id:r,item:m});if(typeof g=="string")return N({ok:!1,reason:g});if(g===!1)return N({ok:!1,reason:"blocked-by-hook"})}t.todoStore.patch(r,{...o!==void 0?{status:o}:{},...c!==void 0?{subject:c}:{},...l!==void 0?{description:l}:{},...a!==void 0?{activeForm:a}:{},...s!==void 0?{note:s}:{},...d!==void 0?{evaluator:d}:{},...u!==void 0?{metadata:u}:{}});let h=t.todoStore.getAll().find(g=>g.id===r);if(h){let g=zv(m,h);g.length>0&&await Hn("todo:updated",{id:r,before:m,after:h,changedFields:g,source:"tool"})}let p=t.todoStore.getAll();return p.length>=If&&p.every(w=>zn.has(w.status))&&!(t.todoStore.getAll().filter(y=>y.id!==r).every(y=>zn.has(y.status))&&zn.has(m.status))?N({ok:!0,reminder:Lf}):N({ok:!0})}i(Pf,"toolTodoUpdate");function Kv(e){return{id:e.id,subject:e.subject,status:e.status,...e.description?{description:e.description}:{},...e.activeForm?{activeForm:e.activeForm}:{},...e.note?{note:e.note}:{}}}i(Kv,"toDTO");function Nf(e){return JSON.stringify(e)}i(Nf,"jsonResult");async function Df(e,t){if(!t.todoStore)return Nf({ok:!1,reason:"todo_list is not active in this run (no plan list infrastructure is wired). Either no managed task is active, or the runtime did not provide a todo store. You may continue working without querying the plan list."});let n=t.todoStore.getAll().map(Kv);return Nf({ok:!0,count:n.length,items:n})}i(Df,"toolTodoList");var Xv=new Set(["build","test","lint"]);function Fe(e){return JSON.stringify(e)}i(Fe,"jsonResult");function Vv(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Vv,"isPlainObject");async function Ff(e,t){let{subject:n,description:r,activeForm:o,evaluator:s,metadata:a}=e;if(!t.todoStore)return Fe({ok:!1,reason:"todo_create is not active in this run (no plan list was seeded). You may continue working without calling todo_create."});if(typeof n!="string"||n.length===0)return Fe({ok:!1,reason:'Missing or invalid required parameter: subject (non-empty string). Provide a brief imperative title for the plan-list row, e.g. "Audit handleAuth callers".'});if(r!==void 0&&typeof r!="string")return Fe({ok:!1,reason:"Invalid description: when provided, must be a string (fuller context / work instructions; multi-line OK)."});if(o!==void 0&&typeof o!="string")return Fe({ok:!1,reason:'Invalid activeForm: when provided, must be a string (present-continuous form, e.g. "Running tests").'});if(s!==void 0&&(typeof s!="string"||!Xv.has(s)))return Fe({ok:!1,reason:`Invalid evaluator: when provided, must be one of 'build' | 'test' | 'lint'. Got ${JSON.stringify(s)}.`});if(a!==void 0&&!Vv(a))return Fe({ok:!1,reason:"Invalid metadata: when provided, must be a plain object."});let c={subject:n,...typeof r=="string"?{description:r}:{},...typeof o=="string"?{activeForm:o}:{},...typeof s=="string"?{evaluator:s}:{},...a!==void 0?{metadata:a}:{}},l=await Jr("todo:before-create",{seed:c});if(typeof l=="string")return Fe({ok:!1,reason:l});if(l===!1)return Fe({ok:!1,reason:"blocked-by-hook"});let d=t.todoStore.add(c),f=t.todoStore.getAll().find(m=>m.id===d);return f&&await Hn("todo:created",{id:d,item:f,source:"tool"}),Fe({ok:!0,id:d})}i(Ff,"toolTodoCreate");function Jv(e){return{id:e.id,subject:e.subject,status:e.status,...e.description?{description:e.description}:{},...e.activeForm?{activeForm:e.activeForm}:{},...e.note?{note:e.note}:{},...e.evaluator?{evaluator:e.evaluator}:{},...e.metadata?{metadata:e.metadata}:{}}}i(Jv,"toDTO");function Yr(e){return JSON.stringify(e)}i(Yr,"jsonResult");async function jf(e,t){let{id:n}=e;if(!t.todoStore)return Yr({ok:!1,reason:"todo_get is not active in this run (no plan list infrastructure is wired). Either no managed task is active, or the runtime did not provide a todo store. You may continue working without querying the plan list."});if(typeof n!="string"||n.length===0)return Yr({ok:!1,reason:"Missing or invalid required parameter: id (non-empty string)."});let r=t.todoStore.getAll().find(o=>o.id===n);if(!r){let o=t.todoStore.allIds(),s=o.length===0?"no todos currently exist":o.join(", ");return Yr({ok:!1,reason:`Unknown todo id: ${JSON.stringify(n)}. Current valid ids: ${s}. Call todo_list to see the full plan, or retry with one of the valid ids.`})}return Yr({ok:!0,item:Jv(r)})}i(jf,"toolTodoGet");function Us(e){if(typeof e!="string"||e.length===0)return"<no-artifact>";try{let t=JSON.parse(e),n=typeof t?.name=="string"?t.name:"<no-name>",r=typeof t?.version=="string"?t.version:"<no-version>";return`${n}@${r}`}catch{return"<unparseable>"}}i(Us,"stageArtifactPreview");function Yv(e,t){if(!e)return Rr("<no-server>","<no-tool>",t);try{let{serverId:n,kind:r,name:o}=aa(be(e));return Rr(n,`${r}:${o}`,t)}catch{return Rr(e,"<invalid-id>",t)}}i(Yv,"mcpCapabilityPreview");var QP="When you would otherwise fan several of these out and then synthesize or cross-check their results into one answer (comparing several codebases, reviewing a diff from multiple angles, fanning many files out and ranking what comes back), prefer run_workflow instead: one call gives you a bounded parallel/pipeline, per-child structured output, and same-session resume that dispatch_child_task does not.",ge=[{name:"read",description:["Read a file from the local filesystem with bounded output.","- Text files: returns line-numbered content. Large files are capped per call; use offset/limit to continue in smaller slices.",'- Image files (PNG, JPG, JPEG, GIF, WEBP): returns the image as inline vision content. The model is multimodal \u2014 when an image is delivered through this tool, you can see the picture directly in your next turn. Describe what you see; do NOT claim binary files are unsupported \u2014 the tool decodes the image bytes into vision content for the model, so refusing as "binary file" skips a valid read and frustrates the user.',"- For pasted/attached images already inlined in the user message, you already perceive them via native vision \u2014 no `read` call is needed. Use `read` on an image path only when the file is on disk and not yet in the conversation (e.g., a fresh path the user mentioned in text without attaching).","- PDF files (.pdf): do not use this tool for PDF content. If the `read_pdf` tool is available, call `read_pdf` directly with the PDF path; it extracts page-marked text and can OCR scanned pages when configured. If `read_pdf` is unavailable, tell the user to enable/install the read_pdf extension."].join(`
317
+ `),input_schema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file"},offset:{type:"number",description:"Line number to start from (text files only)"},limit:{type:"number",description:"Number of lines to read (text files only)"}},required:["path"]},handler:mo,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"kodax_manual",description:wo(),input_schema:{type:"object",properties:{topic:{type:"string",description:'A manual topic id (e.g. "providers", "config", "agents", "extensions", "doctor"). Unknown topics return the index.'},query:{type:"string",description:"A free-text question when you do not know the topic id (English or Chinese)."}},required:[]},handler:Yl,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"skill",description:["Invoke a discovered skill by name. Returns the skill's expanded content (variables resolved) as the tool_result so you can follow its instructions in your next turn.",`- Use this whenever a skill listed in your "Available Skills" matches the user's request. The BLOCKING REQUIREMENT in the skills section binds on THIS tool, not on read.`,"- DO NOT call `read` on a `SKILL.md` path to load a skill \u2014 skill loading is `skill`'s job; `read` is for plain files.",'- `args` is an optional free-form string the skill resolver can substitute into its template (e.g. `args: "123"` for `/review-pr 123`). Most skills ignore it.'].join(`
318
+ `),input_schema:{type:"object",properties:{skill:{type:"string",description:'The skill name (e.g. "commit", "review-pr"). Leading slash is tolerated.'},args:{type:"string",description:"Optional arguments forwarded to the skill resolver."}},required:["skill"]},handler:Zl,sideEffect:"mutates-state",toClassifierInput:i(()=>"","toClassifierInput")},{name:"write",description:'Write content to a file on the local filesystem. Large diffs may be summarized in the tool result.\n\n## When to Use This Tool\n\n- Creating a NEW file the user explicitly asked for.\n- Performing a complete rewrite of an existing file the user explicitly requested.\n- Writing a structural skeleton with placeholder markers (e.g. `<!-- SECTION_A -->` or `// === SECTION_A ===`), then filling each section with `edit` / `multi_edit`. This pattern streams reliably for files too large to write in one pass.\n\n## When NOT to Use This Tool\n\n- Modifying an existing file \u2014 call `edit` (single change) or `multi_edit` (multiple independent changes) instead. `edit` sends only the diff and avoids output-token pressure and mid-stream truncation on large files.\n- Generating a known-content file through `bash` heredocs (`cat > file <<EOF`), `echo > file`, PowerShell `Set-Content` / `Out-File`, or python/node heredoc. Shell redirection bypasses mutation tracking, loses diff visibility to downstream verification, and recurses the same streaming limit onto the generator script itself.\n- Switching to `python` / `bash` scripts to "avoid encoding problems". `write` calls Node `fs.writeFile(path, content, "utf-8")` \u2014 content goes directly from your tool_use input to disk WITHOUT passing through any shell. UTF-8 (Chinese / emoji / etc.) works correctly by default; routing through a shell adds encoding surface area rather than removing it.\n\n## Recovery\n\nIf a `write` failed mid-stream, retry with a smaller skeleton, then `edit` each section.',input_schema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file"},content:{type:"string",description:"The content to write"}},required:["path","content"]},handler:ko,sideEffect:"mutates-fs",toClassifierInput:i(e=>{let t=e,n=typeof t?.content=="string"?t.content.length:0;return`Write ${t?.path??"<unknown>"} (${n} bytes)`},"toClassifierInput")},{name:"edit",description:'Replace exact (or normalized) text in an existing file. The most efficient way to modify a file \u2014 only the diff is sent.\n\n## When to Use This Tool\n\n- Modifying an existing file with one targeted text change.\n- Renaming a single occurrence; use `replace_all: true` only when every match in the file should change.\n- Filling in one placeholder produced by a prior `write(path, skeleton)`.\n\n## When NOT to Use This Tool\n\n- Without first calling `read` on the file in this conversation \u2014 your `old_string` will almost certainly be wrong and the edit will fail with "old_string not found", costing a retry round-trip more expensive than the initial read.\n- For multiple independent edits to the same file \u2014 call `multi_edit` instead, which batches N edits atomically in one tool call.\n- As a recovery from a failed `edit` by rewriting the whole file via `write` \u2014 that discards the partial-edit context and re-streams the entire file, which is exactly what `edit` was designed to avoid. Instead retry with a smaller unique snippet, or use `insert_after_anchor`.',input_schema:{type:"object",properties:{path:{type:"string",description:"The file to edit"},old_string:{type:"string",description:"The text to replace"},new_string:{type:"string",description:"The replacement text"},replace_all:{type:"boolean",description:"Replace all occurrences"}},required:["path","old_string","new_string"]},handler:_o,sideEffect:"mutates-fs",toClassifierInput:i(e=>{let t=e;return`Edit ${t?.path??"<unknown>"}${t?.replace_all?" [replace_all]":""}`},"toClassifierInput")},{name:"multi_edit",description:'Apply multiple exact-text replacements to a single file in ONE atomic tool call.\n\n## When to Use This Tool\n\n- Several independent edits to the same file \u2014 especially when filling in a skeleton you just created with `write`.\n- Bulk renames within one file (use `replace_all: true` per edit).\n- Refactors that touch multiple spots in one file and should land all-or-nothing.\n\n## When NOT to Use This Tool\n\n- For a single change \u2014 call `edit` directly; the extra wrapping is unnecessary overhead.\n- Without first calling `read` on the file in this conversation \u2014 your first failing `old_string` aborts the ENTIRE batch, so you pay for all the edits in tokens but land none of them.\n- When later edits need to reference text an earlier edit overlaps \u2014 edits compose sequentially (each sees the result of the previous), so once `edits[k]` rewrites a region, text inside that region is no longer a valid anchor for `edits[k+1..]`. Either shrink the earlier edit to preserve the anchor, or merge them into one edit.\n\n## Atomicity\n\nThe whole batch is atomic: if any single `old_string` fails to match, NO edits are written to disk and you get back an index pointing at the failing edit. Each `edits[i]` has the same semantics as one `edit` call \u2014 exact-match first, then safe-normalized anchor fallback; `replace_all: true` per edit for bulk renames.\n\n## Uniqueness\n\nEach `old_string` must be unique in the WHOLE current file, not just in the window you last read. A short snippet from a narrow `read` (single line, 6-line window, common phrase) is the #1 cause of "matched N places" errors. Widen the anchor with a nearby unique landmark (heading, function signature, distinctive comment, or a multi-line block), or set `replace_all: true` if every occurrence should change.\n\n## Typical Pattern\n\n(1) `write(path, skeleton_with_<!-- SECTION_A -->_placeholders)`; (2) `multi_edit(path, [{SECTION_A, realA}, {SECTION_B, realB}, ...])` \u2014 one batched call.',input_schema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file"},edits:{type:"array",description:"Sequence of edit operations to apply in order",items:{type:"object",properties:{old_string:{type:"string",description:"The text to replace (matched exactly, then via normalized fallback)"},new_string:{type:"string",description:"The replacement text"},replace_all:{type:"boolean",description:"When true, replace every occurrence of old_string (defaults to false)"}},required:["old_string","new_string"]}}},required:["path","edits"]},handler:za,sideEffect:"mutates-fs",toClassifierInput:i(e=>{let t=e,n=Array.isArray(t?.edits)?t.edits.length:0;return`MultiEdit ${t?.path??"<unknown>"}: ${n} edits`},"toClassifierInput")},{name:"insert_after_anchor",description:"Insert content after a unique anchor without rewriting the whole file. Prefer this for appending new sections to existing docs or configs.",input_schema:{type:"object",properties:{path:{type:"string",description:"The file to update"},anchor:{type:"string",description:"A unique heading or nearby marker to insert after"},content:{type:"string",description:"The content to insert after the anchor"}},required:["path","anchor","content"]},handler:xo,sideEffect:"mutates-fs",toClassifierInput:i(e=>{let t=e,n=typeof t?.anchor=="string"?t.anchor.slice(0,40):"<no-anchor>";return`InsertAfterAnchor ${t?.path??"<unknown>"} after "${n}"`},"toClassifierInput")},{name:"bash",description:"Execute a shell command. Use `run_in_background` for long-running commands. Large output may be truncated to the most relevant tail.\n\n## When to Use This Tool\n\n- Tests, builds, lint, type-checking, package managers.\n- Git operations (status, diff, log, blame, commit, push).\n- Process inspection / management (ps, kill, top).\n- File system queries not covered by dedicated tools \u2014 `grep` and `glob` have dedicated tools, but `find` / `du` / `df` etc. go through bash.\n- Computed or templated multi-file generation \u2014 e.g. generating 50 similar test fixtures from a template script.\n\n## When NOT to Use This Tool\n\n- Producing a SINGLE file whose content you already have \u2014 call `write` or `edit` instead. Shell redirection (`cat > file <<EOF`, `echo ... >`, PowerShell `Set-Content` / `Out-File`, python/node heredoc) bypasses the mutation tracker, loses diff visibility to downstream verification, and re-encounters the same streaming limit on the generator script itself.\n- Reproducing a hand-written file you already have in memory \u2014 write it directly with `write`. Use a shell script ONLY when the output is computed (loops, templating over many files, data transformation of an input you are reading).",input_schema:{type:"object",properties:{command:{type:"string",description:"The command to execute"},description:{type:"string",description:"Clear, concise description of what this command does"},timeout:{type:"number",description:"Timeout in seconds"},run_in_background:{type:"boolean",description:"Run command in background. Returns immediately with output file path. Use read tool to check output later."}},required:["command"]},handler:Ro,sideEffect:"mutates-shell",toClassifierInput:i(e=>{let t=e;return`Bash: ${typeof t?.command=="string"?t.command:"<no-command>"}`},"toClassifierInput")},{name:"glob",description:"Find files matching a pattern.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"The glob pattern"},path:{type:"string",description:"Directory to search"}},required:["pattern"]},handler:Oo,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"grep",description:"Search for a regex pattern in file contents. Supports context lines, multiline matching, file type filtering, and pagination.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"The regex pattern to search for in file contents"},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}")'},type:{type:"string",description:"File type to search (e.g. js, ts, py, go, rust, java). More efficient than glob for standard types."},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:'Output mode. "content" shows matching lines (default), "files_with_matches" shows file paths only, "count" shows match counts.'},ignore_case:{type:"boolean",description:"Case insensitive search (default false)"},"-i":{type:"boolean",description:"Alias for ignore_case"},"-A":{type:"number",description:'Number of lines to show after each match. Requires output_mode "content".'},"-B":{type:"number",description:'Number of lines to show before each match. Requires output_mode "content".'},"-C":{type:"number",description:"Alias for context"},context:{type:"number",description:'Number of lines to show before and after each match. Requires output_mode "content".'},multiline:{type:"boolean",description:"Enable multiline mode where . matches newlines and patterns can span lines. Default: false."},head_limit:{type:"number",description:"Limit output to first N entries. Defaults to 250. Pass 0 for unlimited."},offset:{type:"number",description:"Skip first N entries before applying head_limit. Defaults to 0."}},required:["pattern"]},handler:bn,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"dispatch_child_task",description:"Execute a single child agent for an independent sub-task. The child runs its own multi-turn investigation loop and returns findings. Call multiple times in parallel for concurrent sub-tasks \u2014 each call appears as a separate tool with its own status in the transcript.",input_schema:{type:"object",properties:{id:{type:"string",description:"Unique child task identifier"},objective:{type:"string",description:"Detailed multi-step goal for this child agent"},readOnly:{type:"boolean",description:"true (default): child can only read files. false: child may edit files (Generator/Worker only); use for non-conflicting file-level edits across modules."},scope_summary:{type:"string",description:'Optional scope hint (e.g. "packages/llm/src/")'},evidence_refs:{type:"array",items:{type:"string"},description:`Optional known evidence. Prefixed strings: "file:path" inlines the first 200 lines of a working-tree file, "diff:path" inlines the git diff against HEAD, "finding:text" transcribes a fact you already know, "task_id:<child_id>" forwards a completed sibling child's output verbatim \u2014 use this after dispatching one child whose findings feed the next so the new child sees the sibling's full report without you re-narrating it. An unknown prefix is surfaced as an error in the next dispatch tool_result so you can correct it.`},constraints:{type:"array",items:{type:"string"},description:"Optional constraints"},model_hint:{type:"string",enum:["fast","balanced","deep"],description:`Optional hint for routing this child to a tier-appropriate model. "fast" for short focused lookups (reading a handful of files, a simple grep); "balanced" (default; same as omit) for normal subtasks; "deep" for heavy reasoning (multi-file analysis, complex audit). Routing is currently a no-op (every child runs on the parent's model); a future routing feature will activate the hint. Mark "fast" only for trivial focused lookups; mark "deep" only for multi-file research or analytical synthesis; when in doubt, omit.`},subagent_type:{type:"string",description:"When the task matches a registered specialist (e.g., db-reviewer for SQL changes, e2e-runner for browser tests), dispatch as that specialist instead of a generic child."},provider:{type:"string",description:"Optional. Run this child on a specific provider instead of inheriting yours. Use when you deliberately want a different model family \u2014 e.g. a second independent review of the same change by a different family, to catch blind spots a single family would share. Omit to inherit your provider (the default). An unconfigured provider falls back to yours."},model:{type:"string",description:"Optional. Specific model id for this child, paired with `provider`. Omit to inherit your model."},effort:{type:"string",description:"Optional. Reasoning effort for this child (for example off, low, medium, high, xhigh, max). Omit or use auto to inherit the parent/default effort. If subagent_type names a specialist with a declared effort, that specialist effort is locked and a different dispatch effort is rejected. Unsupported values are rejected by the selected provider/model."}},required:["objective"]},handler:wu,sideEffect:"mutates-state",toClassifierInput:i(e=>{let t=e,n=typeof t?.objective=="string"?t.objective.slice(0,200):"<no-objective>";return`Dispatch(${t?.readOnly===!1?"mutating":"readonly"}): ${n}`},"toClassifierInput")},{name:"run_workflow",description:`Author and run a multi-agent workflow inline: you write a small JavaScript orchestration script that runs as child agents under the workflow runtime. run_workflow is ASYNCHRONOUS \u2014 the call returns immediately with a task_id and the workflow runs in the background; its synthesized result arrives later as a <task-completed task_id=\u2026> block, so after calling it you idle-yield (end your turn with no tool calls) or do other work rather than waiting inline, exactly like dispatch_child_task. Reach for this when independent agents working in parallel and then cross-checking each other beat a single linear pass \u2014 comparing several codebases or options, reviewing a diff from multiple independent angles and adversarially verifying each finding, or fanning many files out and synthesizing what they return; common single-phase shapes are understand (parallel readers over subsystems), design (a judge panel of approaches), review (find then verify each), research (a multi-angle sweep), and migrate (discover the sites, then transform each). First investigate with your own tools (read / grep / glob) to find the real files, the actual sub-problems, and the shape of the data; then bake those concrete findings into the child prompts \u2014 exact paths, the specific dimensions to compare, a real outputSchema. Write those child prompts in the same natural language as the user's request, so each child's report and the synthesized result come back in that language. A script that only says "investigate X" and re-delegates all the scouting to its children produces shallow, duplicated work, because each child starts from nothing; the value of the workflow is that its children start from what you already discovered. The run(wf, args) body coordinates agents through wf only: wf.runAgent({name, prompt, readOnly, phase?, modelHint?, outputSchema?}) returns the child's result, or null if it failed or was stopped (so you can .filter(Boolean) instead of guarding every call); modelHint is a tier \u2014 'deep' for an agent that needs a stronger model, 'fast' for a cheap read-only pass \u2014 not a concrete model name; the operator maps tiers to real models, and an unconfigured tier just inherits your model, and with outputSchema \u2014 a JSON-Schema subset of type/enum/required/properties/items/additionalProperties \u2014 the parsed validated object comes back on result.structured, so read your declared fields off result.structured (e.g. result.structured.findings) and never off the top-level result, which is undefined for those fields and yields an empty report; wf.parallel([thunks]) runs thunks concurrently and nulls any that fail rather than rejecting; wf.pipeline(items, stage1, stage2) streams each item through the stages without waiting for the slowest and is the default for staged work \u2014 reach for wf.parallel as a barrier only when a stage genuinely needs every prior result before it can start, such as a dedup or merge across all of them; wf.synthesize({inputs, rubric}) folds results into one; wf.workflow(name, args) runs a saved or built-in workflow as a sub-step; a shared phase tag groups agents in the progress view. Patterns worth composing (these are examples, not a fixed menu): adversarially verify a finding by spawning a few independent agents that each attack it from a distinct failure-mode angle, keeping it only if the majority cannot refute it; run a judge panel by generating several independent attempts from different angles and synthesizing from the strongest; loop until dry by spawning finders until a couple of rounds surface nothing new rather than stopping at a fixed count; sweep multi-modally by pointing agents at one target through different routes (by file, by symbol, by test) so a single blind spot does not sink the search; end with a completeness critic that asks what is still missing. Reach for more than one of these in a single script when the task has more than one shape, and name every pattern you use in manifest.patterns \u2014 chaining them is the norm, not the exception. A review or audit, for instance, combines fan-out-and-synthesize with adversarial-verification as pipeline(findings, find, verify): fan independent reviewers out to surface findings, then pipe each finding straight into an independent verifier that tries to refute it, keeping only the ones it cannot dismiss and ending with .filter(Boolean); weaving verification in this way is what lets you skip a separate re-audit pass afterward. Research that must be exhaustive chains loop-until-done with a completeness critic; a design task chains generate-and-filter with a tournament judge. Declare each pattern the script actually uses, e.g. ['fan-out-and-synthesize', 'adversarial-verification']. Match the effort to the request: a quick 'find any bugs' wants a few finders and one check, while 'thoroughly audit this' wants a larger pool and several independent verifiers before synthesis. If you bound coverage \u2014 top-N, no retry, sampling \u2014 say so in the result, because a silent cap reads as covered-everything when it was not. Prefer dispatch_child_task for a single focused sub-task \u2014 a whole workflow's coordination overhead is wasted on one agent \u2014 and just read files yourself for a quick lookup.`,input_schema:{type:"object",properties:{manifest:{type:"object",description:"Workflow metadata. Set readOnly false only if child agents must write files. patterns names the shapes the script uses (one or more of: classify-and-act, fan-out-and-synthesize, adversarial-verification, generate-and-filter, tournament, loop-until-done).",properties:{name:{type:"string"},description:{type:"string"},phases:{type:"array",items:{type:"string"},description:"Ordered phase names for progress display."},readOnly:{type:"boolean"},maxAgents:{type:"number",description:"Lifetime cap on total child agents across the run."},maxConcurrency:{type:"number",description:"Max simultaneously in-flight child agents."},patterns:{type:"array",items:{type:"string"}},plannedAgents:{type:"number"}},required:["name","description","phases","readOnly","maxAgents","maxConcurrency","patterns"]},source:{type:"string",description:"JavaScript module body defining `async function run(wf, args) { ... }`. Coordinate child agents only through `wf`; the script gets no fs/network/shell and may not use import/require. Return displayable final text (for example `{ synthesis }`)."},args:{type:"object",description:"Optional initial arguments passed to run(wf, args)."},resumeFromRunId:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]*$",description:"Optional run id of a prior run of THIS workflow to resume from. Re-submit the same script (edited or not) with the prior run id: unchanged agent calls return their cached results instantly and only the changed/new calls re-run. Scripts must be deterministic for this \u2014 Date.now()/Math.random() are disabled."}},required:["manifest","source"]},handler:ku,sideEffect:"mutates-state",toClassifierInput:i(e=>{let t=e,n=t?.manifest?.name??t?.manifest?.description??"<workflow>";return`RunWorkflow: ${String(n).slice(0,160)}`},"toClassifierInput")},{name:"send_message",description:`Route a short message to another in-flight agent in this session. Worker \u2192 child appends a <coordinator-instruction> at user priority (drained next tool boundary). Child \u2192 child peer appends a <peer-message from=\u2026> at background priority (drained when the peer next yields). Child \u2192 parent Worker uses to="worker" and appends a <child-notification from=\u2026>. Broadcast to="*" fans the message out to every other in-flight sibling plus the parent Worker, framed as <peer-broadcast from=\u2026>. Use sparingly \u2014 most children should not need mid-flight steering, and peer chatter is for coordination notes that change another agent's plan, not status updates.`,input_schema:{type:"object",properties:{to:{type:"string",description:'One of: an in-flight task_id from a prior dispatch_child_task call (single addressed send), the literal "worker" (notify the parent Worker; only valid when the sender is a child), or "*" (broadcast to all other in-flight siblings plus the parent Worker, capped at 20 recipients). Self-targeted sends are rejected.'},content:{type:"string",description:"Message body. Will be wrapped in the framing tag matching the routing branch (<coordinator-instruction>, <peer-message from=\u2026>, <child-notification from=\u2026>, or <peer-broadcast from=\u2026>) before the recipient sees it."},seen_by:{type:"array",items:{type:"string"},description:'Optional chain of agents that have already handled this message \u2014 only relevant when you are forwarding a peer message you received. The incoming wrapper carries a seen_by="A,B,\u2026" attribute; copy that list into this parameter so the tool can detect cycles (forwarding back to a prior sender is rejected) and cap chain depth. Omit entirely for fresh sends; the tool always auto-appends you to the chain before enqueue.'}},required:["to","content"]},handler:Yi,sideEffect:"mutates-state",toClassifierInput:i(e=>{let t=e,n=typeof t?.to=="string"?t.to:"<no-to>",r=typeof t?.content=="string"?t.content.slice(0,120):"<no-content>";return`SendMessage(${n}): ${r}`},"toClassifierInput")},{name:"task_stop",description:"Request graceful exit of a specific in-flight child task launched via dispatch_child_task. The child finishes its current tool call atomically (no hard kill \u2014 a 90s npm test won't be interrupted), sees an optional <coordinator-stop-request> message explaining why, then emits a final summary. Use when: child went off-scope (e.g. started writing files when launched read-only), user cancelled the parent task that justified the child, or child is pathologically slow with no progress signal. Coordinator-only: child agents cannot call this tool.",input_schema:{type:"object",properties:{task_id:{type:"string",description:"Target child task_id (from a prior dispatch_child_task call). Completed children are auto-cleaned and become invalid targets."},reason:{type:"string",description:"Optional explanation. When provided, the child receives a <coordinator-stop-request> system-reminder with this reason BEFORE the abort fires, so it can frame its final summary accordingly. Omitting the reason still aborts the child; only the explanation is skipped."}},required:["task_id"]},handler:Zi,sideEffect:"mutates-state",planModeAllowed:!0,toClassifierInput:i(e=>{let t=e,n=typeof t?.task_id=="string"?t.task_id:"<no-task_id>",r=typeof t?.reason=="string"?t.reason.slice(0,80):"";return`TaskStop(${n})${r?": "+r:""}`},"toClassifierInput")},{name:"task_output",description:"Peek at the current state of a child task launched via dispatch_child_task. Returns a structured snapshot (status, iteration count, recent tool-call breadcrumbs, and final text once the child settles). Normal Worker usage is task_output({task_id}) with block omitted/false for a status snapshot. If block:true is used, timeout_ms is only a bounded read-window cap; retrieval_status=wait_expired with status=running means the child is still running, not timed out or failed. Prefer idle-yield (end the turn text-only) for normal waits. Coordinator-only: child agents cannot call this tool. Completed children's snapshots remain queryable for the lifetime of the parent runner; very old snapshots may be evicted under a per-runner cap.",input_schema:{type:"object",properties:{task_id:{type:"string",description:"Target child task_id (from a prior dispatch_child_task call). Returns retrieval_status=not_found if the task was never dispatched or its snapshot has been evicted."},block:{type:"boolean",description:"Optional compatibility knob. When false or omitted (normal Worker usage), return the current snapshot immediately. When true, wait only within a bounded read window (up to timeout_ms) before returning the snapshot; wait expiry is not child failure. Idle-yield (end turn text-only) is the canonical wait."},timeout_ms:{type:"number",description:"Max bounded read-window time in milliseconds when block:true. Default 30000 (30s), max 120000 (120s). Ignored when block:false. If the read window expires, returns the current snapshot with retrieval_status=wait_expired; this is not a child task timeout."}},required:["task_id"]},handler:Eu,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(e=>{let t=e,n=typeof t?.task_id=="string"?t.task_id:"<no-task_id>",r=t?.block===!0?" (block)":"";return`TaskOutput(${n})${r}`},"toClassifierInput")},{name:"web_search",description:'Search the web for discovery-oriented results with explicit trust and freshness signaling. Use this for "discover what is out there" queries when you do not yet have a specific URL \u2014 researching a library before integrating it, finding canonical docs for an API, identifying current best-practice patterns. Output includes provenance + trust signals; when relaying answers to the user, cite sources back in markdown link format (`[title](url)`). Pair with `web_fetch` to follow up on a specific result. Search results are geographically scoped (US-based) and freshness metadata reflects when each source was last indexed, not the moment of your query \u2014 interpret "current X" with that caveat. For finding code or documentation INSIDE the repo, prefer `grep` / `code_search` / `semantic_lookup` \u2014 those operate on the local checkout and do not consume network turns.',input_schema:{type:"object",properties:{query:{type:"string",description:"Search query to run"},limit:{type:"number",description:"Maximum number of search results to return"},provider_id:{type:"string",description:"Optional extension capability provider id for provider-backed search"}},required:["query"]},handler:vi,sideEffect:"reads-network",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"web_fetch",description:'Fetch a specific remote source by URL and return bounded text with provenance and trust hints. The handler converts HTML to markdown and caches each unique URL for a short window so repeated reads within the same task are free. If the response is a redirect (3xx), the tool stops and reports the new target URL \u2014 re-issue `web_fetch` against that new URL rather than chasing the redirect manually, so the cache + provenance line up with what the user actually sees. For GitHub URLs specifically (`github.com/...` / `raw.githubusercontent.com/...`), prefer `bash` with the `gh` CLI when available \u2014 `gh api` / `gh pr view` / `gh issue view` are faster, return structured output, and avoid markdown-conversion artifacts; using `web_fetch` on a github.com URL when `gh` would work is the most common "tool waste" pattern in this surface. Despite the `mutates-network` side-effect classification (some providers route POST requests through this surface), the LLM-facing semantics are read-only. Use `web_search` first when you do not yet have a specific URL.',input_schema:{type:"object",properties:{url:{type:"string",description:"Remote URL to fetch"},provider_id:{type:"string",description:"Optional extension capability provider id for provider-backed fetch"},capability_id:{type:"string",description:"Optional provider capability id for provider-backed fetch"}}},handler:_i,sideEffect:"mutates-network",toClassifierInput:i(e=>{let t=e;return`WebFetch ${typeof t?.url=="string"?t.url:"<no-url>"}`},"toClassifierInput")},{name:"code_search",description:'Search local repository code with lower-noise output than ad hoc shell grep. Returns ranked matches with file:line refs and surrounding context, filtered by repo-aware heuristics (skips minified bundles, generated artifacts, lockfiles by default). Prefer `code_search` over `grep` for "find symbol X" / "where is this string used" investigations spanning the whole repo \u2014 the noise reduction saves token budget on the result side. Prefer raw `grep` when you need exact byte-level matching (regex anchors, character classes, multiline patterns) or when scoping is already narrow (a known single file or small subdirectory). For symbol-level intelligence (callers, callees, imports), use `symbol_context` instead \u2014 it pre-resolves the relationships that a text search would only hint at.',input_schema:{type:"object",properties:{query:{type:"string",description:"String query to search for"},path:{type:"string",description:"Optional file or directory scope for the search"},limit:{type:"number",description:"Maximum number of matches to return"},case_sensitive:{type:"boolean",description:"Whether the query should be matched case-sensitively"},provider_id:{type:"string",description:"Optional extension capability provider id for provider-backed code search"}},required:["query"]},handler:Ei,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"semantic_lookup",description:'Search repository intelligence for symbol-, module-, or process-aware semantic matches. "Repository intelligence" here is a pre-indexed structural view of the codebase (symbol definitions, module boundaries, process flows); `semantic_lookup` queries that index rather than scanning raw text. Use it when the question is structural ("what does symbol X relate to", "which module owns concept Y", "what flow does entry Z drive") rather than textual. The `kind` parameter narrows the lookup category (`symbol` / `module` / `process` / `auto`); `target_path` scopes to a subtree. `refresh: true` rebuilds the underlying index \u2014 expensive \u2014 so only set it when you have reason to believe the index is stale (e.g., right after a large bulk edit). For exact text match prefer `grep`; for ranked text search prefer `code_search`; to read a file directly prefer `read`.',input_schema:{type:"object",properties:{query:{type:"string",description:"Semantic query to resolve inside repository intelligence"},kind:{type:"string",enum:["auto","symbol","module","process"],description:"Optional semantic lookup category"},target_path:{type:"string",description:"Optional path hint to scope the semantic lookup"},limit:{type:"number",description:"Maximum number of semantic matches to return"},refresh:{type:"boolean",description:"When true, refresh repository intelligence before searching"}},required:["query"]},handler:Si,sideEffect:"readonly",toClassifierInput:i(e=>$n("semantic_lookup",e),"toClassifierInput")},{name:"mcp_search",description:"Search active MCP tools, resources, and prompts through the shared capability runtime. The KodaX MCP surface is a meta-tool layer: capabilities live on remote MCP servers, and `mcp_search` is the discovery entry point. Returns capability ids in the exact `mcp:<server-id>:<kind>:<capability-name>` format, for example `mcp:git-nexus:tool:list_branches`. Copy the Locator/ID from `mcp_search` exactly, including the `mcp:` prefix; do not rebuild or shorten it. Batch-call `mcp_describe` on the ids you actually plan to use rather than describing every result \u2014 describing capabilities you will not call wastes a turn. The `kind` filter (`tool` / `resource` / `prompt`) narrows the family: tools are the only family that can mutate remote state via `mcp_call`; resources are reads via `mcp_read_resource`; prompts are templates via `mcp_get_prompt`. The `server` filter scopes to a specific MCP server when multiple are connected.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search query. Omit or pass an empty string to browse active MCP catalogs."},server:{type:"string",description:"Optional MCP server id filter"},kind:{type:"string",enum:["tool","resource","prompt"],description:"Optional MCP capability family filter"},limit:{type:"number",description:"Maximum number of search results to return"}}},handler:Ri,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"mcp_describe",description:"Describe a specific MCP capability by id, including its full JSON Schema, trust tier, and provenance. Use this when `mcp_search` returned a candidate id and you need to see the exact parameter shape before invoking it. `mcp_describe` is a pure read against the MCP server catalog \u2014 safe to call freely, but redundant: only describe capabilities you actually plan to call. The schema returned is the source of truth for `mcp_call.args` / `mcp_get_prompt.args` shape; do not guess argument names from the capability id alone.",input_schema:{type:"object",properties:{id:{type:"string",description:"MCP capability id from mcp_search"}},required:["id"]},handler:Oi,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"mcp_call",description:"Invoke an MCP tool capability by id with structured arguments. This is the ONLY side-effecting MCP entry point \u2014 the underlying capability can mutate remote state (file writes, database updates, API calls). Treat each `mcp_call` with the same care as a `bash` command against an unfamiliar shell: confirm the capability is what you intend by `mcp_describe` first when uncertain. The `id` must be the exact `mcp:<server-id>:tool:<tool-name>` id from `mcp_search`, for example `mcp:git-nexus:tool:list_branches`; copy it exactly, including the `mcp:` prefix. `args` must match the JSON Schema returned by `mcp_describe`. For pure reads use `mcp_read_resource` (no mutation) or `mcp_get_prompt` (template retrieval) instead \u2014 `mcp_call` is overkill when the goal is just reading.",input_schema:{type:"object",properties:{id:{type:"string",description:"MCP tool capability id from mcp_search"},args:{type:"object",description:"Structured arguments for the MCP tool call"}},required:["id"]},handler:Ii,sideEffect:"mutates-network",toClassifierInput:i(e=>{let t=e,n=typeof t?.id=="string"?t.id:"<no-id>";return Yv(n,t?.args??{})},"toClassifierInput")},{name:"mcp_read_resource",description:'Read an MCP resource capability by id. Resources are server-published read-only data sources \u2014 file contents, query results, config snapshots \u2014 and `mcp_read_resource` retrieves them without invoking remote code. Unlike `mcp_call`, this entry point cannot mutate remote state, so it is safe to use during plan-mode preview. The `id` must be the exact `mcp:<server-id>:resource:<resource-name>` id from `mcp_search` (with `kind="resource"` filter); copy it exactly, including the `mcp:` prefix. Use `mcp_call` instead when the capability is registered as a tool (mutation-capable), and `mcp_get_prompt` when it is a templated prompt.',input_schema:{type:"object",properties:{id:{type:"string",description:"MCP resource capability id from mcp_search"}},required:["id"]},handler:Li,sideEffect:"reads-network",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"mcp_get_prompt",description:'Retrieve an MCP prompt capability by id, expanding any template arguments. Prompts are server-published reusable text templates (system prompt snippets, structured query templates, task framings); `mcp_get_prompt` returns the expanded text after substituting `args`. Read-only with respect to remote state \u2014 the server resolves the template but does not run code. The `id` must be the exact `mcp:<server-id>:prompt:<prompt-name>` id from `mcp_search` (with `kind="prompt"` filter); copy it exactly, including the `mcp:` prefix. `args` must match the prompt template variables (which `mcp_describe` will list).',input_schema:{type:"object",properties:{id:{type:"string",description:"MCP prompt capability id from mcp_search"},args:{type:"object",description:"Optional arguments for the MCP prompt"}},required:["id"]},handler:Mi,sideEffect:"reads-network",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"worktree_create",description:"Create a new git worktree with an isolated branch for safe agent work.",input_schema:{type:"object",properties:{branch_name:{type:"string",description:"Optional explicit branch name"},description:{type:"string",description:"Optional description to auto-generate branch name from"}}},handler:On,sideEffect:"mutates-fs",toClassifierInput:i(e=>{let t=e;return`WorktreeCreate ${typeof t?.branch_name=="string"?t.branch_name:typeof t?.description=="string"?`<auto from "${t.description.slice(0,40)}">`:"<auto>"}`},"toClassifierInput")},{name:"worktree_remove",description:"Remove a git worktree and optionally its branch.",input_schema:{type:"object",properties:{action:{type:"string",enum:["keep","remove"],description:"Whether to keep or remove the worktree directory and branch"},worktree_path:{type:"string",description:"Absolute path to the worktree directory"},discard_changes:{type:"boolean",description:"If true, bypass safety checks for uncommitted changes or local commits"}},required:["action","worktree_path"]},handler:In,sideEffect:"mutates-fs",toClassifierInput:i(e=>{let t=e,n=t?.discard_changes?" [discard_changes]":"";return`WorktreeRemove ${t?.action??"<no-action>"} ${t?.worktree_path??"<no-path>"}${n}`},"toClassifierInput")},{name:"undo",description:"Revert the last file modification.",input_schema:{type:"object",properties:{}},handler:Io,sideEffect:"mutates-fs",toClassifierInput:i(()=>"Undo: revert last file modification","toClassifierInput")},{name:"ask_user_question",description:'Ask the user a question. Supports single-select (default), multi-select, or free-text input. When you have multiple independent questions, use the "questions" array \u2014 each question is presented separately with its own options. Do NOT combine multiple questions into a single question string, because combining forces the user to mentally disambiguate option combinations themselves, which usually breaks the option-button UI.',input_schema:{type:"object",properties:{question:{type:"string",description:'The question to ask the user. Use this for a single question. For multiple independent questions, use the "questions" array instead.'},questions:{type:"array",description:'Multiple independent questions (1-4). Each question is presented separately with its own options. Use this instead of combining multiple questions into a single "question" string. Takes precedence over "question"+"options" when provided.',items:{type:"object",properties:{question:{type:"string",description:"The question text"},header:{type:"string",description:'Short label (max 12 chars) shown in progress indicator, e.g. "\u73AF\u5883" or "Deploy"'},options:{type:"array",description:"Available options for this question.",items:{type:"object",properties:{label:{type:"string",description:"Display label for this option"},description:{type:"string",description:"Optional description of this option"},value:{type:"string",description:"Optional value to return (defaults to label)"}},required:["label"]}},multi_select:{type:"boolean",description:"Allow multiple selections for this question. Returns an array of the selected values."},min_selections:{type:"integer",description:"Minimum number of options the user must select. Only applies when multi_select is true."},max_selections:{type:"integer",description:"Maximum number of options the user may select. Only applies when multi_select is true."}},required:["question","options"]},minItems:1,maxItems:4},kind:{type:"string",enum:["select","input"],description:'Interaction kind. "select" (default) shows options for the user to pick from. "input" shows a free-text prompt for the user to type anything. Use "input" when the user needs to provide an open-ended answer (e.g. step combinations like "1,3,5", version numbers, custom text).'},options:{type:"array",description:'Available options for the user to choose from. Required for kind="select", ignored for kind="input".',items:{type:"object",properties:{label:{type:"string",description:"Display label for this option"},description:{type:"string",description:"Optional description of this option"},value:{type:"string",description:"Optional value to return (defaults to label)"}},required:["label"]}},multi_select:{type:"boolean",description:'Allow the user to select multiple options (space to toggle, enter to confirm). Only applies to kind="select". Returns an array of the selected values.'},min_selections:{type:"integer",description:"Minimum number of options the user must select. Only applies when multi_select is true."},max_selections:{type:"integer",description:"Maximum number of options the user may select. Only applies when multi_select is true."},default:{type:"string",description:"Optional default choice (for select) or default text (for input)"}},required:["question"]},handler:Lo,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"get_goal",description:"Read the current goal for this session, including status, budget, token and elapsed-time usage, and remaining token budget.",input_schema:{type:"object",properties:{}},handler:$u,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"create_goal",description:"Create a goal only when explicitly requested by the user or system/developer instructions; do not infer goals from ordinary tasks. Set token_budget only when an explicit token budget is requested. Fails if a goal exists; use update_goal only for status changes.",input_schema:{type:"object",properties:{objective:{type:"string",description:"The long-running objective the agent should pursue across turns. A clear, concrete sentence describing the target end-state."},token_budget:{type:"number",description:"Optional positive integer token budget for the entire goal. Omit when the user did not request a budget."}},required:["objective"]},handler:Ru,sideEffect:"mutates-state",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"update_goal",description:`Mark the current goal complete or blocked.
304
319
 
305
320
  Set status to complete only when the objective is achieved and no required work remains. Completion triggers a runtime verifier; if the verifier does not confirm, the call is rejected and you must keep working.
306
321
 
307
322
  Set status to blocked only when the goal cannot proceed without external unblock, and the same blocking condition has persisted across recent goal turns. The runtime counter rejects blocked status until the same blocker_kind has repeated for 3 consecutive turns.
308
323
 
309
- Pause, resume, and budget-limited transitions are controlled by the user, not this tool. Do not call to stop work \u2014 only call when the objective is truly achieved or truly blocked.`,input_schema:{type:"object",properties:{status:{type:"string",enum:["complete","blocked"],description:'New status. "complete" requires verifier confirmation; "blocked" requires the same blocker_kind across 3 consecutive turns.'},blocker_kind:{type:"string",description:'Required when status=blocked. A short identifier for the persistent obstacle (e.g. "awaiting-user-permission", "missing-dependency"). The runtime counter compares this string across turns.'}},required:["status"]},handler:Qd,sideEffect:"mutates-state",planModeAllowed:!1,toClassifierInput:i(()=>"","toClassifierInput")},{name:"exit_plan_mode",description:"Exit plan mode by presenting the finalized plan to the user for approval. On approval, the session flips to accept-edits and implementation can proceed. On rejection, the session remains in plan mode so the plan can be revised. Use this tool once the plan is ready for user review \u2014 do NOT combine with set_permission_mode. Parent-only: requires an interactive approval UI (wired only in REPL sessions).",input_schema:{type:"object",properties:{plan:{type:"string",description:"The finalized plan to present to the user. Include the full plan content, not a summary, so the user can make an informed approval decision. Keep the plan tight: at most 40 lines total, 3 bullet-depth levels, one sentence per bullet. If the plan exceeds this budget, split it into phases and present only the current phase \u2014 the user can approve phase-by-phase."}},required:["plan"]},handler:gi,sideEffect:"mutates-state",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"todo_update",description:'Drive the visible plan checklist so the user sees real-time progress \u2014 single-item PATCH plus status transition for ONE existing todo item. `op="update"` is the default (omit `op` for back-compat); target one item by `id` and change its status, patch its fields, or both in one call.\n\n## When to Use This Tool\n\n- BEFORE starting work on an item \u2014 flip it to `in_progress` and supply `activeForm` (present-continuous form of the subject; e.g. subject "Run failing tests" \u2192 activeForm "Running failing tests") so the spinner reflects what you are doing right now.\n- AFTER finishing work on an item \u2014 flip it to `completed` before moving on, so the plan list stays current. If the item carries an `evaluator` hint, the runner runs the deterministic check on transition and surfaces stderr on failure.\n- WHEN requirements clarify mid-task \u2014 patch `subject` and/or `description` to refine the row in place (e.g. "Run failing tests" \u2192 "Run failing tests AND clean up tmp").\n- WHEN an attempt clearly failed and needs retry \u2014 set status to `failed`.\n- WHEN the item turned out to be unnecessary (e.g. two obligations merged into one) \u2014 set status to `skipped`.\n- WHEN you decide mid-execution to drop an item the user no longer needs \u2014 set status to `cancelled` (UI shows strikethrough as a visible breadcrumb); use `deleted` instead if the item was wholly off-plan and a breadcrumb would just clutter.\n\n## When NOT to Use This Tool\n\n- To ADD a new item \u2014 call `todo_create` instead (one call per planned step, batched). `todo_update` only mutates EXISTING items.\n- When the item is already in the target status \u2014 a redundant update is a silent no-op and clutters the transcript.\n- When uncertain about an item\'s current state \u2014 call `todo_get` first; runner-side auto-handlers may have flipped statuses between your turns, and mutating on a stale view produces silent no-op patches.\n- `op="init"` is reserved for runner-side seeding only. LLMs should never call it \u2014 it destructively replaces the whole list, dropping any item not echoed back, and weaker models routinely under-echo and lose completed work.\n\n## Status Transitions\n\nOnly ONE item per owner should be `in_progress` at any time \u2014 finish or fail the current item before starting the next. Valid statuses: `in_progress`, `completed`, `failed`, `skipped`, `cancelled`, `deleted`. `"pending"` is intentionally not allowed \u2014 items start pending automatically and only the runner moves them back to pending after a revise verdict. Prefer `deleted` over `cancelled` when the item was wholly off-plan; prefer `cancelled` when the user benefits from seeing the discarded record.\n\n## Field Patches (status optional when only patching)\n\n- `subject` (non-empty string) replaces the brief imperative title shown in the row.\n- `description` (string; empty clears) replaces the fuller context shown by `todo_get`.\n- `activeForm` is required with `in_progress`; for other statuses the previous value is preserved but irrelevant.\n- `note` is optional free-text reason; when omitted, any pre-existing note is preserved.\n- `evaluator` ("build" | "test" | "lint") replaces the deterministic evaluator hint.\n- `metadata` (object | null) \u2014 shallow-merge: top-level keys overwrite; a value of `null` inside the object DELETES that key (mixed merge+delete is supported, e.g. `{newKey: "v", oldKey: null}`); pass the whole field as `null` to clear ALL metadata.\n- Patch fields can be combined with a status transition in a single call.\n\n## Error Handling\n\n- `ok=false` with reason "Unknown todo id" \u2014 inspect the listed valid ids and retry, or call `todo_list` to refresh.\n- `ok=false` with reason "todo_update is not active" \u2014 the current run has no plan list; continue without further `todo_update` calls.\n- `ok=false` with reason "blocked-by-hook" (or an extension-supplied string) \u2014 an extension policy rejected the transition; re-read the visible plan and revise your approach before retrying.',input_schema:{type:"object",properties:{op:{type:"string",enum:["init","update"],description:'Operation mode. Default "update" when omitted \u2014 mutate one item by `id`. "init" (legacy / runner-side seeding only) replaces the whole list with `items`; LLMs should NOT call it \u2014 it destructively drops any item not echoed back. Use a batch of `todo_create` calls for both initial commitment and mid-task plan growth.'},items:{type:"array",description:'op="init" (legacy / runner-side only) payload. Each entry: {id: non-empty string (unique within list), subject: non-empty string (brief title), description?: string (fuller context), activeForm?: present-continuous string}. LLMs should use a batch of `todo_create` calls instead.',items:{type:"object",properties:{id:{type:"string",description:'Unique non-empty item id (e.g. "todo_1").'},subject:{type:"string",description:'Brief imperative title shown in the plan-list row (e.g. "Run failing tests").'},description:{type:"string",description:"Optional fuller context / work instructions read when this item is later picked up (todo_get surface). Multi-line OK. Skip when subject alone is enough."},activeForm:{type:"string",description:'Optional present-continuous form (e.g. "Running failing tests") shown by the spinner when this item flips to in_progress.'},evaluator:{type:"string",enum:["build","test","lint"],description:'Optional per-step deterministic evaluator. When set and the item flips to "completed", the runner runs `npm run build` / `npm test` / `npm run lint` accordingly; failure surfaces stderr in your next tool result. Use sparingly \u2014 only on milestone steps.'}},required:["id","subject"]}},id:{type:"string",description:'op="update" only. The id of the todo item to update (e.g. "todo_3"). Must match a current valid id in the plan list.'},status:{type:"string",enum:["in_progress","completed","failed","skipped","cancelled","deleted"],description:'op="update" only. New status. Optional \u2014 when omitted you may still patch subject/description/activeForm/note/evaluator/metadata. "pending" is intentionally not allowed \u2014 items start as pending automatically and only the runner moves them back to pending after a revise verdict. "cancelled" signals a Worker-driven mid-execution decision to drop the item; UI shows strikethrough. "deleted" removes the item from the visible list entirely \u2014 use when the item turned out to be wholly irrelevant and you do not want a strikethrough breadcrumb. The matching extension event is `todo:deleted`.'},note:{type:"string",description:'op="update" only. Optional free-text reason or detail. When omitted, any pre-existing note on the item is preserved.'},activeForm:{type:"string",description:'op="update" only. Present-continuous form of the item subject (e.g. "Running failing tests"). Required when status="in_progress" so the spinner can show the user what you are doing right now. Omitted on completed/failed/skipped (the previous activeForm is preserved but irrelevant once the item leaves in_progress).'},subject:{type:"string",description:'op="update" only. Optional. When provided, REPLACES the brief imperative title shown in the plan-list row. Use for mid-task plan refinement (e.g. "Run failing tests" \u2192 "Run failing tests AND clean up tmp"). Must be a non-empty string.'},description:{type:"string",description:'op="update" only. Optional. When provided, REPLACES the fuller context (work instruction). Multi-line OK. Pass empty string to clear an existing description.'},evaluator:{type:"string",enum:["build","test","lint"],description:`op="update" only. Optional. When provided, REPLACES the item's deterministic evaluator hint. When the item later flips to "completed", the runner runs the corresponding deterministic check and surfaces stderr on failure.`},metadata:{type:"object",description:'op="update" only. Optional opaque key-value bag. Semantics: shallow-merge \u2014 top-level keys overwrite (nested objects are NOT deep-merged); a value of `null` inside the object DELETES that key from existing metadata; mixed merge+delete in one call is supported (e.g. `{newKey: "v", oldKey: null}`); pass the whole `metadata` field as `null` (NOT inside an object) to clear ALL metadata (handler accepts top-level null even though the JSON Schema is `type:"object"`). The UI does NOT render metadata; it is for extension hooks / eval harnesses.'}}},handler:tf,sideEffect:"mutates-state",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"todo_create",description:'Insert ONE new pending item into the visible plan list \u2014 purely additive, existing items untouched. The store auto-generates the id (monotonic `todo_<n>`); never pass an id \u2014 any caller-supplied id is rejected at the schema layer.\n\n## When to Use This Tool\n\n- AT THE START of a non-trivial multi-step task \u2014 commit the full plan up front by batching one `todo_create` call per planned step in the same response, so the user sees the intended trajectory.\n- WHEN you receive a user request with multiple distinct sub-tasks \u2014 capture each as its own item.\n- WHEN you discover an additional step mid-task \u2014 add it additively so the user sees the plan growing rather than the original list being silently rewritten.\n- BEFORE fanning out to child workers via `dispatch_child_task` \u2014 the plan list is the natural anchor for the work each child will execute.\n\n## When NOT to Use This Tool\n\n- For a single straightforward operation that completes in one step \u2014 skip the plan list entirely.\n- For purely informational responses (answering a question, explaining code) where there is no execution work to track.\n- When an equivalent item already exists in the plan list \u2014 call `todo_list` first if unsure; duplicate items confuse the user.\n- For the actual work itself \u2014 `todo_create` only RECORDS planned work; you still need to perform the real operations (read, edit, run, etc.) in subsequent tool calls.\n\n## Fields\n\n- `subject` (required) \u2014 brief imperative title shown in the plan-list row (e.g. "Audit handleAuth callers").\n- `description` (optional) \u2014 fuller context / work instructions read when this item is later picked up via `todo_get`; multi-line OK; NOT rendered in the compact row.\n- `activeForm` (optional) \u2014 present-continuous form (e.g. "Auditing handleAuth callers") shown by the spinner when this item later flips to `in_progress` via `todo_update`.\n- `evaluator` (optional, "build" | "test" | "lint") \u2014 runs the corresponding deterministic check when the item flips to "completed". Use sparingly, only on milestone steps with a real ground-truth check.\n- `metadata` (optional) \u2014 opaque key-value bag carried alongside the item for extension hooks / observability; the UI does NOT render it.\n\nReturns `{ok: true, id: "todo_<n>"}` on success or `{ok: false, reason: "..."}` when the store is not wired, validation fails, or an extension hook blocks the create.',input_schema:{type:"object",properties:{subject:{type:"string",description:'Brief imperative title shown in the plan-list row (e.g. "Audit handleAuth callers").'},description:{type:"string",description:"Optional fuller context / work instructions read when this item is later picked up via todo_get. Multi-line OK; NOT rendered in the compact row. Skip when subject alone is enough."},activeForm:{type:"string",description:'Optional present-continuous form (e.g. "Running failing tests"). Shown by the spinner when this item later flips to `in_progress`.'},evaluator:{type:"string",enum:["build","test","lint"],description:'Optional per-step deterministic evaluator. When set and the item later flips to "completed" via todo_update, the runner runs `npm run build` / `npm test` / `npm run lint` accordingly; failure surfaces stderr in your next tool result. Use sparingly \u2014 only on milestone steps with a real ground-truth check.'},metadata:{type:"object",description:"Optional opaque key-value bag carried alongside the item. Used by extension hooks / eval harnesses. The UI does NOT render metadata. Omit if you have nothing structured to attach."}},required:["subject"]},handler:of,sideEffect:"mutates-state",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"todo_list",description:'Read-only query that returns the current visible plan list as JSON. Never mutates the store.\n\n## When to Use This Tool\n\n- BEFORE deciding the next move \u2014 confirm what items are pending and which is currently `in_progress`.\n- AFTER an "Unknown todo id" error \u2014 see the canonical valid-id set before retrying `todo_update` or `todo_get`.\n- WHEN refining a plan \u2014 compare a proposed new step against existing items to avoid duplicates.\n- AFTER a long quiet stretch \u2014 re-sync with any auto-handler-driven status flips before continuing.\n\n## When NOT to Use This Tool\n\n- When you already know the exact id and want one item\'s full detail \u2014 call `todo_get` directly.\n- When no plan list is active \u2014 the call returns `{ok: false, reason: "todo_list is not active ..."}`; further `todo_*` calls in this run will also be inactive.\n\nReturns `{ok: true, count: N, items: [{id, subject, status, description?, activeForm?, note?}, ...]}` on success. Pair with `todo_create` (additive), `todo_update` (mutate), or `todo_get` (full single-item detail).',input_schema:{type:"object",properties:{}},handler:rf,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"todo_get",description:'Read-only single-item lookup. Returns the full TodoItem detail for one id \u2014 subject, optional description, status, activeForm, note, evaluator, metadata.\n\n## When to Use This Tool\n\n- BEFORE calling `todo_update` when uncertain about an item\'s current state \u2014 runner-side auto-handlers may have flipped statuses between your turns, and mutating on a stale view produces silent no-op patches.\n- WHEN PICKING UP an item to work on \u2014 the full `description` carries the work instruction; the compact row label (`subject`) alone is often not enough.\n- AFTER an "Unknown todo id" error on `todo_update` \u2014 call `todo_list` first to see all ids, then `todo_get` to drill into the specific one.\n\n## When NOT to Use This Tool\n\n- For a high-level overview of all items \u2014 call `todo_list` instead.\n- When you already have a clear status flip + field patch to apply \u2014 call `todo_update` directly; an extra `todo_get` round-trip adds latency without changing the outcome.\n\nReturns `{ok: true, item: {...}}` on success or `{ok: false, reason: "..."}` when the store is not wired or the id is unknown (the reason carries the canonical valid-id list).',input_schema:{type:"object",properties:{id:{type:"string",description:'The todo id to retrieve (e.g. "todo_3"). Must match a current valid id.'}},required:["id"]},handler:sf,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"repo_overview",description:"Summarize the repository structure, key areas, entry hints, and stored repo-intelligence snapshot for the current workspace. Returns a compact top-down map: monorepo packages or top-level directories, entry files, primary languages, build/test commands. Use this once at session start (or after switching into an unfamiliar area) to orient yourself before issuing targeted reads \u2014 calling it at the start of every task is wasteful because the snapshot rarely changes within a session. The `refresh` flag rebuilds the snapshot; expensive, so only set it after a structural change to the workspace (new package added, large directory move). For drilling into a specific module, use `module_context` instead.",input_schema:{type:"object",properties:{target_path:{type:"string",description:"Optional path inside the workspace to resolve the repository root from"},refresh:{type:"boolean",description:"When true, rebuild the repo overview snapshot before returning it"}}},handler:Mo,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"changed_scope",description:'Analyze which files, areas, and categories are touched by the current git diff or a comparison range. This is the canonical entry point for any review / change-audit / commit-prep workflow \u2014 call it first to see the change surface before issuing per-file diffs. Returns files grouped by area/category (e.g., "tests", "docs", "core") with a one-line summary per file. The `scope` parameter selects which change set: `unstaged` (working tree vs HEAD), `staged` (index vs HEAD), `all` (working tree + index vs HEAD, default), `compare` (HEAD vs base_ref). Pair with `changed_diff_bundle` to fetch the actual diffs for the files identified.',input_schema:{type:"object",properties:{target_path:{type:"string",description:"Optional path inside the workspace to resolve the repository root from"},scope:{type:"string",enum:["unstaged","staged","all","compare"],description:"Which git change set to inspect. Defaults to all."},base_ref:{type:"string",description:"Base ref used when scope=compare. Defaults to HEAD~1."},refresh_overview:{type:"boolean",description:"When true, rebuild the repo overview snapshot before analyzing changes"}}},handler:Po,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"changed_diff",description:"Read a paged diff slice for a specific changed file. Prefer this over broad git diff output during large reviews.",input_schema:{type:"object",properties:{target_path:{type:"string",description:"Optional path inside the workspace to resolve the repository root from"},base_ref:{type:"string",description:"Optional base git ref for compare-range review"},target_ref:{type:"string",description:"Optional target git ref for compare-range review (defaults to HEAD when base_ref is provided)"},path:{type:"string",description:"Changed file path to inspect, relative to the workspace root or absolute inside it"},offset:{type:"number",description:"1-based diff line offset for pagination"},limit:{type:"number",description:"Maximum diff lines to return in this slice"},context_lines:{type:"number",description:"Unified diff context lines to request"}},required:["path"]},handler:Do,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"changed_diff_bundle",description:"Read diff slices for multiple changed files in one call. Prefer this for large reviews before drilling down with changed_diff.",input_schema:{type:"object",properties:{target_path:{type:"string",description:"Optional path inside the workspace to resolve the repository root from"},base_ref:{type:"string",description:"Optional base git ref for compare-range review"},target_ref:{type:"string",description:"Optional target git ref for compare-range review (defaults to HEAD when base_ref is provided)"},paths:{type:"array",description:"Changed file paths to inspect in one bundle, relative to the workspace root or absolute inside it",items:{type:"string"}},offset:{type:"number",description:"1-based diff line offset applied to each path in the bundle"},limit_per_path:{type:"number",description:"Maximum diff lines to return per path in this bundle"},context_lines:{type:"number",description:"Unified diff context lines to request"}},required:["paths"]},handler:jo,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"module_context",description:'Return a task-shaped module capsule with dependencies, entry files, top-level symbols, test files, docs, and follow-up handles for further drill-down. Use this when about to read 3+ files in the same module \u2014 the capsule replaces that exploration round-trip with one structured response. Prefer `module_context` over raw `read`+`grep` for "what does this module do / what depends on what" questions. When the question is about a single function or class, use `symbol_context` instead \u2014 it is cheaper because it scopes to one symbol. When you only need exact file content (line numbers, byte-level text), fall back to `read` after the capsule narrows the target. `refresh: true` rebuilds the underlying repo-intel index, which is expensive \u2014 only set it when you have reason to believe the index is stale.',input_schema:{type:"object",properties:{module:{type:"string",description:"Module id, label, or package name to inspect"},target_path:{type:"string",description:"Optional path used to infer the enclosing module"},refresh:{type:"boolean",description:"When true, rebuild repo intelligence before returning the module capsule"}}},handler:ri,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_definition",description:"Jump to where the symbol at a specific line/column is DEFINED, using the language server's live view of the current code. Use this when you are looking at a usage and need its exact definition site \u2014 it resolves through imports, re-exports, and overloads the way the compiler does, which `grep` cannot. Give the 1-based line and column of the symbol as it appears in the file you just read. Prefer this when you want the precise single definition of the symbol right where you are; prefer `symbol_context` when you want the repo-wide usage graph (callers/callees) of a named symbol. Needs a language server for the file's language installed (TypeScript/JS, Python, Go, Rust, Java); returns install guidance otherwise.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol (defaults to the line start)"}},required:["path","line"]},handler:Pl,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_hover",description:"Show the type, signature, and doc of the symbol at a specific line/column, as the language server sees it. Use this to confirm an inferred type, a function's parameter/return types, or a value's declared type before editing \u2014 it reflects the real compiler state, including generics resolved in context, so you do not have to open and read the definition just for its signature. Give the 1-based line and column of the symbol. Needs the matching language server installed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol"}},required:["path","line"]},handler:Nl,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_references",description:"List every place the symbol at a specific line/column is USED (including its declaration), from the language server. Use this before renaming or changing a symbol's signature to see exactly what would break \u2014 it finds the structural references `grep` misses (re-exports, aliased imports) and skips the string/comment matches `grep` wrongly includes. Give the 1-based line and column. When you only have a NAME and want a quick repo-scope blast-radius estimate, use `impact_estimate`; use `lsp_references` when you have the exact position and want the compiler-accurate reference list. Needs the matching language server installed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol"}},required:["path","line"]},handler:Dl,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_document_symbols",description:"Outline the symbols (classes, functions, methods, fields) declared in a single file, with their lines, from the language server. Use this to get oriented in an unfamiliar file without reading all of it, or to find the line of a member before an `lsp_definition` / `lsp_hover` / `edit`. For a repo-scope structural view across modules use `module_context`; `lsp_document_symbols` is the precise single-file outline. Needs the matching language server installed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File to outline"}},required:["path"]},handler:jl,sideEffect:"readonly",toClassifierInput:i(e=>En("relationship_scan",e),"toClassifierInput")},{name:"lsp_workspace_symbols",description:"Search project-wide symbols by name through available language servers. Use this when you know a class/function/type name but not its file, and want compiler-indexed candidates before reading files or running broader text search. An empty query asks the server for its broad symbol list when supported.",input_schema:{type:"object",properties:{query:{type:"string",description:"Symbol query text; may be empty for a broad server-supported listing"}}},handler:Fl,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_implementation",description:"Jump from an interface, abstract method, or declaration site to implementation locations using the language server. Use this when definition only lands on a contract and you need the concrete implementers before changing behavior.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol"},column:{type:"number",description:"Alias for character"}},required:["path","line"]},handler:Ul,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_prepare_call_hierarchy",description:"Prepare call hierarchy roots for the symbol at a file position. Use this to confirm the language server can identify the callable before asking for incoming or outgoing calls.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the callable symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol"},column:{type:"number",description:"Alias for character"}},required:["path","line"]},handler:ql,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_incoming_calls",description:"List language-server incoming callers for the callable at a file position. Use this for upstream/caller questions when you have the exact symbol location.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the callable symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol"},column:{type:"number",description:"Alias for character"}},required:["path","line"]},handler:Bl,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_outgoing_calls",description:"List language-server outgoing callees from the callable at a file position. Use this for downstream/callee questions when you have the exact symbol location.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the callable symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol"},column:{type:"number",description:"Alias for character"}},required:["path","line"]},handler:Wl,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"relationship_scan",description:'Answer upstream/downstream relationship questions for a symbol, module, path, or entry point in one compact scan. Returns identity, upstream callers/dependents, downstream callees/dependencies/process steps, impact, evidence, confidence, and gaps. Use this first for "what calls this", "what depends on this", "upstream/downstream", "\u8C03\u7528\u94FE", "\u4E0A\u4E0B\u6E38", and blast-radius questions before falling back to separate module_context / symbol_context / process_context calls.',input_schema:{type:"object",properties:{symbol:{type:"string",description:"Optional symbol/function/class name to trace"},module:{type:"string",description:"Optional module/package label to trace"},path:{type:"string",description:"Optional repository-relative or absolute path to trace"},entry:{type:"string",description:"Optional entry symbol or file hint for execution/process tracing"},direction:{type:"string",enum:["upstream","downstream","both"],description:"Relationship direction to emphasize. Defaults to both."},depth:{type:"number",enum:[1,2,3],description:"Requested traversal depth. Light mode reports bounded direct edges first."},target_path:{type:"string",description:"Optional path used to resolve the repository root or narrow context"},refresh:{type:"boolean",description:"When true, rebuild repo intelligence before the first relationship lookup"},include_lsp:{type:"boolean",description:"When true, attach LSP incoming/outgoing call hierarchy evidence when an LSP service is available"},include_text_search:{type:"boolean",description:"When true, attach bounded exact-name grep evidence for cross-checking static relationships"}}},handler:Il,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"symbol_context",description:'Return the definition, probable callers/callees, imports, and naming alternatives for a single repository symbol. Use this when tracing the usage of one function, class, or constant \u2014 the response pre-resolves the relationships that would otherwise take several `grep -n "symbolName"` + `read` rounds to assemble. Cheaper than `module_context` when the question is symbol-scoped rather than module-scoped (the callers/callees graph is bounded by symbol degree, not module surface). The `module` parameter disambiguates when the same symbol name appears in multiple packages. For "where is this exact string used" without symbol semantics, prefer `grep` or `code_search` instead. For impact estimation before a refactor, use `impact_estimate` \u2014 it combines symbol info with changed-scope overlap.',input_schema:{type:"object",properties:{symbol:{type:"string",description:"The symbol name to inspect"},module:{type:"string",description:"Optional module hint to disambiguate the symbol search"},target_path:{type:"string",description:"Optional path inside the workspace to resolve the repository root from"},refresh:{type:"boolean",description:"When true, rebuild repo intelligence before returning the symbol capsule"}}},handler:oi,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"process_context",description:'Return an approximate static execution/process capsule for an entry symbol, module, or path. Use this when the question is "how does this flow execute" rather than "what depends on what" \u2014 `process_context` traces from an entry point through likely call paths, giving you the sequence of file/symbol transitions without N rounds of follow-up reads. The `entry` parameter is the starting point (function name, file path, or module label); `module` is an optional disambiguating hint. Prefer over `module_context` when you care about runtime sequence, not module structure; prefer over `symbol_context` when you need the multi-hop call chain rather than just direct callers/callees. The trace is static (no runtime sampling), so it captures plausible paths, not actual hit rates.',input_schema:{type:"object",properties:{entry:{type:"string",description:"Entry symbol or file hint for the process to trace"},module:{type:"string",description:"Optional module hint used to select a process capsule"},target_path:{type:"string",description:"Optional path used to infer the relevant module or entry file"},refresh:{type:"boolean",description:"When true, rebuild repo intelligence before returning the process capsule"}}},handler:ii,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"impact_estimate",description:"Estimate the blast radius of changing a symbol, path, or module \u2014 combines repo-intelligence usage graph with current changed-scope overlap. Call this BEFORE planning a rename, refactor, or breaking change, not after the work is started \u2014 its purpose is to scope the work up front so the plan reflects reality (which packages need touching, which call sites assume current behavior, which tests must update). Returns ranked impact sites with severity hints. Prefer over guessing impact from a `grep` of the symbol name \u2014 `grep` overcounts (matches strings + comments) and undercounts (misses re-exports + structural callers). The `refresh` flag rebuilds the underlying index \u2014 expensive \u2014 so reserve it for cases where a recent large edit may have invalidated the cached graph.",input_schema:{type:"object",properties:{symbol:{type:"string",description:"Optional symbol to estimate impact for"},module:{type:"string",description:"Optional module to estimate impact for"},path:{type:"string",description:"Optional repository-relative or absolute path to estimate impact for"},target_path:{type:"string",description:"Optional path used to resolve the repository root from"},refresh:{type:"boolean",description:"When true, rebuild repo intelligence before returning the impact estimate"}}},handler:si,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"cyclic_dependencies",description:'Detect circular import/dependency chains (Tarjan SCC) over the module-level import graph. Answers "is there a dependency cycle" \u2014 the one question the 1-hop tools (impact_estimate / module_context / symbol_context) cannot. Use when refactoring or moving modules, before merging a PR that reshapes imports, or to enforce a no-cycles rule. Returns each cycle as an ordered module chain with a hop count + severity. Distinct from impact_estimate (that is 1-hop blast radius; this is reachability cycles).',input_schema:{type:"object",properties:{}},handler:Ml,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"scaffold_tool",description:"Generate a fillable ConstructionArtifact JSON skeleton for a new tool. Returns a draft you must edit before calling validate_tool / stage_construction. Use this as the FIRST step when authoring a runtime tool \u2014 do NOT hand-write the JSON shape from scratch, because the construction schema has required fields and version constraints that hand-authored JSON routinely misses, producing scaffolds the validator rejects.",input_schema:{type:"object",properties:{name:{type:"string",description:"Tool name (must match the value the LLM will use to invoke it)."},version:{type:"string",description:'Semver string. Defaults to "0.1.0".'},description:{type:"string",description:"One-sentence description of what the tool does."},capabilities:{type:"object",description:"Optional starter capabilities; defaults to {tools: []}.",properties:{tools:{type:"array",items:{type:"string"},description:"Whitelist of builtin tool names the handler may call via ctx.tools.<name>."}}}},required:["name"]},handler:fs,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"validate_tool",description:"Dry-run validate a candidate tool artifact JSON: shape sanity + AST hard rules (no-eval / no-Function-constructor / require-handler-signature) + provider schema validation. Does NOT touch disk. Use this BEFORE stage_construction to fail fast on malformed handlers.",input_schema:{type:"object",properties:{artifact_json:{type:"string",description:"The full ConstructionArtifact as a JSON string."},provider:{type:"string",description:"Provider whose tool-schema constraints are checked. Defaults to 'anthropic'."}},required:["artifact_json"]},handler:ps,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"stage_construction",description:"Persist an artifact to .kodax/constructed/<kind>s/<name>/<version>.json with status=staged. Refuses to overwrite an active artifact at the same name+version (bump the version instead). Run validate_tool first; this tool itself does not re-validate the AST or schema.",input_schema:{type:"object",properties:{artifact_json:{type:"string",description:"The full ConstructionArtifact as a JSON string."}},required:["artifact_json"]},handler:ms,sideEffect:"mutates-fs",toClassifierInput:i(e=>`StageTool: ${Cs(e?.artifact_json)}`,"toClassifierInput")},{name:"test_tool",description:"Run the full Phase 2 check pipeline (shape \u2192 AST \u2192 provider schema \u2192 handler materialize) on a staged artifact. Returns ok=true/false plus errors/warnings. On ok=true the artifact is ready for activate_tool. LLM static review is NOT run from this tool \u2014 the calling agent must drive that separately if desired.",input_schema:{type:"object",properties:{name:{type:"string",description:"Artifact name as stored on disk."},version:{type:"string",description:"Artifact version as stored on disk."},provider:{type:"string",description:"Provider whose tool-schema constraints are checked. Defaults to 'anthropic'."}},required:["name","version"]},handler:hs,sideEffect:"mutates-state",toClassifierInput:i(()=>"","toClassifierInput")},{name:"activate_tool",description:"Activate a staged-and-tested artifact. Invokes the construction policy gate, registers the handler into TOOL_REGISTRY, flips status=active. The tool is then immediately callable as `<name>` in subsequent turns. Policy: in the Ink REPL, the user sees an approve/reject dialog before activation. In non-interactive surfaces (ACP / single-shot CLI / child agents) activation is rejected by default \u2014 this prevents silent capability expansion without user consent.",input_schema:{type:"object",properties:{name:{type:"string",description:"Artifact name to activate."},version:{type:"string",description:"Artifact version to activate."}},required:["name","version"]},handler:gs,sideEffect:"mutates-state",toClassifierInput:i(e=>{let t=e;return`ActivateTool: ${t?.name??"<no-name>"}@${t?.version??"<no-version>"}`},"toClassifierInput")},{name:"scaffold_agent",description:"Generate a fillable AgentArtifact JSON skeleton for a new agent. Returns a draft you must edit before calling validate_agent / stage_agent_construction. Use this as the FIRST step when authoring a runtime agent \u2014 do NOT hand-write the JSON shape from scratch, because the construction schema has required fields and version constraints that hand-authored JSON routinely misses, producing scaffolds the validator rejects.",input_schema:{type:"object",properties:{name:{type:"string",description:"Agent name (resolver lookup key once activated)."},version:{type:"string",description:'Semver string. Defaults to "0.1.0".'},description:{type:"string",description:"One-sentence description of the agent's purpose. Becomes the lead line of `instructions`."}},required:["name"]},handler:Iu,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"validate_agent",description:"Dry-run admission audit on a candidate agent manifest JSON: schema validation + invariant.admit hooks + tool-capability cap + budget cap + handoff DAG check. Does NOT touch disk. Use this BEFORE stage_agent_construction to fail fast on rejected manifests.",input_schema:{type:"object",properties:{artifact_json:{type:"string",description:"The full AgentArtifact as a JSON string."}},required:["artifact_json"]},handler:Lu,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"stage_agent_construction",description:"Persist an agent manifest to .kodax/constructed/agents/<name>/<version>.json with status=staged. Refuses to overwrite an existing same-name+version (bump the version instead). Run validate_agent first; this tool itself does not re-run admission.",input_schema:{type:"object",properties:{artifact_json:{type:"string",description:"The full AgentArtifact as a JSON string."}},required:["artifact_json"]},handler:Mu,sideEffect:"mutates-fs",toClassifierInput:i(e=>`StageAgent: ${Cs(e?.artifact_json)}`,"toClassifierInput")},{name:"test_agent",description:"Run the agent test pipeline (manifest shape check + Runner.admit + sandbox case execution) on a staged agent. Returns ok=true/false with errors / warnings. On ok=true the agent is ready for activate_agent.",input_schema:{type:"object",properties:{name:{type:"string",description:"Agent name as stored on disk."},version:{type:"string",description:"Agent version as stored on disk."}},required:["name","version"]},handler:Pu,sideEffect:"mutates-state",toClassifierInput:i(()=>"","toClassifierInput")},{name:"activate_agent",description:"Activate a staged-and-tested agent. Invokes the construction policy gate, flips status=active, records contentHash, and registers the agent in the resolver so Runner.run can find it by name. Policy: in the Ink REPL, the user sees an approve/reject dialog before activation. In non-interactive surfaces activation is rejected by default \u2014 this prevents silent capability expansion without user consent.",input_schema:{type:"object",properties:{name:{type:"string",description:"Agent name to activate."},version:{type:"string",description:"Agent version to activate."}},required:["name","version"]},handler:Nu,sideEffect:"mutates-state",toClassifierInput:i(e=>{let t=e;return`ActivateAgent: ${t?.name??"<no-name>"}@${t?.version??"<no-version>"}`},"toClassifierInput")},{name:Me,description:"Stage a new version of YOURSELF \u2014 the active constructed agent calling this tool. Requires artifact.name === artifact.sourceAgent === your own name, plus an existing active version on disk. Runs hard checks (guardrail ratchet \u2014 cannot remove existing guardrails; reasoning ceiling; modification budget) before persisting. Then call test_agent and activate_agent on the staged version. Activation force-prompts the user (no auto-approve for self-modify) and only takes effect on the NEXT Runner.run, never within the run that submitted the change.",input_schema:{type:"object",properties:{artifact_json:{type:"string",description:"The full AgentArtifact as a JSON string. artifact.name must equal artifact.sourceAgent."}},required:["artifact_json"]},handler:Cu,sideEffect:"mutates-fs",toClassifierInput:i(e=>`StageSelfModify: ${Cs(e?.artifact_json)}`,"toClassifierInput")},Wu];var Ne=new Map,Hk=0,Du=["repo_overview","changed_scope","changed_diff","changed_diff_bundle","module_context","symbol_context","process_context","impact_estimate","relationship_scan","cyclic_dependencies","semantic_lookup"],Kk=new Set(Du),ju=["mcp_search","mcp_describe","mcp_call","mcp_read_resource","mcp_get_prompt"],zk=new Set(ju);function Rs(e){return!e||typeof e!="object"||!("required"in e)||!Array.isArray(e.required)?[]:e.required.filter(t=>typeof t=="string"&&t.trim().length>0)}i(Rs,"extractRequiredParams");function Gk(e){let{handler:t,registrationId:n,requiredParams:r,source:o,...s}=e;return s}i(Gk,"toToolDefinition");function ve(e){let t=Ne.get(e);if(!(!t||t.length===0))return t[t.length-1]}i(ve,"getActiveToolRegistration");function Xk(e){for(let[t,n]of Ne){let r=n.filter(o=>o.registrationId!==e);if(r.length!==n.length){r.length===0?Ne.delete(t):Ne.set(t,r);return}}}i(Xk,"removeToolRegistration");function af(e,t={}){let n=`tool:${++Hk}`,r=t.source??{kind:"extension",id:n,label:e.name},o={...e,registrationId:n,requiredParams:Rs(e.input_schema),source:r},s=Ne.get(e.name)??[];return Ne.set(e.name,[...s,o]),()=>{Xk(n)}}i(af,"registerToolInternal");for(let e of fe)af(e,{source:{kind:"builtin",id:`builtin:${e.name}`,label:e.name}});var Xb=fe.map(e=>{let{handler:t,...n}=e;return n});function on(e,t={}){return af(e,t)}i(on,"registerTool");function Vb(e){return ve(e)?.handler}i(Vb,"getTool");function Dn(e){let t=ve(e);return t?Gk(t):void 0}i(Dn,"getToolDefinition");function tt(e){return ve(e)}i(tt,"getRegisteredToolDefinition");function Et(e){return[...Ne.get(e)??[]]}i(Et,"getToolRegistrations");function Jb(e){let t=fe.find(o=>o.name===e);if(!t)return;let{handler:n,...r}=t;return r}i(Jb,"getBuiltinToolDefinition");function bs(e){let t=fe.find(n=>n.name===e);if(t)return{...t,registrationId:`builtin:${t.name}`,requiredParams:Rs(t.input_schema),source:{kind:"builtin",id:`builtin:${t.name}`,label:t.name}}}i(bs,"getBuiltinRegisteredToolDefinition");function Yb(e){let t=fe.find(n=>n.name===e);if(t)return{...t,input_schema:t.input_schema?JSON.parse(JSON.stringify(t.input_schema)):t.input_schema}}i(Yb,"createBuiltinToolDefinition");function Qb(){return fe.map(e=>({...e,registrationId:`builtin:${e.name}`,requiredParams:Rs(e.input_schema),source:{kind:"builtin",id:`builtin:${e.name}`,label:e.name}}))}i(Qb,"listBuiltinToolDefinitions");function Cn(){let e=[];for(let[t]of Ne){let n=ve(t);n&&e.push(n)}return e.sort((t,n)=>t.name.localeCompare(n.name)),e}i(Cn,"getAllRegisteredTools");function Zb(e){let t=ve(e)??fe.find(n=>n.name===e);return t?t.planModeAllowed===!0?!0:t.planModeAllowed===!1?!1:t.sideEffect==="readonly":!1}i(Zb,"isToolPlanModeAllowed");function ek(e){return(ve(e)??fe.find(n=>n.name===e))?.sideEffect==="mutates-fs"}i(ek,"isToolFileMutation");function tk(e){return(ve(e)??fe.find(n=>n.name===e))?.sideEffect==="reads-network"}i(tk,"isToolNetworkRead");function nk(e){let t=ve(e)??fe.find(n=>n.name===e);return t?t.sideEffect!=="readonly":!0}i(nk,"isToolMutation");function rk(e){return ve(e)?.requiredParams??[]}i(rk,"getRequiredToolParams");function Le(){return Array.from(Ne.keys()).filter(e=>ve(e)!==void 0).sort((e,t)=>e.localeCompare(t))}i(Le,"listTools");function ok(){return Le().map(e=>Dn(e)).filter(e=>e!==void 0)}i(ok,"listToolDefinitions");function Fu(e){return Kk.has(e)}i(Fu,"isRepoIntelligenceWorkingToolName");function ik(e){return e.filter(t=>!Fu(t))}i(ik,"filterRepoIntelligenceWorkingToolNames");function Vk(e){return zk.has(e)}i(Vk,"isMcpToolName");function sk(e){return e.filter(t=>!Vk(t))}i(sk,"filterMcpToolNames");function Jk(e){return e!=null&&typeof e=="object"&&Symbol.asyncIterator in e}i(Jk,"isAsyncGenerator");async function Yk(e,t){let n=await e.next();for(;!n.done;){let r=n.value;r&&typeof r.message=="string"&&t?.(r.message),n=await e.next()}return n.value}i(Yk,"consumeToolGenerator");async function Hi(e,t,n){let r=tt(e);if(!r)return`[Tool Error] Unknown tool: ${e}. Available tools: ${Le().join(", ")}`;let o=r.requiredParams.filter(s=>t[s]===void 0||t[s]===null);if(o.length>0)return`[Tool Error] ${e}: Missing required parameter(s): ${o.join(", ")}`;try{let s=r.handler(t,n);return Jk(s)?await Yk(s,n.reportToolProgress):await s}catch(s){let a=s instanceof Error?s.message:String(s);return a.includes("ENOENT")?`[Tool Error] ${e}: File or directory not found`:a.includes("EACCES")||a.includes("EPERM")?`[Tool Error] ${e}: Permission denied`:a.includes("ENOSPC")?`[Tool Error] ${e}: No space left on device`:`[Tool Error] ${e}: ${a}`}}i(Hi,"executeTool");var Qk=new Map([["worker",_r],["kodax/role/worker",_r]]),_e=new Map,De=new Map;function Oe(e){return _e.get(e)?.agent}i(Oe,"resolveConstructedAgent");function ae(){return Array.from(_e.values()).map(e=>e.agent)}i(ae,"listConstructedAgents");function es(){for(let e of _e.values())Rt(e.agent);_e.clear();for(let e of De.values())Rt(e.agent);De.clear()}i(es,"_resetAgentResolverForTesting");function Pb(e){return De.has(e)}i(Pb,"hasPendingSwap");function Nb(){if(De.size===0)return[];let e=[];for(let[t,n]of De){let r=_e.get(t);r&&Rt(r.agent),_e.set(t,n),e.push(t)}return De.clear(),e}i(Nb,"drainPendingSwaps");function Zk(e){let t=e.ref.indexOf(":"),n=t===-1?e.ref:e.ref.slice(t+1).split("@")[0],r=tt(n);if(r)return{name:r.name,description:r.description,input_schema:r.input_schema}}i(Zk,"liftToolRef");function ev(e){let t=e.target.ref.indexOf(":"),n=t===-1?"":e.target.ref.slice(0,t),r=t===-1?e.target.ref:e.target.ref.slice(t+1),o=r.indexOf("@"),s=o===-1?r:r.slice(0,o),a;return n==="builtin"?a=Qk.get(s)??{name:s,instructions:""}:a=_e.get(s)?.agent??{name:s,instructions:""},{target:a,kind:e.kind,description:e.description}}i(ev,"liftHandoffRef");function tv(e,t){let n=[];if(t.tools)for(let o of t.tools){let s=Zk(o);s&&n.push(s)}let r=t.handoffs?.map(ev);return{name:e,instructions:t.instructions,...n.length>0?{tools:n}:{},...r&&r.length>0?{handoffs:r}:{},...t.reasoning?{reasoning:t.reasoning}:{},...t.guardrails?{guardrails:t.guardrails.map(o=>{let s=o.ref.indexOf(":");return{kind:o.kind,name:s===-1?o.ref:o.ref.slice(s+1).split("@")[0]}})}:{},...t.model?{model:t.model}:{},...t.provider?{provider:t.provider}:{},...t.effort?{effort:t.effort}:{},...t.outputSchema?{outputSchema:t.outputSchema}:{},...t.description?{description:t.description}:{}}}i(tv,"buildAgentFromContent");function de(e,t={},n={}){let r=tv(e.name,e.content);return t.bindings&&t.manifest&&Hs(r,t.manifest,t.bindings),(n.deferred?De:_e).set(e.name,{artifact:e,agent:r,source:t.source}),()=>{let s=De.get(e.name);if(s&&s.artifact.version===e.version){Rt(s.agent),De.delete(e.name);return}let a=_e.get(e.name);a&&a.artifact.version===e.version&&(Rt(a.agent),_e.delete(e.name))}}i(de,"registerConstructedAgent");var nv=Object.freeze({".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"typescriptreact",".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python",".go":"go",".rs":"rust",".java":"java"});function qn(e){let t=e.lastIndexOf(".");if(t<0)return;let n=e.slice(t).toLowerCase();return nv[n]}i(qn,"languageIdForPath");var rv=Object.freeze({1:"ERROR",2:"WARN",3:"INFO",4:"HINT"});function ov(e){let t=rv[e.severity??1]??"ERROR",n=e.range.start.line+1,r=e.range.start.character+1;return`${t} [${n}:${r}] ${e.message}`}i(ov,"pretty");function cf(e,t){let n=t.filter(a=>(a.severity??1)===1);if(n.length===0)return"";let r=n.slice(0,20),o=n.length-20,s=o>0?`
324
+ Pause, resume, and budget-limited transitions are controlled by the user, not this tool. Do not call to stop work \u2014 only call when the objective is truly achieved or truly blocked.`,input_schema:{type:"object",properties:{status:{type:"string",enum:["complete","blocked"],description:'New status. "complete" requires verifier confirmation; "blocked" requires the same blocker_kind across 3 consecutive turns.'},blocker_kind:{type:"string",description:'Required when status=blocked. A short identifier for the persistent obstacle (e.g. "awaiting-user-permission", "missing-dependency"). The runtime counter compares this string across turns.'}},required:["status"]},handler:Ou,sideEffect:"mutates-state",planModeAllowed:!1,toClassifierInput:i(()=>"","toClassifierInput")},{name:"exit_plan_mode",description:"Exit plan mode by presenting the finalized plan to the user for approval. On approval, the session flips to accept-edits and implementation can proceed. On rejection, the session remains in plan mode so the plan can be revised. Use this tool once the plan is ready for user review \u2014 do NOT combine with set_permission_mode. Parent-only: requires an interactive approval UI (wired only in REPL sessions).",input_schema:{type:"object",properties:{plan:{type:"string",description:"The finalized plan to present to the user. Include the full plan content, not a summary, so the user can make an informed approval decision. Keep the plan tight: at most 40 lines total, 3 bullet-depth levels, one sentence per bullet. If the plan exceeds this budget, split it into phases and present only the current phase \u2014 the user can approve phase-by-phase."}},required:["plan"]},handler:Ci,sideEffect:"mutates-state",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"todo_update",description:'Drive the visible plan checklist so the user sees real-time progress \u2014 single-item PATCH plus status transition for ONE existing todo item. `op="update"` is the default (omit `op` for back-compat); target one item by `id` and change its status, patch its fields, or both in one call.\n\n## When to Use This Tool\n\n- BEFORE starting work on an item \u2014 flip it to `in_progress` and supply `activeForm` (present-continuous form of the subject; e.g. subject "Run failing tests" \u2192 activeForm "Running failing tests") so the spinner reflects what you are doing right now.\n- AFTER finishing work on an item \u2014 flip it to `completed` before moving on, so the plan list stays current. If the item carries an `evaluator` hint, the runner runs the deterministic check on transition and surfaces stderr on failure.\n- WHEN requirements clarify mid-task \u2014 patch `subject` and/or `description` to refine the row in place (e.g. "Run failing tests" \u2192 "Run failing tests AND clean up tmp").\n- WHEN an attempt clearly failed and needs retry \u2014 set status to `failed`.\n- WHEN the item turned out to be unnecessary (e.g. two obligations merged into one) \u2014 set status to `skipped`.\n- WHEN you decide mid-execution to drop an item the user no longer needs \u2014 set status to `cancelled` (UI shows strikethrough as a visible breadcrumb); use `deleted` instead if the item was wholly off-plan and a breadcrumb would just clutter.\n\n## When NOT to Use This Tool\n\n- To ADD a new item \u2014 call `todo_create` instead (one call per planned step, batched). `todo_update` only mutates EXISTING items.\n- When the item is already in the target status \u2014 a redundant update is a silent no-op and clutters the transcript.\n- When uncertain about an item\'s current state \u2014 call `todo_get` first; runner-side auto-handlers may have flipped statuses between your turns, and mutating on a stale view produces silent no-op patches.\n- `op="init"` is reserved for runner-side seeding only. LLMs should never call it \u2014 it destructively replaces the whole list, dropping any item not echoed back, and weaker models routinely under-echo and lose completed work.\n\n## Status Transitions\n\nOnly ONE item per owner should be `in_progress` at any time \u2014 finish or fail the current item before starting the next. Valid statuses: `in_progress`, `completed`, `failed`, `skipped`, `cancelled`, `deleted`. `"pending"` is intentionally not allowed \u2014 items start pending automatically and only the runner moves them back to pending after a revise verdict. Prefer `deleted` over `cancelled` when the item was wholly off-plan; prefer `cancelled` when the user benefits from seeing the discarded record.\n\n## Field Patches (status optional when only patching)\n\n- `subject` (non-empty string) replaces the brief imperative title shown in the row.\n- `description` (string; empty clears) replaces the fuller context shown by `todo_get`.\n- `activeForm` is required with `in_progress`; for other statuses the previous value is preserved but irrelevant.\n- `note` is optional free-text reason; when omitted, any pre-existing note is preserved.\n- `evaluator` ("build" | "test" | "lint") replaces the deterministic evaluator hint.\n- `metadata` (object | null) \u2014 shallow-merge: top-level keys overwrite; a value of `null` inside the object DELETES that key (mixed merge+delete is supported, e.g. `{newKey: "v", oldKey: null}`); pass the whole field as `null` to clear ALL metadata.\n- Patch fields can be combined with a status transition in a single call.\n\n## Error Handling\n\n- `ok=false` with reason "Unknown todo id" \u2014 inspect the listed valid ids and retry, or call `todo_list` to refresh.\n- `ok=false` with reason "todo_update is not active" \u2014 the current run has no plan list; continue without further `todo_update` calls.\n- `ok=false` with reason "blocked-by-hook" (or an extension-supplied string) \u2014 an extension policy rejected the transition; re-read the visible plan and revise your approach before retrying.',input_schema:{type:"object",properties:{op:{type:"string",enum:["init","update"],description:'Operation mode. Default "update" when omitted \u2014 mutate one item by `id`. "init" (legacy / runner-side seeding only) replaces the whole list with `items`; LLMs should NOT call it \u2014 it destructively drops any item not echoed back. Use a batch of `todo_create` calls for both initial commitment and mid-task plan growth.'},items:{type:"array",description:'op="init" (legacy / runner-side only) payload. Each entry: {id: non-empty string (unique within list), subject: non-empty string (brief title), description?: string (fuller context), activeForm?: present-continuous string}. LLMs should use a batch of `todo_create` calls instead.',items:{type:"object",properties:{id:{type:"string",description:'Unique non-empty item id (e.g. "todo_1").'},subject:{type:"string",description:'Brief imperative title shown in the plan-list row (e.g. "Run failing tests").'},description:{type:"string",description:"Optional fuller context / work instructions read when this item is later picked up (todo_get surface). Multi-line OK. Skip when subject alone is enough."},activeForm:{type:"string",description:'Optional present-continuous form (e.g. "Running failing tests") shown by the spinner when this item flips to in_progress.'},evaluator:{type:"string",enum:["build","test","lint"],description:'Optional per-step deterministic evaluator. When set and the item flips to "completed", the runner runs `npm run build` / `npm test` / `npm run lint` accordingly; failure surfaces stderr in your next tool result. Use sparingly \u2014 only on milestone steps.'}},required:["id","subject"]}},id:{type:"string",description:'op="update" only. The id of the todo item to update (e.g. "todo_3"). Must match a current valid id in the plan list.'},status:{type:"string",enum:["in_progress","completed","failed","skipped","cancelled","deleted"],description:'op="update" only. New status. Optional \u2014 when omitted you may still patch subject/description/activeForm/note/evaluator/metadata. "pending" is intentionally not allowed \u2014 items start as pending automatically and only the runner moves them back to pending after a revise verdict. "cancelled" signals a Worker-driven mid-execution decision to drop the item; UI shows strikethrough. "deleted" removes the item from the visible list entirely \u2014 use when the item turned out to be wholly irrelevant and you do not want a strikethrough breadcrumb. The matching extension event is `todo:deleted`.'},note:{type:"string",description:'op="update" only. Optional free-text reason or detail. When omitted, any pre-existing note on the item is preserved.'},activeForm:{type:"string",description:'op="update" only. Present-continuous form of the item subject (e.g. "Running failing tests"). Required when status="in_progress" so the spinner can show the user what you are doing right now. Omitted on completed/failed/skipped (the previous activeForm is preserved but irrelevant once the item leaves in_progress).'},subject:{type:"string",description:'op="update" only. Optional. When provided, REPLACES the brief imperative title shown in the plan-list row. Use for mid-task plan refinement (e.g. "Run failing tests" \u2192 "Run failing tests AND clean up tmp"). Must be a non-empty string.'},description:{type:"string",description:'op="update" only. Optional. When provided, REPLACES the fuller context (work instruction). Multi-line OK. Pass empty string to clear an existing description.'},evaluator:{type:"string",enum:["build","test","lint"],description:`op="update" only. Optional. When provided, REPLACES the item's deterministic evaluator hint. When the item later flips to "completed", the runner runs the corresponding deterministic check and surfaces stderr on failure.`},metadata:{type:"object",description:'op="update" only. Optional opaque key-value bag. Semantics: shallow-merge \u2014 top-level keys overwrite (nested objects are NOT deep-merged); a value of `null` inside the object DELETES that key from existing metadata; mixed merge+delete in one call is supported (e.g. `{newKey: "v", oldKey: null}`); pass the whole `metadata` field as `null` (NOT inside an object) to clear ALL metadata (handler accepts top-level null even though the JSON Schema is `type:"object"`). The UI does NOT render metadata; it is for extension hooks / eval harnesses.'}}},handler:Pf,sideEffect:"mutates-state",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"todo_create",description:'Insert ONE new pending item into the visible plan list \u2014 purely additive, existing items untouched. The store auto-generates the id (monotonic `todo_<n>`); never pass an id \u2014 any caller-supplied id is rejected at the schema layer.\n\n## When to Use This Tool\n\n- AT THE START of a non-trivial multi-step task \u2014 commit the full plan up front by batching one `todo_create` call per planned step in the same response, so the user sees the intended trajectory.\n- WHEN you receive a user request with multiple distinct sub-tasks \u2014 capture each as its own item.\n- WHEN you discover an additional step mid-task \u2014 add it additively so the user sees the plan growing rather than the original list being silently rewritten.\n- BEFORE fanning out to child workers via `dispatch_child_task` \u2014 the plan list is the natural anchor for the work each child will execute.\n\n## When NOT to Use This Tool\n\n- For a single straightforward operation that completes in one step \u2014 skip the plan list entirely.\n- For purely informational responses (answering a question, explaining code) where there is no execution work to track.\n- When an equivalent item already exists in the plan list \u2014 call `todo_list` first if unsure; duplicate items confuse the user.\n- For the actual work itself \u2014 `todo_create` only RECORDS planned work; you still need to perform the real operations (read, edit, run, etc.) in subsequent tool calls.\n\n## Fields\n\n- `subject` (required) \u2014 brief imperative title shown in the plan-list row (e.g. "Audit handleAuth callers").\n- `description` (optional) \u2014 fuller context / work instructions read when this item is later picked up via `todo_get`; multi-line OK; NOT rendered in the compact row.\n- `activeForm` (optional) \u2014 present-continuous form (e.g. "Auditing handleAuth callers") shown by the spinner when this item later flips to `in_progress` via `todo_update`.\n- `evaluator` (optional, "build" | "test" | "lint") \u2014 runs the corresponding deterministic check when the item flips to "completed". Use sparingly, only on milestone steps with a real ground-truth check.\n- `metadata` (optional) \u2014 opaque key-value bag carried alongside the item for extension hooks / observability; the UI does NOT render it.\n\nReturns `{ok: true, id: "todo_<n>"}` on success or `{ok: false, reason: "..."}` when the store is not wired, validation fails, or an extension hook blocks the create.',input_schema:{type:"object",properties:{subject:{type:"string",description:'Brief imperative title shown in the plan-list row (e.g. "Audit handleAuth callers").'},description:{type:"string",description:"Optional fuller context / work instructions read when this item is later picked up via todo_get. Multi-line OK; NOT rendered in the compact row. Skip when subject alone is enough."},activeForm:{type:"string",description:'Optional present-continuous form (e.g. "Running failing tests"). Shown by the spinner when this item later flips to `in_progress`.'},evaluator:{type:"string",enum:["build","test","lint"],description:'Optional per-step deterministic evaluator. When set and the item later flips to "completed" via todo_update, the runner runs `npm run build` / `npm test` / `npm run lint` accordingly; failure surfaces stderr in your next tool result. Use sparingly \u2014 only on milestone steps with a real ground-truth check.'},metadata:{type:"object",description:"Optional opaque key-value bag carried alongside the item. Used by extension hooks / eval harnesses. The UI does NOT render metadata. Omit if you have nothing structured to attach."}},required:["subject"]},handler:Ff,sideEffect:"mutates-state",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"todo_list",description:'Read-only query that returns the current visible plan list as JSON. Never mutates the store.\n\n## When to Use This Tool\n\n- BEFORE deciding the next move \u2014 confirm what items are pending and which is currently `in_progress`.\n- AFTER an "Unknown todo id" error \u2014 see the canonical valid-id set before retrying `todo_update` or `todo_get`.\n- WHEN refining a plan \u2014 compare a proposed new step against existing items to avoid duplicates.\n- AFTER a long quiet stretch \u2014 re-sync with any auto-handler-driven status flips before continuing.\n\n## When NOT to Use This Tool\n\n- When you already know the exact id and want one item\'s full detail \u2014 call `todo_get` directly.\n- When no plan list is active \u2014 the call returns `{ok: false, reason: "todo_list is not active ..."}`; further `todo_*` calls in this run will also be inactive.\n\nReturns `{ok: true, count: N, items: [{id, subject, status, description?, activeForm?, note?}, ...]}` on success. Pair with `todo_create` (additive), `todo_update` (mutate), or `todo_get` (full single-item detail).',input_schema:{type:"object",properties:{}},handler:Df,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"todo_get",description:'Read-only single-item lookup. Returns the full TodoItem detail for one id \u2014 subject, optional description, status, activeForm, note, evaluator, metadata.\n\n## When to Use This Tool\n\n- BEFORE calling `todo_update` when uncertain about an item\'s current state \u2014 runner-side auto-handlers may have flipped statuses between your turns, and mutating on a stale view produces silent no-op patches.\n- WHEN PICKING UP an item to work on \u2014 the full `description` carries the work instruction; the compact row label (`subject`) alone is often not enough.\n- AFTER an "Unknown todo id" error on `todo_update` \u2014 call `todo_list` first to see all ids, then `todo_get` to drill into the specific one.\n\n## When NOT to Use This Tool\n\n- For a high-level overview of all items \u2014 call `todo_list` instead.\n- When you already have a clear status flip + field patch to apply \u2014 call `todo_update` directly; an extra `todo_get` round-trip adds latency without changing the outcome.\n\nReturns `{ok: true, item: {...}}` on success or `{ok: false, reason: "..."}` when the store is not wired or the id is unknown (the reason carries the canonical valid-id list).',input_schema:{type:"object",properties:{id:{type:"string",description:'The todo id to retrieve (e.g. "todo_3"). Must match a current valid id.'}},required:["id"]},handler:jf,sideEffect:"readonly",planModeAllowed:!0,toClassifierInput:i(()=>"","toClassifierInput")},{name:"repo_overview",description:"Summarize the repository structure, key areas, entry hints, and stored repo-intelligence snapshot for the current workspace. Returns a compact top-down map: monorepo packages or top-level directories, entry files, primary languages, build/test commands. Use this once at session start (or after switching into an unfamiliar area) to orient yourself before issuing targeted reads \u2014 calling it at the start of every task is wasteful because the snapshot rarely changes within a session. The `refresh` flag rebuilds the snapshot; expensive, so only set it after a structural change to the workspace (new package added, large directory move). For drilling into a specific module, use `module_context` instead.",input_schema:{type:"object",properties:{target_path:{type:"string",description:"Optional path inside the workspace to resolve the repository root from"},refresh:{type:"boolean",description:"When true, rebuild the repo overview snapshot before returning it"}}},handler:Go,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"changed_scope",description:'Analyze which files, areas, and categories are touched by the current git diff or a comparison range. This is the canonical entry point for any review / change-audit / commit-prep workflow \u2014 call it first to see the change surface before issuing per-file diffs. Returns files grouped by area/category (e.g., "tests", "docs", "core") with a one-line summary per file. The `scope` parameter selects which change set: `unstaged` (working tree vs HEAD), `staged` (index vs HEAD), `all` (working tree + index vs HEAD, default), `compare` (HEAD vs base_ref). Pair with `changed_diff_bundle` to fetch the actual diffs for the files identified.',input_schema:{type:"object",properties:{target_path:{type:"string",description:"Optional path inside the workspace to resolve the repository root from"},scope:{type:"string",enum:["unstaged","staged","all","compare"],description:"Which git change set to inspect. Defaults to all."},base_ref:{type:"string",description:"Base ref used when scope=compare. Defaults to HEAD~1."},refresh_overview:{type:"boolean",description:"When true, rebuild the repo overview snapshot before analyzing changes"}}},handler:Ko,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"changed_diff",description:"Read a paged diff slice for a specific changed file. Prefer this over broad git diff output during large reviews.",input_schema:{type:"object",properties:{target_path:{type:"string",description:"Optional path inside the workspace to resolve the repository root from"},base_ref:{type:"string",description:"Optional base git ref for compare-range review"},target_ref:{type:"string",description:"Optional target git ref for compare-range review (defaults to HEAD when base_ref is provided)"},path:{type:"string",description:"Changed file path to inspect, relative to the workspace root or absolute inside it"},offset:{type:"number",description:"1-based diff line offset for pagination"},limit:{type:"number",description:"Maximum diff lines to return in this slice"},context_lines:{type:"number",description:"Unified diff context lines to request"}},required:["path"]},handler:Vo,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"changed_diff_bundle",description:"Read diff slices for multiple changed files in one call. Prefer this for large reviews before drilling down with changed_diff.",input_schema:{type:"object",properties:{target_path:{type:"string",description:"Optional path inside the workspace to resolve the repository root from"},base_ref:{type:"string",description:"Optional base git ref for compare-range review"},target_ref:{type:"string",description:"Optional target git ref for compare-range review (defaults to HEAD when base_ref is provided)"},paths:{type:"array",description:"Changed file paths to inspect in one bundle, relative to the workspace root or absolute inside it",items:{type:"string"}},offset:{type:"number",description:"1-based diff line offset applied to each path in the bundle"},limit_per_path:{type:"number",description:"Maximum diff lines to return per path in this bundle"},context_lines:{type:"number",description:"Unified diff context lines to request"}},required:["paths"]},handler:Jo,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"module_context",description:'Return a task-shaped module capsule with dependencies, entry files, top-level symbols, test files, docs, and follow-up handles for further drill-down. Use this when about to read 3+ files in the same module \u2014 the capsule replaces that exploration round-trip with one structured response. Prefer `module_context` over raw `read`+`grep` for "what does this module do / what depends on what" questions. When the question is about a single function or class, use `symbol_context` instead \u2014 it is cheaper because it scopes to one symbol. When you only need exact file content (line numbers, byte-level text), fall back to `read` after the capsule narrows the target. `refresh: true` rebuilds the underlying repo-intel index, which is expensive \u2014 only set it when you have reason to believe the index is stale.',input_schema:{type:"object",properties:{module:{type:"string",description:"Module id, label, or package name to inspect"},target_path:{type:"string",description:"Optional path used to infer the enclosing module"},refresh:{type:"boolean",description:"When true, rebuild repo intelligence before returning the module capsule"}}},handler:hi,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_definition",description:"Jump to where the symbol at a specific line/column is DEFINED, using the language server's live view of the current code. Use this when you are looking at a usage and need its exact definition site \u2014 it resolves through imports, re-exports, and overloads the way the compiler does, which `grep` cannot. Give the 1-based line and column of the symbol as it appears in the file you just read. Prefer this when you want the precise single definition of the symbol right where you are; prefer `symbol_context` when you want the repo-wide usage graph (callers/callees) of a named symbol. Needs a language server for the file's language installed (TypeScript/JS, Python, Go, Rust, Java); returns install guidance otherwise.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol (defaults to the line start)"}},required:["path","line"]},handler:md,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_hover",description:"Show the type, signature, and doc of the symbol at a specific line/column, as the language server sees it. Use this to confirm an inferred type, a function's parameter/return types, or a value's declared type before editing \u2014 it reflects the real compiler state, including generics resolved in context, so you do not have to open and read the definition just for its signature. Give the 1-based line and column of the symbol. Needs the matching language server installed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol"}},required:["path","line"]},handler:hd,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_references",description:"List every place the symbol at a specific line/column is USED (including its declaration), from the language server. Use this before renaming or changing a symbol's signature to see exactly what would break \u2014 it finds the structural references `grep` misses (re-exports, aliased imports) and skips the string/comment matches `grep` wrongly includes. Give the 1-based line and column. When you only have a NAME and want a quick repo-scope blast-radius estimate, use `impact_estimate`; use `lsp_references` when you have the exact position and want the compiler-accurate reference list. Needs the matching language server installed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol"}},required:["path","line"]},handler:gd,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_document_symbols",description:"Outline the symbols (classes, functions, methods, fields) declared in a single file, with their lines, from the language server. Use this to get oriented in an unfamiliar file without reading all of it, or to find the line of a member before an `lsp_definition` / `lsp_hover` / `edit`. For a repo-scope structural view across modules use `module_context`; `lsp_document_symbols` is the precise single-file outline. Needs the matching language server installed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File to outline"}},required:["path"]},handler:yd,sideEffect:"readonly",toClassifierInput:i(e=>$n("relationship_scan",e),"toClassifierInput")},{name:"lsp_workspace_symbols",description:"Search project-wide symbols by name through available language servers. Use this when you know a class/function/type name but not its file, and want compiler-indexed candidates before reading files or running broader text search. An empty query asks the server for its broad symbol list when supported.",input_schema:{type:"object",properties:{query:{type:"string",description:"Symbol query text; may be empty for a broad server-supported listing"}}},handler:wd,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_implementation",description:"Jump from an interface, abstract method, or declaration site to implementation locations using the language server. Use this when definition only lands on a contract and you need the concrete implementers before changing behavior.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol"},column:{type:"number",description:"Alias for character"}},required:["path","line"]},handler:bd,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_prepare_call_hierarchy",description:"Prepare call hierarchy roots for the symbol at a file position. Use this to confirm the language server can identify the callable before asking for incoming or outgoing calls.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the callable symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol"},column:{type:"number",description:"Alias for character"}},required:["path","line"]},handler:kd,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_incoming_calls",description:"List language-server incoming callers for the callable at a file position. Use this for upstream/caller questions when you have the exact symbol location.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the callable symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol"},column:{type:"number",description:"Alias for character"}},required:["path","line"]},handler:vd,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"lsp_outgoing_calls",description:"List language-server outgoing callees from the callable at a file position. Use this for downstream/callee questions when you have the exact symbol location.",input_schema:{type:"object",properties:{path:{type:"string",description:"File containing the callable symbol"},line:{type:"number",description:"1-based line of the symbol"},character:{type:"number",description:"Optional 1-based column of the symbol"},column:{type:"number",description:"Alias for character"}},required:["path","line"]},handler:_d,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"relationship_scan",description:'Answer upstream/downstream relationship questions for a symbol, module, path, or entry point in one compact scan. Returns identity, upstream callers/dependents, downstream callees/dependencies/process steps, impact, evidence, confidence, and gaps. Use this first for "what calls this", "what depends on this", "upstream/downstream", "\u8C03\u7528\u94FE", "\u4E0A\u4E0B\u6E38", and blast-radius questions before falling back to separate module_context / symbol_context / process_context calls.',input_schema:{type:"object",properties:{symbol:{type:"string",description:"Optional symbol/function/class name to trace"},module:{type:"string",description:"Optional module/package label to trace"},path:{type:"string",description:"Optional repository-relative or absolute path to trace"},entry:{type:"string",description:"Optional entry symbol or file hint for execution/process tracing"},direction:{type:"string",enum:["upstream","downstream","both"],description:"Relationship direction to emphasize. Defaults to both."},depth:{type:"number",enum:[1,2,3],description:"Requested traversal depth. Light mode reports bounded direct edges first."},target_path:{type:"string",description:"Optional path used to resolve the repository root or narrow context"},refresh:{type:"boolean",description:"When true, rebuild repo intelligence before the first relationship lookup"},include_lsp:{type:"boolean",description:"When true, attach LSP incoming/outgoing call hierarchy evidence when an LSP service is available"},include_text_search:{type:"boolean",description:"When true, attach bounded exact-name grep evidence for cross-checking static relationships"}}},handler:ud,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"symbol_context",description:'Return the definition, probable callers/callees, imports, and naming alternatives for a single repository symbol. Use this when tracing the usage of one function, class, or constant \u2014 the response pre-resolves the relationships that would otherwise take several `grep -n "symbolName"` + `read` rounds to assemble. Cheaper than `module_context` when the question is symbol-scoped rather than module-scoped (the callers/callees graph is bounded by symbol degree, not module surface). The `module` parameter disambiguates when the same symbol name appears in multiple packages. For "where is this exact string used" without symbol semantics, prefer `grep` or `code_search` instead. For impact estimation before a refactor, use `impact_estimate` \u2014 it combines symbol info with changed-scope overlap.',input_schema:{type:"object",properties:{symbol:{type:"string",description:"The symbol name to inspect"},module:{type:"string",description:"Optional module hint to disambiguate the symbol search"},target_path:{type:"string",description:"Optional path inside the workspace to resolve the repository root from"},refresh:{type:"boolean",description:"When true, rebuild repo intelligence before returning the symbol capsule"}}},handler:gi,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"process_context",description:'Return an approximate static execution/process capsule for an entry symbol, module, or path. Use this when the question is "how does this flow execute" rather than "what depends on what" \u2014 `process_context` traces from an entry point through likely call paths, giving you the sequence of file/symbol transitions without N rounds of follow-up reads. The `entry` parameter is the starting point (function name, file path, or module label); `module` is an optional disambiguating hint. Prefer over `module_context` when you care about runtime sequence, not module structure; prefer over `symbol_context` when you need the multi-hop call chain rather than just direct callers/callees. The trace is static (no runtime sampling), so it captures plausible paths, not actual hit rates.',input_schema:{type:"object",properties:{entry:{type:"string",description:"Entry symbol or file hint for the process to trace"},module:{type:"string",description:"Optional module hint used to select a process capsule"},target_path:{type:"string",description:"Optional path used to infer the relevant module or entry file"},refresh:{type:"boolean",description:"When true, rebuild repo intelligence before returning the process capsule"}}},handler:yi,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"impact_estimate",description:"Estimate the blast radius of changing a symbol, path, or module \u2014 combines repo-intelligence usage graph with current changed-scope overlap. Call this BEFORE planning a rename, refactor, or breaking change, not after the work is started \u2014 its purpose is to scope the work up front so the plan reflects reality (which packages need touching, which call sites assume current behavior, which tests must update). Returns ranked impact sites with severity hints. Prefer over guessing impact from a `grep` of the symbol name \u2014 `grep` overcounts (matches strings + comments) and undercounts (misses re-exports + structural callers). The `refresh` flag rebuilds the underlying index \u2014 expensive \u2014 so reserve it for cases where a recent large edit may have invalidated the cached graph.",input_schema:{type:"object",properties:{symbol:{type:"string",description:"Optional symbol to estimate impact for"},module:{type:"string",description:"Optional module to estimate impact for"},path:{type:"string",description:"Optional repository-relative or absolute path to estimate impact for"},target_path:{type:"string",description:"Optional path used to resolve the repository root from"},refresh:{type:"boolean",description:"When true, rebuild repo intelligence before returning the impact estimate"}}},handler:wi,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"cyclic_dependencies",description:'Detect circular import/dependency chains (Tarjan SCC) over the module-level import graph. Answers "is there a dependency cycle" \u2014 the one question the 1-hop tools (impact_estimate / module_context / symbol_context) cannot. Use when refactoring or moving modules, before merging a PR that reshapes imports, or to enforce a no-cycles rule. Returns each cycle as an ordered module chain with a hop count + severity. Distinct from impact_estimate (that is 1-hop blast radius; this is reachability cycles).',input_schema:{type:"object",properties:{}},handler:pd,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"scaffold_tool",description:"Generate a fillable ConstructionArtifact JSON skeleton for a new tool. Returns a draft you must edit before calling validate_tool / stage_construction. Use this as the FIRST step when authoring a runtime tool \u2014 do NOT hand-write the JSON shape from scratch, because the construction schema has required fields and version constraints that hand-authored JSON routinely misses, producing scaffolds the validator rejects.",input_schema:{type:"object",properties:{name:{type:"string",description:"Tool name (must match the value the LLM will use to invoke it)."},version:{type:"string",description:'Semver string. Defaults to "0.1.0".'},description:{type:"string",description:"One-sentence description of what the tool does."},capabilities:{type:"object",description:"Optional starter capabilities; defaults to {tools: []}.",properties:{tools:{type:"array",items:{type:"string"},description:"Whitelist of builtin tool names the handler may call via ctx.tools.<name>."}}}},required:["name"]},handler:Es,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"validate_tool",description:"Dry-run validate a candidate tool artifact JSON: shape sanity + AST hard rules (no-eval / no-Function-constructor / require-handler-signature) + provider schema validation. Does NOT touch disk. Use this BEFORE stage_construction to fail fast on malformed handlers.",input_schema:{type:"object",properties:{artifact_json:{type:"string",description:"The full ConstructionArtifact as a JSON string."},provider:{type:"string",description:"Provider whose tool-schema constraints are checked. Defaults to 'anthropic'."}},required:["artifact_json"]},handler:Ss,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"stage_construction",description:"Persist an artifact to .kodax/constructed/<kind>s/<name>/<version>.json with status=staged. Refuses to overwrite an active artifact at the same name+version (bump the version instead). Run validate_tool first; this tool itself does not re-validate the AST or schema.",input_schema:{type:"object",properties:{artifact_json:{type:"string",description:"The full ConstructionArtifact as a JSON string."}},required:["artifact_json"]},handler:Ts,sideEffect:"mutates-fs",toClassifierInput:i(e=>`StageTool: ${Us(e?.artifact_json)}`,"toClassifierInput")},{name:"test_tool",description:"Run the full Phase 2 check pipeline (shape \u2192 AST \u2192 provider schema \u2192 handler materialize) on a staged artifact. Returns ok=true/false plus errors/warnings. On ok=true the artifact is ready for activate_tool. LLM static review is NOT run from this tool \u2014 the calling agent must drive that separately if desired.",input_schema:{type:"object",properties:{name:{type:"string",description:"Artifact name as stored on disk."},version:{type:"string",description:"Artifact version as stored on disk."},provider:{type:"string",description:"Provider whose tool-schema constraints are checked. Defaults to 'anthropic'."}},required:["name","version"]},handler:As,sideEffect:"mutates-state",toClassifierInput:i(()=>"","toClassifierInput")},{name:"activate_tool",description:"Activate a staged-and-tested artifact. Invokes the construction policy gate, registers the handler into TOOL_REGISTRY, flips status=active. The tool is then immediately callable as `<name>` in subsequent turns. Policy: in the Ink REPL, the user sees an approve/reject dialog before activation. In non-interactive surfaces (ACP / single-shot CLI / child agents) activation is rejected by default \u2014 this prevents silent capability expansion without user consent.",input_schema:{type:"object",properties:{name:{type:"string",description:"Artifact name to activate."},version:{type:"string",description:"Artifact version to activate."}},required:["name","version"]},handler:Cs,sideEffect:"mutates-state",toClassifierInput:i(e=>{let t=e;return`ActivateTool: ${t?.name??"<no-name>"}@${t?.version??"<no-version>"}`},"toClassifierInput")},{name:"scaffold_agent",description:"Generate a fillable AgentArtifact JSON skeleton for a new agent. Returns a draft you must edit before calling validate_agent / stage_agent_construction. Use this as the FIRST step when authoring a runtime agent \u2014 do NOT hand-write the JSON shape from scratch, because the construction schema has required fields and version constraints that hand-authored JSON routinely misses, producing scaffolds the validator rejects.",input_schema:{type:"object",properties:{name:{type:"string",description:"Agent name (resolver lookup key once activated)."},version:{type:"string",description:'Semver string. Defaults to "0.1.0".'},description:{type:"string",description:"One-sentence description of the agent's purpose. Becomes the lead line of `instructions`."}},required:["name"]},handler:ff,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"validate_agent",description:"Dry-run admission audit on a candidate agent manifest JSON: schema validation + invariant.admit hooks + tool-capability cap + budget cap + handoff DAG check. Does NOT touch disk. Use this BEFORE stage_agent_construction to fail fast on rejected manifests.",input_schema:{type:"object",properties:{artifact_json:{type:"string",description:"The full AgentArtifact as a JSON string."}},required:["artifact_json"]},handler:pf,sideEffect:"readonly",toClassifierInput:i(()=>"","toClassifierInput")},{name:"stage_agent_construction",description:"Persist an agent manifest to .kodax/constructed/agents/<name>/<version>.json with status=staged. Refuses to overwrite an existing same-name+version (bump the version instead). Run validate_agent first; this tool itself does not re-run admission.",input_schema:{type:"object",properties:{artifact_json:{type:"string",description:"The full AgentArtifact as a JSON string."}},required:["artifact_json"]},handler:mf,sideEffect:"mutates-fs",toClassifierInput:i(e=>`StageAgent: ${Us(e?.artifact_json)}`,"toClassifierInput")},{name:"test_agent",description:"Run the agent test pipeline (manifest shape check + Runner.admit + sandbox case execution) on a staged agent. Returns ok=true/false with errors / warnings. On ok=true the agent is ready for activate_agent.",input_schema:{type:"object",properties:{name:{type:"string",description:"Agent name as stored on disk."},version:{type:"string",description:"Agent version as stored on disk."}},required:["name","version"]},handler:hf,sideEffect:"mutates-state",toClassifierInput:i(()=>"","toClassifierInput")},{name:"activate_agent",description:"Activate a staged-and-tested agent. Invokes the construction policy gate, flips status=active, records contentHash, and registers the agent in the resolver so Runner.run can find it by name. Policy: in the Ink REPL, the user sees an approve/reject dialog before activation. In non-interactive surfaces activation is rejected by default \u2014 this prevents silent capability expansion without user consent.",input_schema:{type:"object",properties:{name:{type:"string",description:"Agent name to activate."},version:{type:"string",description:"Agent version to activate."}},required:["name","version"]},handler:gf,sideEffect:"mutates-state",toClassifierInput:i(e=>{let t=e;return`ActivateAgent: ${t?.name??"<no-name>"}@${t?.version??"<no-version>"}`},"toClassifierInput")},{name:De,description:"Stage a new version of YOURSELF \u2014 the active constructed agent calling this tool. Requires artifact.name === artifact.sourceAgent === your own name, plus an existing active version on disk. Runs hard checks (guardrail ratchet \u2014 cannot remove existing guardrails; reasoning ceiling; modification budget) before persisting. Then call test_agent and activate_agent on the staged version. Activation force-prompts the user (no auto-approve for self-modify) and only takes effect on the NEXT Runner.run, never within the run that submitted the change.",input_schema:{type:"object",properties:{artifact_json:{type:"string",description:"The full AgentArtifact as a JSON string. artifact.name must equal artifact.sourceAgent."}},required:["artifact_json"]},handler:cf,sideEffect:"mutates-fs",toClassifierInput:i(e=>`StageSelfModify: ${Us(e?.artifact_json)}`,"toClassifierInput")},xf];var je=new Map,Zv=0,yf=["repo_overview","changed_scope","changed_diff","changed_diff_bundle","module_context","symbol_context","process_context","impact_estimate","relationship_scan","cyclic_dependencies","semantic_lookup"],Qv=new Set(yf),wf=["mcp_search","mcp_describe","mcp_call","mcp_read_resource","mcp_get_prompt"],e_=new Set(wf);function qs(e){return!e||typeof e!="object"||!("required"in e)||!Array.isArray(e.required)?[]:e.required.filter(t=>typeof t=="string"&&t.trim().length>0)}i(qs,"extractRequiredParams");function t_(e){let{handler:t,registrationId:n,requiredParams:r,source:o,...s}=e;return s}i(t_,"toToolDefinition");function Ee(e){let t=je.get(e);if(!(!t||t.length===0))return t[t.length-1]}i(Ee,"getActiveToolRegistration");function n_(e){for(let[t,n]of je){let r=n.filter(o=>o.registrationId!==e);if(r.length!==n.length){r.length===0?je.delete(t):je.set(t,r);return}}}i(n_,"removeToolRegistration");function Uf(e,t={}){let n=`tool:${++Zv}`,r=t.source??{kind:"extension",id:n,label:e.name},o={...e,registrationId:n,requiredParams:qs(e.input_schema),source:r},s=je.get(e.name)??[];return je.set(e.name,[...s,o]),()=>{n_(n)}}i(Uf,"registerToolInternal");for(let e of ge)Uf(e,{source:{kind:"builtin",id:`builtin:${e.name}`,label:e.name}});var nv=ge.map(e=>{let{handler:t,...n}=e;return n});function dn(e,t={}){return Uf(e,t)}i(dn,"registerTool");function rv(e){return Ee(e)?.handler}i(rv,"getTool");function Bn(e){let t=Ee(e);return t?t_(t):void 0}i(Bn,"getToolDefinition");function it(e){return Ee(e)}i(it,"getRegisteredToolDefinition");function Rt(e){return[...je.get(e)??[]]}i(Rt,"getToolRegistrations");function ov(e){let t=ge.find(o=>o.name===e);if(!t)return;let{handler:n,...r}=t;return r}i(ov,"getBuiltinToolDefinition");function Os(e){let t=ge.find(n=>n.name===e);if(t)return{...t,registrationId:`builtin:${t.name}`,requiredParams:qs(t.input_schema),source:{kind:"builtin",id:`builtin:${t.name}`,label:t.name}}}i(Os,"getBuiltinRegisteredToolDefinition");function iv(e){let t=ge.find(n=>n.name===e);if(t)return{...t,input_schema:t.input_schema?JSON.parse(JSON.stringify(t.input_schema)):t.input_schema}}i(iv,"createBuiltinToolDefinition");function sv(){return ge.map(e=>({...e,registrationId:`builtin:${e.name}`,requiredParams:qs(e.input_schema),source:{kind:"builtin",id:`builtin:${e.name}`,label:e.name}}))}i(sv,"listBuiltinToolDefinitions");function Ln(){let e=[];for(let[t]of je){let n=Ee(t);n&&e.push(n)}return e.sort((t,n)=>t.name.localeCompare(n.name)),e}i(Ln,"getAllRegisteredTools");function av(e){let t=Ee(e)??ge.find(n=>n.name===e);return t?t.planModeAllowed===!0?!0:t.planModeAllowed===!1?!1:t.sideEffect==="readonly":!1}i(av,"isToolPlanModeAllowed");function cv(e){return(Ee(e)??ge.find(n=>n.name===e))?.sideEffect==="mutates-fs"}i(cv,"isToolFileMutation");function lv(e){return(Ee(e)??ge.find(n=>n.name===e))?.sideEffect==="reads-network"}i(lv,"isToolNetworkRead");function dv(e){let t=Ee(e)??ge.find(n=>n.name===e);return t?t.sideEffect!=="readonly":!0}i(dv,"isToolMutation");function uv(e){return Ee(e)?.requiredParams??[]}i(uv,"getRequiredToolParams");function Ne(){return Array.from(je.keys()).filter(e=>Ee(e)!==void 0).sort((e,t)=>e.localeCompare(t))}i(Ne,"listTools");function fv(){return Ne().map(e=>Bn(e)).filter(e=>e!==void 0)}i(fv,"listToolDefinitions");function bf(e){return Qv.has(e)}i(bf,"isRepoIntelligenceWorkingToolName");function pv(e){return e.filter(t=>!bf(t))}i(pv,"filterRepoIntelligenceWorkingToolNames");function r_(e){return e_.has(e)}i(r_,"isMcpToolName");function mv(e){return e.filter(t=>!r_(t))}i(mv,"filterMcpToolNames");function o_(e){return e!=null&&typeof e=="object"&&Symbol.asyncIterator in e}i(o_,"isAsyncGenerator");async function i_(e,t){let n=await e.next();for(;!n.done;){let r=n.value;r&&typeof r.message=="string"&&t?.(r.message),n=await e.next()}return n.value}i(i_,"consumeToolGenerator");async function ns(e,t,n){let r=it(e);if(!r)return`[Tool Error] Unknown tool: ${e}. Available tools: ${Ne().join(", ")}`;let o=r.requiredParams.filter(s=>t[s]===void 0||t[s]===null);if(o.length>0)return`[Tool Error] ${e}: Missing required parameter(s): ${o.join(", ")}`;try{let s=r.handler(t,n);return o_(s)?await i_(s,n.reportToolProgress):await s}catch(s){let a=s instanceof Error?s.message:String(s);return a.includes("ENOENT")?`[Tool Error] ${e}: File or directory not found`:a.includes("EACCES")||a.includes("EPERM")?`[Tool Error] ${e}: Permission denied`:a.includes("ENOSPC")?`[Tool Error] ${e}: No space left on device`:`[Tool Error] ${e}: ${a}`}}i(ns,"executeTool");var s_=new Map([["worker",$r],["kodax/role/worker",$r]]),Se=new Map,Ue=new Map;function Me(e){return Se.get(e)?.agent}i(Me,"resolveConstructedAgent");function de(){return Array.from(Se.values()).map(e=>e.agent)}i(de,"listConstructedAgents");function fs(){for(let e of Se.values())Pt(e.agent);Se.clear();for(let e of Ue.values())Pt(e.agent);Ue.clear()}i(fs,"_resetAgentResolverForTesting");function Wk(e){return Ue.has(e)}i(Wk,"hasPendingSwap");function Hk(){if(Ue.size===0)return[];let e=[];for(let[t,n]of Ue){let r=Se.get(t);r&&Pt(r.agent),Se.set(t,n),e.push(t)}return Ue.clear(),e}i(Hk,"drainPendingSwaps");function a_(e){let t=e.ref.indexOf(":"),n=t===-1?e.ref:e.ref.slice(t+1).split("@")[0],r=it(n);if(r)return{name:r.name,description:r.description,input_schema:r.input_schema}}i(a_,"liftToolRef");function c_(e){let t=e.target.ref.indexOf(":"),n=t===-1?"":e.target.ref.slice(0,t),r=t===-1?e.target.ref:e.target.ref.slice(t+1),o=r.indexOf("@"),s=o===-1?r:r.slice(0,o),a;return n==="builtin"?a=s_.get(s)??{name:s,instructions:""}:a=Se.get(s)?.agent??{name:s,instructions:""},{target:a,kind:e.kind,description:e.description}}i(c_,"liftHandoffRef");function l_(e,t){let n=[];if(t.tools)for(let o of t.tools){let s=a_(o);s&&n.push(s)}let r=t.handoffs?.map(c_);return{name:e,instructions:t.instructions,...n.length>0?{tools:n}:{},...r&&r.length>0?{handoffs:r}:{},...t.reasoning?{reasoning:t.reasoning}:{},...t.guardrails?{guardrails:t.guardrails.map(o=>{let s=o.ref.indexOf(":");return{kind:o.kind,name:s===-1?o.ref:o.ref.slice(s+1).split("@")[0]}})}:{},...t.model?{model:t.model}:{},...t.provider?{provider:t.provider}:{},...t.effort?{effort:t.effort}:{},...t.outputSchema?{outputSchema:t.outputSchema}:{},...t.description?{description:t.description}:{}}}i(l_,"buildAgentFromContent");function me(e,t={},n={}){let r=l_(e.name,e.content);return t.bindings&&t.manifest&&na(r,t.manifest,t.bindings),(n.deferred?Ue:Se).set(e.name,{artifact:e,agent:r,source:t.source}),()=>{let s=Ue.get(e.name);if(s&&s.artifact.version===e.version){Pt(s.agent),Ue.delete(e.name);return}let a=Se.get(e.name);a&&a.artifact.version===e.version&&(Pt(a.agent),Se.delete(e.name))}}i(me,"registerConstructedAgent");var d_=Object.freeze({".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"typescriptreact",".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python",".go":"go",".rs":"rust",".java":"java"});function Gn(e){let t=e.lastIndexOf(".");if(t<0)return;let n=e.slice(t).toLowerCase();return d_[n]}i(Gn,"languageIdForPath");var u_=Object.freeze({1:"ERROR",2:"WARN",3:"INFO",4:"HINT"});function f_(e){let t=u_[e.severity??1]??"ERROR",n=e.range.start.line+1,r=e.range.start.character+1;return`${t} [${n}:${r}] ${e.message}`}i(f_,"pretty");function qf(e,t){let n=t.filter(a=>(a.severity??1)===1);if(n.length===0)return"";let r=n.slice(0,20),o=n.length-20,s=o>0?`
310
325
  ... and ${o} more`:"";return`<diagnostics file="${e}">
311
- ${r.map(ov).join(`
326
+ ${r.map(f_).join(`
312
327
  `)}${s}
313
- </diagnostics>`}i(cf,"report");import{existsSync as lf,readFileSync as sv,statSync as av}from"fs";import xe from"path";import{createRequire as df}from"module";var iv=process.platform==="win32";function pe(e){let t=e.replace(/\\/g,"/");return iv?t.toLowerCase():t}i(pe,"normalizeFsPath");var cv=process.platform==="win32",lv=cv?(process.env.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean):[""];function uf(e){try{return lf(e)&&av(e).isFile()}catch{return!1}}i(uf,"isFile");function ff(e){let t=(process.env.PATH??"").split(xe.delimiter).filter(Boolean);for(let n of t)for(let r of lv){let o=r&&e.toLowerCase().endsWith(r.toLowerCase()),s=xe.join(n,o?e:e+r);if(uf(s))return s}}i(ff,"whichGlobal");function pf(e){return df(xe.join(e,"__kodax_lsp_resolve__.js"))}i(pf,"requireFrom");function $s(e,t,n){let r;try{r=pf(t).resolve(`${e}/package.json`)}catch{return}let o;try{o=JSON.parse(sv(r,"utf8")).bin}catch{return}let s;if(typeof o=="string")s=o;else if(o&&typeof o=="object"){let c=o;s=n&&c[n]||c[e]||Object.values(c)[0]}if(!s)return;let a=xe.join(xe.dirname(r),s);if(uf(a))return{command:process.execPath,args:[a]}}i($s,"resolveNodePackageBin");function mf(e,t){try{return pf(e).resolve("typescript/lib/tsserver.js")}catch{}if(t)try{return df(t).resolve("typescript/lib/tsserver.js")}catch{return}}i(mf,"resolveTsserver");function Os(e,t,n){let r=xe.resolve(n),o=pe(r),s=xe.dirname(xe.resolve(e));if(!pe(s).startsWith(o))return r;for(;;){for(let c of t)if(lf(xe.join(s,c)))return s;if(pe(s)===o)return r;let a=xe.dirname(s);if(a===s)return r;s=a}}i(Os,"findNearestRoot");import{spawn as hf}from"child_process";function dv(e){return process.platform==="win32"&&e!==process.execPath&&!/\.exe$/i.test(e)}i(dv,"needsShell");function Kr(e,t,n){if(dv(e)){let r=[uv(e),...t].join(" ");return hf(r,{...n,shell:!0})}return hf(e,[...t],{...n,shell:!1})}i(Kr,"spawnLspProcess");function uv(e){return/[\s"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}i(uv,"quoteIfNeeded");function Is(){return process.env.KODAX_LSP_DOWNLOAD==="1"&&process.env.KODAX_LSP_NO_DOWNLOAD!=="1"}i(Is,"isAutoInstallEnabled");var fv=5*6e4;function gf(e,t={}){return t.signal?.aborted?Promise.resolve(!1):new Promise(n=>{let r=!1,o,s,a=i(l=>{r||(r=!0,s&&clearTimeout(s),o&&t.signal?.removeEventListener("abort",o),n(l))},"done"),c=Kr(e.command,e.args,{stdio:"ignore",env:process.env,detached:process.platform!=="win32"});o=i(()=>{ge(c),a(!1)},"onAbort"),t.signal?.addEventListener("abort",o,{once:!0}),s=setTimeout(()=>{ge(c),t.debug?.(`install timed out: ${e.command} ${e.args.join(" ")}`),a(!1)},t.timeoutMs??fv),c.on("error",l=>{t.debug?.(`install failed to start: ${l.message}`),a(!1)}),c.on("exit",l=>a(l===0))})}i(gf,"runInstallCommand");function Bn(e,t=[]){let n=ff(e);return n?{command:n,args:t}:void 0}i(Bn,"globalLaunch");function pv({root:e,moduleUrl:t}){let n=mf(e,t);if(!n)return;let o=$s("typescript-language-server",e,"typescript-language-server")??Bn("typescript-language-server");if(o)return{command:o.command,args:[...o.args,"--stdio"],initializationOptions:{tsserver:{path:n}}}}i(pv,"discoverTypescript");var mv={id:"typescript",languageIds:["typescript","typescriptreact","javascript","javascriptreact"],rootMarkers:["tsconfig.json","jsconfig.json","package.json",".git"],discover:pv,installGuidance:"Install the TypeScript language server for in-editor diagnostics: `npm i -D typescript typescript-language-server` (project-local, recommended) or `npm i -g typescript-language-server`."};function hv({root:e}){let n=$s("pyright",e,"pyright-langserver")??Bn("pyright-langserver");if(n)return{command:n.command,args:[...n.args,"--stdio"]}}i(hv,"discoverPyright");var gv={id:"pyright",languageIds:["python"],rootMarkers:["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile",".git"],discover:hv,installGuidance:"Install pyright for Python diagnostics: `npm i -g pyright` (or `pip install pyright`)."};function yf(){return Bn("gopls")}i(yf,"discoverGopls");var yv={id:"gopls",languageIds:["go"],rootMarkers:["go.mod","go.work",".git"],discover:yf,async acquire({signal:e,onProgress:t,debug:n}){return t?.("Installing gopls via `go install`\u2026"),await gf({command:"go",args:["install","golang.org/x/tools/gopls@latest"]},{signal:e,debug:n})?yf():void 0},installGuidance:"Install gopls for Go diagnostics: `go install golang.org/x/tools/gopls@latest` (requires the Go toolchain; ensure GOBIN is on PATH)."};function wv(){return Bn("rust-analyzer")}i(wv,"discoverRustAnalyzer");var bv={id:"rust-analyzer",languageIds:["rust"],rootMarkers:["Cargo.toml","Cargo.lock","rust-project.json",".git"],discover:wv,installGuidance:"Install rust-analyzer for Rust diagnostics: `rustup component add rust-analyzer` (or download a release from https://github.com/rust-lang/rust-analyzer/releases)."};function kv(){return Bn("jdtls")}i(kv,"discoverJdtls");var vv={id:"jdtls",languageIds:["java"],rootMarkers:["pom.xml","build.gradle","build.gradle.kts","settings.gradle",".git"],discover:kv,installGuidance:"Install the Eclipse JDT language server (jdtls) for Java diagnostics and put its launcher on PATH; it requires a Java 21+ runtime. See https://github.com/eclipse-jdtls/eclipse.jdt.ls."},wf=Object.freeze([mv,gv,yv,bv,vv]);import ee from"path";import{fileURLToPath as _v}from"url";import{SymbolKind as J}from"vscode-languageserver-protocol";function Ls(e){try{return _v(e)}catch{return e}}i(Ls,"uriToPath");function Gr(e,t){return e.length===0?t:e.map(n=>`${Ls(n.uri)}:${n.range.start.line+1}:${n.range.start.character+1}`).join(`
314
- `)}i(Gr,"formatLocations");function bf(e){return typeof e=="string"?e:e.value}i(bf,"markedToString");function kf(e){if(!e)return"No hover information.";let t=e.contents;return typeof t=="string"?t.trim()||"No hover information.":Array.isArray(t)?t.map(bf).join(`
315
- `).trim()||"No hover information.":"kind"in t?t.value.trim()||"No hover information.":bf(t).trim()||"No hover information."}i(kf,"formatHover");var xv=Object.freeze({[J.File]:"File",[J.Module]:"Module",[J.Namespace]:"Namespace",[J.Package]:"Package",[J.Class]:"Class",[J.Method]:"Method",[J.Property]:"Property",[J.Field]:"Field",[J.Constructor]:"Constructor",[J.Enum]:"Enum",[J.Interface]:"Interface",[J.Function]:"Function",[J.Variable]:"Variable",[J.Constant]:"Constant",[J.Struct]:"Struct",[J.EnumMember]:"EnumMember",[J.TypeParameter]:"TypeParameter"});function zr(e){return xv[e]??"Symbol"}i(zr,"kindName");function Ms(e){return`${e.start.line+1}:${e.start.character+1}`}i(Ms,"rangeStart");function Ev(e){let t=Ls(e.uri);return"range"in e?`${t}:${Ms(e.range)}`:t}i(Ev,"locationText");function vf(e,t){if(e.length===0)return t;let n=[],r=i((o,s)=>{for(let a of o){let c=" ".repeat(s);"location"in a?n.push(`${c}${zr(a.kind)} ${a.name} (${a.location.range.start.line+1})`):(n.push(`${c}${zr(a.kind)} ${a.name} (${a.range.start.line+1})`),a.children&&a.children.length>0&&r(a.children,s+1))}},"walk");return r(e,0),n.join(`
316
- `)}i(vf,"formatSymbols");function _f(e,t){return e.length===0?t:e.map(n=>{let r=n.containerName?` in ${n.containerName}`:"";return`${zr(n.kind)} ${n.name}${r} ${Ev(n.location)}`}).join(`
317
- `)}i(_f,"formatWorkspaceSymbols");function Ps(e){let t=e.detail?` - ${e.detail}`:"";return`${zr(e.kind)} ${e.name} ${Ls(e.uri)}:${Ms(e.selectionRange)}${t}`}i(Ps,"formatCallHierarchyItem");function xf(e){return e.length===0?"unknown call site":e.map(Ms).join(", ")}i(xf,"formatRanges");function Ef(e,t){return e.length===0?t:e.map(Ps).join(`
318
- `)}i(Ef,"formatCallHierarchyItems");function Sf(e,t){return e.length===0?t:e.map(n=>`${Ps(n.from)} calls at ${xf(n.fromRanges)}`).join(`
319
- `)}i(Sf,"formatIncomingCalls");function Tf(e,t){return e.length===0?t:e.map(n=>`${Ps(n.to)} called at ${xf(n.fromRanges)}`).join(`
320
- `)}i(Tf,"formatOutgoingCalls");import{readFile as Sv}from"fs/promises";import{pathToFileURL as je,fileURLToPath as Tv}from"url";import{createProtocolConnection as Av,StreamMessageReader as Cv,StreamMessageWriter as Rv}from"vscode-languageserver-protocol/node";import{InitializeRequest as $v,InitializedNotification as Ov,DidChangeConfigurationNotification as Iv,DidOpenTextDocumentNotification as Lv,DidChangeTextDocumentNotification as Mv,PublishDiagnosticsNotification as Pv,DefinitionRequest as Nv,HoverRequest as Dv,ReferencesRequest as jv,DocumentSymbolRequest as Fv,WorkspaceSymbolRequest as Uv,ImplementationRequest as qv,CallHierarchyPrepareRequest as Bv,CallHierarchyIncomingCallsRequest as Wv,CallHierarchyOutgoingCallsRequest as Hv,ShutdownRequest as Kv,ExitNotification as zv}from"vscode-languageserver-protocol";var Gv=150,Xv=1e4,Vv=3e4;function Ns(e,t,n){return e.catch(()=>{}),new Promise((r,o)=>{let s=setTimeout(()=>o(new Error(n)),t);e.then(a=>{clearTimeout(s),r(a)},a=>{clearTimeout(s),o(a)})})}i(Ns,"withTimeout");function Jv(e){return e.targetUri!==void 0}i(Jv,"isLocationLink");function Af(e){return e?(Array.isArray(e)?e:[e]).map(n=>Jv(n)?{uri:n.targetUri,range:n.targetSelectionRange}:n):[]}i(Af,"normalizeLocations");function Yv(e,t){if(!e)return{};if(!t)return e;let n=e;for(let r of t.split("."))if(n&&typeof n=="object"&&r in n)n=n[r];else return null;return n}i(Yv,"configurationValue");function Qv(e,t){let n=je(e).href;return{processId:process.pid,rootUri:n,workspaceFolders:[{name:"workspace",uri:n}],capabilities:{workspace:{configuration:!0,workspaceFolders:!0,symbol:{dynamicRegistration:!0},didChangeConfiguration:{dynamicRegistration:!0},didChangeWatchedFiles:{dynamicRegistration:!0}},textDocument:{synchronization:{dynamicRegistration:!0,didSave:!0},publishDiagnostics:{relatedInformation:!0},definition:{dynamicRegistration:!0,linkSupport:!0},implementation:{dynamicRegistration:!0,linkSupport:!0},hover:{dynamicRegistration:!0,contentFormat:["markdown","plaintext"]},references:{dynamicRegistration:!0},documentSymbol:{dynamicRegistration:!0,hierarchicalDocumentSymbolSupport:!0},callHierarchy:{dynamicRegistration:!0}},window:{workDoneProgress:!0}},initializationOptions:t}}i(Qv,"buildInitializeParams");async function Cf(e){let{serverId:t,root:n,launch:r,debug:o}=e,s=e.initializeTimeoutMs??Vv,a=Kr(r.command,r.args,{cwd:n,stdio:["pipe","pipe","pipe"],env:process.env,detached:process.platform!=="win32"}),c=dn(a,{kind:`lsp:${t}`,command:r.command,args:r.args,cwd:n});a.stderr.on("data",E=>o?.(`[${t}] stderr: ${E.toString().trim()}`));let l=Av(new Cv(a.stdout),new Rv(a.stdin)),d=new Map,u=new Set;l.onNotification(Pv.type,E=>{let S;try{S=pe(Tv(E.uri))}catch{return}d.set(S,E.diagnostics??[]);let L=Date.now();for(let U of u)U(S,L)}),l.onRequest("workspace/configuration",E=>(E.items??[]).map(S=>Yv(r.initializationOptions,S.section))),l.onRequest("workspace/workspaceFolders",()=>[{name:"workspace",uri:je(n).href}]),l.onRequest("window/workDoneProgress/create",()=>null),l.onRequest("client/registerCapability",()=>null),l.onRequest("client/unregisterCapability",()=>null),l.listen();let f=new Promise((E,S)=>{a.once("error",L=>S(new Error(`spawn failed: ${L.message}`))),a.once("exit",L=>S(new Error(`server exited early (code ${L??"null"})`)))});try{await Promise.race([Ns(l.sendRequest($v.type,Qv(n,r.initializationOptions)),s,`LSP initialize timed out for ${t}`),f])}catch(E){try{l.dispose()}catch{}throw await ge(a),c(),E}finally{f.catch(()=>{})}l.sendNotification(Ov.type,{}),l.sendNotification(Iv.type,{settings:r.initializationOptions??{}});let m=new Map,h=new Set;async function p(E){let S=pe(E),L=await Sv(E,"utf8"),U=qn(E)??"plaintext",$=je(E).href,F=m.get(S);if(F===void 0){m.set(S,1),d.delete(S);let Ee=Date.now();return l.sendNotification(Lv.type,{textDocument:{uri:$,languageId:U,version:1,text:L}}),Ee}let K=F+1;m.set(S,K);let me=Date.now();return l.sendNotification(Mv.type,{textDocument:{uri:$,version:K},contentChanges:[{text:L}]}),me}i(p,"notifyOpenOrChange");function g(E,S){let L=pe(E);return new Promise(U=>{let $=!1,F,K=i(()=>{$||($=!0,clearTimeout(Ee),F&&clearTimeout(F),u.delete(me),h.delete(K),U())},"finish"),me=i((he,an)=>{he!==L||an<S.afterMs||(F&&clearTimeout(F),F=setTimeout(K,Gv))},"listener");u.add(me),h.add(K);let Ee=setTimeout(K,S.timeoutMs)})}i(g,"waitForDiagnostics");function w(E){return d.get(pe(E))??[]}i(w,"diagnostics");function y(E,S){return Ns(E,Xv,`${t} ${S} timed out`)}i(y,"navTimeout");async function b(E,S){let L={uri:je(E).href},U=await y(l.sendRequest(Nv.type,{textDocument:L,position:S}),"definition");return Af(U)}i(b,"definition");async function v(E,S){let L={uri:je(E).href};return y(l.sendRequest(Dv.type,{textDocument:L,position:S}),"hover")}i(v,"hover");async function k(E,S){let L={uri:je(E).href};return await y(l.sendRequest(jv.type,{textDocument:L,position:S,context:{includeDeclaration:!0}}),"references")??[]}i(k,"references");async function C(E){let S={uri:je(E).href};return await y(l.sendRequest(Fv.type,{textDocument:S}),"documentSymbol")??[]}i(C,"documentSymbols");async function T(E){return await y(l.sendRequest(Uv.type,{query:E}),"workspaceSymbol")??[]}i(T,"workspaceSymbols");async function x(E,S){let L={uri:je(E).href},U=await y(l.sendRequest(qv.type,{textDocument:L,position:S}),"implementation");return Af(U)}i(x,"implementation");async function R(E,S){let L={uri:je(E).href};return await y(l.sendRequest(Bv.type,{textDocument:L,position:S}),"prepareCallHierarchy")??[]}i(R,"prepareCallHierarchy");async function A(E){return await y(l.sendRequest(Wv.type,{item:E}),"incomingCalls")??[]}i(A,"incomingCalls");async function D(E){return await y(l.sendRequest(Hv.type,{item:E}),"outgoingCalls")??[]}i(D,"outgoingCalls");function P(){$t(a)}i(P,"killSync");async function G(){for(let E of[...h])E();try{await Ns(l.sendRequest(Kv.type),2e3,"shutdown timeout"),l.sendNotification(zv.type)}catch{}try{l.dispose()}catch{}await new Promise(E=>{if(a.exitCode!==null||a.signalCode!==null){E();return}let S=setTimeout(()=>{$t(a)},1500);a.once("exit",()=>{clearTimeout(S),c(),E()})})}return i(G,"shutdown"),{serverId:t,root:n,notifyOpenOrChange:p,waitForDiagnostics:g,diagnostics:w,definition:b,hover:v,references:k,documentSymbols:C,workspaceSymbols:T,implementation:x,prepareCallHierarchy:R,incomingCalls:A,outgoingCalls:D,shutdown:G,killSync:P}}i(Cf,"createLspClient");var Zv=5e3,Ds=class{static{i(this,"LspService")}config;clients=new Map;broken=new Set;spawning=new Map;servers;shuttingDown=!1;constructor(t={}){this.config=t,this.servers=t.servers??wf}async getDiagnosticsBlock(t,n={}){if(n.signal?.aborted)return"";let r=qn(t);if(!r)return"";let o=this.servers.filter(f=>f.languageIds.includes(r));if(o.length===0)return"";let s=ee.resolve(t),a=n.gitRoot??ee.dirname(s),c=this.config.documentTimeoutMs??Zv,l=[];for(let f of o){let m=Os(s,f.rootMarkers,a),h=await this.getClient(f,m,n);h&&l.push(h)}if(l.length===0)return"";await Promise.all(l.map(async f=>{try{let m=await f.notifyOpenOrChange(s);await f.waitForDiagnostics(s,{afterMs:m,timeoutMs:c})}catch(m){this.config.debug?.(`diagnostics wait failed (${f.serverId}): ${m.message}`)}}));let d=[];for(let f of l)d.push(...f.diagnostics(s));let u=cf(s,d);return u?`
328
+ </diagnostics>`}i(qf,"report");import{existsSync as Bf,readFileSync as m_,statSync as h_}from"fs";import Te from"path";import{createRequire as Wf}from"module";var p_=process.platform==="win32";function ye(e){let t=e.replace(/\\/g,"/");return p_?t.toLowerCase():t}i(ye,"normalizeFsPath");var g_=process.platform==="win32",y_=g_?(process.env.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean):[""];function Hf(e){try{return Bf(e)&&h_(e).isFile()}catch{return!1}}i(Hf,"isFile");function zf(e){let t=(process.env.PATH??"").split(Te.delimiter).filter(Boolean);for(let n of t)for(let r of y_){let o=r&&e.toLowerCase().endsWith(r.toLowerCase()),s=Te.join(n,o?e:e+r);if(Hf(s))return s}}i(zf,"whichGlobal");function Gf(e){return Wf(Te.join(e,"__kodax_lsp_resolve__.js"))}i(Gf,"requireFrom");function Bs(e,t,n){let r;try{r=Gf(t).resolve(`${e}/package.json`)}catch{return}let o;try{o=JSON.parse(m_(r,"utf8")).bin}catch{return}let s;if(typeof o=="string")s=o;else if(o&&typeof o=="object"){let c=o;s=n&&c[n]||c[e]||Object.values(c)[0]}if(!s)return;let a=Te.join(Te.dirname(r),s);if(Hf(a))return{command:process.execPath,args:[a]}}i(Bs,"resolveNodePackageBin");function Kf(e,t){try{return Gf(e).resolve("typescript/lib/tsserver.js")}catch{}if(t)try{return Wf(t).resolve("typescript/lib/tsserver.js")}catch{return}}i(Kf,"resolveTsserver");function Ws(e,t,n){let r=Te.resolve(n),o=ye(r),s=Te.dirname(Te.resolve(e));if(!ye(s).startsWith(o))return r;for(;;){for(let c of t)if(Bf(Te.join(s,c)))return s;if(ye(s)===o)return r;let a=Te.dirname(s);if(a===s)return r;s=a}}i(Ws,"findNearestRoot");import{spawn as Xf}from"child_process";function w_(e){return process.platform==="win32"&&e!==process.execPath&&!/\.exe$/i.test(e)}i(w_,"needsShell");function Zr(e,t,n){if(w_(e)){let r=[b_(e),...t].join(" ");return Xf(r,{...n,shell:!0})}return Xf(e,[...t],{...n,shell:!1})}i(Zr,"spawnLspProcess");function b_(e){return/[\s"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}i(b_,"quoteIfNeeded");function Hs(){return process.env.KODAX_LSP_DOWNLOAD==="1"&&process.env.KODAX_LSP_NO_DOWNLOAD!=="1"}i(Hs,"isAutoInstallEnabled");var k_=5*6e4;function Vf(e,t={}){return t.signal?.aborted?Promise.resolve(!1):new Promise(n=>{let r=!1,o,s,a=i(l=>{r||(r=!0,s&&clearTimeout(s),o&&t.signal?.removeEventListener("abort",o),n(l))},"done"),c=Zr(e.command,e.args,{stdio:"ignore",env:process.env,detached:process.platform!=="win32"});o=i(()=>{ut(c),a(!1)},"onAbort"),t.signal?.addEventListener("abort",o,{once:!0}),s=setTimeout(()=>{ut(c),t.debug?.(`install timed out: ${e.command} ${e.args.join(" ")}`),a(!1)},t.timeoutMs??k_),c.on("error",l=>{t.debug?.(`install failed to start: ${l.message}`),a(!1)}),c.on("exit",l=>a(l===0))})}i(Vf,"runInstallCommand");function Kn(e,t=[]){let n=zf(e);return n?{command:n,args:t}:void 0}i(Kn,"globalLaunch");function v_({root:e,moduleUrl:t}){let n=Kf(e,t);if(!n)return;let o=Bs("typescript-language-server",e,"typescript-language-server")??Kn("typescript-language-server");if(o)return{command:o.command,args:[...o.args,"--stdio"],initializationOptions:{tsserver:{path:n}}}}i(v_,"discoverTypescript");var __={id:"typescript",languageIds:["typescript","typescriptreact","javascript","javascriptreact"],rootMarkers:["tsconfig.json","jsconfig.json","package.json",".git"],discover:v_,installGuidance:"Install the TypeScript language server for in-editor diagnostics: `npm i -D typescript typescript-language-server` (project-local, recommended) or `npm i -g typescript-language-server`."};function x_({root:e}){let n=Bs("pyright",e,"pyright-langserver")??Kn("pyright-langserver");if(n)return{command:n.command,args:[...n.args,"--stdio"]}}i(x_,"discoverPyright");var E_={id:"pyright",languageIds:["python"],rootMarkers:["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile",".git"],discover:x_,installGuidance:"Install pyright for Python diagnostics: `npm i -g pyright` (or `pip install pyright`)."};function Jf(){return Kn("gopls")}i(Jf,"discoverGopls");var S_={id:"gopls",languageIds:["go"],rootMarkers:["go.mod","go.work",".git"],discover:Jf,async acquire({signal:e,onProgress:t,debug:n}){return t?.("Installing gopls via `go install`\u2026"),await Vf({command:"go",args:["install","golang.org/x/tools/gopls@latest"]},{signal:e,debug:n})?Jf():void 0},installGuidance:"Install gopls for Go diagnostics: `go install golang.org/x/tools/gopls@latest` (requires the Go toolchain; ensure GOBIN is on PATH)."};function T_(){return Kn("rust-analyzer")}i(T_,"discoverRustAnalyzer");var A_={id:"rust-analyzer",languageIds:["rust"],rootMarkers:["Cargo.toml","Cargo.lock","rust-project.json",".git"],discover:T_,installGuidance:"Install rust-analyzer for Rust diagnostics: `rustup component add rust-analyzer` (or download a release from https://github.com/rust-lang/rust-analyzer/releases)."};function C_(){return Kn("jdtls")}i(C_,"discoverJdtls");var $_={id:"jdtls",languageIds:["java"],rootMarkers:["pom.xml","build.gradle","build.gradle.kts","settings.gradle",".git"],discover:C_,installGuidance:"Install the Eclipse JDT language server (jdtls) for Java diagnostics and put its launcher on PATH; it requires a Java 21+ runtime. See https://github.com/eclipse-jdtls/eclipse.jdt.ls."},Yf=Object.freeze([__,E_,S_,A_,$_]);import ne from"path";import{fileURLToPath as R_}from"url";import{SymbolKind as J}from"vscode-languageserver-protocol";function zs(e){try{return R_(e)}catch{return e}}i(zs,"uriToPath");function eo(e,t){return e.length===0?t:e.map(n=>`${zs(n.uri)}:${n.range.start.line+1}:${n.range.start.character+1}`).join(`
329
+ `)}i(eo,"formatLocations");function Zf(e){return typeof e=="string"?e:e.value}i(Zf,"markedToString");function Qf(e){if(!e)return"No hover information.";let t=e.contents;return typeof t=="string"?t.trim()||"No hover information.":Array.isArray(t)?t.map(Zf).join(`
330
+ `).trim()||"No hover information.":"kind"in t?t.value.trim()||"No hover information.":Zf(t).trim()||"No hover information."}i(Qf,"formatHover");var O_=Object.freeze({[J.File]:"File",[J.Module]:"Module",[J.Namespace]:"Namespace",[J.Package]:"Package",[J.Class]:"Class",[J.Method]:"Method",[J.Property]:"Property",[J.Field]:"Field",[J.Constructor]:"Constructor",[J.Enum]:"Enum",[J.Interface]:"Interface",[J.Function]:"Function",[J.Variable]:"Variable",[J.Constant]:"Constant",[J.Struct]:"Struct",[J.EnumMember]:"EnumMember",[J.TypeParameter]:"TypeParameter"});function Qr(e){return O_[e]??"Symbol"}i(Qr,"kindName");function Gs(e){return`${e.start.line+1}:${e.start.character+1}`}i(Gs,"rangeStart");function I_(e){let t=zs(e.uri);return"range"in e?`${t}:${Gs(e.range)}`:t}i(I_,"locationText");function ep(e,t){if(e.length===0)return t;let n=[],r=i((o,s)=>{for(let a of o){let c=" ".repeat(s);"location"in a?n.push(`${c}${Qr(a.kind)} ${a.name} (${a.location.range.start.line+1})`):(n.push(`${c}${Qr(a.kind)} ${a.name} (${a.range.start.line+1})`),a.children&&a.children.length>0&&r(a.children,s+1))}},"walk");return r(e,0),n.join(`
331
+ `)}i(ep,"formatSymbols");function tp(e,t){return e.length===0?t:e.map(n=>{let r=n.containerName?` in ${n.containerName}`:"";return`${Qr(n.kind)} ${n.name}${r} ${I_(n.location)}`}).join(`
332
+ `)}i(tp,"formatWorkspaceSymbols");function Ks(e){let t=e.detail?` - ${e.detail}`:"";return`${Qr(e.kind)} ${e.name} ${zs(e.uri)}:${Gs(e.selectionRange)}${t}`}i(Ks,"formatCallHierarchyItem");function np(e){return e.length===0?"unknown call site":e.map(Gs).join(", ")}i(np,"formatRanges");function rp(e,t){return e.length===0?t:e.map(Ks).join(`
333
+ `)}i(rp,"formatCallHierarchyItems");function op(e,t){return e.length===0?t:e.map(n=>`${Ks(n.from)} calls at ${np(n.fromRanges)}`).join(`
334
+ `)}i(op,"formatIncomingCalls");function ip(e,t){return e.length===0?t:e.map(n=>`${Ks(n.to)} called at ${np(n.fromRanges)}`).join(`
335
+ `)}i(ip,"formatOutgoingCalls");import{readFile as L_}from"fs/promises";import{pathToFileURL as qe,fileURLToPath as M_}from"url";import{createProtocolConnection as P_,StreamMessageReader as N_,StreamMessageWriter as D_}from"vscode-languageserver-protocol/node";import{InitializeRequest as F_,InitializedNotification as j_,DidChangeConfigurationNotification as U_,DidOpenTextDocumentNotification as q_,DidChangeTextDocumentNotification as B_,PublishDiagnosticsNotification as W_,DefinitionRequest as H_,HoverRequest as z_,ReferencesRequest as G_,DocumentSymbolRequest as K_,WorkspaceSymbolRequest as X_,ImplementationRequest as V_,CallHierarchyPrepareRequest as J_,CallHierarchyIncomingCallsRequest as Y_,CallHierarchyOutgoingCallsRequest as Z_,ShutdownRequest as Q_,ExitNotification as ex}from"vscode-languageserver-protocol";var tx=150,nx=1e4,rx=3e4;function Xs(e,t,n){return e.catch(()=>{}),new Promise((r,o)=>{let s=setTimeout(()=>o(new Error(n)),t);e.then(a=>{clearTimeout(s),r(a)},a=>{clearTimeout(s),o(a)})})}i(Xs,"withTimeout");function ox(e){return e.targetUri!==void 0}i(ox,"isLocationLink");function sp(e){return e?(Array.isArray(e)?e:[e]).map(n=>ox(n)?{uri:n.targetUri,range:n.targetSelectionRange}:n):[]}i(sp,"normalizeLocations");function ix(e,t){if(!e)return{};if(!t)return e;let n=e;for(let r of t.split("."))if(n&&typeof n=="object"&&r in n)n=n[r];else return null;return n}i(ix,"configurationValue");function sx(e,t){let n=qe(e).href;return{processId:process.pid,rootUri:n,workspaceFolders:[{name:"workspace",uri:n}],capabilities:{workspace:{configuration:!0,workspaceFolders:!0,symbol:{dynamicRegistration:!0},didChangeConfiguration:{dynamicRegistration:!0},didChangeWatchedFiles:{dynamicRegistration:!0}},textDocument:{synchronization:{dynamicRegistration:!0,didSave:!0},publishDiagnostics:{relatedInformation:!0},definition:{dynamicRegistration:!0,linkSupport:!0},implementation:{dynamicRegistration:!0,linkSupport:!0},hover:{dynamicRegistration:!0,contentFormat:["markdown","plaintext"]},references:{dynamicRegistration:!0},documentSymbol:{dynamicRegistration:!0,hierarchicalDocumentSymbolSupport:!0},callHierarchy:{dynamicRegistration:!0}},window:{workDoneProgress:!0}},initializationOptions:t}}i(sx,"buildInitializeParams");async function ap(e){let{serverId:t,root:n,launch:r,debug:o}=e,s=e.initializeTimeoutMs??rx,a=Zr(r.command,r.args,{cwd:n,stdio:["pipe","pipe","pipe"],env:process.env,detached:process.platform!=="win32"}),c=hn(a,{kind:`lsp:${t}`,command:r.command,args:r.args,cwd:n});a.stderr.on("data",E=>o?.(`[${t}] stderr: ${E.toString().trim()}`));let l=P_(new N_(a.stdout),new D_(a.stdin)),d=new Map,u=new Set;l.onNotification(W_.type,E=>{let T;try{T=ye(M_(E.uri))}catch{return}d.set(T,E.diagnostics??[]);let C=Date.now();for(let U of u)U(T,C)}),l.onRequest("workspace/configuration",E=>(E.items??[]).map(T=>ix(r.initializationOptions,T.section))),l.onRequest("workspace/workspaceFolders",()=>[{name:"workspace",uri:qe(n).href}]),l.onRequest("window/workDoneProgress/create",()=>null),l.onRequest("client/registerCapability",()=>null),l.onRequest("client/unregisterCapability",()=>null),l.listen();let f=new Promise((E,T)=>{a.once("error",C=>T(new Error(`spawn failed: ${C.message}`))),a.once("exit",C=>T(new Error(`server exited early (code ${C??"null"})`)))});try{await Promise.race([Xs(l.sendRequest(F_.type,sx(n,r.initializationOptions)),s,`LSP initialize timed out for ${t}`),f])}catch(E){try{l.dispose()}catch{}throw await ut(a),c(),E}finally{f.catch(()=>{})}l.sendNotification(j_.type,{}),l.sendNotification(U_.type,{settings:r.initializationOptions??{}});let m=new Map,h=new Set;async function p(E){let T=ye(E),C=await L_(E,"utf8"),U=Gn(E)??"plaintext",L=qe(E).href,F=m.get(T);if(F===void 0){m.set(T,1),d.delete(T);let Ae=Date.now();return l.sendNotification(q_.type,{textDocument:{uri:L,languageId:U,version:1,text:C}}),Ae}let G=F+1;m.set(T,G);let ue=Date.now();return l.sendNotification(B_.type,{textDocument:{uri:L,version:G},contentChanges:[{text:C}]}),ue}i(p,"notifyOpenOrChange");function g(E,T){let C=ye(E);return new Promise(U=>{let L=!1,F,G=i(()=>{L||(L=!0,clearTimeout(Ae),F&&clearTimeout(F),u.delete(ue),h.delete(G),U())},"finish"),ue=i((we,fn)=>{we!==C||fn<T.afterMs||(F&&clearTimeout(F),F=setTimeout(G,tx))},"listener");u.add(ue),h.add(G);let Ae=setTimeout(G,T.timeoutMs)})}i(g,"waitForDiagnostics");function w(E){return d.get(ye(E))??[]}i(w,"diagnostics");function y(E,T){return Xs(E,nx,`${t} ${T} timed out`)}i(y,"navTimeout");async function b(E,T){let C={uri:qe(E).href},U=await y(l.sendRequest(H_.type,{textDocument:C,position:T}),"definition");return sp(U)}i(b,"definition");async function v(E,T){let C={uri:qe(E).href};return y(l.sendRequest(z_.type,{textDocument:C,position:T}),"hover")}i(v,"hover");async function k(E,T){let C={uri:qe(E).href};return await y(l.sendRequest(G_.type,{textDocument:C,position:T,context:{includeDeclaration:!0}}),"references")??[]}i(k,"references");async function $(E){let T={uri:qe(E).href};return await y(l.sendRequest(K_.type,{textDocument:T}),"documentSymbol")??[]}i($,"documentSymbols");async function S(E){return await y(l.sendRequest(X_.type,{query:E}),"workspaceSymbol")??[]}i(S,"workspaceSymbols");async function x(E,T){let C={uri:qe(E).href},U=await y(l.sendRequest(V_.type,{textDocument:C,position:T}),"implementation");return sp(U)}i(x,"implementation");async function R(E,T){let C={uri:qe(E).href};return await y(l.sendRequest(J_.type,{textDocument:C,position:T}),"prepareCallHierarchy")??[]}i(R,"prepareCallHierarchy");async function A(E){return await y(l.sendRequest(Y_.type,{item:E}),"incomingCalls")??[]}i(A,"incomingCalls");async function O(E){return await y(l.sendRequest(Z_.type,{item:E}),"outgoingCalls")??[]}i(O,"outgoingCalls");function P(){Nt(a)}i(P,"killSync");async function q(){for(let E of[...h])E();try{await Xs(l.sendRequest(Q_.type),2e3,"shutdown timeout"),l.sendNotification(ex.type)}catch{}try{l.dispose()}catch{}await new Promise(E=>{if(a.exitCode!==null||a.signalCode!==null){E();return}let T=setTimeout(()=>{Nt(a)},1500);a.once("exit",()=>{clearTimeout(T),c(),E()})})}return i(q,"shutdown"),{serverId:t,root:n,notifyOpenOrChange:p,waitForDiagnostics:g,diagnostics:w,definition:b,hover:v,references:k,documentSymbols:$,workspaceSymbols:S,implementation:x,prepareCallHierarchy:R,incomingCalls:A,outgoingCalls:O,shutdown:q,killSync:P}}i(ap,"createLspClient");var ax=5e3,Vs=class{static{i(this,"LspService")}config;clients=new Map;broken=new Set;spawning=new Map;servers;shuttingDown=!1;constructor(t={}){this.config=t,this.servers=t.servers??Yf}async getDiagnosticsBlock(t,n={}){if(n.signal?.aborted)return"";let r=Gn(t);if(!r)return"";let o=this.servers.filter(f=>f.languageIds.includes(r));if(o.length===0)return"";let s=ne.resolve(t),a=n.gitRoot??ne.dirname(s),c=this.config.documentTimeoutMs??ax,l=[];for(let f of o){let m=Ws(s,f.rootMarkers,a),h=await this.getClient(f,m,n);h&&l.push(h)}if(l.length===0)return"";await Promise.all(l.map(async f=>{try{let m=await f.notifyOpenOrChange(s);await f.waitForDiagnostics(s,{afterMs:m,timeoutMs:c})}catch(m){this.config.debug?.(`diagnostics wait failed (${f.serverId}): ${m.message}`)}}));let d=[];for(let f of l)d.push(...f.diagnostics(s));let u=qf(s,d);return u?`
321
336
 
322
337
  LSP errors detected in this file, please fix:
323
- ${u}`:""}async getDefinition(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.definition(ee.resolve(t),n).catch(()=>[]);return Gr(s,"No definition found at that position.")}async getHover(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.hover(ee.resolve(t),n).catch(()=>null);return kf(s)}async getReferences(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.references(ee.resolve(t),n).catch(()=>[]);return Gr(s,"No references found at that position.")}async getDocumentSymbols(t,n={}){let r=await this.navClient(t,n);if(r.kind!=="client")return r.message;let o=await r.client.documentSymbols(ee.resolve(t)).catch(()=>[]);return vf(o,"No symbols found in this file.")}async getWorkspaceSymbols(t,n={}){let r=await this.workspaceClients(n);if(r.length===0)return"No language server is available for workspace symbol search.";let o=await Promise.all(r.map(s=>s.workspaceSymbols(t).catch(()=>[])));return _f(o.flat(),"No workspace symbols found for that query.")}async getImplementation(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.implementation(ee.resolve(t),n).catch(()=>[]);return Gr(s,"No implementation found at that position.")}async getPrepareCallHierarchy(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.prepareCallHierarchy(ee.resolve(t),n).catch(()=>[]);return Ef(s,"No call hierarchy item found at that position.")}async getIncomingCalls(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=ee.resolve(t),a=await o.client.prepareCallHierarchy(s,n).catch(()=>[]);if(a.length===0)return"No call hierarchy item found at that position.";let c=await Promise.all(a.map(l=>o.client.incomingCalls(l).catch(()=>[])));return Sf(c.flat(),"No incoming calls found for that symbol.")}async getOutgoingCalls(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=ee.resolve(t),a=await o.client.prepareCallHierarchy(s,n).catch(()=>[]);if(a.length===0)return"No call hierarchy item found at that position.";let c=await Promise.all(a.map(l=>o.client.outgoingCalls(l).catch(()=>[])));return Tf(c.flat(),"No outgoing calls found for that symbol.")}async navClient(t,n){let r=qn(t);if(!r)return{kind:"message",message:`No language server is configured for ${ee.basename(t)}.`};let o=this.servers.filter(c=>c.languageIds.includes(r));if(o.length===0)return{kind:"message",message:`No language server is configured for ${ee.basename(t)}.`};let s=ee.resolve(t),a=n.gitRoot??ee.dirname(s);for(let c of o){let l=Os(s,c.rootMarkers,a),d=await this.getClient(c,l,n);if(d)return await d.notifyOpenOrChange(s).catch(()=>{}),{kind:"client",client:d}}return{kind:"message",message:o.map(c=>c.installGuidance).join(`
324
- `)}}async workspaceClients(t){let n=ee.resolve(t.gitRoot??process.cwd()),r=[];for(let o of this.servers){let s=await this.getClient(o,n,t);s&&r.push(s)}return r}async shutdownAll(){this.shuttingDown=!0;try{await Promise.all([...this.spawning.values()].map(n=>n.catch(()=>{})));let t=[...this.clients.values()];this.clients.clear(),this.broken.clear(),await Promise.all(t.map(n=>n.shutdown().catch(()=>{})))}finally{this.shuttingDown=!1}}killAllSync(){for(let t of this.clients.values())t.killSync();this.clients.clear()}resetBroken(t){t?this.broken.delete(t):this.broken.clear()}async getClient(t,n,r){let o=`${pe(n)}|${t.id}`,s=this.clients.get(o);if(s)return s;if(this.broken.has(o))return;let a=this.spawning.get(o);if(a)return a;let c=this.spawnClient(t,n,o,r);this.spawning.set(o,c);try{return await c}finally{this.spawning.delete(o)}}async spawnClient(t,n,r,o){try{let s=t.discover({root:n,moduleUrl:this.config.moduleUrl});if(s||(s=await this.acquireIfEnabled(t,n,o)),!s){this.broken.add(r),this.config.debug?.(`${t.id} not installed at ${n} \u2014 ${t.installGuidance}`);return}o.onProgress?.(`Starting ${t.id} language server\u2026`);let c=await(this.config.createClient??Cf)({serverId:t.id,root:n,launch:s,debug:this.config.debug});if(this.shuttingDown){await c.shutdown().catch(()=>{});return}return this.clients.set(r,c),c}catch(s){this.broken.add(r),this.config.debug?.(`${t.id} failed to start at ${n}: ${s.message}`);return}}async acquireIfEnabled(t,n,r){if(!(!t.acquire||!Is()))try{return await t.acquire({root:n,signal:r.signal,onProgress:r.onProgress,debug:this.config.debug})}catch(o){this.config.debug?.(`${t.id} auto-install failed: ${o.message}`);return}}},Wn,Rf=!1;function $f(){let e=Hn()?.lsp;if(!(e===!1||e===void 0&&process.env.KODAX_LSP==="0"))return Wn||(Wn=new Ds({moduleUrl:import.meta.url,debug:process.env.KODAX_DEBUG_LSP?t=>process.stderr.write(`[kodax:lsp] ${t}
325
- `):void 0}),Rf||(Rf=!0,process.once("exit",()=>Wn?.killAllSync()))),Wn}i($f,"getDefaultLspService");async function JM(){await Wn?.shutdownAll()}i(JM,"shutdownDefaultLspService");import Of from"node:path";var e_=80;function t_(e){let t=e.trim().replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,e_);return!t||t==="."||t===".."?"session":t}i(t_,"sanitizeScratchSessionId");function If(e){let t=e.session?.id?.trim();if(!t)return;let n=e.context?.gitRoot?.trim(),r=n?Of.resolve(n):Q(e.context);return Of.resolve(r,".agent","tmp","sessions",t_(t))}i(If,"getSessionScratchDir");import{join as n_}from"node:path";function r_(e,t){if(t&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return n_(e,t)}i(r_,"resolveResumeFromRunDir");function cP(e){let{options:t,runtime:n,managedProtocolPayloadRef:r,sessionId:o}=e,s=t.events??{},a=Q(t.context),c=If(t);return{backups:new Map,gitRoot:t.context?.gitRoot??void 0,sessionId:o,taskSurface:t.context?.taskSurface,agentProfile:t.context?.agentProfile,selfManual:t.selfManual,skillDynamicContext:t.skillDynamicContext,lspService:t.context?.lspService??$f(),executionCwd:a,sessionScratchDir:c,extensionRuntime:n,askUser:s.askUser,askUserMulti:s.askUserMulti,askUserInput:s.askUserInput,exitPlanMode:s.exitPlanMode,abortSignal:t.abortSignal,managedProtocolRole:t.context?.managedProtocolEmission?.enabled?t.context.managedProtocolEmission.role:void 0,emitManagedProtocol:t.context?.managedProtocolEmission?.enabled?l=>{r.current=Sd(r.current,l)}:void 0,mutationTracker:t.context?.mutationTracker,planModeBlockCheck:t.context?.planModeBlockCheck,guardrails:t.guardrails,parentAgentConfig:{provider:t.provider,model:t.modelOverride??t.model,reasoningMode:t.reasoningMode,effort:t.effort,repoIntelligenceMode:t.context?.repoIntelligenceMode,repoIntelligenceTrace:t.context?.repoIntelligenceTrace},parentEvents:s,onChildProgress:void 0,childTaskRegistry:t.context?.inheritedChildTaskRegistry??new Map,currentAgentId:t.context?.currentAgentId,parentAgentId:t.context?.parentAgentId,goalContext:t.context?.goalRuntime?.goalContext,sendMessageTurnCounter:{count:0},childAbortControllers:new Map,childProgressSnapshots:new Map,workflowRunProgress:new Map,workflowHost:s_(t,o)}}i(cP,"buildToolExecutionContext");function o_(e,t){return{...t?{sessionId:t}:{},...e.context?.agentProfile?.surface?{surface:e.context.agentProfile.surface}:{},...e.context?.taskSurface?{taskSurface:e.context.taskSurface}:{},...e.context?.gitRoot?{projectRoot:e.context.gitRoot}:{}}}i(o_,"buildWorkflowHostMetadata");function i_(e){let t=e.items.filter(s=>s.kind==="agent"),n=t.filter(s=>s.status==="running").map(s=>s.title),r=e.activePhaseId===void 0?void 0:e.items.find(s=>s.id===e.activePhaseId)?.title;return{status:e.status==="completed"?"completed":e.status==="failed"?"failed":e.status==="cancelled"?"stopped":"running",workflowName:e.displayName??e.workflowName,...r!==void 0?{phase:r}:{},...e.activePhaseIndex!==void 0?{phaseIndex:e.activePhaseIndex}:{},...e.phaseCount!==void 0?{phaseTotal:e.phaseCount}:{},activeAgents:n,completedAgents:t.filter(s=>s.status==="completed").length,failedAgents:t.filter(s=>s.status==="failed").length,stoppedAgents:t.filter(s=>s.status==="cancelled").length,totalSpawned:e.progress.spawnedAgents,...e.progress.plannedItems!==void 0?{plannedAgents:e.progress.plannedItems}:{},...e.elapsedMs!==void 0?{elapsedMs:e.elapsedMs}:{}}}i(i_,"toWorkflowRunProgressView");function s_(e,t){let n=e.workflowRunsBaseDir;if(process.env.KODAX_DEBUG_WORKFLOW_GATE){let o=n===void 0?"no-host: workflowRunsBaseDir undefined":e.agentMode!=="amaw"&&e.agentMode!=="ama"?`no-host: agentMode=${String(e.agentMode)} (need ama|amaw)`:"host wired";process.stderr.write(`[workflow-gate] agentMode=${String(e.agentMode)} runsBaseDir=${n??"<undef>"} -> ${o}
326
- `)}if(n===void 0||e.agentMode!=="amaw"&&e.agentMode!=="ama")return;let r=i(async({manifest:o,source:s,args:a,resumeFromRunId:c,signal:l})=>{let[{startManagedWorkflow:d},{getDefaultWorkflowRunManager:u}]=await Promise.all([import("./host-FLG7FJZT.js"),import("./run-manager-IU5COC6X.js")]),f=[e.abortSignal,l].filter(w=>w!==void 0),m=f.length===0?void 0:f.length===1?f[0]:AbortSignal.any(f),h=await d({source:{kind:"inline",manifest:o,source:s},args:a,options:e,runsBaseDir:n,manager:u(),...(()=>{let w=r_(n,c);return w?{resumeFromRunDir:w}:{}})(),...m?{signal:m}:{},processMetadata:{hostMetadata:o_(e,t)}});if(h.kind==="declined")return{kind:"declined",reason:h.reason};let p=h.managed.done.then(w=>{let y=h.managed.getSnapshot?.(),b=w.kind==="completed"?w.state.events.reduce((v,k)=>{if(k.type==="agent_unverified"){let C=k.data?.name??k.data?.taskId;v.push(typeof C=="string"&&C.length>0?C:"agent")}return v},[]):[];return{kind:"started",runId:h.runId,...y?.status!==void 0?{status:y.status}:{},...y?.resultText!==void 0?{resultText:y.resultText}:{},...y?.error!==void 0?{error:y.error}:{},...b.length>0?{verificationWarnings:b}:{}}}),g=i(()=>{let w=h.managed.getProcessSnapshot?.();return w?i_(w):void 0},"getProgress");return{kind:"started",runId:h.runId,done:p,getProgress:g}},"startInline");return{startInline:r,runInline:i(async o=>{let s=await r(o);return s.kind==="declined"?{kind:"declined",reason:s.reason}:await s.done},"runInline")}}i(s_,"buildWorkflowToolHost");export{h_ as a,g_ as b,y_ as c,Qr as d,Zr as e,Q as f,q as g,L_ as h,sa as i,It as j,Vn as k,to as l,Lt as m,N as n,Mt as o,Pt as p,un as q,Nt as r,so as s,fa as t,z_ as u,pa as v,wa as w,uo as x,ba as y,rx as z,po as A,ho as B,Rp as C,$p as D,go as E,wo as F,bo as G,mn as H,ko as I,vo as J,Te as K,YE as L,gc as M,Oo as N,Io as O,yc as P,Lo as Q,Mo as R,Po as S,Do as T,Fo as U,Uo as V,qo as W,Bo as X,wn as Y,X as Z,Rh as _,Hh as $,zS as aa,GS as ba,XS as ca,kn as da,wr as ea,br as fa,vn as ga,Kh as ha,zh as ia,VS as ja,ri as ka,oi as la,ii as ma,si as na,al as oa,_n as pa,pt as qa,ai as ra,Gt as sa,ci as ta,ul as ua,B as va,li as wa,di as xa,fi as ya,pi as za,Og as Aa,ml as Ba,hl as Ca,Xl as Da,Vl as Ea,cC as Fa,GT as Ga,XT as Ha,VT as Ia,Mg as Ja,_r as Ka,JT as La,Oe as Ma,ae as Na,Pb as Oa,Nb as Pa,ow as Qa,$C as Ra,iw as Sa,OC as Ta,IC as Ua,Ed as Va,Sd as Wa,LC as Xa,MC as Ya,PC as Za,NC as _a,Ad as $a,WC as ab,HC as bb,uw as cb,Cd as db,KC as eb,QC as fb,ZC as gb,eR as hb,tR as ib,nR as jb,rR as kb,oR as lb,iR as mb,sR as nb,aR as ob,cR as pb,Pd as qb,lR as rb,dR as sb,If as tb,qn as ub,cf as vb,wf as wb,Ds as xb,$f as yb,JM as zb,vd as Ab,_d as Bb,xd as Cb,cP as Db,Hu as Eb,Ku as Fb,jn as Gb,Ek as Hb,Ss as Ib,Vu as Jb,w0 as Kb,Ak as Lb,Ck as Mb,b0 as Nb,Rn as Ob,Mr as Pb,tn as Qb,et as Rb,Wi as Sb,zi as Tb,$n as Ub,On as Vb,ou as Wb,iu as Xb,Vi as Yb,Ie as Zb,eb as _b,Qi as $b,bt as ac,nn as bc,rb as cc,In as dc,ib as ec,ub as fc,fb as gc,vt as hc,Ln as ic,Mn as jc,bb as kc,ss as lc,_t as mc,xt as nc,kb as oc,vb as pc,_b as qc,Tb as rc,Cb as sc,Ur as tc,bu as uc,Ib as vc,Lb as wc,Ts as xc,As as yc,L0 as zc,M0 as Ac,P0 as Bc,N0 as Cc,D0 as Dc,Fn as Ec,Wr as Fc,qr as Gc,Uu as Hc,n0 as Ic,Oi as Jc,SC as Kc,mR as Lc,Fd as Mc,zd as Nc,Gd as Oc,qR as Pc,Xd as Qc,zR as Rc,GR as Sc,XR as Tc,VR as Uc,JR as Vc,YR as Wc,Vd as Xc,tf as Yc,of as Zc,jb as _c,Gb as $c,zL as ad,Xb as bd,on as cd,Vb as dd,Dn as ed,tt as fd,Et as gd,Jb as hd,bs as id,Yb as jd,Qb as kd,Cn as ld,Zb as md,ek as nd,tk as od,nk as pd,rk as qd,Le as rd,ok as sd,ik as td,Vk as ud,sk as vd,Hi as wd};
338
+ ${u}`:""}async getDefinition(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.definition(ne.resolve(t),n).catch(()=>[]);return eo(s,"No definition found at that position.")}async getHover(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.hover(ne.resolve(t),n).catch(()=>null);return Qf(s)}async getReferences(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.references(ne.resolve(t),n).catch(()=>[]);return eo(s,"No references found at that position.")}async getDocumentSymbols(t,n={}){let r=await this.navClient(t,n);if(r.kind!=="client")return r.message;let o=await r.client.documentSymbols(ne.resolve(t)).catch(()=>[]);return ep(o,"No symbols found in this file.")}async getWorkspaceSymbols(t,n={}){let r=await this.workspaceClients(n);if(r.length===0)return"No language server is available for workspace symbol search.";let o=await Promise.all(r.map(s=>s.workspaceSymbols(t).catch(()=>[])));return tp(o.flat(),"No workspace symbols found for that query.")}async getImplementation(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.implementation(ne.resolve(t),n).catch(()=>[]);return eo(s,"No implementation found at that position.")}async getPrepareCallHierarchy(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.prepareCallHierarchy(ne.resolve(t),n).catch(()=>[]);return rp(s,"No call hierarchy item found at that position.")}async getIncomingCalls(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=ne.resolve(t),a=await o.client.prepareCallHierarchy(s,n).catch(()=>[]);if(a.length===0)return"No call hierarchy item found at that position.";let c=await Promise.all(a.map(l=>o.client.incomingCalls(l).catch(()=>[])));return op(c.flat(),"No incoming calls found for that symbol.")}async getOutgoingCalls(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=ne.resolve(t),a=await o.client.prepareCallHierarchy(s,n).catch(()=>[]);if(a.length===0)return"No call hierarchy item found at that position.";let c=await Promise.all(a.map(l=>o.client.outgoingCalls(l).catch(()=>[])));return ip(c.flat(),"No outgoing calls found for that symbol.")}async navClient(t,n){let r=Gn(t);if(!r)return{kind:"message",message:`No language server is configured for ${ne.basename(t)}.`};let o=this.servers.filter(c=>c.languageIds.includes(r));if(o.length===0)return{kind:"message",message:`No language server is configured for ${ne.basename(t)}.`};let s=ne.resolve(t),a=n.gitRoot??ne.dirname(s);for(let c of o){let l=Ws(s,c.rootMarkers,a),d=await this.getClient(c,l,n);if(d)return await d.notifyOpenOrChange(s).catch(()=>{}),{kind:"client",client:d}}return{kind:"message",message:o.map(c=>c.installGuidance).join(`
339
+ `)}}async workspaceClients(t){let n=ne.resolve(t.gitRoot??process.cwd()),r=[];for(let o of this.servers){let s=await this.getClient(o,n,t);s&&r.push(s)}return r}async shutdownAll(){this.shuttingDown=!0;try{await Promise.all([...this.spawning.values()].map(n=>n.catch(()=>{})));let t=[...this.clients.values()];this.clients.clear(),this.broken.clear(),await Promise.all(t.map(n=>n.shutdown().catch(()=>{})))}finally{this.shuttingDown=!1}}killAllSync(){for(let t of this.clients.values())t.killSync();this.clients.clear()}resetBroken(t){t?this.broken.delete(t):this.broken.clear()}async getClient(t,n,r){let o=`${ye(n)}|${t.id}`,s=this.clients.get(o);if(s)return s;if(this.broken.has(o))return;let a=this.spawning.get(o);if(a)return a;let c=this.spawnClient(t,n,o,r);this.spawning.set(o,c);try{return await c}finally{this.spawning.delete(o)}}async spawnClient(t,n,r,o){try{let s=t.discover({root:n,moduleUrl:this.config.moduleUrl});if(s||(s=await this.acquireIfEnabled(t,n,o)),!s){this.broken.add(r),this.config.debug?.(`${t.id} not installed at ${n} \u2014 ${t.installGuidance}`);return}o.onProgress?.(`Starting ${t.id} language server\u2026`);let c=await(this.config.createClient??ap)({serverId:t.id,root:n,launch:s,debug:this.config.debug});if(this.shuttingDown){await c.shutdown().catch(()=>{});return}return this.clients.set(r,c),c}catch(s){this.broken.add(r),this.config.debug?.(`${t.id} failed to start at ${n}: ${s.message}`);return}}async acquireIfEnabled(t,n,r){if(!(!t.acquire||!Hs()))try{return await t.acquire({root:n,signal:r.signal,onProgress:r.onProgress,debug:this.config.debug})}catch(o){this.config.debug?.(`${t.id} auto-install failed: ${o.message}`);return}}},Xn,cp=!1;function lp(){let e=Vn()?.lsp;if(!(e===!1||e===void 0&&process.env.KODAX_LSP==="0"))return Xn||(Xn=new Vs({moduleUrl:import.meta.url,debug:process.env.KODAX_DEBUG_LSP?t=>process.stderr.write(`[kodax:lsp] ${t}
340
+ `):void 0}),cp||(cp=!0,process.once("exit",()=>Xn?.killAllSync()))),Xn}i(lp,"getDefaultLspService");async function rD(){await Xn?.shutdownAll()}i(rD,"shutdownDefaultLspService");import dp from"node:path";var cx=80;function lx(e){let t=e.trim().replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,cx);return!t||t==="."||t===".."?"session":t}i(lx,"sanitizeScratchSessionId");function up(e){let t=e.session?.id?.trim();if(!t)return;let n=e.context?.gitRoot?.trim(),r=n?dp.resolve(n):Z(e.context);return dp.resolve(r,".agent","tmp","sessions",lx(t))}i(up,"getSessionScratchDir");import{join as dx}from"node:path";function ux(e,t){if(t&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return dx(e,t)}i(ux,"resolveResumeFromRunDir");function hD(e){let{options:t,runtime:n,managedProtocolPayloadRef:r,sessionId:o}=e,s=t.events??{},a=Z(t.context),c=up(t);return{backups:new Map,gitRoot:t.context?.gitRoot??void 0,sessionId:o,taskSurface:t.context?.taskSurface,agentProfile:t.context?.agentProfile,selfManual:t.selfManual,skillDynamicContext:t.skillDynamicContext,lspService:t.context?.lspService??lp(),executionCwd:a,sessionScratchDir:c,extensionRuntime:n,askUser:s.askUser,askUserMulti:s.askUserMulti,askUserInput:s.askUserInput,exitPlanMode:s.exitPlanMode,abortSignal:t.abortSignal,managedProtocolRole:t.context?.managedProtocolEmission?.enabled?t.context.managedProtocolEmission.role:void 0,emitManagedProtocol:t.context?.managedProtocolEmission?.enabled?l=>{r.current=ou(r.current,l)}:void 0,mutationTracker:t.context?.mutationTracker,planModeBlockCheck:t.context?.planModeBlockCheck,guardrails:t.guardrails,parentAgentConfig:{provider:t.provider,model:t.modelOverride??t.model,reasoningMode:t.reasoningMode,effort:t.effort,repoIntelligenceMode:t.context?.repoIntelligenceMode,repoIntelligenceTrace:t.context?.repoIntelligenceTrace},parentEvents:s,onChildProgress:void 0,childTaskRegistry:t.context?.inheritedChildTaskRegistry??new Map,currentAgentId:t.context?.currentAgentId,parentAgentId:t.context?.parentAgentId,goalContext:t.context?.goalRuntime?.goalContext,sendMessageTurnCounter:{count:0},childAbortControllers:new Map,childProgressSnapshots:new Map,workflowRunProgress:new Map,workflowHost:mx(t,o)}}i(hD,"buildToolExecutionContext");function fx(e,t){return{...t?{sessionId:t}:{},...e.context?.agentProfile?.surface?{surface:e.context.agentProfile.surface}:{},...e.context?.taskSurface?{taskSurface:e.context.taskSurface}:{},...e.context?.gitRoot?{projectRoot:e.context.gitRoot}:{}}}i(fx,"buildWorkflowHostMetadata");function px(e){let t=e.items.filter(s=>s.kind==="agent"),n=t.filter(s=>s.status==="running").map(s=>s.title),r=e.activePhaseId===void 0?void 0:e.items.find(s=>s.id===e.activePhaseId)?.title;return{status:e.status==="completed"?"completed":e.status==="failed"?"failed":e.status==="cancelled"?"stopped":"running",workflowName:e.displayName??e.workflowName,...r!==void 0?{phase:r}:{},...e.activePhaseIndex!==void 0?{phaseIndex:e.activePhaseIndex}:{},...e.phaseCount!==void 0?{phaseTotal:e.phaseCount}:{},activeAgents:n,completedAgents:t.filter(s=>s.status==="completed").length,failedAgents:t.filter(s=>s.status==="failed").length,stoppedAgents:t.filter(s=>s.status==="cancelled").length,totalSpawned:e.progress.spawnedAgents,...e.progress.plannedItems!==void 0?{plannedAgents:e.progress.plannedItems}:{},...e.elapsedMs!==void 0?{elapsedMs:e.elapsedMs}:{}}}i(px,"toWorkflowRunProgressView");function mx(e,t){let n=e.workflowRunsBaseDir;if(process.env.KODAX_DEBUG_WORKFLOW_GATE){let o=n===void 0?"no-host: workflowRunsBaseDir undefined":e.agentMode!=="amaw"&&e.agentMode!=="ama"?`no-host: agentMode=${String(e.agentMode)} (need ama|amaw)`:"host wired";process.stderr.write(`[workflow-gate] agentMode=${String(e.agentMode)} runsBaseDir=${n??"<undef>"} -> ${o}
341
+ `)}if(n===void 0||e.agentMode!=="amaw"&&e.agentMode!=="ama")return;let r=i(async({manifest:o,source:s,args:a,resumeFromRunId:c,signal:l})=>{let[{startManagedWorkflow:d},{getDefaultWorkflowRunManager:u}]=await Promise.all([import("./host-FRQXOEHH.js"),import("./run-manager-FGCG7DFF.js")]),f=[e.abortSignal,l].filter(y=>y!==void 0),m=f.length===0?void 0:f.length===1?f[0]:AbortSignal.any(f),h=await d({source:{kind:"inline",manifest:o,source:s},args:a,options:e,runsBaseDir:n,manager:u(),...(()=>{let y=ux(n,c);return y?{resumeFromRunDir:y}:{}})(),...m?{signal:m}:{},processMetadata:{hostMetadata:fx(e,t)}});if(h.kind==="declined")return{kind:"declined",reason:h.reason};let p=h.qualityWarnings?.map(y=>`${y.code}: ${y.message}`),g=h.managed.done.then(y=>{let b=h.managed.getSnapshot?.(),v=y.kind==="completed"?y.state.events.reduce((k,$)=>{if($.type==="agent_unverified"){let S=$.data?.name??$.data?.taskId;k.push(typeof S=="string"&&S.length>0?S:"agent")}return k},[]):[];return{kind:"started",runId:h.runId,...b?.status!==void 0?{status:b.status}:{},...b?.resultText!==void 0?{resultText:b.resultText}:{},...b?.error!==void 0?{error:b.error}:{},...v.length>0?{verificationWarnings:v}:{},...p&&p.length>0?{workflowQualityWarnings:p}:{}}}),w=i(()=>{let y=h.managed.getProcessSnapshot?.();return y?px(y):void 0},"getProgress");return{kind:"started",runId:h.runId,done:g,...p&&p.length>0?{workflowQualityWarnings:p}:{},getProgress:w}},"startInline");return{startInline:r,runInline:i(async o=>{let s=await r(o);return s.kind==="declined"?{kind:"declined",reason:s.reason}:await s.done},"runInline")}}i(mx,"buildWorkflowToolHost");export{xx as a,Ex as b,Sx as c,io as d,so as e,Z as f,B as g,qx as h,wa as i,Ft as j,tr as k,co as l,jt as m,D as n,Ut as o,ft as p,gn as q,We as r,mo as s,Ea as t,eE as u,Sa as v,Ra as w,wo as x,Oa as y,uE as z,ko as A,_o as B,cm as C,lm as D,xo as E,Ro as F,Oo as G,bn as H,Io as I,Lo as J,$e as K,aA as L,Vc as M,Wo as N,Ho as O,Jc as P,zo as Q,Go as R,Ko as S,Vo as T,Yo as U,Zo as V,Qo as W,ei as X,xn as Y,X as Z,Dg as _,Zg as $,nC as aa,rC as ba,oC as ca,Sn as da,Sr as ea,Tr as fa,Tn as ga,Qg as ha,ey as ia,iC as ja,hi as ka,gi as la,yi as ma,wi as na,Ul as oa,An as pa,bt as qa,bi as ra,Zt as sa,ki as ta,Hl as ua,W as va,vi as wa,_i as xa,Ei as ya,Si as za,jy as Aa,Kl as Ba,Xl as Ca,Ad as Da,Cd as Ea,wR as Fa,r$ as Ga,o$ as Ha,i$ as Ia,By as Ja,$r as Ka,s$ as La,Me as Ma,de as Na,Wk as Oa,Hk as Pa,fb as Qa,UR as Ra,pb as Sa,qR as Ta,BR as Ua,ru as Va,ou as Wa,WR as Xa,HR as Ya,zR as Za,GR as _a,su as $a,JR as ab,YR as bb,bb as cb,au as db,ZR as eb,iO as fb,sO as gb,aO as hb,cO as ib,lO as jb,dO as kb,uO as lb,fO as mb,pO as nb,mO as ob,hO as pb,mu as qb,gO as rb,yO as sb,up as tb,Gn as ub,qf as vb,Yf as wb,Vs as xb,lp as yb,rD as zb,eu as Ab,tu as Bb,nu as Cb,hD as Db,Ef as Eb,Sf as Fb,Wn as Gb,Iv as Hb,Ds as Ib,$f as Jb,SM as Kb,Pv as Lb,Nv as Mb,TM as Nb,Mn as Ob,qr as Pb,an as Qb,ot as Rb,ts as Sb,os as Tb,Pn as Ub,Nn as Vb,Du as Wb,Fu as Xb,as as Yb,Pe as Zb,ck as _b,ds as $b,St as ac,cn as bc,uk as cc,Dn as dc,pk as ec,bk as fc,kk as gc,At as hc,Fn as ic,jn as jc,Ak as kc,ws as lc,Ct as mc,$t as nc,Ck as oc,$k as pc,Rk as qc,Mk as rc,Nk as sc,Kr as tc,Zu as uc,Uk as vc,qk as wc,Fs as xc,js as yc,UM as zc,qM as Ac,BM as Bc,WM as Cc,HM as Dc,Hn as Ec,Jr as Fc,Xr as Gc,kf as Hc,lM as Ic,Wi as Jc,PR as Kc,vO as Lc,wu as Mc,Su as Nc,Tu as Oc,XO as Pc,Au as Qc,QO as Rc,eI as Sc,tI as Tc,nI as Uc,rI as Vc,oI as Wc,Cu as Xc,Pf as Yc,Ff as Zc,Gk as _c,tv as $c,QP as ad,nv as bd,dn as cd,rv as dd,Bn as ed,it as fd,Rt as gd,ov as hd,Os as id,iv as jd,sv as kd,Ln as ld,av as md,cv as nd,lv as od,dv as pd,uv as qd,Ne as rd,fv as sd,pv as td,r_ as ud,mv as vd,ns as wd};