@kodax-ai/kodax 0.7.78 → 0.7.79
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.
- package/CHANGELOG.md +3475 -3197
- package/README.md +346 -275
- package/README_CN.md +274 -214
- package/config-templates/config.example.jsonc +11 -1
- package/config-templates/integrations/a2a.example.jsonc +23 -7
- package/dist/builtin/skill-creator/scripts/aggregate-benchmark.js +2 -1
- package/dist/builtin/skill-creator/scripts/analyze-benchmark.d.ts +1 -0
- package/dist/builtin/skill-creator/scripts/analyze-benchmark.js +4 -3
- package/dist/builtin/skill-creator/scripts/compare-runs.d.ts +1 -0
- package/dist/builtin/skill-creator/scripts/compare-runs.js +4 -3
- package/dist/builtin/skill-creator/scripts/generate-review.js +2 -1
- package/dist/builtin/skill-creator/scripts/grade-evals.d.ts +1 -0
- package/dist/builtin/skill-creator/scripts/grade-evals.js +4 -3
- package/dist/builtin/skill-creator/scripts/improve-description.js +2 -1
- package/dist/builtin/skill-creator/scripts/init-skill.d.ts +1 -0
- package/dist/builtin/skill-creator/scripts/init-skill.js +4 -3
- package/dist/builtin/skill-creator/scripts/install-skill.d.ts +1 -0
- package/dist/builtin/skill-creator/scripts/install-skill.js +4 -3
- package/dist/builtin/skill-creator/scripts/package-skill.d.ts +1 -0
- package/dist/builtin/skill-creator/scripts/package-skill.js +4 -3
- package/dist/builtin/skill-creator/scripts/quick-validate.d.ts +1 -0
- package/dist/builtin/skill-creator/scripts/quick-validate.js +4 -3
- package/dist/builtin/skill-creator/scripts/run-eval.d.ts +1 -0
- package/dist/builtin/skill-creator/scripts/run-eval.js +4 -3
- package/dist/builtin/skill-creator/scripts/run-loop.js +2 -1
- package/dist/builtin/skill-creator/scripts/run-trigger-eval.js +2 -1
- package/dist/builtin/skill-creator/scripts/utils.d.ts +3 -0
- package/dist/builtin/skill-creator/scripts/utils.js +5 -1
- package/dist/chunks/{agent-ASP4MS3X.js → agent-V4AC5JZD.js} +1 -1
- package/dist/chunks/argument-completer-ZPC2MLES.js +2 -0
- package/dist/chunks/{chunk-Z3KFRTSB.js → chunk-67THZRM6.js} +1 -1
- package/dist/chunks/chunk-6GVQDQTQ.js +292 -0
- package/dist/chunks/{chunk-TQDBTTIM.js → chunk-B6UY3VHV.js} +40 -40
- package/dist/chunks/{chunk-7OEBJGHK.js → chunk-BBOVVDQJ.js} +1 -1
- package/dist/chunks/chunk-CR2IF7VF.js +30 -0
- package/dist/chunks/{chunk-UID7BLAB.js → chunk-CXHEZY5G.js} +1 -1
- package/dist/chunks/chunk-EDZ4QILG.js +266 -0
- package/dist/chunks/chunk-GEECPO2H.js +218 -0
- package/dist/chunks/chunk-H5LLM7DB.js +89 -0
- package/dist/chunks/chunk-KLWP7POA.js +467 -0
- package/dist/chunks/{chunk-2CFHBKRE.js → chunk-M4N2JZTZ.js} +2 -2
- package/dist/chunks/{chunk-YAZQTC2L.js → chunk-OWQT3FTE.js} +1 -1
- package/dist/chunks/chunk-Q4M7DJOD.js +319 -0
- package/dist/chunks/{chunk-6FOJVETH.js → chunk-QCZLCLFL.js} +7 -7
- package/dist/chunks/chunk-RQPMGRTR.js +810 -0
- package/dist/chunks/chunk-SG6P4SZS.js +123 -0
- package/dist/chunks/chunk-TSTVAU5E.js +386 -0
- package/dist/chunks/chunk-ZCZZUE5E.js +662 -0
- package/dist/chunks/compaction-config-AEUGVROL.js +2 -0
- package/dist/chunks/{construction-bootstrap-VQLQGWPY.js → construction-bootstrap-K3ZGEN5N.js} +1 -1
- package/dist/chunks/dist-GFJFRPAV.js +2 -0
- package/dist/chunks/{dist-BFT5YIGU.js → dist-JMO47GJV.js} +1 -1
- package/dist/chunks/host-23K2Q6RZ.js +2 -0
- package/dist/chunks/run-manager-PGIR6ITA.js +2 -0
- package/dist/chunks/{utils-SID4HW2Q.js → utils-6LEKJPQN.js} +1 -1
- package/dist/index.d.ts +20 -20
- package/dist/index.js +2 -2
- package/dist/kodax_bootstrap.js +2 -1
- package/dist/kodax_cli.js +1816 -1458
- package/dist/kodax_resume.js +570 -34
- package/dist/provider-capabilities.json +85 -50
- package/dist/runtime-worker.js +1713 -1361
- package/dist/sandbox-workspace-session.js +285 -19
- package/dist/sdk-a2a.d.ts +19 -13
- package/dist/sdk-a2a.js +8 -8
- package/dist/sdk-agent.d.ts +73 -141
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-coding.d.ts +29 -60
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-experimental-memory.d.ts +3 -3
- package/dist/sdk-experimental-memory.js +1 -1
- package/dist/sdk-llm.d.ts +7 -7
- package/dist/sdk-llm.js +1 -1
- package/dist/sdk-mcp.d.ts +1 -1
- package/dist/sdk-mcp.js +1 -1
- package/dist/sdk-media.d.ts +1 -1
- package/dist/sdk-media.js +1 -1
- package/dist/sdk-repl.d.ts +25 -26
- package/dist/sdk-repl.js +2 -2
- package/dist/sdk-runtime.d.ts +227 -31
- package/dist/sdk-runtime.js +1 -1
- package/dist/sdk-sandbox.js +1 -1
- package/dist/sdk-session.d.ts +8 -8
- package/dist/sdk-session.js +1 -1
- package/dist/sdk-skills.js +1 -1
- package/dist/semantic-worker.js +283 -18
- package/dist/types-chunks/{base.d-4e74xDdy.d.ts → base.d-DxG0m09Z.d.ts} +1 -1
- package/dist/types-chunks/{bash-prefix-extractor.d-uAe2Oqda.d.ts → bash-prefix-extractor.d-CNSidpmv.d.ts} +28 -7
- package/dist/types-chunks/{capability-learning.d-CVsdHw4j.d.ts → capability-learning.d-iPSiAmc_.d.ts} +1 -1
- package/dist/types-chunks/{capsule.d-BlSv9l3V.d.ts → capsule.d-B3q98pLQ.d.ts} +9 -7
- package/dist/types-chunks/{types.d-BA-Jwpfs.d.ts → controller.d-RGV7Pjv9.d.ts} +328 -3
- package/dist/types-chunks/{guardrail.d-CXDYRgZ3.d.ts → guardrail.d-1NLSFTyN.d.ts} +126 -52
- package/dist/types-chunks/{history-retrieval.d-DtCy7x64.d.ts → history-retrieval.d-BAegI14A.d.ts} +16 -3
- package/dist/types-chunks/{oauth-login.d-Bgb4rdLN.d.ts → oauth-login.d-6i-vidxv.d.ts} +6 -2
- package/dist/types-chunks/{public-api.d-B3AohsxN.d.ts → public-api.d-BpJhHoa7.d.ts} +334 -25
- package/dist/types-chunks/{repl.d-Ie_ZXb_U.d.ts → repl.d-CZ12Ow3X.d.ts} +5 -5
- package/dist/types-chunks/{resolver.d-iAQ9ocLB.d.ts → resolver.d-C9IW4fmU.d.ts} +5 -2
- package/dist/types-chunks/{run-manager.d-D1twIhF9.d.ts → run-manager.d-CX3AUocA.d.ts} +1 -1
- package/dist/types-chunks/{sdk-session-DB9KksIx.d.ts → sdk-session-B3cfJKqF.d.ts} +3 -3
- package/dist/types-chunks/{side-query.d-DTuLPcC5.d.ts → side-query.d-CP1LiRiH.d.ts} +8 -2
- package/dist/types-chunks/{types-D3g6XUQr.d.ts → types-Bf3Y3mW-.d.ts} +1 -1
- package/dist/types-chunks/{types.d-BH0ZkTGf.d.ts → types.d-BZ9oXvTV.d.ts} +2 -2
- package/dist/types-chunks/{types.d-DVDTIfB_.d.ts → types.d-C0_rn--1.d.ts} +4 -4
- package/dist/types-chunks/{types.d-DIpZJKUl.d.ts → types.d-CgrXrFrq.d.ts} +16 -2
- package/dist/types-chunks/{utils.d-CVp6bFl9.d.ts → utils.d-CGpHavsU.d.ts} +14 -6
- package/docs/SDK_EMBEDDER_GUIDE.md +1144 -598
- package/package.json +4 -1
- package/dist/chunks/argument-completer-JYQ7FX3W.js +0 -2
- package/dist/chunks/chunk-35PPHOQ2.js +0 -292
- package/dist/chunks/chunk-43QNNDHR.js +0 -29
- package/dist/chunks/chunk-5GO6FH7L.js +0 -458
- package/dist/chunks/chunk-5NDCSFOP.js +0 -78
- package/dist/chunks/chunk-6XM4B6K2.js +0 -48
- package/dist/chunks/chunk-6YZUE6NC.js +0 -240
- package/dist/chunks/chunk-KQLQYHWU.js +0 -386
- package/dist/chunks/chunk-NXO6GWSY.js +0 -46
- package/dist/chunks/chunk-T2XZTLYE.js +0 -316
- package/dist/chunks/chunk-VAT2QYXM.js +0 -765
- package/dist/chunks/chunk-YVRYHC4C.js +0 -655
- package/dist/chunks/compaction-config-BQSSIWK5.js +0 -2
- package/dist/chunks/dist-PCFE24YP.js +0 -2
- package/dist/chunks/host-UTFXCYYM.js +0 -2
- package/dist/chunks/run-manager-PJU3WIFJ.js +0 -2
- package/dist/types-chunks/guardrail.d-BRE_ErEj.d.ts +0 -156
package/dist/kodax_resume.js
CHANGED
|
@@ -1,10 +1,546 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
`).length,o={width:r,height:n};return Mr.set(e,o),o},"measureText"),gt=ui;import fi from"wrap-ansi";import di from"cli-truncate";var Ir={},pi=i((e,t,r)=>{let n=e+String(t)+String(r),o=Ir[n];if(o)return o;let s=e;if(r==="wrap"&&(s=fi(e,t,{trim:!1,hard:!0})),r.startsWith("truncate")){let c="end";r==="truncate-middle"&&(c="middle"),r==="truncate-start"&&(c="start"),s=di(e,t,{position:c})}return Ir[n]=s,s},"wrapText"),je=pi;var hi=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=48&&t<=63},"isCsiParameterCharacter"),mi=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=32&&t<=47},"isCsiIntermediateCharacter"),gi=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=64&&t<=126},"isCsiFinalCharacter"),kr=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=32&&t<=47},"isEscapeIntermediateCharacter"),xi=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=48&&t<=126},"isEscapeFinalCharacter"),Ar=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=128&&t<=159},"isC1ControlCharacter"),Or=i((e,t)=>{let r=t;for(;r<e.length;){let a=e[r];if(!hi(a))break;r++}let n=e.slice(t,r),o=r;for(;r<e.length;){let a=e[r];if(!mi(a))break;r++}let s=e.slice(o,r),c=e[r];if(!(c===void 0||!gi(c)))return{endIndex:r+1,parameterString:n,intermediateString:s,finalCharacter:c}},"readCsiSequence"),_r=i((e,t,r)=>{for(let n=t;n<e.length;n++){let o=e[n];if(r&&o==="\x07"||o==="\x9C")return n+1;if(o==="\x1B"){let s=e[n+1];if(s==="\x1B"){n++;continue}if(s==="\\")return n+2}}},"findControlStringTerminatorIndex"),wi=i((e,t)=>{let r=t;for(;r<e.length;){let s=e[r];if(!kr(s))break;r++}let n=e.slice(t,r),o=e[r];if(!(o===void 0||!xi(o)))return{endIndex:r+1,intermediateString:n,finalCharacter:o}},"readEscapeSequence"),Si=i(e=>{switch(e){case"]":return{type:"osc",allowBellTerminator:!0};case"P":return{type:"dcs",allowBellTerminator:!1};case"^":return{type:"pm",allowBellTerminator:!1};case"_":return{type:"apc",allowBellTerminator:!1};case"X":return{type:"sos",allowBellTerminator:!1};default:return}},"getControlStringFromEscapeIntroducer"),yi=i(e=>{switch(e){case"\x9D":return{type:"osc",allowBellTerminator:!0};case"\x90":return{type:"dcs",allowBellTerminator:!1};case"\x9E":return{type:"pm",allowBellTerminator:!1};case"\x9F":return{type:"apc",allowBellTerminator:!1};case"\x98":return{type:"sos",allowBellTerminator:!1};default:return}},"getControlStringFromC1Introducer"),xt=i(e=>{if(e.includes("\x1B"))return!0;for(let t of e)if(Ar(t))return!0;return!1},"hasAnsiControlCharacters"),de=i((e,t,r,n)=>(n>r&&e.push({type:"text",value:t.slice(r,n)}),e.push({type:"invalid",value:t.slice(n)}),e),"malformedFromIndex"),Nr=i(e=>{if(!xt(e))return[{type:"text",value:e}];let t=[],r=0;for(let n=0;n<e.length;){let o=e[n];if(o===void 0)break;if(o==="\x1B"){let c=e[n+1];if(c===void 0)return de(t,e,r,n);if(c==="["){let u=Or(e,n+2);if(u===void 0)return de(t,e,r,n);n>r&&t.push({type:"text",value:e.slice(r,n)}),t.push({type:"csi",value:e.slice(n,u.endIndex),parameterString:u.parameterString,intermediateString:u.intermediateString,finalCharacter:u.finalCharacter}),n=u.endIndex,r=n;continue}let a=Si(c);if(a!==void 0){let u=_r(e,n+2,a.allowBellTerminator);if(u===void 0)return de(t,e,r,n);n>r&&t.push({type:"text",value:e.slice(r,n)}),t.push({type:a.type,value:e.slice(n,u)}),n=u,r=n;continue}let l=wi(e,n+1);if(l===void 0){if(kr(c))return de(t,e,r,n);n>r&&t.push({type:"text",value:e.slice(r,n)}),n++,r=n;continue}n>r&&t.push({type:"text",value:e.slice(r,n)}),t.push({type:"esc",value:e.slice(n,l.endIndex),intermediateString:l.intermediateString,finalCharacter:l.finalCharacter}),n=l.endIndex,r=n;continue}if(o==="\x9B"){let c=Or(e,n+1);if(c===void 0)return de(t,e,r,n);n>r&&t.push({type:"text",value:e.slice(r,n)}),t.push({type:"csi",value:e.slice(n,c.endIndex),parameterString:c.parameterString,intermediateString:c.intermediateString,finalCharacter:c.finalCharacter}),n=c.endIndex,r=n;continue}let s=yi(o);if(s!==void 0){let c=_r(e,n+1,s.allowBellTerminator);if(c===void 0)return de(t,e,r,n);n>r&&t.push({type:"text",value:e.slice(r,n)}),t.push({type:s.type,value:e.slice(n,c)}),n=c,r=n;continue}if(o==="\x9C"){n>r&&t.push({type:"text",value:e.slice(r,n)}),t.push({type:"st",value:o}),n++,r=n;continue}if(Ar(o)){n>r&&t.push({type:"text",value:e.slice(r,n)}),t.push({type:"c1",value:o}),n++,r=n;continue}n++}return r<e.length&&t.push({type:"text",value:e.slice(r)}),t},"tokenizeAnsi");var Ti=/^[\d:;]*$/,Ci=i(e=>{if(!xt(e))return e;let t="";for(let r of Nr(e)){if(r.type==="text"||r.type==="osc"){t+=r.value;continue}r.type==="csi"&&r.finalCharacter==="m"&&r.intermediateString===""&&Ti.test(r.parameterString)&&(t+=r.value)}return t},"sanitizeAnsi"),Pr=Ci;var Lr=i(e=>{let t="";for(let r=0;r<e.childNodes.length;r++){let n=e.childNodes[r];if(n===void 0)continue;let o="";n.nodeName==="#text"?o=n.nodeValue:((n.nodeName==="ink-text"||n.nodeName==="ink-virtual-text")&&(o=Lr(n)),o.length>0&&typeof n.internal_transform=="function"&&(o=n.internal_transform(o,r))),t+=o}return Pr(t)},"squashTextNodes"),Re=Lr;var Ye=i(e=>{let t={nodeName:e,style:{},attributes:{},childNodes:[],parentNode:void 0,yogaNode:e==="ink-virtual-text"?void 0:Ri.Node.create(),internal_accessibility:{}};return e==="ink-text"&&t.yogaNode?.setMeasureFunc(bi.bind(null,t)),t},"createNode"),Ge=i((e,t)=>{t.parentNode&&be(t.parentNode,t),t.parentNode=e,e.childNodes.push(t),t.yogaNode&&e.yogaNode?.insertChild(t.yogaNode,e.yogaNode.getChildCount()),(e.nodeName==="ink-text"||e.nodeName==="ink-virtual-text")&&Ve(e)},"appendChildNode"),wt=i((e,t,r)=>{t.parentNode&&be(t.parentNode,t),t.parentNode=e;let n=e.childNodes.indexOf(r);n>=0?(e.childNodes.splice(n,0,t),t.yogaNode&&e.yogaNode?.insertChild(t.yogaNode,n)):(e.childNodes.push(t),t.yogaNode&&e.yogaNode?.insertChild(t.yogaNode,e.yogaNode.getChildCount())),(e.nodeName==="ink-text"||e.nodeName==="ink-virtual-text")&&Ve(e)},"insertBeforeNode"),be=i((e,t)=>{t.yogaNode&&t.parentNode?.yogaNode?.removeChild(t.yogaNode),t.parentNode=void 0;let r=e.childNodes.indexOf(t);r>=0&&e.childNodes.splice(r,1),(e.nodeName==="ink-text"||e.nodeName==="ink-virtual-text")&&Ve(e)},"removeChildNode"),St=i((e,t,r)=>{if(t==="internal_accessibility"){e.internal_accessibility=r;return}e.attributes[t]=r},"setAttribute"),yt=i((e,t)=>{e.style=t},"setStyle"),Fr=i(e=>{let t={nodeName:"#text",nodeValue:e,yogaNode:void 0,parentNode:void 0,style:{}};return Ee(t,e),t},"createTextNode"),bi=i(function(e,t){let r=e.nodeName==="#text"?e.nodeValue:Re(e),n=gt(r);if(n.width<=t||n.width>=1&&t>0&&t<1)return n;let o=e.style?.textWrap??"wrap",s=je(r,t,o);return gt(s)},"measureTextNode"),Wr=i(e=>{if(e?.parentNode)return e.yogaNode??Wr(e.parentNode)},"findClosestYogaNode"),Ve=i(e=>{Wr(e)?.markDirty()},"markNodeAsDirty"),Ee=i((e,t)=>{typeof t!="string"&&(t=String(t)),e.nodeValue=t,Ve(e)},"setTextNodeValue");import S from"yoga-layout";var vi=i((e,t)=>{"position"in t&&e.setPositionType(t.position==="absolute"?S.POSITION_TYPE_ABSOLUTE:S.POSITION_TYPE_RELATIVE),"top"in t&&e.setPosition(S.EDGE_TOP,t.top??0),"bottom"in t&&e.setPosition(S.EDGE_BOTTOM,t.bottom??0),"left"in t&&e.setPosition(S.EDGE_LEFT,t.left??0),"right"in t&&e.setPosition(S.EDGE_RIGHT,t.right??0)},"applyPositionStyles"),Mi=i((e,t)=>{"margin"in t&&e.setMargin(S.EDGE_ALL,t.margin??0),"marginX"in t&&e.setMargin(S.EDGE_HORIZONTAL,t.marginX??0),"marginY"in t&&e.setMargin(S.EDGE_VERTICAL,t.marginY??0),"marginLeft"in t&&e.setMargin(S.EDGE_START,t.marginLeft||0),"marginRight"in t&&e.setMargin(S.EDGE_END,t.marginRight||0),"marginTop"in t&&e.setMargin(S.EDGE_TOP,t.marginTop||0),"marginBottom"in t&&e.setMargin(S.EDGE_BOTTOM,t.marginBottom||0)},"applyMarginStyles"),Ii=i((e,t)=>{"padding"in t&&e.setPadding(S.EDGE_ALL,t.padding??0),"paddingX"in t&&e.setPadding(S.EDGE_HORIZONTAL,t.paddingX??0),"paddingY"in t&&e.setPadding(S.EDGE_VERTICAL,t.paddingY??0),"paddingLeft"in t&&e.setPadding(S.EDGE_LEFT,t.paddingLeft||0),"paddingRight"in t&&e.setPadding(S.EDGE_RIGHT,t.paddingRight||0),"paddingTop"in t&&e.setPadding(S.EDGE_TOP,t.paddingTop||0),"paddingBottom"in t&&e.setPadding(S.EDGE_BOTTOM,t.paddingBottom||0)},"applyPaddingStyles"),Oi=i((e,t)=>{"flexGrow"in t&&e.setFlexGrow(t.flexGrow??0),"flexShrink"in t&&e.setFlexShrink(typeof t.flexShrink=="number"?t.flexShrink:1),"flexWrap"in t&&(t.flexWrap==="nowrap"&&e.setFlexWrap(S.WRAP_NO_WRAP),t.flexWrap==="wrap"&&e.setFlexWrap(S.WRAP_WRAP),t.flexWrap==="wrap-reverse"&&e.setFlexWrap(S.WRAP_WRAP_REVERSE)),"flexDirection"in t&&(t.flexDirection==="row"&&e.setFlexDirection(S.FLEX_DIRECTION_ROW),t.flexDirection==="row-reverse"&&e.setFlexDirection(S.FLEX_DIRECTION_ROW_REVERSE),t.flexDirection==="column"&&e.setFlexDirection(S.FLEX_DIRECTION_COLUMN),t.flexDirection==="column-reverse"&&e.setFlexDirection(S.FLEX_DIRECTION_COLUMN_REVERSE)),"flexBasis"in t&&(typeof t.flexBasis=="number"?e.setFlexBasis(t.flexBasis):typeof t.flexBasis=="string"?e.setFlexBasisPercent(Number.parseInt(t.flexBasis,10)):e.setFlexBasis(Number.NaN)),"alignItems"in t&&((t.alignItems==="stretch"||!t.alignItems)&&e.setAlignItems(S.ALIGN_STRETCH),t.alignItems==="flex-start"&&e.setAlignItems(S.ALIGN_FLEX_START),t.alignItems==="center"&&e.setAlignItems(S.ALIGN_CENTER),t.alignItems==="flex-end"&&e.setAlignItems(S.ALIGN_FLEX_END)),"alignSelf"in t&&((t.alignSelf==="auto"||!t.alignSelf)&&e.setAlignSelf(S.ALIGN_AUTO),t.alignSelf==="flex-start"&&e.setAlignSelf(S.ALIGN_FLEX_START),t.alignSelf==="center"&&e.setAlignSelf(S.ALIGN_CENTER),t.alignSelf==="flex-end"&&e.setAlignSelf(S.ALIGN_FLEX_END)),"justifyContent"in t&&((t.justifyContent==="flex-start"||!t.justifyContent)&&e.setJustifyContent(S.JUSTIFY_FLEX_START),t.justifyContent==="center"&&e.setJustifyContent(S.JUSTIFY_CENTER),t.justifyContent==="flex-end"&&e.setJustifyContent(S.JUSTIFY_FLEX_END),t.justifyContent==="space-between"&&e.setJustifyContent(S.JUSTIFY_SPACE_BETWEEN),t.justifyContent==="space-around"&&e.setJustifyContent(S.JUSTIFY_SPACE_AROUND),t.justifyContent==="space-evenly"&&e.setJustifyContent(S.JUSTIFY_SPACE_EVENLY))},"applyFlexStyles"),_i=i((e,t)=>{"width"in t&&(typeof t.width=="number"?e.setWidth(t.width):typeof t.width=="string"?e.setWidthPercent(Number.parseInt(t.width,10)):e.setWidthAuto()),"height"in t&&(typeof t.height=="number"?e.setHeight(t.height):typeof t.height=="string"?e.setHeightPercent(Number.parseInt(t.height,10)):e.setHeightAuto()),"minWidth"in t&&(typeof t.minWidth=="string"?e.setMinWidthPercent(Number.parseInt(t.minWidth,10)):e.setMinWidth(t.minWidth??0)),"minHeight"in t&&(typeof t.minHeight=="string"?e.setMinHeightPercent(Number.parseInt(t.minHeight,10)):e.setMinHeight(t.minHeight??0))},"applyDimensionStyles"),ki=i((e,t)=>{"display"in t&&e.setDisplay(t.display==="flex"?S.DISPLAY_FLEX:S.DISPLAY_NONE)},"applyDisplayStyles"),Ai=i((e,t)=>{if("borderStyle"in t){let r=t.borderStyle?1:0;t.borderTop!==!1&&e.setBorder(S.EDGE_TOP,r),t.borderBottom!==!1&&e.setBorder(S.EDGE_BOTTOM,r),t.borderLeft!==!1&&e.setBorder(S.EDGE_LEFT,r),t.borderRight!==!1&&e.setBorder(S.EDGE_RIGHT,r)}},"applyBorderStyles"),Ni=i((e,t)=>{"gap"in t&&e.setGap(S.GUTTER_ALL,t.gap??0),"columnGap"in t&&e.setGap(S.GUTTER_COLUMN,t.columnGap??0),"rowGap"in t&&e.setGap(S.GUTTER_ROW,t.rowGap??0)},"applyGapStyles"),Pi=i((e,t={})=>{vi(e,t),Mi(e,t),Ii(e,t),Oi(e,t),_i(e,t),ki(e,t),Ai(e,t),Ni(e,t)},"styles"),Tt=Pi;if(Ue())try{await Promise.resolve().then(()=>(Yr(),Li))}catch(e){if(e.code==="ERR_MODULE_NOT_FOUND")console.warn(`
|
|
2
|
+
var Uc=Object.defineProperty;var o=(e,t)=>Uc(e,"name",{value:t,configurable:!0});var At=(e,t)=>()=>(e&&(t=e(e=0)),t);var Er,Js,Qs=At(()=>{Er=class{static{o(this,"WebSocketStub")}},Js=Er});var an,Zs=At(()=>{"use strict";Qs();an=global;an.WebSocket||=Js;an.window||=global;an.self||=global;an.window.__REACT_DEVTOOLS_COMPONENT_FILTERS__=[{type:1,value:7,isEnabled:!0},{type:2,value:"InternalApp",isEnabled:!0,isValid:!0},{type:2,value:"InternalAppContext",isEnabled:!0,isValid:!0},{type:2,value:"InternalStdoutContext",isEnabled:!0,isValid:!0},{type:2,value:"InternalStderrContext",isEnabled:!0,isValid:!0},{type:2,value:"InternalStdinContext",isEnabled:!0,isValid:!0},{type:2,value:"InternalFocusContext",isEnabled:!0,isValid:!0}]});var ea,Ir,ta=At(()=>{ea=o(()=>{},"noop"),Ir={initialize:ea,connectToDevTools:ea}});var Eg={};var na=At(()=>{"use strict";Zs();ta();Ir.initialize();Ir.connectToDevTools()});import Je from"node:fs/promises";import Uw from"node:os";import Qe from"node:path";import R from"fs/promises";import Os from"fs";import P from"path";import Cn from"path";import{createHash as qc}from"crypto";import{execFile as Wc}from"child_process";import Hc from"path";import{promisify as zc}from"util";var nv=zc(Wc);function In(e){if(!(!e||!e.trim()))return Hc.resolve(e).replace(/\\/g,"/")}o(In,"normalizePath");function mo(e){let t=In(e.runtimeInfo?.workspaceRoot??e.gitRoot),n=In(e.runtimeInfo?.executionCwd??t),r=In(e.runtimeInfo?.canonicalRepoRoot??t);if(!(!t&&!n&&!r))return{canonicalRepoRoot:r,workspaceRoot:t,executionCwd:n,branch:e.runtimeInfo?.branch,workspaceKind:e.runtimeInfo?.workspaceKind??"detected"}}o(mo,"resolveSessionRuntimeInfo");var Ze="_unknown",ho=80;function Vc(e){return process.platform==="win32"||process.platform==="darwin"?e.toLowerCase():e}o(Vc,"caseFold");function Gc(e){return Vc(Cn.resolve(e).replace(/\\/g,"/"))}o(Gc,"normalizeRoot");function go(e){return qc("sha256").update(e).digest("hex").slice(0,10)}o(go,"shortHash");function Yc(e){let t=e.replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"");return t.length>ho?t.slice(t.length-ho):t}o(Yc,"slugify");function Jc(e){if(!e||!e.trim())return{key:Ze,canonicalRoot:null,displayName:Ze};let t=Gc(e),n=Yc(t),r=n?`${n}-${go(t)}`:go(t),i=Cn.basename(Cn.resolve(e).replace(/\\/g,"/"))||e;return{key:r,canonicalRoot:t,displayName:i}}o(Jc,"deriveProjectKeyFromRoot");function yo(e){let t=mo({gitRoot:e.gitRoot??"",runtimeInfo:e.runtimeInfo}),n=t?.canonicalRepoRoot??t?.executionCwd??(e.gitRoot&&e.gitRoot.trim()?e.gitRoot:void 0);return Jc(n)}o(yo,"deriveProjectKeyFromData");import Zt from"node:fs/promises";import pt from"node:path";import{getEncoding as fv}from"js-tiktoken";import{AsyncLocalStorage as Qc}from"node:async_hooks";var Zc=new Qc;function Pt(e){let t=Zc.getStore()?.credential;return t?et(e,t,new WeakMap):e}o(Pt,"redactScopedProviderCredential");function et(e,t,n){if(typeof e=="string")return e.split(t).join("[REDACTED_CREDENTIAL]");if(e===null||typeof e!="object")return e;let r=n.get(e);if(r!==void 0)return r;if(e instanceof Error){let s=new Error(et(e.message,t,n));return n.set(e,s),s.name=e.name,e.stack!==void 0&&(s.stack=et(e.stack,t,n)),s}if(Array.isArray(e)){let s=[];n.set(e,s);for(let a of e)s.push(et(a,t,n));return s}let i={};n.set(e,i);for(let[s,a]of Object.entries(Object.getOwnPropertyDescriptors(e))){if(!a.enumerable||!("value"in a))continue;let c=s.split(t).join("[REDACTED_CREDENTIAL]");i[c]=et(a.value,t,n)}return i}o(et,"redactCredentialValue");import{AsyncLocalStorage as ed}from"node:async_hooks";var Nv=new ed;var tt={transport:"native-api",conversationSemantics:"full-history",mcpSupport:"none",contextFidelity:"full",toolCallingFidelity:"full",sessionSupport:"full",longRunningSupport:"full",multimodalSupport:"none",evidenceSupport:"full"},wo={...tt,multimodalSupport:"image-input"},Mt={transport:"cli-bridge",conversationSemantics:"last-user-message",mcpSupport:"none",contextFidelity:"lossy",toolCallingFidelity:"limited",sessionSupport:"stateless",longRunningSupport:"limited",multimodalSupport:"none",evidenceSupport:"limited"},vo={...Mt,multimodalSupport:"image-input"};import fb from"@anthropic-ai/sdk";import{parse as Qv}from"partial-json";import Rb from"openai";import{ClientSideConnection as qb,PROTOCOL_VERSION as Vb,ndJsonStream as Gb}from"@agentclientprotocol/sdk";var Kb=Object.freeze({status:"terminated"}),Bb=Object.freeze({status:"already-exited"}),Xb=Object.freeze({status:"unknown"}),Ub=String.raw`
|
|
3
|
+
using System;
|
|
4
|
+
using System.Runtime.InteropServices;
|
|
5
|
+
using System.Text;
|
|
6
|
+
public static class KodaXNativeProcessSnapshot {
|
|
7
|
+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
|
|
8
|
+
private struct ProcessEntry32 {
|
|
9
|
+
public uint dwSize;
|
|
10
|
+
public uint cntUsage;
|
|
11
|
+
public uint th32ProcessID;
|
|
12
|
+
public IntPtr th32DefaultHeapID;
|
|
13
|
+
public uint th32ModuleID;
|
|
14
|
+
public uint cntThreads;
|
|
15
|
+
public uint th32ParentProcessID;
|
|
16
|
+
public int pcPriClassBase;
|
|
17
|
+
public uint dwFlags;
|
|
18
|
+
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
|
|
19
|
+
public string szExeFile;
|
|
20
|
+
}
|
|
21
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
22
|
+
private static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processId);
|
|
23
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
|
24
|
+
private static extern bool Process32First(IntPtr snapshot, ref ProcessEntry32 entry);
|
|
25
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
|
26
|
+
private static extern bool Process32Next(IntPtr snapshot, ref ProcessEntry32 entry);
|
|
27
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
28
|
+
private struct FileTime {
|
|
29
|
+
public uint Low;
|
|
30
|
+
public uint High;
|
|
31
|
+
}
|
|
32
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
33
|
+
private static extern IntPtr OpenProcess(uint access, bool inheritHandle, uint processId);
|
|
34
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
35
|
+
private static extern bool GetProcessTimes(IntPtr process, out FileTime creation, out FileTime exit, out FileTime kernel, out FileTime user);
|
|
36
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
37
|
+
private static extern bool TerminateProcess(IntPtr process, uint exitCode);
|
|
38
|
+
[DllImport("kernel32.dll")]
|
|
39
|
+
private static extern void GetSystemTimeAsFileTime(out FileTime systemTime);
|
|
40
|
+
[DllImport("kernel32.dll")]
|
|
41
|
+
private static extern bool CloseHandle(IntPtr handle);
|
|
42
|
+
private static ulong ReadCreationTime(uint processId) {
|
|
43
|
+
var process = OpenProcess(0x1000, false, processId);
|
|
44
|
+
if (process == IntPtr.Zero) return 0;
|
|
45
|
+
try {
|
|
46
|
+
FileTime creation, exit, kernel, user;
|
|
47
|
+
if (!GetProcessTimes(process, out creation, out exit, out kernel, out user)) return 0;
|
|
48
|
+
return ((ulong)creation.High << 32) | creation.Low;
|
|
49
|
+
} finally {
|
|
50
|
+
CloseHandle(process);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
public static int TerminateExact(uint processId, ulong expectedCreationTime) {
|
|
54
|
+
var process = OpenProcess(0x1001, false, processId);
|
|
55
|
+
if (process == IntPtr.Zero) return 0;
|
|
56
|
+
try {
|
|
57
|
+
FileTime creation, exit, kernel, user;
|
|
58
|
+
if (!GetProcessTimes(process, out creation, out exit, out kernel, out user)) return 0;
|
|
59
|
+
var actual = (((ulong)creation.High << 32) | creation.Low) / 10000;
|
|
60
|
+
if (actual != expectedCreationTime) return 2;
|
|
61
|
+
return TerminateProcess(process, 1) ? 1 : 0;
|
|
62
|
+
} finally {
|
|
63
|
+
CloseHandle(process);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
public static string ReadRows() {
|
|
67
|
+
FileTime cutoffTime;
|
|
68
|
+
GetSystemTimeAsFileTime(out cutoffTime);
|
|
69
|
+
var cutoff = (((ulong)cutoffTime.High << 32) | cutoffTime.Low) / 10000;
|
|
70
|
+
var snapshot = CreateToolhelp32Snapshot(2, 0);
|
|
71
|
+
if (snapshot == new IntPtr(-1)) return string.Empty;
|
|
72
|
+
var rows = new StringBuilder();
|
|
73
|
+
var entry = new ProcessEntry32();
|
|
74
|
+
entry.dwSize = (uint)Marshal.SizeOf(entry);
|
|
75
|
+
try {
|
|
76
|
+
if (!Process32First(snapshot, ref entry)) return string.Empty;
|
|
77
|
+
do {
|
|
78
|
+
var creationTime = ReadCreationTime(entry.th32ProcessID) / 10000;
|
|
79
|
+
if (creationTime == 0 || creationTime <= cutoff) {
|
|
80
|
+
rows.Append(entry.th32ProcessID).Append(',').Append(entry.th32ParentProcessID).Append(',').Append(creationTime).Append('\n');
|
|
81
|
+
}
|
|
82
|
+
entry.dwSize = (uint)Marshal.SizeOf(entry);
|
|
83
|
+
} while (Process32Next(snapshot, ref entry));
|
|
84
|
+
return rows.ToString();
|
|
85
|
+
} finally {
|
|
86
|
+
CloseHandle(snapshot);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}`;import Co from"node:fs";import To from"node:os";import Ro from"node:path";var Sd="gpt-5.4",Ed="auto-gemini-3",Id=["gpt-5.4","gpt-5.3-codex","gpt-5.3-codex-spark"],Cd=["auto-gemini-3","gemini-3.1-pro-preview","gemini-3-flash-preview","gemini-2.5-pro","gemini-2.5-flash"];function _o(e){let t=new Set,n=[];for(let r of e){let i=r.trim();if(!i)continue;let s=i.toLowerCase();t.has(s)||(t.add(s),n.push(i))}return n}o(_o,"dedupePreserveOrder");function Td(){let e=Ro.join(To.homedir(),".codex","config.toml");try{return Co.readFileSync(e,"utf8").match(/^\s*model\s*=\s*"([^"]+)"/m)?.[1]?.trim()||null}catch{return null}}o(Td,"readCodexConfiguredModel");function Rd(){let e=Ro.join(To.homedir(),".gemini","settings.json");try{let t=JSON.parse(Co.readFileSync(e,"utf8")),n=typeof t.model=="string"?t.model.trim():"";return n||(typeof t.general?.model=="string"?t.general.model.trim():"")||null}catch{return null}}o(Rd,"readGeminiConfiguredModel");function Oe(){return Td()||Sd}o(Oe,"getCodexCliDefaultModel");function Ne(){return Rd()||Ed}o(Ne,"getGeminiCliDefaultModel");function nt(){return _o([Oe(),...Id])}o(nt,"getCodexCliKnownModels");function rt(){return _o([Ne(),...Cd])}o(rt,"getGeminiCliKnownModels");var _k=Ne(),Ak=rt();var Xk=Oe(),Uk=nt();import{existsSync as jd,readFileSync as Kd}from"node:fs";import De from"node:path";import{fileURLToPath as Bd}from"node:url";var Ao=["none","prompt-only","native-effort","native-budget","native-toggle","native-adaptive","unknown"],Po=["openai-responses-effort","openai-chat-effort","codex-cli-config","anthropic-output-effort","anthropic-reasoning-effort","provider-budget","provider-toggle","prompt-only","none"],Mo=["anthropic-adaptive","anthropic-budget","provider-budget","provider-toggle","none"],Oo=["zai-glm-5.2","zai-glm-toggle","deepseek-v4-flash-openai","deepseek-v4-pro-openai","deepseek-v4-openai","deepseek-v4-anthropic","deepseek-toggle","kimi-k3","kimi-k2.7-code","kimi-hybrid-toggle","minimax-m3","minimax-m2-always","mimo-v2.5-toggle","qwen-hybrid-thinking","openai-chat-reasoning","openai-responses-reasoning","codex-cli-effort","claude-adaptive-xhigh","claude-adaptive-max","anthropic-budget","generic-thinking-toggle","none"],No=["max_tokens","max_completion_tokens"],$o=["native","image-input-native","cli-bridge","image-input-cli-bridge"],Do=["count-tokens","models-list","minimal-message","unsupported"];function ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(ne,"isPlainObject");function ke(e,t){if(typeof e!="string"||e.length===0)throw new Error(`provider-capabilities.json: ${t} must be a non-empty string`);return e}o(ke,"requireString");function $e(e,t){if(e!==void 0)return ke(e,t)}o($e,"optionalString");function jo(e,t){if(e!==void 0){if(typeof e!="string"||!No.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${No.join(", ")}, got ${JSON.stringify(e)}`);return e}}o(jo,"optionalMaxOutputTokensField");function pe(e,t){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error(`provider-capabilities.json: ${t} must be a non-negative finite number`);return e}}o(pe,"optionalNumber");function D(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`provider-capabilities.json: ${t} must be a boolean`);return e}}o(D,"optionalBoolean");function Lo(e,t){if(e!==void 0){if(!Array.isArray(e))throw new Error(`provider-capabilities.json: ${t} must be an array`);return e.map((n,r)=>ke(n,`${t}[${r}]`))}}o(Lo,"optionalStringArray");function Ad(e,t){if(e===void 0)return;if(!ne(e))throw new Error(`provider-capabilities.json: ${t} must be an object`);let n={};for(let[r,i]of Object.entries(e))n[r]=ke(i,`${t}.${r}`);return n}o(Ad,"optionalStringMap");function Pd(e,t){if(e!==void 0){if(typeof e!="string"||!Oo.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Oo.join(", ")}, got ${JSON.stringify(e)}`);return e}}o(Pd,"optionalReasoningPreset");function _n(e,t){if(typeof e!="string"||!Ao.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Ao.join(", ")}, got ${JSON.stringify(e)}`);return e}o(_n,"requireReasoningCapability");function Md(e,t){if(typeof e!="string"||!Po.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Po.join(", ")}, got ${JSON.stringify(e)}`);return e}o(Md,"requireEffortStrategy");function Od(e,t){if(e!==void 0){if(typeof e!="string"||!Mo.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Mo.join(", ")}, got ${JSON.stringify(e)}`);return e}}o(Od,"optionalThinkingStrategy");function Fo(e,t){if(e===void 0)return;if(!ne(e))throw new Error(`provider-capabilities.json: ${t} must be an object`);let n=Md(e.effortStrategy,`${t}.effortStrategy`),r=Pd(e.reasoningPreset,`${t}.reasoningPreset`),i=Od(e.thinkingStrategy,`${t}.thinkingStrategy`),s=$e(e.defaultEffort,`${t}.defaultEffort`),a=Ad(e.effortAliases,`${t}.effortAliases`),c=Lo(e.disabledEfforts,`${t}.disabledEfforts`),d=Lo(e.localRejectEfforts,`${t}.localRejectEfforts`),u=D(e.allowCustomEffort,`${t}.allowCustomEffort`),l=D(e.supportsReasoningEffort,`${t}.supportsReasoningEffort`),f=D(e.supportsReasoningSummary,`${t}.supportsReasoningSummary`),m=D(e.supportsEncryptedReasoningReplay,`${t}.supportsEncryptedReasoningReplay`),p=D(e.supportsAdaptiveThinking,`${t}.supportsAdaptiveThinking`),g=D(e.supportsManualThinkingBudget,`${t}.supportsManualThinkingBudget`),v=D(e.supportsDisabledThinking,`${t}.supportsDisabledThinking`),w=D(e.requiresEffortBetaHeader,`${t}.requiresEffortBetaHeader`),y={effortStrategy:n};if(r!==void 0&&(y.reasoningPreset=r),i!==void 0&&(y.thinkingStrategy=i),s!==void 0&&(y.defaultEffort=s),a!==void 0&&(y.effortAliases=a),c!==void 0&&(y.disabledEfforts=c),d!==void 0&&(y.localRejectEfforts=d),e.supportedEfforts!==void 0){if(!Array.isArray(e.supportedEfforts))throw new Error(`provider-capabilities.json: ${t}.supportedEfforts must be an array`);y.supportedEfforts=e.supportedEfforts.map((h,b)=>{if(!ne(h))throw new Error(`provider-capabilities.json: ${t}.supportedEfforts[${b}] must be an object`);return{value:ke(h.value,`${t}.supportedEfforts[${b}].value`),...$e(h.description,`${t}.supportedEfforts[${b}].description`)!==void 0?{description:$e(h.description,`${t}.supportedEfforts[${b}].description`)}:{},...D(h.isDefault,`${t}.supportedEfforts[${b}].isDefault`)!==void 0?{isDefault:D(h.isDefault,`${t}.supportedEfforts[${b}].isDefault`)}:{},...D(h.isUserVisible,`${t}.supportedEfforts[${b}].isUserVisible`)!==void 0?{isUserVisible:D(h.isUserVisible,`${t}.supportedEfforts[${b}].isUserVisible`)}:{}}})}if(e.budgetByEffort!==void 0){if(!ne(e.budgetByEffort))throw new Error(`provider-capabilities.json: ${t}.budgetByEffort must be an object`);let h={};for(let[b,I]of Object.entries(e.budgetByEffort))h[b]=pe(I,`${t}.budgetByEffort.${b}`)??0;y.budgetByEffort=h}return u!==void 0&&(y.allowCustomEffort=u),l!==void 0&&(y.supportsReasoningEffort=l),f!==void 0&&(y.supportsReasoningSummary=f),m!==void 0&&(y.supportsEncryptedReasoningReplay=m),p!==void 0&&(y.supportsAdaptiveThinking=p),g!==void 0&&(y.supportsManualThinkingBudget=g),v!==void 0&&(y.supportsDisabledThinking=v),w!==void 0&&(y.requiresEffortBetaHeader=w),y}o(Fo,"validateReasoningProfile");function Ko(e,t){let n=e.reasoningProfile,r=e.reasoningCapabilityV2;if(n!==void 0&&r!==void 0)throw new Error(`provider-capabilities.json: ${t} must not define both reasoningProfile and deprecated reasoningCapabilityV2`);return n!==void 0?Fo(n,`${t}.reasoningProfile`):Fo(r,`${t}.reasoningCapabilityV2`)}o(Ko,"validateReasoningProfileField");function Nd(e,t){if(typeof e!="string"||!$o.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${$o.join(", ")}, got ${JSON.stringify(e)}`);return e}o(Nd,"requireProfileName");function $d(e,t){if(typeof e!="string"||!Do.includes(e))throw new Error(`provider-capabilities.json: ${t} must be one of ${Do.join(", ")}, got ${JSON.stringify(e)}`);return e}o($d,"requireVerifyStrategy");function Dd(e,t){if(!ne(e))throw new Error(`provider-capabilities.json: ${t} must be an object`);let n=ke(e.id,`${t}.id`),r=$e(e.wireModel,`${t}.wireModel`),i=$e(e.displayName,`${t}.displayName`),s=pe(e.contextWindow,`${t}.contextWindow`),a=pe(e.maxOutputTokens,`${t}.maxOutputTokens`),c=jo(e.maxOutputTokensField,`${t}.maxOutputTokensField`),d=pe(e.thinkingBudgetCap,`${t}.thinkingBudgetCap`),u=D(e.replayReasoningContent,`${t}.replayReasoningContent`),l=D(e.strictThinkingSignature,`${t}.strictThinkingSignature`),f=pe(e.streamMaxDurationMs,`${t}.streamMaxDurationMs`),m=e.reasoningCapability===void 0?void 0:_n(e.reasoningCapability,`${t}.reasoningCapability`),p=Ko(e,t),g={id:n};return r!==void 0&&(g.wireModel=r),i!==void 0&&(g.displayName=i),s!==void 0&&(g.contextWindow=s),a!==void 0&&(g.maxOutputTokens=a),c!==void 0&&(g.maxOutputTokensField=c),d!==void 0&&(g.thinkingBudgetCap=d),m!==void 0&&(g.reasoningCapability=m),p!==void 0&&(g.reasoningProfile=p),u!==void 0&&(g.replayReasoningContent=u),l!==void 0&&(g.strictThinkingSignature=l),f!==void 0&&(g.streamMaxDurationMs=f),g}o(Dd,"validateModelDescriptor");function Ld(e,t){if(e===void 0)return;if(!ne(e))throw new Error(`provider-capabilities.json: ${t} must be an object`);let n={};for(let[r,i]of Object.entries(e))n[r]=_n(i,`${t}.${r}`);return n}o(Ld,"validateModelReasoningCapabilities");function Fd(e,t){if(!ne(e))throw new Error(`provider-capabilities.json: providers.${t} must be an object`);let n=D(e.cliBridge,`providers.${t}.cliBridge`),r=ke(e.apiKeyEnv,`providers.${t}.apiKeyEnv`),i=_n(e.reasoningCapability,`providers.${t}.reasoningCapability`),s=Ko(e,`providers.${t}`),a=Nd(e.capabilityProfile,`providers.${t}.capabilityProfile`),c=$d(e.verifyStrategy,`providers.${t}.verifyStrategy`);if(n&&c!=="unsupported")throw new Error(`provider-capabilities.json: providers.${t} is a cliBridge entry but verifyStrategy="${c}" \u2014 must be "unsupported" (CLI binary owns credentials)`);let d=pe(e.contextWindow,`providers.${t}.contextWindow`),u=pe(e.maxOutputTokens,`providers.${t}.maxOutputTokens`),l=jo(e.maxOutputTokensField,`providers.${t}.maxOutputTokensField`),f=pe(e.thinkingBudgetCap,`providers.${t}.thinkingBudgetCap`),m=D(e.supportsThinking,`providers.${t}.supportsThinking`),p=Ld(e.modelReasoningCapabilities,`providers.${t}.modelReasoningCapabilities`),g=$e(e.model,`providers.${t}.model`);if(n&&(g!==void 0||e.models!==void 0))throw new Error(`provider-capabilities.json: providers.${t} is a cliBridge entry but defines model/models \u2014 must be omitted (filled at load time)`);if(!n&&g===void 0)throw new Error(`provider-capabilities.json: providers.${t}.model is required (only cliBridge entries may omit)`);let v;if(e.models!==void 0){if(!Array.isArray(e.models))throw new Error(`provider-capabilities.json: providers.${t}.models must be an array`);v=e.models.map((h,b)=>Dd(h,`providers.${t}.models[${b}]`));let y=new Set([...g===void 0?[]:[g],...v.map(h=>h.id)]);for(let[h,b]of v.entries())if(b.wireModel!==void 0&&!y.has(b.wireModel))throw new Error(`provider-capabilities.json: providers.${t}.models[${h}].wireModel must reference a declared model, got ${JSON.stringify(b.wireModel)}`)}let w={apiKeyEnv:r,reasoningCapability:i,capabilityProfile:a,verifyStrategy:c};return s!==void 0&&(w.reasoningProfile=s),g!==void 0&&(w.model=g),v!==void 0&&(w.models=v),d!==void 0&&(w.contextWindow=d),u!==void 0&&(w.maxOutputTokens=u),l!==void 0&&(w.maxOutputTokensField=l),f!==void 0&&(w.thinkingBudgetCap=f),m!==void 0&&(w.supportsThinking=m),p!==void 0&&(w.modelReasoningCapabilities=p),n&&(w.cliBridge=!0),w}o(Fd,"validateProviderEntry");function Bo(e){if(!ne(e))throw new Error("provider-capabilities.json: root must be an object");if(e.version!==1)throw new Error(`provider-capabilities.json: version must be 1, got ${JSON.stringify(e.version)}`);let t=ke(e.updatedAt,"updatedAt");if(!ne(e.providers))throw new Error("provider-capabilities.json: providers must be an object");let n={};for(let[r,i]of Object.entries(e.providers))n[r]=Fd(i,r);return{version:1,updatedAt:t,providers:n}}o(Bo,"validateProviderCapabilitiesJson");var Xd=Object.freeze({native:tt,"image-input-native":wo,"cli-bridge":Mt,"image-input-cli-bridge":vo}),Dt=null;function Ud(){if(process.env.KODAX_BUNDLED==="true")return De.join(De.dirname(process.execPath),"provider-capabilities.json");let e=De.dirname(Bd(import.meta.url)),t=[De.join(e,"provider-capabilities.json"),De.join(De.dirname(e),"provider-capabilities.json")];for(let n of t)if(jd(n))return n;return t[0]}o(Ud,"resolveJsonPath");function Wd(e){if(e.models){for(let t of e.models)t.reasoningProfile&&Xo(t.reasoningProfile);for(let t of e.models)Object.freeze(t);Object.freeze(e.models)}return e.reasoningProfile&&Xo(e.reasoningProfile),e.modelReasoningCapabilities&&Object.freeze(e.modelReasoningCapabilities),Object.freeze(e)}o(Wd,"deepFreezeSnapshot");function Xo(e){if(e.supportedEfforts){for(let t of e.supportedEfforts)Object.freeze(t);Object.freeze(e.supportedEfforts)}e.budgetByEffort&&Object.freeze(e.budgetByEffort),e.effortAliases&&Object.freeze(e.effortAliases),e.disabledEfforts&&Object.freeze(e.disabledEfforts),e.localRejectEfforts&&Object.freeze(e.localRejectEfforts),Object.freeze(e)}o(Xo,"freezeReasoningProfile");function Hd(e){if(e==="gemini-cli"){let t=Ne();return{model:t,models:rt().filter(n=>n!==t).map(n=>({id:n}))}}if(e==="codex-cli"){let t=Oe();return{model:t,models:nt().filter(n=>n!==t).map(n=>({id:n}))}}throw new Error(`provider-capabilities loader: unknown cliBridge provider '${e}'`)}o(Hd,"resolveCliBridgeModels");function zd(e,t){let n=Xd[t.capabilityProfile];if(!n)throw new Error(`provider-capabilities loader: unknown capabilityProfile '${t.capabilityProfile}' for provider '${e}'`);if(t.cliBridge){let i=Hd(e),s={model:i.model,models:i.models,apiKeyEnv:t.apiKeyEnv,reasoningCapability:t.reasoningCapability,capabilityProfile:n,verifyStrategy:t.verifyStrategy};return t.reasoningProfile!==void 0&&(s.reasoningProfile=t.reasoningProfile),t.supportsThinking!==void 0&&(s.supportsThinking=t.supportsThinking),s}let r={model:t.model,apiKeyEnv:t.apiKeyEnv,reasoningCapability:t.reasoningCapability,capabilityProfile:n,verifyStrategy:t.verifyStrategy};return t.reasoningProfile!==void 0&&(r.reasoningProfile=t.reasoningProfile),t.models!==void 0&&(r.models=t.models),t.modelReasoningCapabilities!==void 0&&(r.modelReasoningCapabilities=t.modelReasoningCapabilities),t.contextWindow!==void 0&&(r.contextWindow=t.contextWindow),t.maxOutputTokens!==void 0&&(r.maxOutputTokens=t.maxOutputTokens),t.maxOutputTokensField!==void 0&&(r.maxOutputTokensField=t.maxOutputTokensField),t.thinkingBudgetCap!==void 0&&(r.thinkingBudgetCap=t.thinkingBudgetCap),t.supportsThinking!==void 0&&(r.supportsThinking=t.supportsThinking),r}o(zd,"buildSnapshot");function Uo(){if(Dt)return Dt;let e=Ud(),t;try{let i=Kd(e,"utf8");t=JSON.parse(i)}catch(i){let s=i instanceof Error?i.message:String(i);throw new Error(`provider-capabilities loader: failed to read ${e}: ${s}`)}let n=Bo(t),r={};for(let[i,s]of Object.entries(n.providers))r[i]=Wd(zd(i,s));return Dt=Object.freeze(r),Dt}o(Uo,"getProviderSnapshots");import px from"@anthropic-ai/sdk";var Lt=Uo();var Wo=process.env.KODAX_PROVIDER??"zhipu-coding";var Su=[];function z(e){let t=Pt(e),n=Su.at(-1)?.sink;if(n){try{n(t)}catch{}return}if(process.env.KODAX_DIAGNOSTICS_STDERR==="1")try{process.stderr.write(`${ai(t)}
|
|
90
|
+
`)}catch{}}o(z,"emitKodaXDiagnostic");function ai(e){let t=Pt(e),n=Eu(t.detail);return`[${t.source}] ${t.level}: ${t.message}${n?` ${n}`:""}`}o(ai,"formatKodaXDiagnostic");function Eu(e){if(e===void 0)return"";if(e instanceof Error)return e.stack??e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}o(Eu,"formatDiagnosticDetail");var ot=class e{static{o(this,"SpanImpl")}id;traceId;parentId;name;data;startedAt;_endedAt;_error;_children=[];now;nextSpanId;onChildCreated;onSpanEnd;_ended=!1;constructor(t){this.id=t.id,this.traceId=t.traceId,this.parentId=t.parentId,this.name=t.name,this.data=t.data,this.now=t.now??(()=>Date.now()),this.startedAt=t.startedAt??this.now(),this.nextSpanId=t.nextSpanId??Iu,this.onChildCreated=t.onChildCreated,this.onSpanEnd=t.onSpanEnd}get endedAt(){return this._endedAt}get error(){return this._error}get children(){return this._children}addChild(t,n){let r=new e({id:this.nextSpanId(),traceId:this.traceId,parentId:this.id,name:t,data:n,now:this.now,nextSpanId:this.nextSpanId,onChildCreated:this.onChildCreated,onSpanEnd:this.onSpanEnd});return this._children.push(r),this.onChildCreated&&this.onChildCreated(r),r}setError(t){t instanceof Error?this._error={message:t.message,stack:t.stack}:this._error=t}end(){this._ended||(this._ended=!0,this._endedAt=this.now(),this.onSpanEnd&&this.onSpanEnd(this))}},ci=0;function Iu(){ci+=1;let e=Math.random().toString(36).slice(2,8);return`span-${Date.now()}-${ci}-${e}`}o(Iu,"defaultNextSpanId");var di=0;function Cu(){di+=1;let e=Math.random().toString(36).slice(2,8);return`trace-${Date.now()}-${di}-${e}`}o(Cu,"defaultNextTraceId");function Dn(e={}){let t=e.now??(()=>Date.now()),n=e.id??(e.nextTraceId??Cu)(),r=t(),i=e.name??"trace",s=e.metadata??new Map,a=e.rootSpanData??{kind:"agent",agentName:i},c=!1,d,u,l=new ot({id:`${n}-root`,traceId:n,name:i,data:a,startedAt:r,now:t,nextSpanId:e.nextSpanId,onChildCreated:e.onSpanStart,onSpanEnd:e.onSpanEnd});e.onSpanStart&&e.onSpanStart(l);let f={id:n,startedAt:r,rootSpan:l,metadata:s,get endedAt(){return d},get error(){return u??l.error},end(){c||(c=!0,d=t(),l.end(),e.onTraceEnd&&e.onTraceEnd(f))}};return f}o(Dn,"createTrace");var Ln=[];function Fn(e){for(let t of Ln)try{t.onSpanStart(e)}catch{}}o(Fn,"_emitSpanStart");function jn(e){for(let t of Ln)try{t.onSpanEnd(e)}catch{}}o(jn,"_emitSpanEnd");function Kn(e){for(let t of Ln)try{t.onTraceEnd(e)}catch{}}o(Kn,"_emitTraceEnd");var Ft=class{static{o(this,"Tracer")}options;constructor(t={}){this.options=t}startTrace(t={}){return Dn({id:t.id,name:t.name,rootSpanData:t.rootSpanData,metadata:t.metadata,now:this.options.now,nextSpanId:this.options.nextSpanId,nextTraceId:this.options.nextTraceId,onSpanStart:Fn,onSpanEnd:jn,onTraceEnd:Kn})}},ui=new Ft;var Mu=["read","edit","bash:test","bash:read-only","bash:mutating","bash:network","subagent"];var eI=new Set(Mu);var HI=String.raw`
|
|
91
|
+
using System;
|
|
92
|
+
using System.Runtime.InteropServices;
|
|
93
|
+
using System.Text;
|
|
94
|
+
public static class KodaXNativeProcessSnapshot {
|
|
95
|
+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
|
|
96
|
+
private struct ProcessEntry32 {
|
|
97
|
+
public uint dwSize;
|
|
98
|
+
public uint cntUsage;
|
|
99
|
+
public uint th32ProcessID;
|
|
100
|
+
public IntPtr th32DefaultHeapID;
|
|
101
|
+
public uint th32ModuleID;
|
|
102
|
+
public uint cntThreads;
|
|
103
|
+
public uint th32ParentProcessID;
|
|
104
|
+
public int pcPriClassBase;
|
|
105
|
+
public uint dwFlags;
|
|
106
|
+
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
|
|
107
|
+
public string szExeFile;
|
|
108
|
+
}
|
|
109
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
110
|
+
private static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processId);
|
|
111
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
|
112
|
+
private static extern bool Process32First(IntPtr snapshot, ref ProcessEntry32 entry);
|
|
113
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
|
114
|
+
private static extern bool Process32Next(IntPtr snapshot, ref ProcessEntry32 entry);
|
|
115
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
116
|
+
private struct FileTime {
|
|
117
|
+
public uint Low;
|
|
118
|
+
public uint High;
|
|
119
|
+
}
|
|
120
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
121
|
+
private static extern IntPtr OpenProcess(uint access, bool inheritHandle, uint processId);
|
|
122
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
123
|
+
private static extern bool GetProcessTimes(IntPtr process, out FileTime creation, out FileTime exit, out FileTime kernel, out FileTime user);
|
|
124
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
125
|
+
private static extern bool TerminateProcess(IntPtr process, uint exitCode);
|
|
126
|
+
[DllImport("kernel32.dll")]
|
|
127
|
+
private static extern void GetSystemTimeAsFileTime(out FileTime systemTime);
|
|
128
|
+
[DllImport("kernel32.dll")]
|
|
129
|
+
private static extern bool CloseHandle(IntPtr handle);
|
|
130
|
+
private static ulong ReadCreationTime(uint processId) {
|
|
131
|
+
var process = OpenProcess(0x1000, false, processId);
|
|
132
|
+
if (process == IntPtr.Zero) return 0;
|
|
133
|
+
try {
|
|
134
|
+
FileTime creation, exit, kernel, user;
|
|
135
|
+
if (!GetProcessTimes(process, out creation, out exit, out kernel, out user)) return 0;
|
|
136
|
+
return ((ulong)creation.High << 32) | creation.Low;
|
|
137
|
+
} finally {
|
|
138
|
+
CloseHandle(process);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
public static int TerminateExact(uint processId, ulong expectedCreationTime) {
|
|
142
|
+
var process = OpenProcess(0x1001, false, processId);
|
|
143
|
+
if (process == IntPtr.Zero) return 0;
|
|
144
|
+
try {
|
|
145
|
+
FileTime creation, exit, kernel, user;
|
|
146
|
+
if (!GetProcessTimes(process, out creation, out exit, out kernel, out user)) return 0;
|
|
147
|
+
var actual = (((ulong)creation.High << 32) | creation.Low) / 10000;
|
|
148
|
+
if (actual != expectedCreationTime) return 2;
|
|
149
|
+
return TerminateProcess(process, 1) ? 1 : 0;
|
|
150
|
+
} finally {
|
|
151
|
+
CloseHandle(process);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
public static string ReadRows() {
|
|
155
|
+
FileTime cutoffTime;
|
|
156
|
+
GetSystemTimeAsFileTime(out cutoffTime);
|
|
157
|
+
var cutoff = (((ulong)cutoffTime.High << 32) | cutoffTime.Low) / 10000;
|
|
158
|
+
var snapshot = CreateToolhelp32Snapshot(2, 0);
|
|
159
|
+
if (snapshot == new IntPtr(-1)) return string.Empty;
|
|
160
|
+
var rows = new StringBuilder();
|
|
161
|
+
var entry = new ProcessEntry32();
|
|
162
|
+
entry.dwSize = (uint)Marshal.SizeOf(entry);
|
|
163
|
+
try {
|
|
164
|
+
if (!Process32First(snapshot, ref entry)) return string.Empty;
|
|
165
|
+
do {
|
|
166
|
+
var creationTime = ReadCreationTime(entry.th32ProcessID) / 10000;
|
|
167
|
+
if (creationTime == 0 || creationTime <= cutoff) {
|
|
168
|
+
rows.Append(entry.th32ProcessID).Append(',').Append(entry.th32ParentProcessID).Append(',').Append(creationTime).Append('\n');
|
|
169
|
+
}
|
|
170
|
+
entry.dwSize = (uint)Marshal.SizeOf(entry);
|
|
171
|
+
} while (Process32Next(snapshot, ref entry));
|
|
172
|
+
return rows.ToString();
|
|
173
|
+
} finally {
|
|
174
|
+
CloseHandle(snapshot);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}`,zI=Object.freeze({status:"terminated"}),qI=Object.freeze({status:"already-exited"}),VI=Object.freeze({status:"unknown"});import{Jimp as SC}from"jimp";var cl=Math.floor(3.75*1024*1024);var ul=1440*60*1e3;import{fileURLToPath as Ll}from"url";import{dirname as Fl}from"path";var jl=Ll(import.meta.url),CR=Fl(jl);import{readFile as Wl,readdir as Hl}from"fs/promises";import{join as xe,relative as zl}from"path";import Si from"yaml";var Kl=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","Stop","SubagentStop","Notification"];function Bl(e){let t=e.split(`
|
|
178
|
+
`),n=[];for(let r of t){let i=r.indexOf(":");if(i>0){let s=r.slice(0,i).trim(),a=r.slice(i+1).trim();if(a.includes(":")&&!a.startsWith('"')&&!a.startsWith("'")&&!a.startsWith("[")&&!a.startsWith("|")&&!a.startsWith(">")){n.push(`${s}: |-`),n.push(` ${a}`);continue}}n.push(r)}return n.join(`
|
|
179
|
+
`)}o(Bl,"sanitizeYaml");function Ei(e,t={}){let n=e.replace(/^/,"").replace(/\r\n/g,`
|
|
180
|
+
`).replace(/\r/g,`
|
|
181
|
+
`).trimStart();if(!n.startsWith(`---
|
|
182
|
+
`)){if(t.throwOnMissing)throw new Error("Invalid markdown: missing YAML frontmatter");return[null,e]}let r=n.indexOf(`
|
|
183
|
+
---
|
|
184
|
+
`,4);if(r===-1){let c=n.indexOf(`
|
|
185
|
+
---`,4);c!==-1&&c===n.length-4&&(r=c)}if(r===-1){if(t.throwOnMissing)throw new Error("Invalid markdown: unclosed YAML frontmatter");return[null,e]}let i=n.slice(4,r),s=n.slice(r+5).trim(),a;try{a=Si.parse(i)??{}}catch{a=Si.parse(Bl(i))??{}}if(a==null||typeof a!="object"||Array.isArray(a)){if(t.throwOnMissing)throw new Error("Invalid markdown: YAML frontmatter must be an object");return[null,s]}return[a,s]}o(Ei,"parseYamlFrontmatter");function Ii(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){let t=e.map(n=>String(n).trim()).filter(n=>n.length>0);return t.length>0?t.join(", "):void 0}}o(Ii,"normalizeAllowedToolsString");function Xl(e){if(typeof e=="string"){let t=e.trim();return t?{command:t}:void 0}if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e,n=typeof t.command=="string"?t.command.trim():"";if(!n)return;let r=typeof t.matcher=="string"&&t.matcher.trim()?t.matcher.trim():void 0;return{command:n,matcher:r}}}o(Xl,"normalizeYamlHookEntry");function Ul(e){if(e==null)return;let n=(Array.isArray(e)?e:[e]).map(r=>Xl(r)).filter(r=>r!==void 0);return n.length>0?n:void 0}o(Ul,"normalizeYamlHookEntryList");function Ci(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n={};for(let r of Kl){let i=Ul(t[r]);i&&(n[r]=i)}return Object.keys(n).length>0?n:void 0}o(Ci,"normalizeYamlHookMap");function Ti(e){let[t,n]=Ei(e,{throwOnMissing:!0});if(!t)throw new Error("Invalid SKILL.md: YAML frontmatter must be an object");if(!t.name||typeof t.name!="string")throw new Error('Invalid SKILL.md: missing required "name" field');if(!t.description||typeof t.description!="string")throw new Error('Invalid SKILL.md: missing required "description" field');return{frontmatter:{name:t.name,description:t.description,disableModelInvocation:t["disable-model-invocation"]===!0,userInvocable:t["user-invocable"]!==!1,allowedTools:Ii(t["allowed-tools"]),context:t.context==="fork"?"fork":void 0,agent:typeof t.agent=="string"?t.agent:void 0,argumentHint:typeof t["argument-hint"]=="string"?t["argument-hint"]:void 0,model:typeof t.model=="string"?t.model:void 0,hooks:Ci(t.hooks),license:typeof t.license=="string"?t.license:void 0,compatibility:typeof t.compatibility=="string"?t.compatibility:void 0,metadata:t.metadata&&typeof t.metadata=="object"&&!Array.isArray(t.metadata)?t.metadata:void 0},body:n}}o(Ti,"parseSkillMarkdown");async function jt(e,t){let n=xe(e,"SKILL.md");try{let r=await Wl(n,"utf-8"),{frontmatter:i,body:s}=Ti(r),[a,c,d,u,l]=await Promise.all([Le(xe(e,"scripts")),Le(xe(e,"references")),Le(xe(e,"assets")),Le(xe(e,"templates")),Le(xe(e,"resources"))]);return{...i,path:e,skillFilePath:n,content:s,rawContent:s,loaded:!0,source:t,...a.length>0&&{scripts:a},...c.length>0&&{references:c},...d.length>0&&{assets:d},...u.length>0&&{templates:u},...l.length>0&&{resources:l}}}catch(r){return z({source:"agent:skills",level:"error",message:`Failed to load skill from ${e}.`,detail:r}),null}}o(jt,"loadFullSkill");async function Le(e,t=e){let n=[];try{let r=await Hl(e,{withFileTypes:!0});r.sort((i,s)=>i.name.localeCompare(s.name));for(let i of r){let s=xe(e,i.name);if(i.isDirectory()){n.push(...await Le(s,t));continue}i.isFile()&&n.push({name:i.name,path:s,relativePath:zl(t,s).replace(/\\/g,"/")})}}catch{}return n}o(Le,"loadSkillFiles");var Ri=64*1024,_i=256*1024;var g_=1024*1024;var z_=16*1024;var tA=16*1024;import{execSync as _f}from"child_process";import Af from"path";var Pf=new Set(["ls","cat","pwd","echo","whoami","date","which","whereis","tree","dir","type","get-childitem","get-content","select-string","get-location","grep","find","awk","sed","head","tail","less","more","wc","git status","git diff","git log","git show","git branch","git remote","git ls-files","git rev-parse","git grep","node","npm","yarn","pnpm","tsc","python","pip","go","cargo","rustc"]);function Wi(e){if(!e||!e.trim())return!1;let t=e.trim().replace(/\s+/g," ").toLowerCase();for(let n of Pf)if(t===n||t.startsWith(`${n} `)){if(n==="sed"&&t.split(/\s+/).some(s=>s.startsWith("-i")||s==="--in-place"))return!1;if(n==="awk"){let i=t.split(/\s+/);if(i.includes("-f")||i.includes("--file"))return!1}if(["node","npm","yarn","pnpm","tsc","python","pip","go","cargo","rustc"].includes(n)){let i=t.split(/\s+/).slice(1);if(i.length>0&&!i.every(s=>/^(-v|--version|-h|--help)$/.test(s)))return!1}return!0}return!1}o(Wi,"isSingleSafeDynamicContextCommand");function Mf(e){if(!e||!e.trim())return!1;let t=e.trim().replace(/\\\r?\n/g," ");if(/[<>|;`]|\$\(|(?<!&)&(?!&)/.test(t)||t.includes("\\")&&Af.sep!=="\\"&&t.replace(/\\ /g,"").includes("\\"))return!1;let r=t.split(/\s*&&\s*/);if(r.length===1)return Wi(r[0]);for(let i of r){let s=i?.trim();if(s&&!/^cd\s+/.test(s.toLowerCase())&&!Wi(s))return!1}return!0}o(Mf,"isSafeDynamicContextCommand");function Hi(e){let t=[],n="",r=!1,i="";for(let s=0;s<e.length;s++){let a=e[s];r?a===i?r=!1:n+=a:a==='"'||a==="'"?(r=!0,i=a):a===" "?n&&(t.push(n),n=""):n+=a}return n&&t.push(n),t}o(Hi,"parseArguments");var Wt=class{static{o(this,"VariableResolver")}context;constructor(t){this.context=t}async resolve(t,n){let r=t,i=Hi(n);return r=this.resolvePositionalArgs(r,i),r=this.resolveArguments(r,n),r=this.resolveEnvVars(r),r=await this.resolveDynamicContext(r),r}resolvePositionalArgs(t,n){return t.replace(/\$(\d+)(?![a-zA-Z0-9_])/g,(r,i)=>{let s=parseInt(i,10);return n[s]??""})}resolveArguments(t,n){return t.replace(/\$ARGUMENTS/g,n)}resolveEnvVars(t){let n={...this.context.environment,CLAUDE_SESSION_ID:this.context.sessionId??"",KODAX_SESSION_ID:this.context.sessionId??"",KODAX_WORKING_DIR:this.context.workingDirectory};return t.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(r,i)=>n[i]??r)}async resolveDynamicContext(t){let n=/!`([^`]+)`/g,r=[],i;for(;(i=n.exec(t))!==null;)r.push({match:i[0],command:i[1]});if(r.length===0)return t;let s=t;for(let{match:a,command:c}of r)try{let d=await this.executeDynamicCommand(c);s=s.replace(a,d)}catch(d){let u=d instanceof Error?d.message:String(d);s=s.replace(a,`[Error: ${u}]`)}return s}async executeDynamicCommand(t){if(this.context.disableDynamicContext)throw new Error("Dynamic context disabled by host. Skill `!`cmd`` blocks are not allowed in this environment.");if(this.context.executeDynamicContext){let n=await this.context.executeDynamicContext(t,this.context.workingDirectory);return typeof n=="string"?n.trim():""}if(!Mf(t))throw new Error("Unsafe dynamic context command blocked. Only simple read-only commands are allowed in !`...` blocks.");try{return _f(t,{cwd:this.context.workingDirectory,encoding:"utf-8",timeout:5e3,maxBuffer:1048576,windowsHide:!0}).trim()}catch(n){throw n instanceof Error?new Error(`Command failed: ${n.message}`):n}}};async function at(e,t,n){return new Wt(n).resolve(e,t)}o(at,"resolveSkillContent");function zi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}o(zi,"escapeXml");var zn=120;function Ht(e){return e.replace(/\\/g,"/")}o(Ht,"formatDisplayPath");function $f(e){return[...(e.references??[]).map(t=>({folder:"references",file:t})),...(e.scripts??[]).map(t=>({folder:"scripts",file:t})),...(e.assets??[]).map(t=>({folder:"assets",file:t})),...(e.templates??[]).map(t=>({folder:"templates",file:t})),...(e.resources??[]).map(t=>({folder:"resources",file:t}))]}o($f,"collectSupportFiles");function Df(e){let t=$f(e);if(t.length===0)return[];let n=[["references",e.references],["scripts",e.scripts],["assets",e.assets],["templates",e.templates],["resources",e.resources]],r=["Skill support files are rooted at the skill root above. When the skill references `references/...`, `assets/...`, `scripts/...`, `templates/...`, or `resources/...`, read it from this skill root.","","Support roots:"];for(let[i,s]of n)s?.length&&r.push(`- ${i}/: ${Ht(`${e.path}/${i}`)} (${s.length} files)`);r.push("","Support file inventory:");for(let{folder:i,file:s}of t.slice(0,zn))r.push(`- ${i}/${s.relativePath}: ${Ht(s.path)}`);return t.length>zn&&r.push(`- ... ${t.length-zn} more files under ${Ht(e.path)}`),r}o(Df,"buildSupportFileContext");function Lf(e,t,n){let r=[];r.push(`<skill name="${zi(e.name)}" location="${zi(e.path)}">`),r.push(""),r.push(`Skill root: ${Ht(e.path)}`),e.source==="builtin"?r.push("This is a built-in KodaX skill."):e.source==="project"?r.push("This is a project-defined skill. Project work paths are relative to the project root; skill support files are relative to the skill root above."):e.source==="user"&&r.push("This is a user-defined skill."),r.push("");let i=Df(e);return i.length>0&&(r.push(...i),r.push("")),r.push(t),n.trim()&&(r.push(""),r.push(`User provided arguments: ${n}`)),r.push(""),r.push("</skill>"),r.join(`
|
|
186
|
+
`)}o(Lf,"buildSkillBlock");async function qn(e,t,n){let r=await at(e.content,t,n);return{content:Lf(e,r,t),disableModelInvocation:e.disableModelInvocation??!1,skill:e}}o(qn,"expandSkillForLLM");import{writeFile as Ji}from"node:fs/promises";import he from"node:path";import{existsSync as Ff}from"node:fs";import{mkdir as jf,readFile as Vn,readdir as Kf,stat as Vi,writeFile as ZA}from"node:fs/promises";import Bf from"node:os";import re from"node:path";import{fileURLToPath as Gi,pathToFileURL as Xf}from"node:url";import Uf from"yaml";var Fe=null;async function me(){if(Fe)return Fe;let e=re.dirname(Gi(import.meta.url)),t=[],n=re.resolve(e,"../../../index.js");if(Ff(n))return Fe=await import(Xf(n).href),Fe;t.push(`relative SDK path not found: ${n}`);try{return Fe=await import(["@kodax-ai","kodax"].join("/")),Fe}catch(r){t.push(`bare-name @kodax-ai/kodax failed: ${r?.code??r?.message}`)}throw new Error(`Cannot locate KodaX SDK from helper script ${import.meta.url}.
|
|
187
|
+
Attempted:
|
|
188
|
+
- ${t.join(`
|
|
189
|
+
- `)}`)}o(me,"loadKodaXSDK");function Wf(e){let t=e.replace(/^\uFEFF/,"").replace(/\r\n/g,`
|
|
190
|
+
`).replace(/\r/g,`
|
|
191
|
+
`).trimStart();if(!t.startsWith(`---
|
|
192
|
+
`))throw new Error("SKILL.md missing YAML frontmatter");let n=t.indexOf(`
|
|
193
|
+
---
|
|
194
|
+
`,4);if(n===-1)throw new Error("SKILL.md has unclosed YAML frontmatter");return{yamlText:t.slice(4,n),body:t.slice(n+5).trim()}}o(Wf,"extractFrontmatter");function zt(e){let{yamlText:t,body:n}=Wf(e),r=Uf.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Frontmatter must be a YAML object");return{frontmatter:r,body:n}}o(zt,"parseSkillMarkdown");async function dt(e){let t=re.join(e,"SKILL.md");if(!(await Vi(t).catch(()=>null))?.isFile())throw new Error(`SKILL.md not found in ${e}`);let r=await Vn(t,"utf8"),{frontmatter:i,body:s}=zt(r);return{skillDir:re.resolve(e),skillMdPath:t,rawContent:r,body:s,frontmatter:i}}o(dt,"loadSkill");async function ut(e){try{return await Vi(e),!0}catch{return!1}}o(ut,"pathExists");function qt(e){if(!e.length)return{mean:0,stddev:0,min:0,max:0};let t=e.reduce((r,i)=>r+i,0)/e.length,n=e.length>1?e.reduce((r,i)=>r+(i-t)**2,0)/(e.length-1):0;return{mean:ct(t),stddev:ct(Math.sqrt(n)),min:ct(Math.min(...e)),max:ct(Math.max(...e))}}o(qt,"calculateStats");function ct(e,t=4){return Number(e.toFixed(t))}o(ct,"roundNumber");function Vt(e){return e>=0?`+${e.toFixed(4)}`:e.toFixed(4)}o(Vt,"formatDelta");function qi(e){try{return JSON.parse(e)}catch{return null}}o(qi,"safeJsonParse");function je(e){let t=qi(e.trim());if(t&&typeof t=="object")return t;let n=e.indexOf("{"),r=e.lastIndexOf("}");return n===-1||r===-1||r<=n?null:qi(e.slice(n,r+1))}o(je,"extractJsonObject");async function Y(e,t=null){try{return JSON.parse(await Vn(e,"utf8"))}catch{return t}}o(Y,"readJsonFile");async function Ke(e,t){let n=re.dirname(Gi(e));return Vn(re.resolve(n,t),"utf8")}o(Ke,"loadRelativeText");function L(e,t=12e3){let n=typeof e=="string"?e:String(e??"");if(n.length<=t)return n;let r=n.length-t;return`${n.slice(0,t)}
|
|
195
|
+
|
|
196
|
+
[truncated ${r} chars]`}o(L,"truncateText");function Yi(e){let t=Array.isArray(e)?e.length:0,n=Array.isArray(e)?e.filter(i=>i?.passed===!0).length:0,r=Math.max(t-n,0);return{passed:n,failed:r,total:t,pass_rate:t>0?ct(n/t):0}}o(Yi,"computePassSummary");async function Gn(e,t=e,n=[]){let r=await Kf(t,{withFileTypes:!0}).catch(()=>[]);for(let i of r.sort((s,a)=>s.name.localeCompare(a.name))){let s=re.join(t,i.name);if(i.isDirectory()){await Gn(e,s,n);continue}i.isFile()&&n.push({absolutePath:s,relativePath:re.relative(e,s).replace(/\\/g,"/")})}return n}o(Gn,"collectFiles");function lt(){return re.join(Bf.homedir(),".kodax","skills")}o(lt,"getDefaultSkillsDir");async function F(e){return await jf(e,{recursive:!0}),e}o(F,"ensureDirectory");function Hf(e){return e.split("-").filter(Boolean).map(t=>t[0]?.toUpperCase()+t.slice(1)).join(" ")}o(Hf,"titleFromSlug");function zf(e,t){let n=Hf(e);return`---
|
|
197
|
+
name: ${e}
|
|
198
|
+
description: ${t}
|
|
199
|
+
user-invocable: true
|
|
200
|
+
allowed-tools: "Read, Grep, Glob"
|
|
201
|
+
compatibility: "Optimized for KodaX and Agent Skills style directories."
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
# ${n}
|
|
205
|
+
|
|
206
|
+
Describe the task this skill handles, the trigger boundary, and the expected outcome.
|
|
207
|
+
|
|
208
|
+
## When to use
|
|
209
|
+
|
|
210
|
+
- Use this skill when the user asks for ${n.toLowerCase()}.
|
|
211
|
+
- Do not use this skill when the request only needs a short explanation or is out of scope.
|
|
212
|
+
|
|
213
|
+
## Workflow
|
|
214
|
+
|
|
215
|
+
1. Restate the task boundary in one sentence.
|
|
216
|
+
2. Gather the minimum context needed to do the work well.
|
|
217
|
+
3. Execute the task, preferring small, verifiable steps.
|
|
218
|
+
4. Summarize what changed, what was validated, and any remaining risks.
|
|
219
|
+
|
|
220
|
+
## References
|
|
221
|
+
|
|
222
|
+
- Put deeper guidance in \`references/\`.
|
|
223
|
+
- Put reusable templates or static files in \`assets/\`.
|
|
224
|
+
- Put repeatable helper scripts in \`scripts/\`.
|
|
225
|
+
`}o(zf,"renderSkillTemplate");function qf(e){return JSON.stringify({skill_name:e,evals:[{id:1,prompt:"TODO: Add a realistic user request to evaluate this skill.",expected_output:"Describe what a successful result should accomplish.",files:[],assertions:[]}]},null,2)}o(qf,"renderEvalTemplate");async function Vf(e){let t=he.resolve(e.baseDir??lt()),n=he.join(t,e.name),r=e.description??`Describe what ${e.name} does and when it should be used.`;if(await ut(n)&&!e.force)throw new Error(`Skill directory already exists: ${n}`);return await F(n),await F(he.join(n,"references")),await F(he.join(n,"assets")),await F(he.join(n,"scripts")),await Ji(he.join(n,"SKILL.md"),zf(e.name,r),"utf8"),e.includeEvals!==!1&&(await F(he.join(n,"evals")),await Ji(he.join(n,"evals","evals.json"),`${qf(e.name)}
|
|
226
|
+
`,"utf8")),{skillDir:n,created:["SKILL.md",...e.includeEvals!==!1?["evals/evals.json"]:[],"references/","assets/","scripts/"]}}o(Vf,"initSkill");function Gf(e){let t={name:e[2],baseDir:void 0,description:void 0,force:!1,includeEvals:!0};for(let n=3;n<e.length;n+=1){let r=e[n];(r==="--path"||r==="--dest")&&e[n+1]?t.baseDir=e[++n]:r==="--description"&&e[n+1]?t.description=e[++n]:r==="--force"?t.force=!0:r==="--no-evals"&&(t.includeEvals=!1)}return t}o(Gf,"parseArgs");async function Qi(e=process.argv){let t=Gf(e);t.name||(console.error("Usage: node scripts/init-skill.js <skill-name> [--path <skills-dir>] [--description <text>] [--force] [--no-evals]"),process.exit(1));let n=await Vf(t);console.log(`Initialized ${n.skillDir}`)}o(Qi,"main");var Yf=!1;Yf&&Qi().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});import Zi from"node:path";var Jf=new Set(["name","description","license","compatibility","metadata","allowed-tools","disable-model-invocation","user-invocable","argument-hint","context","agent","model","hooks"]);async function ft(e){let t={valid:!1,errors:[],warnings:[],frontmatter:null},n;try{n=await dt(e)}catch(d){return t.errors.push(d instanceof Error?d.message:String(d)),t}let{frontmatter:r,body:i}=n;t.frontmatter=r;let s=Object.keys(r).filter(d=>!Jf.has(d));s.length>0&&t.errors.push(`Unexpected frontmatter keys: ${s.sort().join(", ")}`);let a=typeof r.name=="string"?r.name.trim():"",c=typeof r.description=="string"?r.description.trim():"";if(!a)t.errors.push("Missing required frontmatter field: name");else{/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(a)||t.errors.push(`Invalid skill name "${a}". Use lowercase kebab-case and avoid consecutive hyphens.`),a.length>64&&t.errors.push(`Skill name is too long (${a.length}/64).`);let d=Zi.basename(Zi.resolve(e));d!==a&&t.warnings.push(`Skill directory name "${d}" does not match frontmatter name "${a}".`)}if(c?(c.length>1024&&t.errors.push(`Description is too long (${c.length}/1024).`),/[<>]/.test(c)&&t.errors.push("Description cannot contain angle brackets."),/[。.!?]/.test(c)||t.warnings.push("Description may be too terse; consider making the trigger conditions clearer.")):t.errors.push("Missing required frontmatter field: description"),i.trim()||t.errors.push("SKILL.md body is empty."),r.compatibility!=null&&(typeof r.compatibility!="string"?t.errors.push("compatibility must be a string if provided."):r.compatibility.length>500&&t.errors.push(`compatibility is too long (${r.compatibility.length}/500).`)),r["allowed-tools"]!=null){let d=r["allowed-tools"];typeof d=="string"||Array.isArray(d)&&d.every(l=>typeof l=="string")||t.errors.push("allowed-tools must be a string or string array.")}return r["disable-model-invocation"]!=null&&typeof r["disable-model-invocation"]!="boolean"&&t.errors.push("disable-model-invocation must be a boolean."),r["user-invocable"]!=null&&typeof r["user-invocable"]!="boolean"&&t.errors.push("user-invocable must be a boolean."),r.context!=null&&r.context!=="fork"&&t.errors.push('context must be "fork" when provided.'),r.hooks!=null&&(typeof r.hooks!="object"||Array.isArray(r.hooks))&&t.errors.push("hooks must be an object when provided."),t.valid=t.errors.length===0,t}o(ft,"validateSkillDirectory");async function es(e=process.argv){let t=e[2];t||(console.error("Usage: node scripts/quick-validate.js <skill-directory>"),process.exit(1));let n=await ft(t);if(n.errors.length===0)console.log("Skill is valid.");else{console.error("Skill validation failed:");for(let r of n.errors)console.error(`- ${r}`)}if(n.warnings.length>0){console.log("Warnings:");for(let r of n.warnings)console.log(`- ${r}`)}process.exit(n.valid?0:1)}o(es,"main");var Qf=!1;Qf&&es().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});import{readFile as Yn,writeFile as oe}from"node:fs/promises";import C from"node:path";function Zf(e){return typeof e=="string"?{text:e}:e&&typeof e=="object"&&typeof e.text=="string"?{text:e.text}:null}o(Zf,"normalizeAssertion");function ep(e){return e.reduce((t,n)=>Array.isArray(n.content)?t+n.content.filter(r=>r?.type==="tool_use").length:t,0)}o(ep,"countToolCalls");function tp(e){return e.reduce((t,n)=>Array.isArray(n.content)?t+n.content.filter(r=>r?.type==="tool_result"&&r.is_error===!0).length:t,0)}o(tp,"countToolErrors");function np(e,t){return`${["# Skill Eval Transcript","","## Eval Prompt","",e,"","## Final Response","",t.lastText||"(No final text)","","## Result Flags","",`- success: ${t.success}`,`- signal: ${t.signal??"none"}`,`- interrupted: ${t.interrupted===!0}`,`- limit_reached: ${t.limitReached===!0}`].join(`
|
|
227
|
+
`)}
|
|
228
|
+
`}o(np,"renderTranscript");async function rp(e,t){let n=C.dirname(C.resolve(t.evalsPath)),r=C.resolve(t.cwd??process.cwd()),i=[];for(let s of e??[]){let a=C.isAbsolute(s)?s:C.resolve(n,s),c=C.resolve(r,s),d=null,u=a;try{d=await Yn(a,"utf8")}catch{d=await Yn(c,"utf8").catch(()=>null),u=c}if(d==null)throw new Error(`Input file not found for eval: ${s}`);i.push(`### ${s}
|
|
229
|
+
\`\`\`
|
|
230
|
+
${d}
|
|
231
|
+
\`\`\`
|
|
232
|
+
(Resolved from ${u})`)}return i.length===0?"":`## Input Files
|
|
233
|
+
|
|
234
|
+
${i.join(`
|
|
235
|
+
|
|
236
|
+
`)}
|
|
237
|
+
|
|
238
|
+
`}o(rp,"readInputFiles");async function op(e,t){let n=String(e.prompt??e.query??"").trim();return`${await rp(e.files,t)}${n}`.trim()}o(op,"buildEvalPrompt");async function ip(e,t){let{runKodaX:n,estimateTokens:r}=await me(),i=Date.now(),s=await n({provider:t.provider??"anthropic",model:t.model,maxIter:t.maxIter??30,reasoningMode:t.reasoningMode??"off",thinking:t.reasoningMode?t.reasoningMode!=="off":!1,context:{gitRoot:C.resolve(t.cwd??process.cwd())}},e);return{result:s,totalTokens:r(s.messages),durationMs:Date.now()-i}}o(ip,"defaultRunAgent");async function sp(e,t,n,r){return e==="with_skill"?(await qn(t,n,{workingDirectory:C.resolve(r.cwd??process.cwd()),projectRoot:C.resolve(r.cwd??process.cwd()),sessionId:"skill-eval",environment:{}})).content:n}o(sp,"prepareConfigPrompt");async function ap(e,t,n,r,i){let s=C.join(e,"outputs");await F(s);let a={total_tool_calls:ep(i.result.messages),errors_encountered:tp(i.result.messages),output_chars:i.result.lastText.length};await oe(C.join(s,"result.md"),`${i.result.lastText}
|
|
239
|
+
`,"utf8"),await oe(C.join(s,"prompt.txt"),`${r}
|
|
240
|
+
`,"utf8"),await oe(C.join(e,"transcript.md"),np(r,i.result),"utf8"),await oe(C.join(s,"metrics.json"),`${JSON.stringify({config:t,eval_id:n.id??null,session_id:i.result.sessionId,...a},null,2)}
|
|
241
|
+
`,"utf8"),await oe(C.join(s,"messages.json"),`${JSON.stringify(i.result.messages,null,2)}
|
|
242
|
+
`,"utf8"),await oe(C.join(e,"timing.json"),`${JSON.stringify({total_tokens:i.totalTokens,duration_ms:i.durationMs,total_duration_seconds:Number((i.durationMs/1e3).toFixed(4))},null,2)}
|
|
243
|
+
`,"utf8"),await oe(C.join(e,"result.json"),`${JSON.stringify({success:i.result.success,signal:i.result.signal??null,signal_reason:i.result.signalReason??null,interrupted:i.result.interrupted===!0,limit_reached:i.result.limitReached===!0,session_id:i.result.sessionId,execution_metrics:a},null,2)}
|
|
244
|
+
`,"utf8")}o(ap,"writeRunArtifacts");async function cp(e,t=ip){let n=await jt(C.resolve(e.skillPath),"user");if(!n)throw new Error(`Failed to load skill from ${e.skillPath}`);let r=C.resolve(e.workspaceDir);await F(r);let i=JSON.parse(await Yn(e.evalsPath,"utf8")),s=Array.isArray(i.evals)?i.evals:[],a=e.configs?.length?e.configs:["with_skill","without_skill"],c=Number.isFinite(e.runsPerConfig)&&e.runsPerConfig>0?Math.floor(e.runsPerConfig):1,d=[];for(let u=0;u<s.length;u+=1){let l=s[u],f=C.join(r,`eval-${u}`);await F(f),await oe(C.join(f,"eval_metadata.json"),`${JSON.stringify({eval_id:l.id??u,eval_name:l.name??`eval-${u}`,prompt:l.prompt??l.query??"",expected_output:l.expected_output??"",assertions:(Array.isArray(l.assertions)?l.assertions:[]).map(Zf).filter(Boolean)},null,2)}
|
|
245
|
+
`,"utf8");let m=await op(l,e),p={};for(let g of a){let v=C.join(f,g);await F(v),p[g]=[];for(let w=1;w<=c;w+=1){let y=C.join(v,`run-${w}`);await F(y);let h=await sp(g,n,m,e),b=await t(h,{...e,configName:g,evalItem:l,runIndex:w});await ap(y,g,l,h,b),p[g].push({run_id:`run-${w}`,session_id:b.result.sessionId,success:b.result.success,total_tokens:b.totalTokens,duration_ms:b.durationMs,output_chars:b.result.lastText.length})}}d.push({eval_id:l.id??u,prompt:l.prompt??l.query??"",configs:p})}return{workspace:r,skill_name:n.name,eval_count:s.length,configs:a,runs_per_config:c,reports:d}}o(cp,"runEvalWorkspace");function dp(e){let t={skillPath:"",evalsPath:"",workspaceDir:"",provider:"anthropic",model:void 0,runsPerConfig:1,maxIter:30,reasoningMode:"off",cwd:process.cwd(),configs:["with_skill","without_skill"],output:void 0};for(let n=2;n<e.length;n+=1){let r=e[n];r==="--skill-path"&&e[n+1]?t.skillPath=e[++n]:r==="--evals"&&e[n+1]?t.evalsPath=e[++n]:r==="--workspace"&&e[n+1]?t.workspaceDir=e[++n]:r==="--provider"&&e[n+1]?t.provider=e[++n]:r==="--model"&&e[n+1]?t.model=e[++n]:r==="--runs"&&e[n+1]?t.runsPerConfig=Number(e[++n]):r==="--max-iter"&&e[n+1]?t.maxIter=Number(e[++n]):r==="--reasoning"&&e[n+1]?t.reasoningMode=e[++n]:r==="--cwd"&&e[n+1]?t.cwd=e[++n]:r==="--configs"&&e[n+1]?t.configs=e[++n].split(",").map(i=>i.trim()).filter(Boolean):r==="--output"&&e[n+1]&&(t.output=e[++n])}return t}o(dp,"parseArgs");async function ts(e=process.argv){let t=dp(e);(!t.skillPath||!t.evalsPath||!t.workspaceDir)&&(console.error("Usage: node scripts/run-eval.js --skill-path <dir> --evals <evals.json> --workspace <dir> [--provider anthropic] [--runs 1]"),process.exit(1));let n=await cp(t),r=`${JSON.stringify(n,null,2)}
|
|
246
|
+
`;t.output?(await oe(t.output,r,"utf8"),console.log(`Wrote ${C.resolve(t.output)}`)):process.stdout.write(r)}o(ts,"main");var up=!1;up&&ts().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});import{readdir as lp,readFile as Jn,writeFile as rs}from"node:fs/promises";import T from"node:path";function Ee(e){return String(e??"").trim()}o(Ee,"normalizeExpectationText");function os(e){let n=(Array.isArray(e?.assertions)?e.assertions:[]).map(i=>typeof i=="string"?Ee(i):i&&typeof i=="object"&&typeof i.text=="string"?Ee(i.text):"").filter(Boolean);if(n.length>0)return n;let r=Ee(e?.expected_output);return r?[r]:[]}o(os,"normalizeExpectedRubric");function Qn(e){return Array.isArray(e)?e.map(t=>String(t??"").trim()).filter(Boolean):[]}o(Qn,"normalizeStringArray");function ns(e,t){return{text:Ee(e?.text??t),passed:e?.passed===!0,evidence:Ee(e?.evidence)}}o(ns,"normalizeExpectationEntry");function fp(e,t){let n=je(e)??{},r=Array.isArray(n.expectations)?n.expectations:[],i=[],s=new Set;for(let a of t){let c=r.findIndex((d,u)=>s.has(u)?!1:Ee(d?.text).toLowerCase()===a.toLowerCase());if(c===-1){i.push({text:a,passed:!1,evidence:""});continue}s.add(c),i.push(ns(r[c],a))}if(t.length===0)for(let a of r){let c=ns(a,"");c.text&&i.push(c)}return{overall_summary:Ee(n.overall_summary),expectations:i,user_notes_summary:{uncertainties:Qn(n.user_notes_summary?.uncertainties),needs_review:Qn(n.user_notes_summary?.needs_review),workarounds:Qn(n.user_notes_summary?.workarounds)}}}o(fp,"normalizeParsedGrading");async function Zn(e){return(await lp(e,{withFileTypes:!0}).catch(()=>[])).filter(n=>n.isDirectory()).map(n=>T.join(e,n.name)).sort((n,r)=>n.localeCompare(r))}o(Zn,"listDirectories");async function pp(e){let t=T.dirname(e),n=T.dirname(t),r=T.basename(t),i=T.basename(e),s=T.join(e,"outputs"),a=await Y(T.join(n,"eval_metadata.json"),{}),c=await Jn(T.join(s,"result.md"),"utf8").catch(()=>""),d=await Jn(T.join(s,"prompt.txt"),"utf8").catch(()=>""),u=await Jn(T.join(e,"transcript.md"),"utf8").catch(()=>""),l=await Y(T.join(s,"metrics.json"),{}),f=await Y(T.join(e,"result.json"),{}),m=await Y(T.join(e,"timing.json"),{});return{evalDir:n,runDir:e,runId:i,configName:r,evalMetadata:a,outputsDir:s,resultText:c,promptText:d,transcript:u,metrics:l,result:f,timing:m}}o(pp,"loadRunContext");function mp(e){let t=os(e.evalMetadata),n=t.length>0?t.map((r,i)=>`${i+1}. ${r}`).join(`
|
|
247
|
+
`):"(No explicit assertions; infer one expectation from expected_output if present.)";return`${e.agentInstructions.trim()}
|
|
248
|
+
|
|
249
|
+
Return JSON with this shape:
|
|
250
|
+
{
|
|
251
|
+
"overall_summary": "short summary",
|
|
252
|
+
"expectations": [
|
|
253
|
+
{
|
|
254
|
+
"text": "expectation text",
|
|
255
|
+
"passed": true,
|
|
256
|
+
"evidence": "short evidence grounded in the output"
|
|
257
|
+
}
|
|
258
|
+
],
|
|
259
|
+
"user_notes_summary": {
|
|
260
|
+
"uncertainties": [],
|
|
261
|
+
"needs_review": [],
|
|
262
|
+
"workarounds": []
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
## Run Metadata
|
|
267
|
+
- eval_id: ${e.evalMetadata.eval_id??"unknown"}
|
|
268
|
+
- eval_name: ${e.evalMetadata.eval_name??"unknown"}
|
|
269
|
+
- config: ${e.configName}
|
|
270
|
+
- run_id: ${e.runId}
|
|
271
|
+
|
|
272
|
+
## Eval Prompt
|
|
273
|
+
${L(e.evalMetadata.prompt??e.promptText,4e3)}
|
|
274
|
+
|
|
275
|
+
## Expected Outcome
|
|
276
|
+
${L(e.evalMetadata.expected_output??"",2e3)}
|
|
277
|
+
|
|
278
|
+
## Assertions
|
|
279
|
+
${n}
|
|
280
|
+
|
|
281
|
+
## Final Output
|
|
282
|
+
${L(e.resultText,12e3)}
|
|
283
|
+
|
|
284
|
+
## Result Flags
|
|
285
|
+
${JSON.stringify({success:e.result.success??null,signal:e.result.signal??null,interrupted:e.result.interrupted??!1,limit_reached:e.result.limit_reached??e.result.limitReached??!1},null,2)}
|
|
286
|
+
|
|
287
|
+
## Execution Metrics
|
|
288
|
+
${JSON.stringify({total_tool_calls:e.metrics.total_tool_calls??e.result.execution_metrics?.total_tool_calls??0,errors_encountered:e.metrics.errors_encountered??e.result.execution_metrics?.errors_encountered??0,output_chars:e.metrics.output_chars??e.result.execution_metrics?.output_chars??e.resultText.length,total_tokens:e.timing.total_tokens??0,total_duration_seconds:e.timing.total_duration_seconds??0},null,2)}
|
|
289
|
+
|
|
290
|
+
## Transcript Excerpt
|
|
291
|
+
${L(e.transcript,5e3)}
|
|
292
|
+
`}o(mp,"buildGradingPrompt");async function is(e,t){let{runKodaX:n}=await me();return(await n({provider:t.provider??"anthropic",model:t.model,maxIter:t.maxIter??20,reasoningMode:t.reasoningMode??"balanced",thinking:t.reasoningMode?t.reasoningMode!=="off":!0,context:{gitRoot:T.resolve(t.cwd??t.workspaceDir??process.cwd())}},e)).lastText}o(is,"defaultRunJudge");async function hp(e,t,n=is){let r=await pp(T.resolve(e)),i=os(r.evalMetadata),s=await Ke(import.meta.url,"../agents/grader.md"),a=mp({...r,agentInstructions:s}),c=await n(a,{...t,runDir:r.runDir,configName:r.configName,evalMetadata:r.evalMetadata,runId:r.runId}),d=fp(c,i),u={total_tool_calls:r.metrics.total_tool_calls??r.result.execution_metrics?.total_tool_calls??0,errors_encountered:r.metrics.errors_encountered??r.result.execution_metrics?.errors_encountered??0,output_chars:r.metrics.output_chars??r.result.execution_metrics?.output_chars??r.resultText.length},l={summary:Yi(d.expectations),expectations:d.expectations,execution_metrics:u,user_notes_summary:d.user_notes_summary,overall_summary:d.overall_summary,timing:{total_tokens:r.timing.total_tokens??0,total_duration_seconds:r.timing.total_duration_seconds??0},meta:{generated_at:new Date().toISOString(),eval_id:r.evalMetadata.eval_id??null,eval_name:r.evalMetadata.eval_name??null,config:r.configName,run_id:r.runId}};return await rs(T.join(r.runDir,"grading.json"),`${JSON.stringify(l,null,2)}
|
|
293
|
+
`,"utf8"),{runDir:r.runDir,grading:l,prompt:a,rawResponse:c}}o(hp,"gradeRun");async function gp(e,t=is){let n=T.resolve(e.workspaceDir);await F(n);let r=new Set((e.configs??[]).map(c=>String(c).trim()).filter(Boolean)),i=[],s=[];for(let c of await Zn(n))if(T.basename(c).startsWith("eval-"))for(let d of await Zn(c)){let u=T.basename(d);if(!(r.size>0&&!r.has(u)))for(let l of await Zn(d)){if(!T.basename(l).startsWith("run-"))continue;let f=T.join(l,"grading.json");if(await Y(f,null)&&e.overwrite!==!0){s.push(T.relative(n,l).replace(/\\/g,"/"));continue}let p=await hp(l,e,t);i.push({run:T.relative(n,l).replace(/\\/g,"/"),summary:p.grading.summary,config:p.grading.meta.config,eval_id:p.grading.meta.eval_id})}}let a={workspace:n,generated_at:new Date().toISOString(),processed:i.length,skipped:s.length,processed_runs:i,skipped_runs:s};return await rs(T.join(n,"grading-summary.json"),`${JSON.stringify(a,null,2)}
|
|
294
|
+
`,"utf8"),a}o(gp,"gradeWorkspace");function yp(e){let t={workspaceDir:e[2]??"",provider:"anthropic",model:void 0,reasoningMode:"balanced",maxIter:20,cwd:process.cwd(),overwrite:!1,configs:[]};for(let n=3;n<e.length;n+=1){let r=e[n];r==="--provider"&&e[n+1]?t.provider=e[++n]:r==="--model"&&e[n+1]?t.model=e[++n]:r==="--reasoning"&&e[n+1]?t.reasoningMode=e[++n]:r==="--max-iter"&&e[n+1]?t.maxIter=Number(e[++n]):r==="--cwd"&&e[n+1]?t.cwd=e[++n]:r==="--overwrite"?t.overwrite=!0:r==="--configs"&&e[n+1]&&(t.configs=e[++n].split(",").map(i=>i.trim()).filter(Boolean))}return t}o(yp,"parseArgs");async function ss(e=process.argv){let t=yp(e);t.workspaceDir||(console.error("Usage: node scripts/grade-evals.js <workspace> [--provider anthropic] [--configs with_skill,without_skill] [--overwrite]"),process.exit(1));let n=await gp(t);process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
295
|
+
`)}o(ss,"main");var wp=!1;wp&&ss().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});import{writeFile as rr}from"node:fs/promises";import ie from"node:path";import{readFile as vp,readdir as bp,stat as kp,writeFile as as}from"node:fs/promises";import j from"node:path";async function er(e){return JSON.parse(await vp(e,"utf8"))}o(er,"readJson");async function xp(e){try{return await kp(e),!0}catch{return!1}}o(xp,"pathExists");async function tr(e){return(await bp(e,{withFileTypes:!0}).catch(()=>[])).filter(n=>n.isDirectory()).map(n=>j.join(e,n.name)).sort((n,r)=>n.localeCompare(r))}o(tr,"listDirectories");async function Gt(e){let t=await xp(j.join(e,"runs"))?j.join(e,"runs"):e,n=(await tr(t)).filter(i=>j.basename(i).startsWith("eval-")),r={};for(let i of n){let s=j.join(i,"eval_metadata.json"),c=(await er(s).catch(()=>({}))).eval_id??j.basename(i);for(let d of await tr(i)){let u=j.basename(d),l=(await tr(d)).filter(f=>j.basename(f).startsWith("run-"));if(l.length!==0){r[u]??=[];for(let f of l){let m=await er(j.join(f,"grading.json")).catch(()=>null);if(!m)continue;let p=await er(j.join(f,"timing.json")).catch(()=>({}));r[u].push({eval_id:c,run_id:j.basename(f),pass_rate:m.summary?.pass_rate??0,passed:m.summary?.passed??0,failed:m.summary?.failed??0,total:m.summary?.total??0,time_seconds:p.total_duration_seconds??m.timing?.total_duration_seconds??0,tokens:p.total_tokens??m.execution_metrics?.output_chars??0,tool_calls:m.execution_metrics?.total_tool_calls??0,errors:m.execution_metrics?.errors_encountered??0,expectations:Array.isArray(m.expectations)?m.expectations:[],notes:[...m.user_notes_summary?.uncertainties??[],...m.user_notes_summary?.needs_review??[],...m.user_notes_summary?.workarounds??[]]})}}}}return r}o(Gt,"loadRunResults");function Sp(e){let t={};for(let[s,a]of Object.entries(e))t[s]={pass_rate:qt(a.map(c=>Number(c.pass_rate??0))),time_seconds:qt(a.map(c=>Number(c.time_seconds??0))),tokens:qt(a.map(c=>Number(c.tokens??0)))};let n=Object.keys(t),r=t[n[0]]??{pass_rate:{mean:0},time_seconds:{mean:0},tokens:{mean:0}},i=t[n[1]]??{pass_rate:{mean:0},time_seconds:{mean:0},tokens:{mean:0}};return{configs:t,delta:{pass_rate:Vt(r.pass_rate.mean-i.pass_rate.mean),time_seconds:Vt(r.time_seconds.mean-i.time_seconds.mean),tokens:Vt(r.tokens.mean-i.tokens.mean)}}}o(Sp,"summarizeConfigs");function nr(e,t,n){let r=Sp(n);return{skill_name:t,generated_at:new Date().toISOString(),workspace:j.resolve(e),configs:r.configs,delta:r.delta,runs:n}}o(nr,"buildBenchmarkDocument");function Ep(e){let t=[`# Benchmark: ${e.skill_name}`,"",`Generated: ${e.generated_at}`,"","| Config | Pass Rate | Time (s) | Tokens |","| --- | --- | --- | --- |"];for(let[n,r]of Object.entries(e.configs))t.push(`| ${n} | ${r.pass_rate.mean} \xB1 ${r.pass_rate.stddev} | ${r.time_seconds.mean} \xB1 ${r.time_seconds.stddev} | ${r.tokens.mean} \xB1 ${r.tokens.stddev} |`);return t.push(""),t.push("## Delta"),t.push(""),t.push(`- Pass rate: ${e.delta.pass_rate}`),t.push(`- Time (s): ${e.delta.time_seconds}`),t.push(`- Tokens: ${e.delta.tokens}`),t.join(`
|
|
296
|
+
`)}o(Ep,"renderBenchmarkMarkdown");function Ip(e){let t={iterationDir:e[2],skillName:"unknown-skill"};for(let n=3;n<e.length;n+=1)e[n]==="--skill-name"&&e[n+1]&&(t.skillName=e[n+1],n+=1);return t}o(Ip,"parseArgs");async function Cp(){let{iterationDir:e,skillName:t}=Ip(process.argv);e||(console.error("Usage: node scripts/aggregate-benchmark.js <iteration-dir> --skill-name <name>"),process.exit(1));let n=await Gt(e);Object.keys(n).length===0&&(console.error(`No benchmark runs found in ${e}`),process.exit(1));let r=nr(e,t,n),i=j.join(e,"benchmark.json"),s=j.join(e,"benchmark.md");await as(i,JSON.stringify(r,null,2)),await as(s,`${Ep(r)}
|
|
297
|
+
`),console.log(`Wrote ${i}`),console.log(`Wrote ${s}`)}o(Cp,"main");var Tp=!1;Tp&&Cp().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});function Yt(e){return Array.isArray(e)?e.map(t=>String(t??"").trim()).filter(Boolean):[]}o(Yt,"normalizeStringArray");function Rp(e){let t={};for(let[n,r]of Object.entries(e)){let i=new Map,s=[];for(let a of r){for(let c of a.expectations??[]){if(c?.passed===!0)continue;let d=String(c?.text??"").trim();d&&i.set(d,(i.get(d)??0)+1)}for(let c of a.notes??[]){let d=String(c??"").trim();d&&s.push(d)}}t[n]={repeated_failures:Array.from(i.entries()).sort((a,c)=>c[1]-a[1]).slice(0,10).map(([a,c])=>({text:a,count:c})),notes:s.slice(0,10)}}return t}o(Rp,"summarizeFailureClusters");function _p(e,t,n){let r=je(e)??{};return{skill_name:t.skill_name,generated_at:new Date().toISOString(),workspace:t.workspace,verdict:["improves","regresses","mixed","inconclusive"].includes(r.verdict)?r.verdict:"inconclusive",release_readiness:["ready","needs_iteration","needs_manual_review"].includes(r.release_readiness)?r.release_readiness:"needs_manual_review",recommendation:String(r.recommendation??"").trim(),key_findings:Yt(r.key_findings),variance_hotspots:Yt(r.variance_hotspots),suggested_actions:Yt(r.suggested_actions),watchouts:Yt(r.watchouts),supporting_metrics:{pass_rate_delta:t.delta?.pass_rate??"n/a",time_seconds_delta:t.delta?.time_seconds??"n/a",tokens_delta:t.delta?.tokens??"n/a"},failure_clusters:n}}o(_p,"normalizeAnalysisResult");function Ap(e){return`${e.agentInstructions.trim()}
|
|
298
|
+
|
|
299
|
+
Return JSON with this shape:
|
|
300
|
+
{
|
|
301
|
+
"verdict": "improves | regresses | mixed | inconclusive",
|
|
302
|
+
"release_readiness": "ready | needs_iteration | needs_manual_review",
|
|
303
|
+
"recommendation": "short recommendation",
|
|
304
|
+
"key_findings": [],
|
|
305
|
+
"variance_hotspots": [],
|
|
306
|
+
"suggested_actions": [],
|
|
307
|
+
"watchouts": []
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
## Benchmark Summary
|
|
311
|
+
${L(JSON.stringify({skill_name:e.benchmark.skill_name,configs:e.benchmark.configs,delta:e.benchmark.delta},null,2),12e3)}
|
|
312
|
+
|
|
313
|
+
## Failure Clusters
|
|
314
|
+
${L(JSON.stringify(e.failureClusters,null,2),8e3)}
|
|
315
|
+
`}o(Ap,"buildAnalysisPrompt");async function Pp(e,t){let{runKodaX:n}=await me();return(await n({provider:t.provider??"anthropic",model:t.model,maxIter:t.maxIter??20,reasoningMode:t.reasoningMode??"balanced",thinking:t.reasoningMode?t.reasoningMode!=="off":!0,context:{gitRoot:ie.resolve(t.cwd??t.workspaceDir??process.cwd())}},e)).lastText}o(Pp,"defaultRunAnalyst");function Mp(e){let t=[`# Benchmark Analysis: ${e.skill_name}`,"",`Generated: ${e.generated_at}`,"",`- Verdict: ${e.verdict}`,`- Release readiness: ${e.release_readiness}`,`- Recommendation: ${e.recommendation||"n/a"}`,""],n=[["key_findings","Key Findings"],["variance_hotspots","Variance Hotspots"],["suggested_actions","Suggested Actions"],["watchouts","Watchouts"]];for(let[r,i]of n){t.push(`## ${i}`),t.push("");let s=Array.isArray(e[r])?e[r]:[];if(s.length===0)t.push("- None");else for(let a of s)t.push(`- ${a}`);t.push("")}return t.push("## Supporting Metrics"),t.push(""),t.push(`- Pass rate delta: ${e.supporting_metrics.pass_rate_delta}`),t.push(`- Time delta: ${e.supporting_metrics.time_seconds_delta}`),t.push(`- Tokens delta: ${e.supporting_metrics.tokens_delta}`),`${t.join(`
|
|
316
|
+
`)}
|
|
317
|
+
`}o(Mp,"renderAnalysisMarkdown");async function Op(e,t=Pp){let n=ie.resolve(e.workspaceDir),r=ie.resolve(e.benchmarkPath??ie.join(n,"benchmark.json")),i=await Y(r,null);if(!i){let p=await Gt(n);if(Object.keys(p).length===0)throw new Error(`No benchmark data found in ${n}`);i=nr(n,e.skillName??ie.basename(n),p),await rr(r,`${JSON.stringify(i,null,2)}
|
|
318
|
+
`,"utf8")}let s=await Gt(n),a=Rp(s),c=await Ke(import.meta.url,"../agents/analyzer.md"),d=Ap({agentInstructions:c,benchmark:i,failureClusters:a}),u=await t(d,{...e,workspaceDir:n,benchmarkPath:r,benchmark:i}),l=_p(u,i,a),f=ie.resolve(e.outputPath??ie.join(n,"analysis.json")),m=ie.resolve(e.markdownPath??ie.join(n,"analysis.md"));return await rr(f,`${JSON.stringify(l,null,2)}
|
|
319
|
+
`,"utf8"),await rr(m,Mp(l),"utf8"),{analysis:l,prompt:d,rawResponse:u,analysisJsonPath:f,analysisMdPath:m}}o(Op,"analyzeBenchmark");function Np(e){let t={workspaceDir:e[2]??"",benchmarkPath:void 0,outputPath:void 0,markdownPath:void 0,skillName:void 0,provider:"anthropic",model:void 0,reasoningMode:"balanced",maxIter:20,cwd:process.cwd()};for(let n=3;n<e.length;n+=1){let r=e[n];r==="--benchmark"&&e[n+1]?t.benchmarkPath=e[++n]:r==="--output"&&e[n+1]?t.outputPath=e[++n]:r==="--markdown"&&e[n+1]?t.markdownPath=e[++n]:r==="--skill-name"&&e[n+1]?t.skillName=e[++n]:r==="--provider"&&e[n+1]?t.provider=e[++n]:r==="--model"&&e[n+1]?t.model=e[++n]:r==="--reasoning"&&e[n+1]?t.reasoningMode=e[++n]:r==="--max-iter"&&e[n+1]?t.maxIter=Number(e[++n]):r==="--cwd"&&e[n+1]&&(t.cwd=e[++n])}return t}o(Np,"parseArgs");async function cs(e=process.argv){let t=Np(e);t.workspaceDir||(console.error("Usage: node scripts/analyze-benchmark.js <workspace> [--benchmark benchmark.json] [--output analysis.json] [--markdown analysis.md]"),process.exit(1));let n=await Op(t);process.stdout.write(`${JSON.stringify({analysis:n.analysis,analysis_json:n.analysisJsonPath,analysis_md:n.analysisMdPath},null,2)}
|
|
320
|
+
`)}o(cs,"main");var $p=!1;$p&&cs().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});import{readdir as Dp,readFile as ds,writeFile as us}from"node:fs/promises";import O from"node:path";async function ir(e){return(await Dp(e,{withFileTypes:!0}).catch(()=>[])).filter(n=>n.isDirectory()).map(n=>O.join(e,n.name)).sort((n,r)=>n.localeCompare(r))}o(ir,"listDirectories");function or(e){return Array.isArray(e)?e.map(t=>String(t??"").trim()).filter(Boolean):[]}o(or,"normalizeStringArray");function Lp(e){let t=je(e)??{},n=["A","B","tie","inconclusive"].includes(t.winner)?t.winner:"inconclusive",r=Number(t.confidence);return{winner:n,confidence:Number.isFinite(r)?Math.max(0,Math.min(1,Number(r.toFixed(4)))):0,rationale:String(t.rationale??"").trim(),strengths_a:or(t.strengths_a),strengths_b:or(t.strengths_b),risks:or(t.risks)}}o(Lp,"normalizeComparisonResult");async function Fp(e,t,n,r){let i=(await ir(O.join(e,t))).filter(f=>O.basename(f).startsWith("run-")),s=(await ir(O.join(e,n))).filter(f=>O.basename(f).startsWith("run-")),a=i[r],c=s[r];if(!a||!c)return null;let d=await Y(O.join(e,"eval_metadata.json"),{}),u=await ds(O.join(a,"outputs","result.md"),"utf8").catch(()=>""),l=await ds(O.join(c,"outputs","result.md"),"utf8").catch(()=>"");return{evalDir:e,evalMetadata:d,runA:{runDir:a,runId:O.basename(a),configName:t,output:u},runB:{runDir:c,runId:O.basename(c),configName:n,output:l}}}o(Fp,"loadComparisonPair");function jp(e){let t=e.presentPrimaryFirst?{A:e.runA,B:e.runB}:{A:e.runB,B:e.runA};return`${e.agentInstructions.trim()}
|
|
321
|
+
|
|
322
|
+
Return JSON with this shape:
|
|
323
|
+
{
|
|
324
|
+
"winner": "A | B | tie | inconclusive",
|
|
325
|
+
"confidence": 0.0,
|
|
326
|
+
"rationale": "short explanation",
|
|
327
|
+
"strengths_a": [],
|
|
328
|
+
"strengths_b": [],
|
|
329
|
+
"risks": []
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
Judge only the visible outputs. Do not mention hidden config names in the rationale.
|
|
333
|
+
|
|
334
|
+
## Eval Prompt
|
|
335
|
+
${L(e.evalMetadata.prompt??"",4e3)}
|
|
336
|
+
|
|
337
|
+
## Expected Outcome
|
|
338
|
+
${L(e.evalMetadata.expected_output??"",2e3)}
|
|
339
|
+
|
|
340
|
+
## Assertions
|
|
341
|
+
${L(JSON.stringify(e.evalMetadata.assertions??[],null,2),4e3)}
|
|
342
|
+
|
|
343
|
+
## Candidate A
|
|
344
|
+
${L(t.A.output,12e3)}
|
|
345
|
+
|
|
346
|
+
## Candidate B
|
|
347
|
+
${L(t.B.output,12e3)}
|
|
348
|
+
`}o(jp,"buildComparisonPrompt");async function Kp(e,t){let{runKodaX:n}=await me();return(await n({provider:t.provider??"anthropic",model:t.model,maxIter:t.maxIter??20,reasoningMode:t.reasoningMode??"balanced",thinking:t.reasoningMode?t.reasoningMode!=="off":!0,context:{gitRoot:O.resolve(t.cwd??t.workspaceDir??process.cwd())}},e)).lastText}o(Kp,"defaultRunComparator");function Bp(e,t,n,r){return e==="A"?t?n:r:e==="B"?t?r:n:e}o(Bp,"mapWinnerToConfig");function Xp(e){let t=[`# Blind Comparison: ${e.config_a} vs ${e.config_b}`,"",`Generated: ${e.generated_at}`,"",`- ${e.config_a} wins: ${e.summary.config_a_wins}`,`- ${e.config_b} wins: ${e.summary.config_b_wins}`,`- ties: ${e.summary.ties}`,`- inconclusive: ${e.summary.inconclusive}`,""];for(let n of e.comparisons)t.push(`## Eval ${n.eval_id??n.eval_name??n.index}`),t.push(""),t.push(`- Winner: ${n.winner_config}`),t.push(`- Confidence: ${n.confidence}`),t.push(`- Rationale: ${n.rationale||"n/a"}`),t.push("");return`${t.join(`
|
|
349
|
+
`)}
|
|
350
|
+
`}o(Xp,"renderComparisonMarkdown");async function Up(e,t=Kp){let n=O.resolve(e.workspaceDir),r=e.configA??"with_skill",i=e.configB??"without_skill",s=Number.isFinite(e.maxPairs)&&e.maxPairs>0?Math.floor(e.maxPairs):Number.POSITIVE_INFINITY,a=await Ke(import.meta.url,"../agents/comparator.md"),c=[];for(let f of await ir(n))if(O.basename(f).startsWith("eval-"))for(let m=0;m<s;m+=1){let p=await Fp(f,r,i,m);if(!p)break;let g=c.length%2===0,v=jp({agentInstructions:a,evalMetadata:p.evalMetadata,runA:p.runA,runB:p.runB,presentPrimaryFirst:g}),w=await t(v,{...e,workspaceDir:n,evalDir:f,pairIndex:m,configA:r,configB:i}),y=Lp(w),h=Bp(y.winner,g,r,i);c.push({index:c.length+1,eval_id:p.evalMetadata.eval_id??null,eval_name:p.evalMetadata.eval_name??null,run_a:O.relative(n,p.runA.runDir).replace(/\\/g,"/"),run_b:O.relative(n,p.runB.runDir).replace(/\\/g,"/"),presented_as:g?{A:r,B:i}:{A:i,B:r},winner_label:y.winner,winner_config:h,confidence:y.confidence,rationale:y.rationale,strengths_a:y.strengths_a,strengths_b:y.strengths_b,risks:y.risks})}if(c.length===0)throw new Error(`No comparable run pairs found for ${r} vs ${i} in ${n}`);let d={workspace:n,generated_at:new Date().toISOString(),config_a:r,config_b:i,summary:{total_pairs:c.length,config_a_wins:c.filter(f=>f.winner_config===r).length,config_b_wins:c.filter(f=>f.winner_config===i).length,ties:c.filter(f=>f.winner_config==="tie").length,inconclusive:c.filter(f=>f.winner_config==="inconclusive").length},comparisons:c},u=O.resolve(e.outputPath??O.join(n,"comparison.json")),l=O.resolve(e.markdownPath??O.join(n,"comparison.md"));return await us(u,`${JSON.stringify(d,null,2)}
|
|
351
|
+
`,"utf8"),await us(l,Xp(d),"utf8"),{document:d,outputPath:u,markdownPath:l}}o(Up,"compareWorkspace");function Wp(e){let t={workspaceDir:e[2]??"",configA:"with_skill",configB:"without_skill",outputPath:void 0,markdownPath:void 0,provider:"anthropic",model:void 0,reasoningMode:"balanced",maxIter:20,maxPairs:void 0,cwd:process.cwd()};for(let n=3;n<e.length;n+=1){let r=e[n];r==="--config-a"&&e[n+1]?t.configA=e[++n]:r==="--config-b"&&e[n+1]?t.configB=e[++n]:r==="--output"&&e[n+1]?t.outputPath=e[++n]:r==="--markdown"&&e[n+1]?t.markdownPath=e[++n]:r==="--provider"&&e[n+1]?t.provider=e[++n]:r==="--model"&&e[n+1]?t.model=e[++n]:r==="--reasoning"&&e[n+1]?t.reasoningMode=e[++n]:r==="--max-iter"&&e[n+1]?t.maxIter=Number(e[++n]):r==="--max-pairs"&&e[n+1]?t.maxPairs=Number(e[++n]):r==="--cwd"&&e[n+1]&&(t.cwd=e[++n])}return t}o(Wp,"parseArgs");async function ls(e=process.argv){let t=Wp(e);t.workspaceDir||(console.error("Usage: node scripts/compare-runs.js <workspace> [--config-a with_skill] [--config-b without_skill] [--output comparison.json]"),process.exit(1));let n=await Up(t);process.stdout.write(`${JSON.stringify({comparison:n.document.summary,output:n.outputPath,markdown:n.markdownPath},null,2)}
|
|
352
|
+
`)}o(ls,"main");var Hp=!1;Hp&&ls().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});import{readFile as zp,writeFile as qp}from"node:fs/promises";import{createHash as Vp}from"node:crypto";import sr from"node:path";import{zipSync as Gp,strToU8 as Yp}from"fflate";var Jp=".kodax-package.json";function Qp(e){return e instanceof Uint8Array?e:new Uint8Array(e)}o(Qp,"toUint8Array");function Zp(e){return Vp("sha256").update(e).digest("hex")}o(Zp,"sha256");function em(e,t,n={}){return{format:"kodax-skill-package",version:1,created_at:n.createdAt??new Date().toISOString(),entrypoint:"SKILL.md",skill:{name:e.frontmatter.name,description:e.frontmatter.description,compatibility:e.frontmatter.compatibility??null,user_invocable:e.frontmatter["user-invocable"]??!0,disable_model_invocation:e.frontmatter["disable-model-invocation"]??!1},files:t.map(r=>({path:r.relativePath,size:r.bytes.length,sha256:r.sha256})),note:"This archive is a zip file with a .skill extension. Compatible agents can extract and install the included skill directory."}}o(em,"createPackageManifest");async function tm(e,t={}){let n=await ft(e);if(!n.valid)throw new Error(`Cannot package invalid skill:
|
|
353
|
+
- ${n.errors.join(`
|
|
354
|
+
- `)}`);let r=await dt(e),i=await Gn(e),s=[];for(let d of i){if(d.relativePath.endsWith(".skill"))continue;let u=Qp(await zp(d.absolutePath));s.push({...d,bytes:u,sha256:Zp(u)})}let a=em(r,s,t),c={[Jp]:Yp(JSON.stringify(a,null,2))};for(let d of s)c[d.relativePath]=d.bytes;return{manifest:a,bytes:Gp(c,{level:6})}}o(tm,"buildSkillPackage");async function nm(e,t,n={}){let r=await tm(e,n);return await qp(t,r.bytes),{...r,outputPath:sr.resolve(t)}}o(nm,"writeSkillPackage");function rm(e){let t={skillDir:e[2],output:void 0};for(let n=3;n<e.length;n+=1)e[n]==="--output"&&e[n+1]&&(t.output=e[++n]);return t}o(rm,"parseArgs");async function fs(e=process.argv){let t=rm(e);t.skillDir||(console.error("Usage: node scripts/package-skill.js <skill-dir> [--output <file.skill>]"),process.exit(1));let n=await dt(t.skillDir),r=t.output??sr.join(sr.dirname(t.skillDir),`${n.frontmatter.name}.skill`),i=await nm(t.skillDir,r);console.log(`Wrote ${i.outputPath}`)}o(fs,"main");var om=!1;om&&fs().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});import{cp as im,mkdir as ar,readFile as hs,rm as gs,stat as sm,writeFile as am}from"node:fs/promises";import J from"node:path";import{strFromU8 as ps,unzipSync as cm}from"fflate";var ms=".kodax-package.json";function dm(e){return e.replace(/\\/g,"/").replace(/^\.?\//,"")}o(dm,"normalizeArchivePath");function um(e){let t=dm(e);if(!t||t.startsWith("/")||t.includes("../"))throw new Error(`Unsafe archive entry path: ${e}`);return t}o(um,"assertSafeArchivePath");function lm(e){return/\.(skill|zip)$/i.test(e)}o(lm,"isZipLike");function fm(e){let t=cm(e),n=Object.entries(t).map(([u,l])=>({relativePath:um(u),bytes:l})),r=n.find(u=>u.relativePath==="SKILL.md");if(!r)throw new Error("Archive is missing SKILL.md");let i=zt(ps(r.bytes)),s=typeof i.frontmatter.name=="string"?i.frontmatter.name.trim():"",a=typeof i.frontmatter.description=="string"?i.frontmatter.description.trim():"";if(!s||!a)throw new Error("Archive SKILL.md is missing required frontmatter fields.");let c=n.find(u=>u.relativePath===ms),d=c?JSON.parse(ps(c.bytes)):null;return{skillName:s,manifest:d,entries:n.filter(u=>u.relativePath!==ms)}}o(fm,"readSkillPackageBuffer");async function pm(e,t){if(await ut(e)){if(!t)throw new Error(`Target skill already exists: ${e}`);await gs(e,{recursive:!0,force:!0})}await ar(e,{recursive:!0})}o(pm,"ensureInstallTarget");async function mm(e,t={}){let n=J.resolve(t.skillsDir??lt()),r=fm(await hs(e)),i=J.join(n,r.skillName);await pm(i,t.force===!0);for(let s of r.entries){let a=J.join(i,s.relativePath);await ar(J.dirname(a),{recursive:!0}),await am(a,s.bytes)}return{skillName:r.skillName,installedTo:i,source:J.resolve(e),manifest:r.manifest}}o(mm,"installSkillArchive");async function hm(e,t={}){let n=await ft(e);if(!n.valid)throw new Error(`Cannot install invalid skill:
|
|
355
|
+
- ${n.errors.join(`
|
|
356
|
+
- `)}`);let r=J.join(e,"SKILL.md"),i=zt(await hs(r,"utf8")),s=J.resolve(t.skillsDir??lt()),a=J.join(s,i.frontmatter.name);if(await ut(a)){if(!t.force)throw new Error(`Target skill already exists: ${a}`);await gs(a,{recursive:!0,force:!0})}return await ar(s,{recursive:!0}),await im(e,a,{recursive:!0}),{skillName:i.frontmatter.name,installedTo:a,source:J.resolve(e),manifest:null}}o(hm,"installSkillDirectory");async function gm(e,t={}){let n=J.resolve(e),r=await sm(n).catch(()=>null);if(!r)throw new Error(`Input not found: ${n}`);if(r.isDirectory())return hm(n,t);if(r.isFile()&&lm(n))return mm(n,t);throw new Error("Input must be a skill directory or a .skill/.zip archive.")}o(gm,"installSkill");function ym(e){let t={input:e[2],skillsDir:void 0,force:!1};for(let n=3;n<e.length;n+=1){let r=e[n];r==="--dest"&&e[n+1]?t.skillsDir=e[++n]:r==="--force"&&(t.force=!0)}return t}o(ym,"parseArgs");async function ys(e=process.argv){let t=ym(e);t.input||(console.error("Usage: node scripts/install-skill.js <skill-dir-or-archive> [--dest <skills-dir>] [--force]"),process.exit(1));let n=await gm(t.input,t);console.log(`Installed ${n.skillName} to ${n.installedTo}`)}o(ys,"main");var wm=!1;wm&&ys().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});var tM=1440*60*1e3;var cM=5*6e4;var YM=new Intl.Segmenter("zh-CN",{granularity:"word"});var ZO=String.raw`const TOOL_NAME = 'echo_tool';
|
|
357
|
+
const RESOURCE_URI = 'memory://guide';
|
|
358
|
+
const PROMPT_NAME = 'draft_prompt';
|
|
359
|
+
let buffer = '';
|
|
360
|
+
|
|
361
|
+
function writeMessage(payload) {
|
|
362
|
+
process.stdout.write(JSON.stringify(payload) + '\n');
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function handleRequest(message) {
|
|
366
|
+
const id = message.id;
|
|
367
|
+
const method = message.method;
|
|
368
|
+
const params = message.params || {};
|
|
369
|
+
if (method === 'initialize') {
|
|
370
|
+
writeMessage({
|
|
371
|
+
jsonrpc: '2.0',
|
|
372
|
+
id,
|
|
373
|
+
result: {
|
|
374
|
+
protocolVersion: '2025-11-25',
|
|
375
|
+
capabilities: {
|
|
376
|
+
tools: {},
|
|
377
|
+
resources: {},
|
|
378
|
+
prompts: {},
|
|
379
|
+
},
|
|
380
|
+
serverInfo: {
|
|
381
|
+
name: 'kodax-mcp-test-server',
|
|
382
|
+
version: '1.0.0',
|
|
383
|
+
},
|
|
384
|
+
},
|
|
385
|
+
});
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
if (method === 'tools/list') {
|
|
389
|
+
writeMessage({
|
|
390
|
+
jsonrpc: '2.0',
|
|
391
|
+
id,
|
|
392
|
+
result: {
|
|
393
|
+
tools: [{
|
|
394
|
+
name: TOOL_NAME,
|
|
395
|
+
title: 'Echo Tool',
|
|
396
|
+
description: 'Echo text back from the MCP test server.',
|
|
397
|
+
inputSchema: {
|
|
398
|
+
type: 'object',
|
|
399
|
+
properties: {
|
|
400
|
+
text: { type: 'string' },
|
|
401
|
+
mode: { type: 'string' },
|
|
402
|
+
},
|
|
403
|
+
required: ['text'],
|
|
404
|
+
},
|
|
405
|
+
annotations: {
|
|
406
|
+
destructive: false,
|
|
407
|
+
},
|
|
408
|
+
}],
|
|
409
|
+
},
|
|
410
|
+
});
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
if (method === 'resources/list') {
|
|
414
|
+
writeMessage({
|
|
415
|
+
jsonrpc: '2.0',
|
|
416
|
+
id,
|
|
417
|
+
result: {
|
|
418
|
+
resources: [{
|
|
419
|
+
uri: RESOURCE_URI,
|
|
420
|
+
title: 'Guide Resource',
|
|
421
|
+
description: 'Provides guide text.',
|
|
422
|
+
mimeType: 'text/plain',
|
|
423
|
+
}],
|
|
424
|
+
},
|
|
425
|
+
});
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
if (method === 'prompts/list') {
|
|
429
|
+
writeMessage({
|
|
430
|
+
jsonrpc: '2.0',
|
|
431
|
+
id,
|
|
432
|
+
result: {
|
|
433
|
+
prompts: [{
|
|
434
|
+
name: PROMPT_NAME,
|
|
435
|
+
title: 'Draft Prompt',
|
|
436
|
+
description: 'A simple prompt from the MCP test server.',
|
|
437
|
+
}],
|
|
438
|
+
},
|
|
439
|
+
});
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
if (method === 'tools/call') {
|
|
443
|
+
const args = params.arguments || params.args || {};
|
|
444
|
+
writeMessage({
|
|
445
|
+
jsonrpc: '2.0',
|
|
446
|
+
id,
|
|
447
|
+
result: {
|
|
448
|
+
content: [{
|
|
449
|
+
type: 'text',
|
|
450
|
+
text: 'echo:' + String(args.text || ''),
|
|
451
|
+
}],
|
|
452
|
+
structuredContent: {
|
|
453
|
+
echo: args.text || '',
|
|
454
|
+
mode: args.mode || null,
|
|
455
|
+
},
|
|
456
|
+
},
|
|
457
|
+
});
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (method === 'resources/read') {
|
|
461
|
+
const uri = params.uri || params.name || RESOURCE_URI;
|
|
462
|
+
writeMessage({
|
|
463
|
+
jsonrpc: '2.0',
|
|
464
|
+
id,
|
|
465
|
+
result: {
|
|
466
|
+
contents: [{
|
|
467
|
+
uri,
|
|
468
|
+
mimeType: 'text/plain',
|
|
469
|
+
text: 'resource:' + String(uri),
|
|
470
|
+
}],
|
|
471
|
+
},
|
|
472
|
+
});
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
if (method === 'prompts/get') {
|
|
476
|
+
const args = params.arguments || params.args || {};
|
|
477
|
+
const topic = args.topic || 'none';
|
|
478
|
+
writeMessage({
|
|
479
|
+
jsonrpc: '2.0',
|
|
480
|
+
id,
|
|
481
|
+
result: {
|
|
482
|
+
description: 'Prompt result for ' + String(params.name || PROMPT_NAME),
|
|
483
|
+
messages: [{
|
|
484
|
+
role: 'user',
|
|
485
|
+
content: {
|
|
486
|
+
type: 'text',
|
|
487
|
+
text: 'prompt:' + String(params.name || PROMPT_NAME) + ':' + String(topic),
|
|
488
|
+
},
|
|
489
|
+
}],
|
|
490
|
+
},
|
|
491
|
+
});
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
writeMessage({
|
|
496
|
+
jsonrpc: '2.0',
|
|
497
|
+
id,
|
|
498
|
+
error: {
|
|
499
|
+
code: -32601,
|
|
500
|
+
message: 'Method not found: ' + String(method),
|
|
501
|
+
},
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function handleFrame(raw) {
|
|
506
|
+
let message;
|
|
507
|
+
try {
|
|
508
|
+
message = JSON.parse(raw);
|
|
509
|
+
} catch (error) {
|
|
510
|
+
process.stderr.write('bad json: ' + String(error) + '\n');
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
if (message.id !== undefined) {
|
|
514
|
+
handleRequest(message);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
process.stdin.setEncoding('utf8');
|
|
519
|
+
process.stdin.on('data', (chunk) => {
|
|
520
|
+
buffer += chunk;
|
|
521
|
+
while (true) {
|
|
522
|
+
const lineEnd = buffer.indexOf('\n');
|
|
523
|
+
if (lineEnd < 0) {
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
const line = buffer.slice(0, lineEnd).replace(/\r$/, '').trim();
|
|
527
|
+
buffer = buffer.slice(lineEnd + 1);
|
|
528
|
+
if (line) {
|
|
529
|
+
handleFrame(line);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
|
|
534
|
+
process.on('SIGTERM', () => process.exit(0));
|
|
535
|
+
process.on('SIGINT', () => process.exit(0));
|
|
536
|
+
`;var ks=Object.freeze(["message","label","compaction","branch_summary","archive_marker","rewind_marker","artifact_ledger","memory_outcome_digest","memory_review_receipt"]),Km=0,Bm=0,xs=o(e=>{let t=e==="label"?++Km:++Bm,n=Math.random().toString(36).slice(2,8);return`${e}-${Date.now()}-${t}-${n}`},"nextId");async function Xm(e,t,n){let r=xs("label");return await e.append({id:r,ts:Date.now(),type:"label",payload:{targetId:t,label:n}}),r}o(Xm,"appendLabel");async function Um(e,t,n){let r=xs("artifact");return await e.append({id:r,ts:Date.now(),type:"artifact_ledger",payload:{ref:t,summary:n}}),r}o(Um,"appendArtifact");function Wm(e){let t=[],n=new Map,r=[],i=null;for(let s of e){if(s.type==="label"){let c=s.payload;c?.targetId&&r.push({targetId:c.targetId,label:c.label});continue}let a={entry:s,children:[]};if(s.type==="message"){t.push(a),n.set(s.id,a),i=a;continue}i?i.children.push(a):t.push(a)}for(let{targetId:s,label:a}of r){let c=n.get(s);c&&a!==void 0&&(c.label=a)}return t}o(Wm,"buildLineageTree");var Hm=Object.freeze({name:"lineage",entryTypes:ks,operators:Object.freeze({label:o((async(e,...t)=>{let[n,r]=t;return Xm(e,n,r)}),"label"),attachArtifact:o((async(e,...t)=>{let[n,r]=t;return Um(e,n,r)}),"attachArtifact")}),reducers:Object.freeze({buildLineageTree:o(e=>Wm(e),"buildLineageTree")})});var eh=new Set(["skill","ask_user_question","exit_plan_mode","spawn_agent","send_message","followup_task","wait_agent","interrupt_agent","list_agents","agent_output","tool_search","get_goal","create_goal","update_goal","todo_create","todo_update","todo_list","todo_get","worktree_create","worktree_remove","undo","mcp_search","mcp_describe","mcp_call","mcp_read_resource","mcp_get_prompt","repo_overview","changed_scope","changed_diff","changed_diff_bundle","module_context","symbol_context","process_context","impact_estimate","relationship_scan","cyclic_dependencies","semantic_lookup"]),dr=eh,Jt=`[\u5BF9\u8BDD\u5386\u53F2\u6458\u8981]
|
|
537
|
+
|
|
538
|
+
`;var y$=Jt.trimEnd();var w$=16*1024;var ih={enabled:!1,maxAge:20,protectedTools:Array.from(dr)};import EL from"typescript";var KF=new Intl.Segmenter("en",{granularity:"grapheme"});var aK=4*1024;var uK=64*1024;var ur=".conversation-cache.",xK=`${ur}json`,SK=1024*1024,EK=1024*1024,IK=1024*1024,CK=4*1024*1024,TK=128*1024;var Ie=class extends Error{static{o(this,"ConversationPageCacheCleanupError")}directory;cleanupCause;constructor(t,n){super(`Unable to remove recoverable Conversation page caches from ${t}`),this.directory=t,this.cleanupCause=n,this.name="ConversationPageCacheCleanupError"}};function _s(e){let t=e.lastIndexOf(ur);if(t<=0)return;let n=e.slice(t+ur.length);if(!(n!=="json"&&!(n.startsWith("json.")&&n.endsWith(".tmp"))&&!n.endsWith(".data")&&!n.endsWith(".index")))return e.slice(0,t)}o(_s,"cacheArtifactSessionId");async function As(e){let t=pt.dirname(e),n=pt.basename(e,pt.extname(e)),r;try{r=await Zt.readdir(t)}catch(i){if(i.code==="ENOENT")return;throw i}await Promise.all(r.filter(i=>_s(i)===n).map(i=>Zt.rm(pt.join(t,i),{force:!0})))}o(As,"removeConversationPageCache");async function lr(e){let t;try{t=await Zt.readdir(e,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return;throw new Ie(e,n)}try{await Promise.all(t.filter(n=>!n.isDirectory()&&_s(n.name)!==void 0).map(n=>Zt.rm(pt.join(e,n.name),{force:!0})))}catch(n){throw new Ie(e,n)}}o(lr,"removeConversationPageCachesInDirectory");var Ns=3,Rh=300*1e3,Ps=65536,fr=o(e=>P.join(e,".layout.json"),"layoutMarkerPath"),mr=o(e=>P.join(e,".migration-lock"),"lockDirPath"),$s=o(e=>P.join(mr(e),"owner.json"),"ownerPath"),pr=o(e=>P.join(e,".migration-journal.jsonl"),"journalPath"),hr=o(e=>P.join(P.dirname(e),"sessions-archive"),"sessionsArchiveDir");function gr(e){return e.endsWith(".jsonl")&&!e.endsWith(".archive.jsonl")&&!e.endsWith(".islands.jsonl")&&!e.startsWith(".")}o(gr,"isSessionFile");function Ds(e){return e.endsWith(".archive.jsonl")||e.endsWith(".islands.jsonl")?e.slice(0,-14):null}o(Ds,"sidecarId");async function _h(e){let t;try{t=await R.open(e,"r");let n=Buffer.allocUnsafe(Ps),{bytesRead:r}=await t.read(n,0,Ps,0);if(r===0)return null;let i=n.toString("utf8",0,r),s=i.indexOf(`
|
|
539
|
+
`),a=(s>=0?i.slice(0,s):i).trim();if(!a)return null;let c=JSON.parse(a);if(c&&typeof c=="object"&&c._type==="meta"){let d=c;return{gitRoot:typeof d.gitRoot=="string"?d.gitRoot:void 0,runtimeInfo:d.runtimeInfo}}return null}catch{return null}finally{await t?.close()}}o(_h,"readMeta");async function Ah(e){let t=await _h(e);return t?yo({gitRoot:t.gitRoot,runtimeInfo:t.runtimeInfo}).key:Ze}o(Ah,"destKeyFor");async function Ph(e){let t=[],n=o(async(r,i)=>{let s=[];try{s=await R.readdir(r,{withFileTypes:!0})}catch{return}for(let a of s)!a.isFile()||a.name.startsWith(".")||(gr(a.name)||i&&Ds(a.name)!==null)&&t.push(P.join(r,a.name))},"pushDir");return await n(e,!0),await n(hr(e),!0),t}o(Ph,"collectFlatSources");async function Mh(e){let t=await Ph(e),n=t.filter(s=>gr(P.basename(s))),r=new Set(n.map(s=>P.basename(s,".jsonl"))),i=[];for(let s of n){let a=P.basename(s,".jsonl"),c=await Ah(s);i.push({from:s,to:P.join(e,c,`${a}.jsonl`),reason:`session\u2192${c}`});for(let d of[".archive.jsonl",".islands.jsonl"]){let u=P.join(P.dirname(s),`${a}${d}`);Os.existsSync(u)&&i.push({from:u,to:P.join(e,c,`${a}.islands.jsonl`),reason:"sidecar\u2192islands"})}}for(let s of t){let a=Ds(P.basename(s));a===null||r.has(a)||i.push({from:s,to:P.join(e,Ze,"orphan-islands",`${a}.islands.jsonl`),reason:"orphan-sidecar\u2192_unknown"})}return i}o(Mh,"planMigration");async function Oh(e){try{let t=JSON.parse(await R.readFile(fr(e),"utf8"));return t!==null&&typeof t=="object"&&t.version===Ns}catch{return!1}}o(Oh,"isMigrated");async function Ms(e){await lr(e),await lr(hr(e))}o(Ms,"removeLegacyConversationCaches");async function Nh(e){try{let t=JSON.parse(await R.readFile($s(e),"utf8"));if(typeof t.pid=="number"&&t.pid!==process.pid)try{process.kill(t.pid,0)}catch(n){if(n.code==="ESRCH")return!0}return typeof t.heartbeatAt=="number"&&Date.now()-t.heartbeatAt>Rh}catch{return!0}}o(Nh,"lockIsStale");async function $h(e){let t=mr(e);for(let n=0;n<2;n+=1)try{return await R.mkdir(t),await R.writeFile($s(e),JSON.stringify({pid:process.pid,startTime:Date.now(),heartbeatAt:Date.now()})),!0}catch(r){if(r.code!=="EEXIST")return!1;if(n===0&&await Nh(e)){await R.rm(t,{recursive:!0,force:!0}).catch(()=>{});continue}return!1}return!1}o($h,"acquireLock");async function Dh(e){await R.rm(mr(e),{recursive:!0,force:!0}).catch(()=>{})}o(Dh,"releaseLock");async function Lh(e){try{if((await R.readdir(P.join(e,".write-locks"),{withFileTypes:!0})).some(n=>n.isFile()&&/^[0-9a-f]{64}\.lock$/.test(n.name)))throw new Error("Session layout migration deferred while a Session writer is active")}catch(t){if(t.code==="ENOENT")return;throw t}}o(Lh,"assertNoActiveSessionWriters");async function Fh(e){let t=new Set;try{let n=await R.readFile(pr(e),"utf8");for(let r of n.split(`
|
|
540
|
+
`))if(r.trim())try{let i=JSON.parse(r);i.done&&typeof i.from=="string"&&t.add(i.from)}catch{}}catch{}return t}o(Fh,"readJournalDone");async function jh(e){if(await R.mkdir(P.dirname(e.to),{recursive:!0}),Os.existsSync(e.to)){await R.unlink(e.from).catch(()=>{});return}try{await R.rename(e.from,e.to)}catch(t){let n=t.code;if(n==="EXDEV")await R.copyFile(e.from,e.to),await R.unlink(e.from).catch(()=>{});else if(n!=="ENOENT")throw t}}o(jh,"executeMove");async function Kh(e){await R.mkdir(e,{recursive:!0});let t=`${fr(e)}.${process.pid}.tmp`,n=JSON.stringify({version:Ns,migratedAt:new Date().toISOString(),from:"flat-v1"});await R.writeFile(t,n+`
|
|
541
|
+
`,"utf8"),await R.rename(t,fr(e))}o(Kh,"writeMarker");async function Bh(e){let t=hr(e);try{(await R.readdir(t)).length===0&&await R.rmdir(t).catch(()=>{})}catch{}}o(Bh,"retireSessionsArchive");async function Xh(e){if(!await $h(e))return{moved:0,planned:0};try{await Lh(e),await Ms(e);let t=await Mh(e),n=await Fh(e),r=await R.open(pr(e),"a"),i=0;try{for(let s of t){if(gr(P.basename(s.from)))try{await As(s.to)}catch(a){throw new Ie(P.dirname(s.to),a)}n.has(s.from)||(await jh(s),await r.write(JSON.stringify({from:s.from,to:s.to,done:!0})+`
|
|
542
|
+
`),i+=1)}}finally{await r.close()}return await Bh(e),await Ms(e),await Kh(e),await R.rm(pr(e),{force:!0}).catch(()=>{}),{moved:i,planned:t.length}}finally{await Dh(e)}}o(Xh,"runMigration");async function Ls(e){try{if(await Oh(e))return;await Xh(e)}catch(t){if(t instanceof Ie)throw t}}o(Ls,"ensureLayoutMigrated");import{jsx as Ct,jsxs as Ye}from"react/jsx-runtime";import{useMemo as Dw,useRef as Lw,useState as to}from"react";import{jsx as Ec}from"react/jsx-runtime";import{createContext as Sw,useContext as Jr,useEffect as Ge,useMemo as Sc,useState as Ew,useCallback as Ic,useRef as vn}from"react";import{Stream as Zy}from"node:stream";import{openSync as ew,writeSync as fc}from"node:fs";import{performance as tw}from"node:perf_hooks";import{tmpdir as nw}from"node:os";import{join as rw}from"node:path";import yr,{forwardRef as Hh,useContext as zh}from"react";import{createContext as Uh}from"react";var Be=Uh({isScreenReaderEnabled:!1});import{createContext as Wh}from"react";var en=Wh(void 0);var Fs=Hh(({children:e,backgroundColor:t,"aria-label":n,"aria-hidden":r,"aria-role":i,"aria-state":s,...a},c)=>{let{isScreenReaderEnabled:d}=zh(Be),u=n?yr.createElement("ink-text",null,n):void 0;if(d&&r)return null;let l=yr.createElement("ink-box",{ref:c,style:{flexWrap:"nowrap",flexDirection:"row",flexGrow:0,flexShrink:1,...a,backgroundColor:t,overflowX:a.overflowX??a.overflow??"visible",overflowY:a.overflowY??a.overflow??"visible"},internal_accessibility:{role:i,state:s}},d&&u?u:e);return t?yr.createElement(en.Provider,{value:t},l):l});Fs.displayName="Box";var q=Fs;import Yh,{useContext as js}from"react";import Xe from"chalk";import ge from"chalk";var qh=/^rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)$/,Vh=/^ansi256\(\s?(\d+)\s?\)$/;function Gh(e){return e in ge}o(Gh,"isNamedColor");function G(e,t,n){if(!t)return e;if(Gh(t)){let r=ge;if(n==="foreground")return r[t]?.(e)??e;let i=`bg${t[0].toUpperCase()+t.slice(1)}`;return r[i]?.(e)??e}if(t.startsWith("#"))return n==="foreground"?ge.hex(t)(e):ge.bgHex(t)(e);if(t.startsWith("ansi256")){let r=Vh.exec(t);if(!r)return e;let i=Number(r[1]);return n==="foreground"?ge.ansi256(i)(e):ge.bgAnsi256(i)(e)}if(t.startsWith("rgb")){let r=qh.exec(t);if(!r)return e;let i=Number(r[1]),s=Number(r[2]),a=Number(r[3]);return n==="foreground"?ge.rgb(i,s,a)(e):ge.bgRgb(i,s,a)(e)}return e}o(G,"colorize");function K({color:e,backgroundColor:t,dimColor:n=!1,bold:r=!1,italic:i=!1,underline:s=!1,strikethrough:a=!1,inverse:c=!1,wrap:d="wrap",children:u,"aria-label":l,"aria-hidden":f=!1,internal_cursorAnchor:m=!1}){let{isScreenReaderEnabled:p}=js(Be),g=js(en),v=p&&l?l:u;if(v==null)return null;let w=o(y=>{let h=y;n&&(h=Xe.dim(h)),e&&(h=G(h,e,"foreground"));let b=t??g;return b&&(h=G(h,b,"background")),r&&(h=Xe.bold(h)),i&&(h=Xe.italic(h)),s&&(h=Xe.underline(h)),a&&(h=Xe.strikethrough(h)),c&&(h=Xe.inverse(h)),h},"transform");return p&&f?null:Yh.createElement("ink-text",{style:{flexGrow:0,flexShrink:1,flexDirection:"row",textWrap:d},internal_transform:w,...m?{internal_cursorAnchor:!0}:{}},p&&l?l:u)}o(K,"Text");import nB,{useLayoutEffect as rB,useMemo as oB,useState as iB}from"react";import Pe from"node:process";import dc from"react";import{throttle as Ny}from"es-toolkit/compat";import B from"ansi-escapes";import fe from"is-in-ci";import $y from"auto-bind";import{onExit as Dy}from"signal-exit";import Ly from"patch-console";import{LegacyRoot as Fy,ConcurrentRoot as jy}from"react-reconciler/constants.js";import Ky from"yoga-layout";import By from"wrap-ansi";import Xy from"terminal-size";import Jh from"node:process";var tn=o(()=>Jh.env.DEV==="true","isDev");import Ig from"react-reconciler";import{DefaultEventPriority as Cg,NoEventPriority as aa}from"react-reconciler/constants.js";import*as ye from"scheduler";import ra from"yoga-layout";import{createContext as Tg}from"react";import fg from"yoga-layout";import Qh from"widest-line";var Ks=new Map,Zh=o(e=>{if(e.length===0)return{width:0,height:0};let t=Ks.get(e);if(t)return t;let n=Qh(e),r=e.split(`
|
|
543
|
+
`).length,i={width:n,height:r};return Ks.set(e,i),i},"measureText"),wr=Zh;import eg from"wrap-ansi";import tg from"cli-truncate";var Bs={},ng=o((e,t,n)=>{let r=e+String(t)+String(n),i=Bs[r];if(i)return i;let s=e;if(n==="wrap"&&(s=eg(e,t,{trim:!1,hard:!0})),n.startsWith("truncate")){let a="end";n==="truncate-middle"&&(a="middle"),n==="truncate-start"&&(a="start"),s=tg(e,t,{position:a})}return Bs[r]=s,s},"wrapText"),nn=ng;var rg=o(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=48&&t<=63},"isCsiParameterCharacter"),og=o(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=32&&t<=47},"isCsiIntermediateCharacter"),ig=o(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=64&&t<=126},"isCsiFinalCharacter"),Ws=o(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=32&&t<=47},"isEscapeIntermediateCharacter"),sg=o(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=48&&t<=126},"isEscapeFinalCharacter"),Hs=o(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=128&&t<=159},"isC1ControlCharacter"),Xs=o((e,t)=>{let n=t;for(;n<e.length;){let c=e[n];if(!rg(c))break;n++}let r=e.slice(t,n),i=n;for(;n<e.length;){let c=e[n];if(!og(c))break;n++}let s=e.slice(i,n),a=e[n];if(!(a===void 0||!ig(a)))return{endIndex:n+1,parameterString:r,intermediateString:s,finalCharacter:a}},"readCsiSequence"),Us=o((e,t,n)=>{for(let r=t;r<e.length;r++){let i=e[r];if(n&&i==="\x07"||i==="\x9C")return r+1;if(i==="\x1B"){let s=e[r+1];if(s==="\x1B"){r++;continue}if(s==="\\")return r+2}}},"findControlStringTerminatorIndex"),ag=o((e,t)=>{let n=t;for(;n<e.length;){let s=e[n];if(!Ws(s))break;n++}let r=e.slice(t,n),i=e[n];if(!(i===void 0||!sg(i)))return{endIndex:n+1,intermediateString:r,finalCharacter:i}},"readEscapeSequence"),cg=o(e=>{switch(e){case"]":return{type:"osc",allowBellTerminator:!0};case"P":return{type:"dcs",allowBellTerminator:!1};case"^":return{type:"pm",allowBellTerminator:!1};case"_":return{type:"apc",allowBellTerminator:!1};case"X":return{type:"sos",allowBellTerminator:!1};default:return}},"getControlStringFromEscapeIntroducer"),dg=o(e=>{switch(e){case"\x9D":return{type:"osc",allowBellTerminator:!0};case"\x90":return{type:"dcs",allowBellTerminator:!1};case"\x9E":return{type:"pm",allowBellTerminator:!1};case"\x9F":return{type:"apc",allowBellTerminator:!1};case"\x98":return{type:"sos",allowBellTerminator:!1};default:return}},"getControlStringFromC1Introducer"),vr=o(e=>{if(e.includes("\x1B"))return!0;for(let t of e)if(Hs(t))return!0;return!1},"hasAnsiControlCharacters"),Ue=o((e,t,n,r)=>(r>n&&e.push({type:"text",value:t.slice(n,r)}),e.push({type:"invalid",value:t.slice(r)}),e),"malformedFromIndex"),zs=o(e=>{if(!vr(e))return[{type:"text",value:e}];let t=[],n=0;for(let r=0;r<e.length;){let i=e[r];if(i===void 0)break;if(i==="\x1B"){let a=e[r+1];if(a===void 0)return Ue(t,e,n,r);if(a==="["){let u=Xs(e,r+2);if(u===void 0)return Ue(t,e,n,r);r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:"csi",value:e.slice(r,u.endIndex),parameterString:u.parameterString,intermediateString:u.intermediateString,finalCharacter:u.finalCharacter}),r=u.endIndex,n=r;continue}let c=cg(a);if(c!==void 0){let u=Us(e,r+2,c.allowBellTerminator);if(u===void 0)return Ue(t,e,n,r);r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:c.type,value:e.slice(r,u)}),r=u,n=r;continue}let d=ag(e,r+1);if(d===void 0){if(Ws(a))return Ue(t,e,n,r);r>n&&t.push({type:"text",value:e.slice(n,r)}),r++,n=r;continue}r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:"esc",value:e.slice(r,d.endIndex),intermediateString:d.intermediateString,finalCharacter:d.finalCharacter}),r=d.endIndex,n=r;continue}if(i==="\x9B"){let a=Xs(e,r+1);if(a===void 0)return Ue(t,e,n,r);r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:"csi",value:e.slice(r,a.endIndex),parameterString:a.parameterString,intermediateString:a.intermediateString,finalCharacter:a.finalCharacter}),r=a.endIndex,n=r;continue}let s=dg(i);if(s!==void 0){let a=Us(e,r+1,s.allowBellTerminator);if(a===void 0)return Ue(t,e,n,r);r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:s.type,value:e.slice(r,a)}),r=a,n=r;continue}if(i==="\x9C"){r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:"st",value:i}),r++,n=r;continue}if(Hs(i)){r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:"c1",value:i}),r++,n=r;continue}r++}return n<e.length&&t.push({type:"text",value:e.slice(n)}),t},"tokenizeAnsi");var ug=/^[\d:;]*$/,lg=o(e=>{if(!vr(e))return e;let t="";for(let n of zs(e)){if(n.type==="text"||n.type==="osc"){t+=n.value;continue}n.type==="csi"&&n.finalCharacter==="m"&&n.intermediateString===""&&ug.test(n.parameterString)&&(t+=n.value)}return t},"sanitizeAnsi"),qs=lg;var Vs=o(e=>{let t="";for(let n=0;n<e.childNodes.length;n++){let r=e.childNodes[n];if(r===void 0)continue;let i="";r.nodeName==="#text"?i=r.nodeValue:((r.nodeName==="ink-text"||r.nodeName==="ink-virtual-text")&&(i=Vs(r)),i.length>0&&typeof r.internal_transform=="function"&&(i=r.internal_transform(i,n))),t+=i}return qs(t)},"squashTextNodes"),mt=Vs;var rn=o(e=>{let t={nodeName:e,style:{},attributes:{},childNodes:[],parentNode:void 0,yogaNode:e==="ink-virtual-text"?void 0:fg.Node.create(),internal_accessibility:{}};return e==="ink-text"&&t.yogaNode?.setMeasureFunc(pg.bind(null,t)),t},"createNode"),on=o((e,t)=>{t.parentNode&&ht(t.parentNode,t),t.parentNode=e,e.childNodes.push(t),t.yogaNode&&e.yogaNode?.insertChild(t.yogaNode,e.yogaNode.getChildCount()),(e.nodeName==="ink-text"||e.nodeName==="ink-virtual-text")&&sn(e)},"appendChildNode"),br=o((e,t,n)=>{t.parentNode&&ht(t.parentNode,t),t.parentNode=e;let r=e.childNodes.indexOf(n);r>=0?(e.childNodes.splice(r,0,t),t.yogaNode&&e.yogaNode?.insertChild(t.yogaNode,r)):(e.childNodes.push(t),t.yogaNode&&e.yogaNode?.insertChild(t.yogaNode,e.yogaNode.getChildCount())),(e.nodeName==="ink-text"||e.nodeName==="ink-virtual-text")&&sn(e)},"insertBeforeNode"),ht=o((e,t)=>{t.yogaNode&&t.parentNode?.yogaNode?.removeChild(t.yogaNode),t.parentNode=void 0;let n=e.childNodes.indexOf(t);n>=0&&e.childNodes.splice(n,1),(e.nodeName==="ink-text"||e.nodeName==="ink-virtual-text")&&sn(e)},"removeChildNode"),kr=o((e,t,n)=>{if(t==="internal_accessibility"){e.internal_accessibility=n;return}e.attributes[t]=n},"setAttribute"),xr=o((e,t)=>{e.style=t},"setStyle"),Gs=o(e=>{let t={nodeName:"#text",nodeValue:e,yogaNode:void 0,parentNode:void 0,style:{}};return gt(t,e),t},"createTextNode"),pg=o(function(e,t){let n=e.nodeName==="#text"?e.nodeValue:mt(e),r=wr(n);if(r.width<=t||r.width>=1&&t>0&&t<1)return r;let i=e.style?.textWrap??"wrap",s=nn(n,t,i);return wr(s)},"measureTextNode"),Ys=o(e=>{if(e?.parentNode)return e.yogaNode??Ys(e.parentNode)},"findClosestYogaNode"),sn=o(e=>{Ys(e)?.markDirty()},"markNodeAsDirty"),gt=o((e,t)=>{typeof t!="string"&&(t=String(t)),e.nodeValue=t,sn(e)},"setTextNodeValue");import k from"yoga-layout";var hg=o((e,t)=>{"position"in t&&e.setPositionType(t.position==="absolute"?k.POSITION_TYPE_ABSOLUTE:k.POSITION_TYPE_RELATIVE),"top"in t&&e.setPosition(k.EDGE_TOP,t.top??0),"bottom"in t&&e.setPosition(k.EDGE_BOTTOM,t.bottom??0),"left"in t&&e.setPosition(k.EDGE_LEFT,t.left??0),"right"in t&&e.setPosition(k.EDGE_RIGHT,t.right??0)},"applyPositionStyles"),gg=o((e,t)=>{"margin"in t&&e.setMargin(k.EDGE_ALL,t.margin??0),"marginX"in t&&e.setMargin(k.EDGE_HORIZONTAL,t.marginX??0),"marginY"in t&&e.setMargin(k.EDGE_VERTICAL,t.marginY??0),"marginLeft"in t&&e.setMargin(k.EDGE_START,t.marginLeft||0),"marginRight"in t&&e.setMargin(k.EDGE_END,t.marginRight||0),"marginTop"in t&&e.setMargin(k.EDGE_TOP,t.marginTop||0),"marginBottom"in t&&e.setMargin(k.EDGE_BOTTOM,t.marginBottom||0)},"applyMarginStyles"),yg=o((e,t)=>{"padding"in t&&e.setPadding(k.EDGE_ALL,t.padding??0),"paddingX"in t&&e.setPadding(k.EDGE_HORIZONTAL,t.paddingX??0),"paddingY"in t&&e.setPadding(k.EDGE_VERTICAL,t.paddingY??0),"paddingLeft"in t&&e.setPadding(k.EDGE_LEFT,t.paddingLeft||0),"paddingRight"in t&&e.setPadding(k.EDGE_RIGHT,t.paddingRight||0),"paddingTop"in t&&e.setPadding(k.EDGE_TOP,t.paddingTop||0),"paddingBottom"in t&&e.setPadding(k.EDGE_BOTTOM,t.paddingBottom||0)},"applyPaddingStyles"),wg=o((e,t)=>{"flexGrow"in t&&e.setFlexGrow(t.flexGrow??0),"flexShrink"in t&&e.setFlexShrink(typeof t.flexShrink=="number"?t.flexShrink:1),"flexWrap"in t&&(t.flexWrap==="nowrap"&&e.setFlexWrap(k.WRAP_NO_WRAP),t.flexWrap==="wrap"&&e.setFlexWrap(k.WRAP_WRAP),t.flexWrap==="wrap-reverse"&&e.setFlexWrap(k.WRAP_WRAP_REVERSE)),"flexDirection"in t&&(t.flexDirection==="row"&&e.setFlexDirection(k.FLEX_DIRECTION_ROW),t.flexDirection==="row-reverse"&&e.setFlexDirection(k.FLEX_DIRECTION_ROW_REVERSE),t.flexDirection==="column"&&e.setFlexDirection(k.FLEX_DIRECTION_COLUMN),t.flexDirection==="column-reverse"&&e.setFlexDirection(k.FLEX_DIRECTION_COLUMN_REVERSE)),"flexBasis"in t&&(typeof t.flexBasis=="number"?e.setFlexBasis(t.flexBasis):typeof t.flexBasis=="string"?e.setFlexBasisPercent(Number.parseInt(t.flexBasis,10)):e.setFlexBasis(Number.NaN)),"alignItems"in t&&((t.alignItems==="stretch"||!t.alignItems)&&e.setAlignItems(k.ALIGN_STRETCH),t.alignItems==="flex-start"&&e.setAlignItems(k.ALIGN_FLEX_START),t.alignItems==="center"&&e.setAlignItems(k.ALIGN_CENTER),t.alignItems==="flex-end"&&e.setAlignItems(k.ALIGN_FLEX_END)),"alignSelf"in t&&((t.alignSelf==="auto"||!t.alignSelf)&&e.setAlignSelf(k.ALIGN_AUTO),t.alignSelf==="flex-start"&&e.setAlignSelf(k.ALIGN_FLEX_START),t.alignSelf==="center"&&e.setAlignSelf(k.ALIGN_CENTER),t.alignSelf==="flex-end"&&e.setAlignSelf(k.ALIGN_FLEX_END)),"justifyContent"in t&&((t.justifyContent==="flex-start"||!t.justifyContent)&&e.setJustifyContent(k.JUSTIFY_FLEX_START),t.justifyContent==="center"&&e.setJustifyContent(k.JUSTIFY_CENTER),t.justifyContent==="flex-end"&&e.setJustifyContent(k.JUSTIFY_FLEX_END),t.justifyContent==="space-between"&&e.setJustifyContent(k.JUSTIFY_SPACE_BETWEEN),t.justifyContent==="space-around"&&e.setJustifyContent(k.JUSTIFY_SPACE_AROUND),t.justifyContent==="space-evenly"&&e.setJustifyContent(k.JUSTIFY_SPACE_EVENLY))},"applyFlexStyles"),vg=o((e,t)=>{"width"in t&&(typeof t.width=="number"?e.setWidth(t.width):typeof t.width=="string"?e.setWidthPercent(Number.parseInt(t.width,10)):e.setWidthAuto()),"height"in t&&(typeof t.height=="number"?e.setHeight(t.height):typeof t.height=="string"?e.setHeightPercent(Number.parseInt(t.height,10)):e.setHeightAuto()),"minWidth"in t&&(typeof t.minWidth=="string"?e.setMinWidthPercent(Number.parseInt(t.minWidth,10)):e.setMinWidth(t.minWidth??0)),"minHeight"in t&&(typeof t.minHeight=="string"?e.setMinHeightPercent(Number.parseInt(t.minHeight,10)):e.setMinHeight(t.minHeight??0))},"applyDimensionStyles"),bg=o((e,t)=>{"display"in t&&e.setDisplay(t.display==="flex"?k.DISPLAY_FLEX:k.DISPLAY_NONE)},"applyDisplayStyles"),kg=o((e,t)=>{if("borderStyle"in t){let n=t.borderStyle?1:0;t.borderTop!==!1&&e.setBorder(k.EDGE_TOP,n),t.borderBottom!==!1&&e.setBorder(k.EDGE_BOTTOM,n),t.borderLeft!==!1&&e.setBorder(k.EDGE_LEFT,n),t.borderRight!==!1&&e.setBorder(k.EDGE_RIGHT,n)}},"applyBorderStyles"),xg=o((e,t)=>{"gap"in t&&e.setGap(k.GUTTER_ALL,t.gap??0),"columnGap"in t&&e.setGap(k.GUTTER_COLUMN,t.columnGap??0),"rowGap"in t&&e.setGap(k.GUTTER_ROW,t.rowGap??0)},"applyGapStyles"),Sg=o((e,t={})=>{hg(e,t),gg(e,t),yg(e,t),wg(e,t),vg(e,t),bg(e,t),kg(e,t),xg(e,t)},"styles"),Sr=Sg;if(tn())try{await Promise.resolve().then(()=>(na(),Eg))}catch(e){if(e.code==="ERR_MODULE_NOT_FOUND")console.warn(`
|
|
8
544
|
The environment variable DEV is set to true, so Ink tried to import \`react-devtools-core\`,
|
|
9
545
|
but this failed as it was not installed. Debugging with React Devtools requires it.
|
|
10
546
|
|
|
@@ -12,33 +548,33 @@ To install use this command:
|
|
|
12
548
|
|
|
13
549
|
$ npm install --save-dev react-devtools-core
|
|
14
550
|
`.trim()+`
|
|
15
|
-
`);else throw e}var
|
|
16
|
-
`).repeat(
|
|
17
|
-
`).repeat(
|
|
18
|
-
`.repeat(
|
|
19
|
-
`;
|
|
20
|
-
`))
|
|
21
|
-
`),u=
|
|
22
|
-
`),height:t.length}}};var
|
|
23
|
-
`).length,
|
|
24
|
-
`:"",frame:void 0}}let
|
|
25
|
-
`:"",frame:f}}return{output:"",outputHeight:0,staticOutput:"",frame:void 0}},"renderer"),
|
|
26
|
-
`)}]}
|
|
27
|
-
`};function _e(e,t,r){let n=t.width===j.Wide?2:1,o=e.viewportWidth,s=!1;return e.txn(c=>{let a=c.x;if(n===2&&a<o){let d=t.char.length>2?o:o+1;if(a+2>=d)return[[],{dx:0,dy:0}]}let l=[];r.length>0&&l.push({type:"stdout",content:r});let u=n===2&&yn(t.char);return u&&a+1<o&&(l.push({type:"cursorTo",col:a+2}),l.push({type:"stdout",content:" "}),l.push({type:"cursorTo",col:a+1})),l.push({type:"stdout",content:t.char}),u&&l.push({type:"cursorTo",col:a+n+1}),s=!0,a>=o?[l,{dx:n-a,dy:1}]:[l,{dx:n,dy:0}]}),s}i(_e,"writeCellWithStyleStr");function se(e,t,r){e.txn(n=>{let o=t-n.x,s=r-n.y;return n.x>=e.viewportWidth?[[K,{type:"cursorMove",x:t,y:s}],{dx:o,dy:s}]:s!==0?[[K,{type:"cursorMove",x:t,y:s}],{dx:o,dy:s}]:[[{type:"cursorMove",x:o,y:s}],{dx:o,dy:s}]})}i(se,"moveCursorTo");function ke(e,t,r,n,o=!1){let s="",c;for(let a=r;a<n;a++){if(e.cursor.y<a){let f=a-e.cursor.y;e.txn(h=>{let p=new Array(1+f);p[0]=K;for(let x=0;x<f;x++)p[1+x]=Ie;return[p,{dx:-h.x,dy:f}]})}for(let f=0;f<t.screen.width;f++){let h=ne(t.screen,f,a);if(!h||h.width===j.SpacerTail||h.char===" "&&h.style===""&&h.hyperlink===void 0)continue;se(e,f,a);let p=$(c,h.hyperlink);for(let T of p.patches)e.txn(()=>[[T],{dx:0,dy:0}]);c=p.current;let x=Oe(s,h.style);_e(e,h,x.str)&&(s=x.current)}let l=oe(s,"");for(let f of l.patches)e.txn(()=>[[f],{dx:0,dy:0}]);s=l.current;let u=$(c,void 0);for(let f of u.patches)e.txn(()=>[[f],{dx:0,dy:0}]);c=u.current;let d=a===n-1&&t.screen.height<=t.viewport.height&&(a+1>=t.viewport.height||o);e.txn(f=>d?[[K],{dx:-f.x,dy:0}]:[[K,Ie],{dx:-f.x,dy:1}])}if(s!==""||c!==void 0){let a=oe(s,"");for(let u of a.patches)e.txn(()=>[[u],{dx:0,dy:0}]);let l=$(c,void 0);for(let u of l.patches)e.txn(()=>[[u],{dx:0,dy:0}])}}i(ke,"renderFrameSlice");function Nt(e,t,r,n){let o=Math.max(0,Math.floor(r)),s=Math.min(t.screen.height-1,t.viewport.height-1,Math.floor(n));for(let c=o;c<=s;c++)ls(e,t,c)}i(Nt,"repaintFrameRows");function ls(e,t,r){let n="",o;se(e,0,r),e.txn(()=>[[{type:"stdout",content:he+ve},{type:"eraseLine"}],{dx:0,dy:0}]);for(let s=0;s<t.screen.width;s++){let c=ne(t.screen,s,r);if(!c||c.width===j.SpacerTail||c.char===" "&&c.style===""&&c.hyperlink===void 0)continue;se(e,s,r);let a=$(o,c.hyperlink);for(let u of a.patches)e.txn(()=>[[u],{dx:0,dy:0}]);o=a.current;let l=Oe(n,c.style);_e(e,c,l.str)&&(n=l.current)}for(let s of oe(n,"").patches)e.txn(()=>[[s],{dx:0,dy:0}]);for(let s of $(o,void 0).patches)e.txn(()=>[[s],{dx:0,dy:0}])}i(ls,"repaintFrameRow");function Pt(e,t){let r="";for(let n=0;n<e.width;n++){let o=ne(e,n,t);r+=o?.char??" "}return r.trimEnd()}i(Pt,"readLine");function me(e,t,r=!1){let n=new ie({x:0,y:0},e.viewport.width);ke(n,e,0,e.screen.height,r);let o=[{type:"clearTerminal",reason:t}];for(let s of n.diff)o.push(s);return o}i(me,"fullResetSequence_CAUSES_FLICKER");function Qe(e,t){let r=e.cursor.y>=e.screen.height,n=t.screen.height>e.screen.height,o=t.screen.height<e.screen.height,s=r&&e.screen.height>=e.viewport.height,c=t.screen.height<=e.viewport.height,a=s?1:0;return{viewportY:n?Math.max(0,e.screen.height-e.viewport.height+a):Math.max(e.screen.height,t.screen.height)-t.viewport.height+a,cursorAtBottom:r,growing:n,shrinking:o,prevHadScrollback:s,nextFitsViewport:c}}i(Qe,"computeViewportState");function Tn(e,t,r){if(t.viewport.height<e.viewport.height||e.viewport.width!==0&&t.viewport.width!==e.viewport.width)return{reset:!0,reason:"resize"};let n=Qe(e,t);if(n.prevHadScrollback&&n.nextFitsViewport&&n.shrinking)return{reset:!0,reason:"offscreen"};if(e.screen.height>=e.viewport.height&&e.screen.height>0&&n.cursorAtBottom&&!n.growing){let s=e.screen.height-e.viewport.height+1;for(let c of Je(e.screen,t.screen))if(c.y<s)return{reset:!0,reason:"offscreen",trigger:{y:c.y,prevLine:r(e.screen,c.y),nextLine:r(t.screen,c.y)}}}return n.shrinking&&e.screen.height-t.screen.height>e.viewport.height?{reset:!0,reason:"offscreen"}:{reset:!1}}i(Tn,"shouldFullReset");function Cn(e,t,r){return!!(t&&t.width===2||e&&e.width===2&&!t||t&&r&&!e)}i(Cn,"shouldSkipDiff");var Ze=class{static{i(this,"LogUpdate")}options;constructor(t){this.options=t}render(t,r,n={}){if(!this.options.isTTY)return At(r);let o=n.inlineBottomAnchored??!1,s=Rn(t,o),c=Rn(r,o);if(n.altScreen===!0&&t.screen.height===0&&c.screen.height>0)return me(c,"clear",o);let a=Tn(s,c,Pt);if(a.reset)return me(c,a.reason,o);if(c.scrollRepaint&&n.altScreen===!0)return us(s,c,c.scrollRepaint);let l=c.scrollHint;if(l&&n.altScreen&&n.decstbmSafe&&process.env.KODAX_SCROLL_DECSTBM==="1"&&l.delta!==0&&l.top>=0&&l.bottom<s.screen.height&&l.bottom<c.screen.height&&Math.abs(l.delta)<=l.bottom-l.top){let u={type:"scrollRegion",top:l.top,bottom:l.bottom,delta:l.delta},d={...s,screen:sn(s.screen,l.top,l.bottom,l.delta)};return[u,...bn(d,c,o)]}return bn(s,c,o)}reset(){}};function Lt(e,t){for(let r of t)e.txn(()=>[[r],{dx:0,dy:0}])}i(Lt,"emitPatches");function Ft(e,t,r){if(t!==""){let n=oe(t,"");Lt(e,n.patches)}if(r!==void 0){let n=$(r,void 0);Lt(e,n.patches)}return{style:"",hyperlink:void 0}}i(Ft,"resetStyleAndHyperlink");function us(e,t,r){let n=Qe(e,t),o=new ie(e.cursor,t.viewport.width);n.shrinking&&En(o,e,t);let s=Math.max(0,Math.floor(r.top)),c=Math.min(t.screen.height-1,t.viewport.height-1,Math.floor(r.bottom)),a=c>=s?{top:s,bottom:c}:void 0;a&&Nt(o,t,a.top,a.bottom);let l=vn(o,e,t,{...n,skipRows:a});return l.needsFullReset?me(t,"offscreen"):(Ft(o,l.currentStyle,l.currentHyperlink),n.growing&&ke(o,t,e.screen.height,t.screen.height),Mn(o,t),o.diff)}i(us,"renderScrollRepaint");function En(e,t,r){let n=t.screen.height-r.screen.height;e.txn(o=>[[{type:"clear",count:n},{type:"cursorMove",x:0,y:-1}],{dx:-o.x,dy:-n}])}i(En,"applyShrink");function vn(e,t,r,n){let o="",s,c=!1;for(let a of Je(t.screen,r.screen)){let{x:l,y:u,prev:d,next:f}=a;if(n.growing&&u>=t.screen.height||n.skipRows&&u>=n.skipRows.top&&u<=n.skipRows.bottom)continue;let h=!!(f&&f.char===" "&&f.style===""&&f.hyperlink===void 0);if(!Cn(d,f,h)){if(u<n.viewportY){c=!0;break}if(se(e,l,u),f){let p=$(s,f.hyperlink);Lt(e,p.patches),s=p.current;let x=Oe(o,f.style);_e(e,f,x.str)&&(o=x.current)}else if(d){let p=Ft(e,o,s);o=p.style,s=p.hyperlink,e.txn(()=>[[{type:"stdout",content:" "}],{dx:1,dy:0}])}}}return{currentStyle:o,currentHyperlink:s,needsFullReset:c}}i(vn,"diffPass");function Rn(e,t){let r=t?Math.max(0,Math.min(e.viewport.height-1,e.screen.height-1)):Math.max(0,e.viewport.height-1);return e.cursor.y<=r?e:{...e,cursor:{...e.cursor,y:r}}}i(Rn,"clampRestingCursor");function Mn(e,t){t.cursor.y>=t.screen.height?e.txn(r=>{let n=t.cursor.y-r.y;if(n>0){let s=new Array(1+n);s[0]=K;for(let c=0;c<n;c++)s[1+c]=Ie;return[s,{dx:-r.x,dy:n}]}let o=t.cursor.y-r.y;return o!==0||r.x!==t.cursor.x?[[K,{type:"cursorMove",x:t.cursor.x,y:o}],{dx:t.cursor.x-r.x,dy:o}]:[[],{dx:0,dy:0}]}):se(e,t.cursor.x,t.cursor.y)}i(Mn,"restoreCursor");function bn(e,t,r=!1){let n=Qe(e,t),o=new ie(e.cursor,t.viewport.width);n.shrinking&&En(o,e,t);let s=vn(o,e,t,n);return s.needsFullReset?me(t,"offscreen",r):(Ft(o,s.currentStyle,s.currentHyperlink),n.growing&&ke(o,t,e.screen.height,t.screen.height,r),Mn(o,t),o.diff)}i(bn,"renderIncremental");var fs="\x1B[?25l",ds="\x1B[?25h",ps=`\x1B[2J${un}`,hs="\x1B[?2026h",ms="\x1B[?2026l";function gs(e){switch(e.type){case"stdout":return e.content;case"carriageReturn":return"\r";case"cursorHide":return fs;case"cursorShow":return ds;case"cursorMove":return fn(e.x,e.y);case"cursorTo":return ln(e.col);case"eraseLine":return kt;case"clear":return dn(e.count);case"clearTerminal":return ps;case"hyperlink":return Me(e.uri);case"scrollRegion":{let t=e.top+1,r=e.bottom+1,n=Math.abs(e.delta),o=e.delta>0?xn(n):wn(n);return hn+gn(t,r)+o+pn+mn}}}i(gs,"patchToBytes");function et(e,t,r=!1){let n="",o=!1;for(let s of t)s.type==="clearTerminal"&&(o=!0),n+=gs(s);if(n.length!==0){if(r&&o){e.write(hs+n+ms);return}e.write(n)}}i(et,"applyDiff");function In(e,t,r={}){if(t===void 0)return!1;let n=e.cellLogUpdate.render(e.prevFrame,t,r);return et(e.stdout,n,r.synchronized??!1),e.prevFrame=t,!0}i(In,"applyCellFrame");function Ae(e,t){return{screen:nn(0,0),viewport:{width:t,height:e},cursor:{x:0,y:0,visible:!0}}}i(Ae,"emptyFrame");import xs from"is-in-ci";var z="\x1B[?2026h",Y="\x1B[?2026l";function X(e){return"isTTY"in e&&e.isTTY===!0&&!xs}i(X,"shouldSynchronize");var ws=new WeakMap,On=ws;import{EventEmitter as Ds}from"node:events";import Hs from"node:process";import ce,{useState as Ht,useRef as ge,useCallback as O,useMemo as xe,useEffect as Kn}from"react";import Bs from"cli-cursor";var Ss=i(e=>e>=48&&e<=63,"isCsiParameterByte"),ys=i(e=>e>=32&&e<=47,"isCsiIntermediateByte"),kn=i(e=>e>=64&&e<=126,"isCsiFinalByte");function Ts(e,t,r){let n=t+r+1,o=n;for(;o<e.length;o+=1){let s=e.codePointAt(o);if(s===void 0)return"pending";if(!(Ss(s)||ys(s))&&!(s===91&&o===n))return kn(s)?{sequence:e.slice(t,o+1),nextIndex:o+1}:void 0}return"pending"}i(Ts,"parseCsiSequence");function Cs(e,t,r){let n=t+r+2;if(n>e.length)return"pending";let o=e.codePointAt(n-1);if(!(o===void 0||!kn(o)))return{sequence:e.slice(t,n),nextIndex:n}}i(Cs,"parseSs3Sequence");function _n(e,t,r){let n=e[t+r];if(n===void 0)return"pending";if(n==="[")return Ts(e,t,r);if(n==="O")return Cs(e,t,r)}i(_n,"parseControlSequence");function Rs(e,t){let r=e.codePointAt(t+1),n=r!==void 0&&r>65535?2:1,o=t+1+n;return{sequence:e.slice(t,o),nextIndex:o}}i(Rs,"parseEscapedCodePoint");function bs(e){let t=[],r=0,n=i(o=>({events:t,pending:e.slice(o)}),"pendingFrom");for(;r<e.length;){let o=e.indexOf("\x1B",r);if(o===-1)return t.push(e.slice(r)),{events:t,pending:""};if(o>r&&t.push(e.slice(r,o)),o===e.length-1)return n(o);let s=_n(e,o,1);if(s==="pending")return n(o);if(s){t.push(s.sequence),r=s.nextIndex;continue}if(e[o+1]==="\x1B"){if(o+2>=e.length)return n(o);let l=_n(e,o,2);if(l==="pending")return n(o);if(l){t.push(l.sequence),r=l.nextIndex;continue}t.push(e.slice(o,o+2)),r=o+2;continue}let a=Rs(e,o);t.push(a.sequence),r=a.nextIndex}return{events:t,pending:""}}i(bs,"parseKeypresses");function tt(){let e="";return{push(t){let r=bs(e+t);return e=r.pending,r.events},hasPendingEscape(){return e.startsWith("\x1B")},flushPendingEscape(){if(!e.startsWith("\x1B"))return;let t=e;return e="",t},reset(){e=""}}}i(tt,"createInputParser");import{createContext as Es}from"react";var An=Es({exit(){}});An.displayName="InternalAppContext";var Nn=An;import{EventEmitter as vs}from"node:events";import{createContext as Ms}from"react";var Is={isTTY:!1,isRaw:!1,on(){},off(){},pause(){},resume(){},setRawMode(){}},Pn=Ms({stdin:Is,internal_eventEmitter:new vs,setRawMode(){},isRawModeSupported:!1,internal_exitOnCtrlC:!0});Pn.displayName="InternalStdinContext";var Ln=Pn;import{createContext as Os}from"react";var _s={isTTY:!1,columns:80,rows:24,write(){return!0},on(){},off(){}},Fn=Os({stdout:_s,write(){}});Fn.displayName="InternalStdoutContext";var Wn=Fn;import{createContext as ks}from"react";var As={isTTY:!1,write(){return!0},on(){},off(){}},Dn=ks({stderr:As,write(){}});Dn.displayName="InternalStderrContext";var Hn=Dn;import{createContext as Ns}from"react";var Bn=Ns({activeId:void 0,add(){},remove(){},activate(){},deactivate(){},enableFocus(){},disableFocus(){},focusNext(){},focusPrevious(){},focus(){}});Bn.displayName="InternalFocusContext";var Un=Bn;import{createContext as Ps}from"react";var jn=Ps({setCursorPosition(){}});jn.displayName="InternalCursorContext";var Yn=jn;import Fs,{PureComponent as Ws}from"react";import*as rt from"node:fs";import{cwd as $n}from"node:process";import _ from"react";import Gn from"stack-utils";import Ls from"code-excerpt";var Wt=i(e=>e?.replace(`file://${$n()}/`,""),"cleanupPath"),Vn=new Gn({cwd:$n(),internals:Gn.nodeInternals()});function Dt({error:e}){let t=e.stack?e.stack.split(`
|
|
28
|
-
`).slice(1):void 0,
|
|
29
|
-
`).slice(1).map(
|
|
551
|
+
`);else throw e}var oa=o((e,t)=>{if(e===t)return;if(!e)return t;let n={},r=!1;for(let i of Object.keys(e))(!t||!Object.hasOwn(t,i))&&(n[i]=void 0,r=!0);if(t)for(let i of Object.keys(t))t[i]!==e[i]&&(n[i]=t[i],r=!0);return r?n:void 0},"diff"),ia=o(e=>{e?.unsetMeasureFunc(),e?.freeRecursive()},"cleanupYogaNode"),cn=aa,Cr,sa={name:void 0,version:void 0},se=Ig({getRootHostContext:o(()=>({isInsideText:!1}),"getRootHostContext"),prepareForCommit:o(()=>null,"prepareForCommit"),preparePortalMount:o(()=>null,"preparePortalMount"),clearContainer:o(()=>!1,"clearContainer"),resetAfterCommit(e){if(typeof e.onComputeLayout=="function"&&e.onComputeLayout(),e.isStaticDirty){e.isStaticDirty=!1,typeof e.onImmediateRender=="function"&&e.onImmediateRender();return}typeof e.onRender=="function"&&e.onRender()},getChildHostContext(e,t){let n=e.isInsideText,r=t==="ink-text"||t==="ink-virtual-text";return n===r?e:{isInsideText:r}},shouldSetTextContent:o(()=>!1,"shouldSetTextContent"),createInstance(e,t,n,r){if(r.isInsideText&&e==="ink-box")throw new Error("<Box> can\u2019t be nested inside <Text> component");let i=e==="ink-text"&&r.isInsideText?"ink-virtual-text":e,s=rn(i);for(let[a,c]of Object.entries(t))if(a!=="children"){if(a==="style"){xr(s,c),s.yogaNode&&Sr(s.yogaNode,c);continue}if(a==="internal_transform"){s.internal_transform=c;continue}if(a==="internal_cursorAnchor"){s.internal_cursorAnchor=c;continue}if(a==="internal_static"){Cr=n,s.internal_static=!0,n.isStaticDirty=!0,n.staticNode=s;continue}kr(s,a,c)}return s},createTextInstance(e,t,n){if(!n.isInsideText)throw new Error(`Text string "${e}" must be rendered inside <Text> component`);return Gs(e)},resetTextContent(){},hideTextInstance(e){gt(e,"")},unhideTextInstance(e,t){gt(e,t)},getPublicInstance:o(e=>e,"getPublicInstance"),hideInstance(e){e.yogaNode?.setDisplay(ra.DISPLAY_NONE)},unhideInstance(e){e.yogaNode?.setDisplay(ra.DISPLAY_FLEX)},appendInitialChild:on,appendChild:on,insertBefore:br,finalizeInitialChildren(){return!1},isPrimaryRenderer:!0,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,supportsMicrotasks:!0,scheduleMicrotask:queueMicrotask,scheduleCallback:ye.unstable_scheduleCallback,cancelCallback:ye.unstable_cancelCallback,shouldYield:ye.unstable_shouldYield,now:ye.unstable_now,scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},detachDeletedInstance(){},getInstanceFromNode:o(()=>null,"getInstanceFromNode"),prepareScopeUpdate(){},getInstanceFromScope:o(()=>null,"getInstanceFromScope"),appendChildToContainer:on,insertInContainerBefore:br,removeChildFromContainer(e,t){ht(e,t),ia(t.yogaNode)},commitUpdate(e,t,n,r){Cr&&e.internal_static&&(Cr.isStaticDirty=!0);let i=oa(n,r),s=oa(n.style,r.style);if(!(!i&&!s)){if(i)for(let[a,c]of Object.entries(i)){if(a==="style"){xr(e,c);continue}if(a==="internal_transform"){e.internal_transform=c;continue}if(a==="internal_cursorAnchor"){e.internal_cursorAnchor=c;continue}if(a==="internal_static"){e.internal_static=!0;continue}kr(e,a,c)}s&&e.yogaNode&&Sr(e.yogaNode,s)}},commitTextUpdate(e,t,n){gt(e,n)},removeChild(e,t){ht(e,t),ia(t.yogaNode)},setCurrentUpdatePriority(e){cn=e},getCurrentUpdatePriority:o(()=>cn,"getCurrentUpdatePriority"),resolveUpdatePriority(){return cn!==aa?cn:Cg},maySuspendCommit(){return!0},NotPendingTransition:void 0,HostTransitionContext:Tg(null),resetFormInstance(){},requestPostPaintCallback(){},shouldAttemptEagerTransition(){return!1},trackSchedulerEvent(){},resolveEventType(){return null},resolveEventTimeStamp(){return-1.1},preloadInstance(){return!0},startSuspendingCommit(){},suspendInstance(){},waitForCommitToBeReady(){return null},rendererPackageName:sa.name,rendererVersion:sa.version});import Mg from"widest-line";import Og from"indent-string";import we from"yoga-layout";import dn from"yoga-layout";var Rg=o(e=>e.getComputedWidth()-e.getComputedPadding(dn.EDGE_LEFT)-e.getComputedPadding(dn.EDGE_RIGHT)-e.getComputedBorder(dn.EDGE_LEFT)-e.getComputedBorder(dn.EDGE_RIGHT),"getMaxWidth"),ca=Rg;import _g from"cli-boxes";import un from"chalk";var Ag=o((e,t,n,r)=>{if(n.style.borderStyle){let i=n.yogaNode.getComputedWidth(),s=n.yogaNode.getComputedHeight(),a=typeof n.style.borderStyle=="string"?_g[n.style.borderStyle]:n.style.borderStyle,c=n.style.borderTopColor??n.style.borderColor,d=n.style.borderBottomColor??n.style.borderColor,u=n.style.borderLeftColor??n.style.borderColor,l=n.style.borderRightColor??n.style.borderColor,f=n.style.borderTopDimColor??n.style.borderDimColor,m=n.style.borderBottomDimColor??n.style.borderDimColor,p=n.style.borderLeftDimColor??n.style.borderDimColor,g=n.style.borderRightDimColor??n.style.borderDimColor,v=n.style.borderTop!==!1,w=n.style.borderBottom!==!1,y=n.style.borderLeft!==!1,h=n.style.borderRight!==!1,b=i-(y?1:0)-(h?1:0),I=v?G((y?a.topLeft:"")+a.top.repeat(b)+(h?a.topRight:""),c,"foreground"):void 0;v&&f&&(I=un.dim(I));let _=s;v&&(_-=1),w&&(_-=1);let W=(G(a.left,u,"foreground")+`
|
|
552
|
+
`).repeat(_);p&&(W=un.dim(W));let H=(G(a.right,l,"foreground")+`
|
|
553
|
+
`).repeat(_);g&&(H=un.dim(H));let A=w?G((y?a.bottomLeft:"")+a.bottom.repeat(b)+(h?a.bottomRight:""),d,"foreground"):void 0;w&&m&&(A=un.dim(A));let Me=v?1:0;I&&r.write(e,t,I,{transformers:[]}),y&&r.write(e,t+Me,W,{transformers:[]}),h&&r.write(e+i-1,t+Me,H,{transformers:[]}),A&&r.write(e,t+s-1,A,{transformers:[]})}},"renderBorder"),da=Ag;var Pg=o((e,t,n,r)=>{if(!n.style.backgroundColor)return;let i=n.yogaNode.getComputedWidth(),s=n.yogaNode.getComputedHeight(),a=n.style.borderStyle&&n.style.borderLeft!==!1?1:0,c=n.style.borderStyle&&n.style.borderRight!==!1?1:0,d=n.style.borderStyle&&n.style.borderTop!==!1?1:0,u=n.style.borderStyle&&n.style.borderBottom!==!1?1:0,l=i-a-c,f=s-d-u;if(!(l>0&&f>0))return;let m=G(" ".repeat(l),n.style.backgroundColor,"background");for(let p=0;p<f;p++)r.write(e+a,t+d+p,m,{transformers:[]})},"renderBackground"),ua=Pg;function la(e){let{rawScrollTop:t,contentHeight:n,viewportHeight:r,previousScrollHeight:i,stickyScroll:s,clampMin:a,clampMax:c,virtualScrollWindowed:d,inWindowScrollTop:u,previousAppliedScrollTop:l,regionTop:f}=e,m=Math.max(0,n-r),p=Math.max(0,Math.min(Math.floor(t),m)),v=s&&n>=i?m:p,w=a!==void 0||c!==void 0?Math.max(a??0,Math.min(v,Math.min(m,c??m))):v,y=d&&u!==void 0,h=Math.max(0,Math.floor(u??0)),b=d?y?h:0:w,I=y?b:w,_=null;if(l!==void 0&&l!==I&&r>0){let W=f+r-1;W>=f&&(_={top:f,bottom:W,delta:I-l})}return{scrollHeight:n,viewportTop:w,appliedScrollTop:I,scrollTop:w,scrollOffsetY:b,scrollHint:_}}o(la,"computeScrollState");var Ng=o((e,t)=>{let n=e.childNodes[0]?.yogaNode;if(n){let r=n.getComputedLeft(),i=n.getComputedTop();t=`
|
|
554
|
+
`.repeat(i)+Og(t,r)}return t},"applyPaddingToText"),ln=o((e,t={})=>{if(t.skipStaticElements&&e.internal_static||e.yogaNode?.getDisplay()===we.DISPLAY_NONE)return"";let n="";if(e.nodeName==="ink-text")n=mt(e);else if(e.nodeName==="ink-box"||e.nodeName==="ink-root"){let r=e.style.flexDirection==="row"||e.style.flexDirection==="row-reverse"?" ":`
|
|
555
|
+
`;n=(e.style.flexDirection==="row-reverse"||e.style.flexDirection==="column-reverse"?[...e.childNodes].reverse():[...e.childNodes]).map(s=>ln(s,{parentRole:e.internal_accessibility?.role,skipStaticElements:t.skipStaticElements})).filter(Boolean).join(r)}if(e.internal_accessibility){let{role:r,state:i}=e.internal_accessibility;if(i){let a=Object.keys(i).filter(c=>i[c]).join(", ");a&&(n=`(${a}) ${n}`)}r&&r!==t.parentRole&&(n=`${r}: ${n}`)}return n},"renderNodeToScreenReaderOutput"),Tr=null,Rr=null;function fa(){Tr=null,Rr=null}o(fa,"resetScrollHint");function pa(){return Tr}o(pa,"getScrollHint");function ma(){return Rr}o(ma,"getScrollRepaint");var ha=o((e,t,n)=>{let{offsetX:r=0,offsetY:i=0,transformers:s=[],skipStaticElements:a}=n;if(a&&e.internal_static)return;let{yogaNode:c}=e;if(c){if(c.getDisplay()===we.DISPLAY_NONE)return;let d=r+c.getComputedLeft(),u=i+c.getComputedTop();e.internal_cursorAnchor&&(t.cursorPosition={x:d,y:u});let l=s;if(typeof e.internal_transform=="function"&&(l=[e.internal_transform,...s]),e.nodeName==="ink-text"){let p=mt(e);if(p.length>0){let g=Mg(p),v=ca(c);if(g>v){let w=e.style.textWrap??"wrap";p=nn(p,v,w)}p=Ng(e,p),t.write(d,u,p,{transformers:l})}return}let f=!1,m=0;if(e.nodeName==="ink-box"){ua(d,u,e,t),da(d,u,e,t);let p=e.style.overflowX??e.style.overflow,g=e.style.overflowY??e.style.overflow,v=p==="hidden"||p==="scroll",w=g==="hidden"||g==="scroll";if(g==="scroll"){let y=c.getComputedBorder(we.EDGE_TOP),h=c.getComputedBorder(we.EDGE_BOTTOM),b=Math.max(0,c.getComputedHeight()-y-h),I=e.attributes?.virtualScrollWindowed===!0,_=e.childNodes[0],W=Math.max(0,Math.floor(I?e.attributes?.scrollHeight??0:_?.yogaNode?.getComputedHeight()??e.attributes?.scrollHeight??0)),H=typeof e.scrollHeight=="number"?e.scrollHeight:W,A=la({rawScrollTop:e.scrollTop??e.attributes?.scrollTop??0,contentHeight:W,viewportHeight:b,previousScrollHeight:H,stickyScroll:e.stickyScroll??!!e.attributes?.stickyScroll,clampMin:e.attributes?.scrollClampMin,clampMax:e.attributes?.scrollClampMax,virtualScrollWindowed:I,inWindowScrollTop:e.attributes?.inWindowScrollTop,previousAppliedScrollTop:e.appliedScrollTop,regionTop:u+y});e.scrollHeight=A.scrollHeight,e.scrollViewportHeight=b,e.scrollViewportTop=A.viewportTop,e.appliedScrollTop=A.appliedScrollTop,A.scrollHint&&(Tr=A.scrollHint,Math.trunc(Number(e.attributes?.pendingScrollDelta??0))!==0&&(Rr={top:A.scrollHint.top,bottom:A.scrollHint.bottom})),e.attributes&&e.attributes.pendingScrollDelta&&(e.attributes.pendingScrollDelta=0),e.scrollTop=A.scrollTop,m=A.scrollOffsetY}if(v||w){let y=v?d+c.getComputedBorder(we.EDGE_LEFT):void 0,h=v?d+c.getComputedWidth()-c.getComputedBorder(we.EDGE_RIGHT):void 0,b=w?u+c.getComputedBorder(we.EDGE_TOP):void 0,I=w?u+c.getComputedHeight()-c.getComputedBorder(we.EDGE_BOTTOM):void 0;t.clip({x1:y,x2:h,y1:b,y2:I}),f=!0}}if(e.nodeName==="ink-root"||e.nodeName==="ink-box"){for(let p of e.childNodes)ha(p,t,{offsetX:d,offsetY:u-m,transformers:l,skipStaticElements:a});f&&t.unclip()}}},"renderNodeToOutput"),_r=ha;import $g from"slice-ansi";import Dg from"string-width";import{styledCharsFromTokens as Lg,styledCharsToString as Fg,tokenize as jg}from"@alcalzone/ansi-tokenize";var Ar=class{static{o(this,"OutputCaches")}widths=new Map;blockWidths=new Map;styledChars=new Map;getStyledChars(t){let n=this.styledChars.get(t);return n===void 0&&(n=Lg(jg(t)),this.styledChars.set(t,n)),n}getStringWidth(t){let n=this.widths.get(t);return n===void 0&&(n=Dg(t),this.widths.set(t,n)),n}getWidestLine(t){let n=this.blockWidths.get(t);if(n===void 0){let r=0;for(let i of t.split(`
|
|
556
|
+
`))r=Math.max(r,this.getStringWidth(i));n=r,this.blockWidths.set(t,n)}return n}},We=class{static{o(this,"Output")}width;height;operations=[];caches=new Ar;constructor(t){let{width:n,height:r}=t;this.width=n,this.height=r}write(t,n,r,i){let{transformers:s}=i;r&&this.operations.push({type:"write",x:t,y:n,text:r,transformers:s})}clip(t){this.operations.push({type:"clip",clip:t})}unclip(){this.operations.push({type:"unclip"})}getGrid(){let t=[];for(let r=0;r<this.height;r++){let i=[];for(let s=0;s<this.width;s++)i.push({type:"char",value:" ",fullWidth:!1,styles:[]});t.push(i)}let n=[];for(let r of this.operations)if(r.type==="clip"&&n.push(r.clip),r.type==="unclip"&&n.pop(),r.type==="write"){let{text:i,transformers:s}=r,{x:a,y:c}=r,d=i.split(`
|
|
557
|
+
`),u=n.at(-1);if(u){let f=typeof u?.x1=="number"&&typeof u?.x2=="number",m=typeof u?.y1=="number"&&typeof u?.y2=="number";if(f){let p=this.caches.getWidestLine(i);if(a+p<u.x1||a>u.x2)continue}if(m){let p=d.length;if(c+p<u.y1||c>u.y2)continue}if(f&&(d=d.map(p=>{let g=a<u.x1?u.x1-a:0,v=this.caches.getStringWidth(p),w=a+v>u.x2?u.x2-a:v;return $g(p,g,w)}),a<u.x1&&(a=u.x1)),m){let p=c<u.y1?u.y1-c:0,g=d.length,v=c+g>u.y2?u.y2-c:g;d=d.slice(p,v),c<u.y1&&(c=u.y1)}}let l=0;for(let[f,m]of d.entries()){let p=t[c+l];if(!p)continue;for(let w of s)m=w(m,f);let g=this.caches.getStyledChars(m),v=a;for(let w of g){p[v]=w;let y=Math.max(1,this.caches.getStringWidth(w.value));if(y>1)for(let h=1;h<y;h++)p[v+h]={type:"char",value:"",fullWidth:!1,styles:w.styles};v+=y}l++}}return t}get(){let t=this.getGrid();return{output:t.map(r=>{let i=r.filter(s=>s!==void 0);return Fg(i).trimEnd()}).join(`
|
|
558
|
+
`),height:t.length}}};var Z={Single:0,Wide:1,SpacerTail:2},Q={char:" ",width:Z.Single,style:"",hyperlink:void 0};function ga(e,t){if(e<0||t<0)throw new RangeError(`Screen dimensions must be non-negative (got width=${e}, height=${t})`);let n=new Array(e*t).fill(Q);return{width:e,height:t,cells:n}}o(ga,"createScreen");function Ce(e,t,n){if(!(t<0||n<0||t>=e.width||n>=e.height))return e.cells[n*e.width+t]}o(Ce,"cellAt");function ya(e,t){if(e<0||t<0)throw new RangeError(`Screen dimensions must be non-negative (got width=${e}, height=${t})`);let n=new Array(e*t).fill(Q),r=!1;return{width:e,height:t,setCellAt(i,s,a){if(r)throw new Error("ScreenBuilder.setCellAt called after build()");if(i<0||s<0||i>=e||s>=t)throw new RangeError(`ScreenBuilder.setCellAt out of bounds: (${i}, ${s}) on ${e}x${t}`);n[s*e+i]=a},build(){if(r)throw new Error("ScreenBuilder.build called twice");return r=!0,{width:e,height:t,cells:n}}}}o(ya,"createScreenBuilder");function*fn(e,t){let n=Math.max(e.width,t.width),r=Math.max(e.height,t.height);for(let i=0;i<r;i++)for(let s=0;s<n;s++){let a=Ce(e,s,i),c=Ce(t,s,i);Kg(a,c)||(yield{x:s,y:i,prev:a,next:c})}}o(fn,"diffEach");function wa(e,t,n,r){if(r===0||e.height===0)return e;let i=Math.max(0,t),s=Math.min(e.height-1,n);if(i>s)return e;let a=e.width,c=e.cells.slice(),d=s-i+1,u=o(l=>{for(let f=0;f<a;f++)c[l*a+f]=Q},"blankRow");if(Math.abs(r)>=d){for(let l=i;l<=s;l++)u(l);return{...e,cells:c}}if(r>0){for(let l=i;l<=s-r;l++)for(let f=0;f<a;f++)c[l*a+f]=e.cells[(l+r)*a+f]??Q;for(let l=s-r+1;l<=s;l++)u(l)}else{let l=-r;for(let f=s;f>=i+l;f--)for(let m=0;m<a;m++)c[f*a+m]=e.cells[(f-l)*a+m]??Q;for(let f=i;f<=i+l-1;f++)u(f)}return{...e,cells:c}}o(wa,"shiftRowsRegion");function Kg(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.char===t.char&&e.width===t.width&&e.style===t.style&&e.hyperlink===t.hyperlink}o(Kg,"cellsEqual");var Pr="\x1B]8;";function Bg(e){return e.endsWith("\x07")?e.slice(0,-1):e}o(Bg,"stripOsc8Terminator");function Xg(e){if(!e.startsWith(Pr))return;let t=e.slice(Pr.length),n=t.indexOf(";");if(n<0)return;let r=t.slice(n+1),i=Bg(r);return i.length>0?i:void 0}o(Xg,"parseOsc8Url");function Ug(e){if(e.value==="")return{char:"",width:Z.SpacerTail,style:"",hyperlink:void 0};let t="",n;for(let r of e.styles)if(r.code.startsWith(Pr)){let i=Xg(r.code);i!==void 0&&(n=i)}else t+=r.code;return{char:e.value,width:e.fullWidth?Z.Wide:Z.Single,style:t,hyperlink:n}}o(Ug,"styledCharToCell");function va(e){let t=e.getGrid(),n=e.width,r=e.height,i=ya(n,r),s=Math.min(t.length,r);for(let a=0;a<s;a++){let c=t[a];if(!c)continue;let d=Math.min(c.length,n);for(let u=0;u<d;u++){let l=c[u];if(!l)continue;let f=Ug(l);f.char===Q.char&&f.width===Q.width&&f.style===Q.style&&f.hyperlink===Q.hyperlink||i.setCellAt(u,a,f)}}return i.build()}o(va,"outputToScreen");var Wg=o((e,t,n)=>{if(e.yogaNode){if(t){let m=ln(e,{skipStaticElements:!0}),p=m===""?0:m.split(`
|
|
559
|
+
`).length,g="";return e.staticNode&&(g=ln(e.staticNode,{skipStaticElements:!1})),{output:m,outputHeight:p,staticOutput:g?`${g}
|
|
560
|
+
`:"",frame:void 0}}let r=new We({width:e.yogaNode.getComputedWidth(),height:e.yogaNode.getComputedHeight()});fa(),_r(e,r,{skipStaticElements:!0});let i;e.staticNode?.yogaNode&&(i=new We({width:e.staticNode.yogaNode.getComputedWidth(),height:e.staticNode.yogaNode.getComputedHeight()}),_r(e.staticNode,i,{skipStaticElements:!1}));let{output:s,height:a}=r.get(),c=va(r),d=n?.columns??e.yogaNode.getComputedWidth(),u=n?.rows??e.yogaNode.getComputedHeight(),l=r.cursorPosition,f={screen:c,viewport:{width:d,height:u},cursor:{x:0,y:c.height,visible:!1},scrollHint:pa(),scrollRepaint:ma(),...l?{inputCursor:{x:l.x,y:l.y}}:{}};return{output:s,outputHeight:a,staticOutput:i?`${i.get().output}
|
|
561
|
+
`:"",frame:f}}return{output:"",outputHeight:0,staticOutput:"",frame:void 0}},"renderer"),Mr=Wg;function U(...e){if(e.length===0)return"\x1B[";if(e.length===1)return`\x1B[${e[0]}`;let t=e.slice(0,-1),n=e[e.length-1];return`\x1B[${t.join(";")}${n}`}o(U,"csi");function ba(e=1){return e===0?"":U(e,"A")}o(ba,"cursorUp");function Hg(e=1){return e===0?"":U(e,"B")}o(Hg,"cursorDown");function zg(e=1){return e===0?"":U(e,"C")}o(zg,"cursorForward");function qg(e=1){return e===0?"":U(e,"D")}o(qg,"cursorBack");function ka(e){return U(e,"G")}o(ka,"cursorTo");var Vg=U("G"),xa=U("H");function Sa(e,t){let n="";return e<0?n+=qg(-e):e>0&&(n+=zg(e)),t<0?n+=ba(-t):t>0&&(n+=Hg(t)),n}o(Sa,"cursorMove");var Or=U(2,"K");function Ea(e){if(e<=0)return"";let t="";for(let n=0;n<e;n++)t+=Or,n<e-1&&(t+=ba(1));return t+=Vg,t}o(Ea,"eraseLines");var Ia=U("r"),Ca="\x1B7",Ta="\x1B8";function Ra(e,t){return U(e,t,"r")}o(Ra,"setScrollRegion");function _a(e=1){return U(e,"S")}o(_a,"scrollUp");function Aa(e=1){return U(e,"T")}o(Aa,"scrollDown");var yt=U(0,"m");function Pa(e){return`\x1B]${e.join(";")}\x07`}o(Pa,"osc");function Gg(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}o(Gg,"osc8Id");function wt(e,t){if(!e)return He;let n={id:Gg(e),...t??{}},r=Object.entries(n).map(([i,s])=>`${i}=${s}`).join(":");return Pa(["8",r,e])}o(wt,"link");var He=Pa(["8","",""]);function Nr(e){let{screen:t}=e;if(t.width===0||t.height===0)return[];let n=[],r="",i;for(let s=0;s<t.height;s++){let a="";for(let c=0;c<t.width;c++){let d=Ce(t,c,s);!d||d.width===Z.SpacerTail||(d.hyperlink!==i&&(i!==void 0&&(a+=He),d.hyperlink!==void 0&&(a+=wt(d.hyperlink)),i=d.hyperlink),d.style!==r&&(r!==""&&(a+=yt),d.style!==""&&(a+=d.style),r=d.style),a+=d.char)}i!==void 0&&(a+=He,i=void 0),r!==""&&(a+=yt,r=""),n.push(a.trimEnd())}return[{type:"stdout",content:n.join(`
|
|
562
|
+
`)}]}o(Nr,"renderFullFrame");var Yg=Object.freeze([]),Jg=Object.freeze([]);function Te(e,t){if(e===t)return{patches:Yg,current:e};let n=[];return e!==""&&n.push({type:"stdout",content:yt}),t!==""&&n.push({type:"stdout",content:t}),{patches:n,current:t}}o(Te,"transitionStyle");function bt(e,t){let n=Te(e,t),r="";for(let i of n.patches)i.type==="stdout"&&(r+=i.content);return{str:r,current:n.current}}o(bt,"transitionStyleStr");function ae(e,t){if(e===t)return{patches:Jg,current:e};let n=[];return e!==void 0&&n.push({type:"stdout",content:He}),t!==void 0&&n.push({type:"stdout",content:wt(t)}),{patches:n,current:t}}o(ae,"transitionHyperlink");function Ma(e){let t=e.codePointAt(0);if(t===void 0)return!1;if(t>=129648&&t<=129791||t>=129792&&t<=130047)return!0;if(e.length>=2){for(let n=0;n<e.length;n++)if(e.charCodeAt(n)===65039)return!0}return!1}o(Ma,"needsWidthCompensation");var Re=class{static{o(this,"VirtualScreen")}viewportWidth;cursor;diff;_cursorMut;_diffMut=[];constructor(t,n){this.viewportWidth=n,this._cursorMut={x:t.x,y:t.y},this.cursor=this._cursorMut,this.diff=this._diffMut}txn(t){let[n,r]=t(this.cursor);for(let i of n)this._diffMut.push(i);this._cursorMut.x+=r.dx,this._cursorMut.y+=r.dy}},ce={type:"carriageReturn"},vt={type:"stdout",content:`
|
|
563
|
+
`};function kt(e,t,n){let r=t.width===Z.Wide?2:1,i=e.viewportWidth,s=!1;return e.txn(a=>{let c=a.x;if(r===2&&c<i){let l=t.char.length>2?i:i+1;if(c+2>=l)return[[],{dx:0,dy:0}]}let d=[];n.length>0&&d.push({type:"stdout",content:n});let u=r===2&&Ma(t.char);return u&&c+1<i&&(d.push({type:"cursorTo",col:c+2}),d.push({type:"stdout",content:" "}),d.push({type:"cursorTo",col:c+1})),d.push({type:"stdout",content:t.char}),u&&d.push({type:"cursorTo",col:c+r+1}),s=!0,c>=i?[d,{dx:r-c,dy:1}]:[d,{dx:r,dy:0}]}),s}o(kt,"writeCellWithStyleStr");function _e(e,t,n){e.txn(r=>{let i=t-r.x,s=n-r.y;return r.x>=e.viewportWidth?[[ce,{type:"cursorMove",x:t,y:s}],{dx:i,dy:s}]:s!==0?[[ce,{type:"cursorMove",x:t,y:s}],{dx:i,dy:s}]:[[{type:"cursorMove",x:i,y:s}],{dx:i,dy:s}]})}o(_e,"moveCursorTo");function xt(e,t,n,r,i=!1){let s="",a;for(let c=n;c<r;c++){if(e.cursor.y<c){let f=c-e.cursor.y;e.txn(m=>{let p=new Array(1+f);p[0]=ce;for(let g=0;g<f;g++)p[1+g]=vt;return[p,{dx:-m.x,dy:f}]})}for(let f=0;f<t.screen.width;f++){let m=Ce(t.screen,f,c);if(!m||m.width===Z.SpacerTail||m.char===" "&&m.style===""&&m.hyperlink===void 0)continue;_e(e,f,c);let p=ae(a,m.hyperlink);for(let v of p.patches)e.txn(()=>[[v],{dx:0,dy:0}]);a=p.current;let g=bt(s,m.style);kt(e,m,g.str)&&(s=g.current)}let d=Te(s,"");for(let f of d.patches)e.txn(()=>[[f],{dx:0,dy:0}]);s=d.current;let u=ae(a,void 0);for(let f of u.patches)e.txn(()=>[[f],{dx:0,dy:0}]);a=u.current;let l=c===r-1&&t.screen.height<=t.viewport.height&&(c+1>=t.viewport.height||i);e.txn(f=>l?[[ce],{dx:-f.x,dy:0}]:[[ce,vt],{dx:-f.x,dy:1}])}if(s!==""||a!==void 0){let c=Te(s,"");for(let u of c.patches)e.txn(()=>[[u],{dx:0,dy:0}]);let d=ae(a,void 0);for(let u of d.patches)e.txn(()=>[[u],{dx:0,dy:0}])}}o(xt,"renderFrameSlice");function $r(e,t,n,r){let i=Math.max(0,Math.floor(n)),s=Math.min(t.screen.height-1,t.viewport.height-1,Math.floor(r));for(let a=i;a<=s;a++)Qg(e,t,a)}o($r,"repaintFrameRows");function Qg(e,t,n){let r="",i;_e(e,0,n),e.txn(()=>[[{type:"stdout",content:He+yt},{type:"eraseLine"}],{dx:0,dy:0}]);for(let s=0;s<t.screen.width;s++){let a=Ce(t.screen,s,n);if(!a||a.width===Z.SpacerTail||a.char===" "&&a.style===""&&a.hyperlink===void 0)continue;_e(e,s,n);let c=ae(i,a.hyperlink);for(let u of c.patches)e.txn(()=>[[u],{dx:0,dy:0}]);i=c.current;let d=bt(r,a.style);kt(e,a,d.str)&&(r=d.current)}for(let s of Te(r,"").patches)e.txn(()=>[[s],{dx:0,dy:0}]);for(let s of ae(i,void 0).patches)e.txn(()=>[[s],{dx:0,dy:0}])}o(Qg,"repaintFrameRow");function Dr(e,t){let n="";for(let r=0;r<e.width;r++){let i=Ce(e,r,t);n+=i?.char??" "}return n.trimEnd()}o(Dr,"readLine");function ze(e,t,n=!1){let r=new Re({x:0,y:0},e.viewport.width);xt(r,e,0,e.screen.height,n);let i=[{type:"clearTerminal",reason:t}];for(let s of r.diff)i.push(s);return i}o(ze,"fullResetSequence_CAUSES_FLICKER");function pn(e,t){let n=e.cursor.y>=e.screen.height,r=t.screen.height>e.screen.height,i=t.screen.height<e.screen.height,s=n&&e.screen.height>=e.viewport.height,a=t.screen.height<=e.viewport.height,c=s?1:0;return{viewportY:r?Math.max(0,e.screen.height-e.viewport.height+c):Math.max(e.screen.height,t.screen.height)-t.viewport.height+c,cursorAtBottom:n,growing:r,shrinking:i,prevHadScrollback:s,nextFitsViewport:a}}o(pn,"computeViewportState");function Oa(e,t,n){if(t.viewport.height<e.viewport.height||e.viewport.width!==0&&t.viewport.width!==e.viewport.width)return{reset:!0,reason:"resize"};let r=pn(e,t);if(r.prevHadScrollback&&r.nextFitsViewport&&r.shrinking)return{reset:!0,reason:"offscreen"};if(e.screen.height>=e.viewport.height&&e.screen.height>0&&r.cursorAtBottom&&!r.growing){let s=e.screen.height-e.viewport.height+1;for(let a of fn(e.screen,t.screen))if(a.y<s)return{reset:!0,reason:"offscreen",trigger:{y:a.y,prevLine:n(e.screen,a.y),nextLine:n(t.screen,a.y)}}}return r.shrinking&&e.screen.height-t.screen.height>e.viewport.height?{reset:!0,reason:"offscreen"}:{reset:!1}}o(Oa,"shouldFullReset");function Na(e,t,n){return!!(t&&t.width===2||e&&e.width===2&&!t||t&&n&&!e)}o(Na,"shouldSkipDiff");var mn=class{static{o(this,"LogUpdate")}options;constructor(t){this.options=t}render(t,n,r={}){if(!this.options.isTTY)return Nr(n);let i=r.inlineBottomAnchored??!1,s=$a(t,i),a=$a(n,i);if(r.altScreen===!0&&t.screen.height===0&&a.screen.height>0)return ze(a,"clear",i);let c=Oa(s,a,Dr);if(c.reset)return ze(a,c.reason,i);if(a.scrollRepaint&&r.altScreen===!0)return Zg(s,a,a.scrollRepaint);let d=a.scrollHint;if(d&&r.altScreen&&r.decstbmSafe&&process.env.KODAX_SCROLL_DECSTBM==="1"&&d.delta!==0&&d.top>=0&&d.bottom<s.screen.height&&d.bottom<a.screen.height&&Math.abs(d.delta)<=d.bottom-d.top){let u={type:"scrollRegion",top:d.top,bottom:d.bottom,delta:d.delta},l={...s,screen:wa(s.screen,d.top,d.bottom,d.delta)};return[u,...Da(l,a,i)]}return Da(s,a,i)}reset(){}};function Lr(e,t){for(let n of t)e.txn(()=>[[n],{dx:0,dy:0}])}o(Lr,"emitPatches");function Fr(e,t,n){if(t!==""){let r=Te(t,"");Lr(e,r.patches)}if(n!==void 0){let r=ae(n,void 0);Lr(e,r.patches)}return{style:"",hyperlink:void 0}}o(Fr,"resetStyleAndHyperlink");function Zg(e,t,n){let r=pn(e,t),i=new Re(e.cursor,t.viewport.width);r.shrinking&&La(i,e,t);let s=Math.max(0,Math.floor(n.top)),a=Math.min(t.screen.height-1,t.viewport.height-1,Math.floor(n.bottom)),c=a>=s?{top:s,bottom:a}:void 0;c&&$r(i,t,c.top,c.bottom);let d=Fa(i,e,t,{...r,skipRows:c});return d.needsFullReset?ze(t,"offscreen"):(Fr(i,d.currentStyle,d.currentHyperlink),r.growing&&xt(i,t,e.screen.height,t.screen.height),ja(i,t),i.diff)}o(Zg,"renderScrollRepaint");function La(e,t,n){let r=t.screen.height-n.screen.height;e.txn(i=>[[{type:"clear",count:r},{type:"cursorMove",x:0,y:-1}],{dx:-i.x,dy:-r}])}o(La,"applyShrink");function Fa(e,t,n,r){let i="",s,a=!1;for(let c of fn(t.screen,n.screen)){let{x:d,y:u,prev:l,next:f}=c;if(r.growing&&u>=t.screen.height||r.skipRows&&u>=r.skipRows.top&&u<=r.skipRows.bottom)continue;let m=!!(f&&f.char===" "&&f.style===""&&f.hyperlink===void 0);if(!Na(l,f,m)){if(u<r.viewportY){a=!0;break}if(_e(e,d,u),f){let p=ae(s,f.hyperlink);Lr(e,p.patches),s=p.current;let g=bt(i,f.style);kt(e,f,g.str)&&(i=g.current)}else if(l){let p=Fr(e,i,s);i=p.style,s=p.hyperlink,e.txn(()=>[[{type:"stdout",content:" "}],{dx:1,dy:0}])}}}return{currentStyle:i,currentHyperlink:s,needsFullReset:a}}o(Fa,"diffPass");function $a(e,t){let n=t?Math.max(0,Math.min(e.viewport.height-1,e.screen.height-1)):Math.max(0,e.viewport.height-1);return e.cursor.y<=n?e:{...e,cursor:{...e.cursor,y:n}}}o($a,"clampRestingCursor");function ja(e,t){t.cursor.y>=t.screen.height?e.txn(n=>{let r=t.cursor.y-n.y;if(r>0){let s=new Array(1+r);s[0]=ce;for(let a=0;a<r;a++)s[1+a]=vt;return[s,{dx:-n.x,dy:r}]}let i=t.cursor.y-n.y;return i!==0||n.x!==t.cursor.x?[[ce,{type:"cursorMove",x:t.cursor.x,y:i}],{dx:t.cursor.x-n.x,dy:i}]:[[],{dx:0,dy:0}]}):_e(e,t.cursor.x,t.cursor.y)}o(ja,"restoreCursor");function Da(e,t,n=!1){let r=pn(e,t),i=new Re(e.cursor,t.viewport.width);r.shrinking&&La(i,e,t);let s=Fa(i,e,t,r);return s.needsFullReset?ze(t,"offscreen",n):(Fr(i,s.currentStyle,s.currentHyperlink),r.growing&&xt(i,t,e.screen.height,t.screen.height,n),ja(i,t),i.diff)}o(Da,"renderIncremental");var ey="\x1B[?25l",ty="\x1B[?25h",ny=`\x1B[2J${xa}`,ry="\x1B[?2026h",oy="\x1B[?2026l";function iy(e){switch(e.type){case"stdout":return e.content;case"carriageReturn":return"\r";case"cursorHide":return ey;case"cursorShow":return ty;case"cursorMove":return Sa(e.x,e.y);case"cursorTo":return ka(e.col);case"eraseLine":return Or;case"clear":return Ea(e.count);case"clearTerminal":return ny;case"hyperlink":return wt(e.uri);case"scrollRegion":{let t=e.top+1,n=e.bottom+1,r=Math.abs(e.delta),i=e.delta>0?_a(r):Aa(r);return Ca+Ra(t,n)+i+Ia+Ta}}}o(iy,"patchToBytes");function hn(e,t,n=!1){let r="",i=!1;for(let s of t)s.type==="clearTerminal"&&(i=!0),r+=iy(s);if(r.length!==0){if(n&&i){e.write(ry+r+oy);return}e.write(r)}}o(hn,"applyDiff");function Ka(e,t,n={}){if(t===void 0)return!1;let r=e.cellLogUpdate.render(e.prevFrame,t,n);return hn(e.stdout,r,n.synchronized??!1),e.prevFrame=t,!0}o(Ka,"applyCellFrame");function St(e,t){return{screen:ga(0,0),viewport:{width:t,height:e},cursor:{x:0,y:0,visible:!0}}}o(St,"emptyFrame");import sy from"is-in-ci";var de="\x1B[?2026h",ee="\x1B[?2026l";function ue(e){return"isTTY"in e&&e.isTTY===!0&&!sy}o(ue,"shouldSynchronize");var ay=new WeakMap,Ba=ay;import{EventEmitter as Ty}from"node:events";import Ry from"node:process";import Ae,{useState as Br,useRef as qe,useCallback as M,useMemo as Ve,useEffect as ic}from"react";import _y from"cli-cursor";var cy=o(e=>e>=48&&e<=63,"isCsiParameterByte"),dy=o(e=>e>=32&&e<=47,"isCsiIntermediateByte"),Ua=o(e=>e>=64&&e<=126,"isCsiFinalByte");function uy(e,t,n){let r=t+n+1,i=r;for(;i<e.length;i+=1){let s=e.codePointAt(i);if(s===void 0)return"pending";if(!(cy(s)||dy(s))&&!(s===91&&i===r))return Ua(s)?{sequence:e.slice(t,i+1),nextIndex:i+1}:void 0}return"pending"}o(uy,"parseCsiSequence");function ly(e,t,n){let r=t+n+2;if(r>e.length)return"pending";let i=e.codePointAt(r-1);if(!(i===void 0||!Ua(i)))return{sequence:e.slice(t,r),nextIndex:r}}o(ly,"parseSs3Sequence");function Xa(e,t,n){let r=e[t+n];if(r===void 0)return"pending";if(r==="[")return uy(e,t,n);if(r==="O")return ly(e,t,n)}o(Xa,"parseControlSequence");function fy(e,t){let n=e.codePointAt(t+1),r=n!==void 0&&n>65535?2:1,i=t+1+r;return{sequence:e.slice(t,i),nextIndex:i}}o(fy,"parseEscapedCodePoint");function py(e){let t=[],n=0,r=o(i=>({events:t,pending:e.slice(i)}),"pendingFrom");for(;n<e.length;){let i=e.indexOf("\x1B",n);if(i===-1)return t.push(e.slice(n)),{events:t,pending:""};if(i>n&&t.push(e.slice(n,i)),i===e.length-1)return r(i);let s=Xa(e,i,1);if(s==="pending")return r(i);if(s){t.push(s.sequence),n=s.nextIndex;continue}if(e[i+1]==="\x1B"){if(i+2>=e.length)return r(i);let d=Xa(e,i,2);if(d==="pending")return r(i);if(d){t.push(d.sequence),n=d.nextIndex;continue}t.push(e.slice(i,i+2)),n=i+2;continue}let c=fy(e,i);t.push(c.sequence),n=c.nextIndex}return{events:t,pending:""}}o(py,"parseKeypresses");function gn(){let e="";return{push(t){let n=py(e+t);return e=n.pending,n.events},hasPendingEscape(){return e.startsWith("\x1B")},flushPendingEscape(){if(!e.startsWith("\x1B"))return;let t=e;return e="",t},reset(){e=""}}}o(gn,"createInputParser");import{createContext as my}from"react";var Wa=my({exit(){}});Wa.displayName="InternalAppContext";var Ha=Wa;import{EventEmitter as hy}from"node:events";import{createContext as gy}from"react";var yy={isTTY:!1,isRaw:!1,on(){},off(){},pause(){},resume(){},setRawMode(){}},za=gy({stdin:yy,internal_eventEmitter:new hy,setRawMode(){},isRawModeSupported:!1,internal_exitOnCtrlC:!0});za.displayName="InternalStdinContext";var qa=za;import{createContext as wy}from"react";var vy={isTTY:!1,columns:80,rows:24,write(){return!0},on(){},off(){}},Va=wy({stdout:vy,write(){}});Va.displayName="InternalStdoutContext";var Ga=Va;import{createContext as by}from"react";var ky={isTTY:!1,write(){return!0},on(){},off(){}},Ya=by({stderr:ky,write(){}});Ya.displayName="InternalStderrContext";var Ja=Ya;import{createContext as xy}from"react";var Qa=xy({activeId:void 0,add(){},remove(){},activate(){},deactivate(){},enableFocus(){},disableFocus(){},focusNext(){},focusPrevious(){},focus(){}});Qa.displayName="InternalFocusContext";var Za=Qa;import{createContext as Sy}from"react";var ec=Sy({setCursorPosition(){}});ec.displayName="InternalCursorContext";var tc=ec;import Iy,{PureComponent as Cy}from"react";import*as yn from"node:fs";import{cwd as oc}from"node:process";import N from"react";import nc from"stack-utils";import Ey from"code-excerpt";var jr=o(e=>e?.replace(`file://${oc()}/`,""),"cleanupPath"),rc=new nc({cwd:oc(),internals:nc.nodeInternals()});function Kr({error:e}){let t=e.stack?e.stack.split(`
|
|
564
|
+
`).slice(1):void 0,n=t?rc.parseLine(t[0]):void 0,r=jr(n?.file),i,s=0;if(r&&n?.line&&yn.existsSync(r)){let a=yn.readFileSync(r,"utf8");if(i=Ey(a,n.line),i)for(let{line:c}of i)s=Math.max(s,String(c).length)}return N.createElement(q,{flexDirection:"column",padding:1},N.createElement(q,null,N.createElement(K,{backgroundColor:"red",color:"white"}," ","ERROR"," "),N.createElement(K,null," ",e.message)),n&&r&&N.createElement(q,{marginTop:1},N.createElement(K,{dimColor:!0},r,":",n.line,":",n.column)),n&&i&&N.createElement(q,{marginTop:1,flexDirection:"column"},i.map(({line:a,value:c})=>N.createElement(q,{key:a},N.createElement(q,{width:s+1},N.createElement(K,{dimColor:a!==n.line,backgroundColor:a===n.line?"red":void 0,color:a===n.line?"white":void 0,"aria-label":a===n.line?`Line ${a}, error`:`Line ${a}`},String(a).padStart(s," "),":")),N.createElement(K,{key:a,backgroundColor:a===n.line?"red":void 0,color:a===n.line?"white":void 0}," "+c)))),e.stack&&N.createElement(q,{marginTop:1,flexDirection:"column"},e.stack.split(`
|
|
565
|
+
`).slice(1).map(a=>{let c=rc.parseLine(a);return c?N.createElement(q,{key:a},N.createElement(K,{dimColor:!0},"- "),N.createElement(K,{dimColor:!0,bold:!0},c.function),N.createElement(K,{dimColor:!0,color:"gray","aria-label":`at ${jr(c.file)??""} line ${c.line} column ${c.column}`}," ","(",jr(c.file)??"",":",c.line,":",c.column,")")):N.createElement(q,{key:a},N.createElement(K,{dimColor:!0},"- "),N.createElement(K,{dimColor:!0,bold:!0},a,"\\t"," "))})))}o(Kr,"ErrorOverview");var Et=class extends Cy{static{o(this,"ErrorBoundary")}static displayName="InternalErrorBoundary";static getDerivedStateFromError(t){return{error:t}}state={error:void 0};componentDidCatch(t){this.props.onError(t)}render(){return this.state.error?Iy.createElement(Kr,{error:this.state.error}):this.props.children}};var Ay=" ",Py="\x1B[Z",My="\x1B";function sc({children:e,stdin:t,stdout:n,stderr:r,writeToStdout:i,writeToStderr:s,exitOnCtrlC:a,onExit:c,setCursorPosition:d}){let[u,l]=Br(!0),[f,m]=Br(void 0),[,p]=Br([]),g=qe(0),v=qe(0),w=qe(new Ty);w.current.setMaxListeners(1/0);let y=qe(void 0),h=qe(gn()),b=qe(void 0),I=M(()=>{b.current&&(clearImmediate(b.current),b.current=void 0)},[]),_=t.isTTY,W=M(()=>{y.current&&(t.removeListener("readable",y.current),y.current=void 0)},[t]),H=M(()=>{t.setRawMode(!1),W(),t.unref(),v.current=0,h.current.reset(),I()},[t,W,I]),A=M(x=>{_&&v.current>0&&H(),c(x)},[_,H,c]),Me=M(x=>{if(x===""&&a){A();return}x===My&&m(S=>S&&void 0)},[a,A]),Tt=M(x=>{Me(x),w.current.emit("input",x)},[Me]),no=M(()=>{I(),b.current=setImmediate(()=>{b.current=void 0;let x=h.current.flushPendingEscape();x&&Tt(x)})},[I,Tt]),En=M(()=>{I();let x;for(;(x=t.read())!==null;){let S=h.current.push(x);for(let E of S)Tt(E)}h.current.hasPendingEscape()&&no()},[t,Tt,I,no]),ro=M(x=>{if(!_)throw t===Ry.stdin?new Error(`Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.
|
|
30
566
|
Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`):new Error(`Raw mode is not supported on the stdin provided to Ink.
|
|
31
|
-
Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`);if(t.setEncoding("utf8"),
|
|
32
|
-
`;if(this.options.debug){
|
|
33
|
-
`,this.lastOutputHeight=
|
|
34
|
-
`).length,
|
|
35
|
-
`;if(this.lastOutputHeight>=this.options.stdout.rows&&
|
|
36
|
-
`)}this.kittyProtocolEnabled=!1,this.shellTransitionPhase=void 0,this.options.concurrent?
|
|
37
|
-
`),
|
|
38
|
-
`),
|
|
39
|
-
`)s.name="enter";else if(t===" ")s.name="tab";else if(t==="\b"||t==="\x1B\b")s.name="backspace",s.meta=t.charAt(0)==="\x1B";else if(t==="\x7F"||t==="\x1B\x7F")s.name="delete",s.meta=t.charAt(0)==="\x1B";else if(t==="\x1B"||t==="\x1B\x1B")s.name="escape",s.meta=t.length===2;else if(t===" "||t==="\x1B ")s.name="space",s.meta=t.length===2;else if(t.length===1&&t<="")s.name=String.fromCharCode(t.charCodeAt(0)+97-1),s.ctrl=!0;else if(t.length===1&&t>="0"&&t<="9")s.name="number";else if(t.length===1&&t>="a"&&t<="z")s.name=t;else if(t.length===1&&t>="A"&&t<="Z")s.name=t.toLowerCase(),s.shift=!0;else if(r=Rc.exec(t))s.meta=!0,s.shift=/^[A-Z]$/.test(r[1]??"");else if(r=bc.exec(t)){let c=[...t];c[0]==="\x1B"&&c[1]==="\x1B"&&(s.option=!0);let a=[r[1],r[2],r[4],r[6]].filter(Boolean).join(""),l=Number(r[3]||r[5]||1)-1;s.ctrl=!!(l&4),s.meta=!!(l&10),s.shift=!!(l&1),s.code=a,s.name=io[a]??"",s.shift=Ec(a)||s.shift,s.ctrl=vc(a)||s.ctrl}return s}i(Kt,"parseKeypress");var Fc=50;function zt(e){return{columns:e?.columns??80,rows:e?.rows??24}}i(zt,"resolveTerminalSize");var it=Pc(null),Wc={isTTY:!1,columns:80,rows:24,write:i(()=>!0,"write"),on:i(()=>{},"on"),off:i(()=>{},"off")};var mo={isTTY:!1,isRaw:!1,on:i(()=>{},"on"),off:i(()=>{},"off"),pause:i(()=>{},"pause"),resume:i(()=>{},"resume"),setRawMode:i(()=>{},"setRawMode")};function Dc(e){for(let t of e)if(t.rawMode)return!0;return!1}i(Dc,"hasRawModeSubscribers");function Hc({stdin:e,setRawMode:t,isRawModeSupported:r}){let n=new Set,o,s=!1,c=!1,a=i(f=>{for(let h of n)h.listener(f)},"handleData"),l=i(()=>{if(c){try{t(!1)}catch{}c=!1}},"disableRawModeIfOwned"),u=i(()=>{let f=o;f?.off?.("data",a),l(),s&&(f?.unref?.(),s=!1),o=void 0},"detachInput"),d=i(()=>{if(o&&o!==e&&u(),!e||n.size===0){u();return}if(o!==e&&(e.hasRef?.()!==!0&&typeof e.ref=="function"&&(e.ref(),s=!0),e.on?.("data",a),e.resume?.(),o=e),!(r&&Dc(n))){l();return}if(e.isRaw===!1&&!c)try{t(!0),c=!0}catch{c=!1}},"syncInputOwnership");return{subscribe(f,h={}){let p={listener:f,rawMode:h.rawMode!==!1};return n.add(p),d(),()=>{n.delete(p),d()}},dispose(){n.clear(),u()}}}i(Hc,"createTerminalInputController");var Bc=i(({children:e,runtime:t})=>{let[r,n]=Lc(()=>t.terminalSize);we(()=>{if(n(zt(t.stdout)),typeof t.stdout?.on!="function"||typeof t.stdout?.off!="function")return;let a=i(()=>{n(zt(t.stdout))},"handleResize");return t.stdout.on("resize",a),()=>{t.stdout.off?.("resize",a)}},[t.stdout]);let o=ho(a=>typeof t.stdout?.write!="function"?!1:(t.stdout.write(a),!0),[t.stdout]),s=fo(()=>Hc({stdin:t.stdin,setRawMode:t.setRawMode,isRawModeSupported:t.isRawModeSupported}),[t.stdin,t.isRawModeSupported,t.setRawMode]);we(()=>()=>{s.dispose()},[s]);let c=fo(()=>({stdout:t.stdout,stdin:t.stdin,setRawMode:t.setRawMode,isRawModeSupported:t.isRawModeSupported,exit:t.exit,terminalSize:r,isTTY:t.stdout?.isTTY===!0,writeRaw:o,subscribeInput:s.subscribe}),[s.subscribe,t.exit,t.isRawModeSupported,t.setRawMode,t.stdin,t.stdout,s.subscribe,r,o]);return po(it.Provider,{value:c,children:e})},"TuiRuntimeProvider");function Uc(e){let t=e?.stdout??Wc,r=e?.stdin??mo,n=i(s=>{typeof r?.setRawMode=="function"&&r.setRawMode(s)},"setRawMode"),o;return{stdout:t,stdin:r,setRawMode:n,isRawModeSupported:typeof r?.setRawMode=="function",exit:i(()=>{o?.()},"exit"),terminalSize:zt(t),isTTY:t?.isTTY===!0,writeRaw:i(s=>typeof t?.write!="function"?!1:(t.write(s),!0),"writeRaw"),subscribeInput:i(()=>()=>{},"subscribeInput"),attachExit(s){o=s}}}i(Uc,"createRuntimeValue");function st(e,t){let r=Uc(t),n=Gt(po(Bc,{runtime:r,children:e}),t);return r.attachExit(n.unmount),n}i(st,"render");var re=ro,H=no;function jc(e){let t={upArrow:e.name==="up",downArrow:e.name==="down",leftArrow:e.name==="left",rightArrow:e.name==="right",pageDown:e.name==="pagedown",pageUp:e.name==="pageup",home:e.name==="home",end:e.name==="end",return:e.name==="return",escape:e.name==="escape",ctrl:e.ctrl,shift:e.shift,tab:e.name==="tab",backspace:e.name==="backspace",delete:e.name==="delete",meta:e.meta||e.name==="escape"||e.option===!0,super:e.super??!1,hyper:e.hyper??!1,capsLock:e.capsLock??!1,numLock:e.numLock??!1,eventType:e.eventType},r="";return e.isKittyProtocol?e.isPrintable?r=e.text??e.name:e.ctrl&&e.name.length===1&&(r=e.name):e.ctrl?r=e.name:r=e.sequence,!e.isKittyProtocol&&so.includes(e.name)&&(r=""),r.startsWith("\x1B")&&(r=r.slice(1)),r.length===1&&typeof r[0]=="string"&&/[A-Z]/.test(r[0])&&(t.shift=!0),{input:r,key:t}}i(jc,"createCompatKeypress");function ct(e,t={}){let{isActive:r=!0}=t,n=ot(e),o=ot(null),s=ot(null);we(()=>{n.current=e},[e]),we(()=>{if(!r){o.current=null,s.current&&(clearTimeout(s.current),s.current=null);return}return o.current=tt(),()=>{o.current?.reset(),o.current=null,s.current&&(clearTimeout(s.current),s.current=null)}},[r]);let c=ho(a=>{let{input:l,key:u}=jc(Kt(a));n.current(l,u)},[]);Jt(a=>{if(!r)return;s.current&&(clearTimeout(s.current),s.current=null);let l=o.current,u=typeof a=="string"?a:a.toString("utf8"),d=l?.push(u)??[u];for(let f of d)c(f);u.length>0&&(s.current=setTimeout(()=>{let f=o.current?.flushPendingEscape();f&&c(f)},Fc))},{isActive:r,rawMode:!0})}i(ct,"useInput");function qt(){let e=Xt(it),t=e?.stdin??mo,r=e?.setRawMode??(n=>{typeof t?.setRawMode=="function"&&t.setRawMode(n)});return{stdin:t,setRawMode:r,isRawModeSupported:e?.isRawModeSupported??typeof t?.setRawMode=="function"}}i(qt,"useStdin");function at(){return{exit:Xt(it)?.exit??(()=>{})}}i(at,"useApp");function Jt(e,t={}){let{isActive:r=!0,rawMode:n=!0}=t,o=Xt(it),{stdin:s,setRawMode:c,isRawModeSupported:a}=qt(),l=ot(e);we(()=>{l.current=e},[e]),we(()=>{if(!r||!s)return;if(o)return o.subscribeInput(h=>{l.current(h)},{rawMode:n});let u=s,d=u.isRaw;n&&a&&d===!1&&c(!0);let f=i(h=>{l.current(h)},"handleData");return u.on?.("data",f),()=>{if(u.off?.("data",f),n&&a&&d===!1)try{c(!1)}catch{}}},[o,s,r,n,a,c])}i(Jt,"useTerminalInput");import{jsx as op}from"react/jsx-runtime";import{useInsertionEffect as sp,useMemo as cp}from"react";import{jsx as Vp,jsxs as $p}from"react/jsx-runtime";import{jsx as Tp}from"react/jsx-runtime";import Rp,{useEffect as bp,useImperativeHandle as Ep,useMemo as vp,useRef as Mp,useCallback as Ip,useState as Op}from"react";var Qt=class{static{i(this,"LRUCache")}capacity;cache;constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let r=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,r),r}set(t,r){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.capacity){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(t,r)}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear()}get size(){return this.cache.size}};var Yc=1e3;var Lp=new Qt(Yc);var Xc=40;function qc(e,t){let r=t.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean);return r.length===0?[...e]:e.filter(n=>{let o=[n.title,n.id,n.surface??"",n.createdAt??"",String(n.msgCount)].join(" ").toLocaleLowerCase();return r.every(s=>o.includes(s))})}i(qc,"filterSessionPickerItems");function Jc(e,t,r){let n=Math.max(1,r),o=e.length===0?0:Math.max(0,Math.min(t,e.length-1)),s=Math.floor(o/n)*n;return{items:e.slice(s,s+n),selectedIndex:o,pageStart:s,pageIndex:Math.floor(s/n),pageCount:Math.max(1,Math.ceil(e.length/n))}}i(Jc,"buildSessionPickerPage");function Qc(e){if(!e)return"unknown time";let t=new Date(e);if(Number.isNaN(t.getTime()))return e;let r=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getDate()).padStart(2,"0"),s=String(t.getHours()).padStart(2,"0"),c=String(t.getMinutes()).padStart(2,"0");return`${r}-${n}-${o} ${s}:${c}`}i(Qc,"formatTimestamp");function Zc({sessions:e,onSelect:t,onSelectionError:r,onCancel:n,pageSize:o=8}){let{exit:s}=at(),[c,a]=Zt(""),[l,u]=Zt(0),[d,f]=Zt(!1),h=zc(!1),p=Kc(()=>qc(e,c),[e,c]),x=Jc(p,l,o),T=p[x.selectedIndex];return ct((g,w)=>{if(!h.current){if(w.escape||w.ctrl&&g==="c"){n(),s();return}if(w.return){let m=p[x.selectedIndex];m&&(h.current=!0,f(!0),(async()=>{await new Promise(C=>setTimeout(C,Xc));try{await t(m)}catch(C){r(C)}finally{s()}})());return}if(w.upArrow)u(m=>Math.max(0,m-1));else if(w.downArrow)u(m=>Math.min(Math.max(0,p.length-1),m+1));else if(w.pageUp)u(m=>Math.max(0,m-o));else if(w.pageDown)u(m=>Math.min(Math.max(0,p.length-1),m+o));else if(w.home)u(0);else if(w.end)u(Math.max(0,p.length-1));else if(w.tab){let m=p[x.selectedIndex];m&&(a(m.title),u(0))}else w.backspace||w.delete?(a(m=>m.slice(0,-1)),u(0)):g&&!w.ctrl&&!w.meta&&!w.super&&(a(m=>m+g),u(0))}}),Se(re,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[Le(H,{bold:!0,color:"cyan",children:"Resume a session"}),Se(H,{children:["Search: ",Le(H,{color:"yellow",children:c||"type to filter"})]}),Le(H,{dimColor:!0,children:d?"Loading selected session...":"\u2191/\u2193 select \xB7 PgUp/PgDn page \xB7 Tab complete \xB7 Enter resume \xB7 Esc cancel"}),Se(re,{flexDirection:"column",marginTop:1,children:[x.items.length===0?Le(H,{color:"yellow",children:"No matching sessions."}):null,x.items.map((g,w)=>{let C=x.pageStart+w===x.selectedIndex,E=g.title.trim()||"Untitled session",M=g.surface?` \xB7 ${g.surface}`:"";return Se(H,{color:C?"cyan":void 0,bold:C,children:[C?"\u276F":" "," ",E," \xB7 ",g.msgCount," msgs",M," \xB7 ",Qc(g.createdAt)," \xB7 ",g.id.slice(0,8)]},g.id)})]}),Se(H,{dimColor:!0,children:[p.length," matches \xB7 Page ",x.pageIndex+1,"/",x.pageCount]}),Se(H,{dimColor:!0,children:["Selected ID: ",T?.id??"none"]})]})}i(Zc,"SessionPicker");async function So(e,t={}){if(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0)throw new Error("Searchable session resume requires an interactive terminal. Pass an exact session ID or title to -r/--resume instead.");let r,n=!1,o=!1,s,c=Math.max(4,Math.min(12,(process.stdout.rows??24)-8)),a=st(Le(Zc,{sessions:e,pageSize:c,onSelect:i(async l=>{r=l,await t.prepareSelection?.(l)},"onSelect"),onSelectionError:i(l=>{o=!0,s=l},"onSelectionError"),onCancel:i(()=>{n=!0},"onCancel")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1,patchConsole:!1});try{await a.waitUntilExit()}finally{a.unmount(),a.cleanup()}if(o)throw s;if(!r&&!n)throw new Error("Session picker exited unexpectedly before selection or cancellation.");return r}i(So,"runSessionPicker");var yo=65536,To=48;function ta(){let e=process.env.KODAX_HOME,t=e&&e.length>0?e:Te.join(ea.homedir(),".kodax");return Te.join(t,"sessions")}i(ta,"defaultSessionsDir");function Co(e){return e.endsWith(".jsonl")&&!e.endsWith(".archive.jsonl")&&!e.endsWith(".islands.jsonl")&&!e.startsWith(".")}i(Co,"isSessionFile");async function ra(e){let t=[],r;try{r=await ye.readdir(e,{withFileTypes:!0})}catch{return t}for(let n of r){let o=Te.join(e,n.name);if(n.isFile()&&Co(n.name)&&!n.name.startsWith("archived-")){t.push(o);continue}if(!(!n.isDirectory()||n.name.startsWith(".")||n.name==="archived"))try{for(let s of await ye.readdir(o,{withFileTypes:!0}))s.isFile()&&Co(s.name)&&t.push(Te.join(o,s.name))}catch{}}return t}i(ra,"collectActiveSessionFiles");function Ro(e){if(!e?.trim())return;let t=Te.resolve(e).replace(/\\/g,"/");return process.platform==="win32"||process.platform==="darwin"?t.toLowerCase():t}i(Ro,"normalizeComparableRoot");function na(e,t){let r=Ro(t);if(!r)return!0;let n=e.runtimeInfo!==null&&typeof e.runtimeInfo=="object"?e.runtimeInfo:void 0;return[typeof n?.canonicalRepoRoot=="string"?n.canonicalRepoRoot:void 0,typeof n?.workspaceRoot=="string"?n.workspaceRoot:void 0,typeof e.gitRoot=="string"?e.gitRoot:void 0].some(s=>Ro(s)===r)}i(na,"matchesProjectRoot");async function oa(e){let t;try{t=await ye.open(e,"r");let r=Buffer.allocUnsafe(yo),{bytesRead:n}=await t.read(r,0,yo,0);if(n===0)return;let o=r.toString("utf8",0,n),s=o.indexOf(`
|
|
40
|
-
`);if(s>=0)return
|
|
41
|
-
`);return(
|
|
42
|
-
`).length-1-
|
|
567
|
+
Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`);if(t.setEncoding("utf8"),x){v.current===0&&(t.ref(),t.setRawMode(!0),y.current=En,t.addListener("readable",En)),v.current++;return}v.current!==0&&--v.current===0&&H()},[_,t,En,H]),oo=M((x,S)=>{let E=x.findIndex($=>$.id===S);for(let $=E+1;$<x.length;$++){let te=x[$];if(te?.isActive)return te.id}},[]),io=M((x,S)=>{let E=x.findIndex($=>$.id===S);for(let $=E-1;$>=0;$--){let te=x[$];if(te?.isActive)return te.id}},[]),Rt=M(()=>{p(x=>(m(S=>{let E=x.find(te=>te.isActive)?.id;return oo(x,S)??E}),x))},[oo]),_t=M(()=>{p(x=>(m(S=>{let E=x.findLast(te=>te.isActive)?.id;return io(x,S)??E}),x))},[io]);ic(()=>{let x=o(E=>{!u||g.current===0||(E===Ay&&Rt(),E===Py&&_t())},"handleTabNavigation");w.current.on("input",x);let S=w.current;return()=>{S.off("input",x)}},[u,Rt,_t]);let so=M(()=>{l(!0)},[]),ao=M(()=>{l(!1)},[]),co=M(x=>{p(S=>(S.some($=>$?.id===x)&&m(x),S))},[]),uo=M((x,{autoFocus:S})=>{p(E=>(g.current=E.length+1,[...E,{id:x,isActive:!0}])),S&&m(E=>E??x)},[]),lo=M(x=>{m(S=>S===x?void 0:S),p(S=>{let E=S.filter($=>$.id!==x);return g.current=E.length,E})},[]),fo=M(x=>{p(S=>S.map(E=>E.id!==x?E:{id:x,isActive:!0}))},[]),po=M(x=>{m(S=>S===x?void 0:S),p(S=>S.map(E=>E.id!==x?E:{id:x,isActive:!1}))},[]);ic(()=>()=>{_y.show(n),_&&v.current>0&&H()},[n,_,H]);let Lc=Ve(()=>({exit:A}),[A]),Fc=Ve(()=>({stdin:t,setRawMode:ro,isRawModeSupported:_,internal_exitOnCtrlC:a,internal_eventEmitter:w.current}),[t,ro,_,a]),jc=Ve(()=>({stdout:n,write:i}),[n,i]),Kc=Ve(()=>({stderr:r,write:s}),[r,s]),Bc=Ve(()=>({setCursorPosition:d}),[d]),Xc=Ve(()=>({activeId:f,add:uo,remove:lo,activate:fo,deactivate:po,enableFocus:so,disableFocus:ao,focusNext:Rt,focusPrevious:_t,focus:co}),[f,uo,lo,fo,po,so,ao,Rt,_t,co]);return Ae.createElement(Ha.Provider,{value:Lc},Ae.createElement(qa.Provider,{value:Fc},Ae.createElement(Ga.Provider,{value:jc},Ae.createElement(Ja.Provider,{value:Kc},Ae.createElement(Za.Provider,{value:Xc},Ae.createElement(tc.Provider,{value:Bc},Ae.createElement(Et,{onError:A},e)))))))}o(sc,"App");sc.displayName="InternalApp";var ac=sc;var Oy={disambiguateEscapeCodes:1,reportEventTypes:2,reportAlternateKeys:4,reportAllKeysAsEscapeCodes:8,reportAssociatedText:16};function cc(e){let t=0;for(let n of e)t|=Oy[n];return t}o(cc,"resolveFlags");var le={shift:1,alt:2,ctrl:4,super:8,hyper:16,meta:32,capsLock:64,numLock:128};var Xr=o((e,t)=>(t<0?B.cursorUp(-t):t>0?B.cursorDown(t):"")+(e<0?B.cursorBackward(-e):e>0?B.cursorForward(e):""),"cursorMoveSeq"),Ur=o((e,t=!1)=>{let n=Math.max(0,e.screen.height-e.viewport.height),r=t?Math.max(0,Math.min(e.viewport.height-1,e.screen.height-1)):Math.max(0,e.viewport.height-1);return i=>({x:i.x,y:Math.min(Math.max(i.y-n,0),r)})},"toVisibleCursor"),wn=o(()=>{},"noop"),Uy=27,Wy=91,Hy=63,zy=117,qy=48,Vy=57,Gy=o(e=>e>=qy&&e<=Vy,"isDigitByte"),uc=o((e,t)=>{if(e[t]!==Uy||e[t+1]!==Wy||e[t+2]!==Hy)return;let n=t+3,r=n;for(;n<e.length&&Gy(e[n]);)n++;if(n!==r){if(n===e.length)return{state:"partial"};if(e[n]===zy)return{state:"complete",endIndex:n}}},"matchKittyQueryResponse"),Yy=o(e=>{for(let t=0;t<e.length;t++)if(uc(e,t)?.state==="complete")return!0;return!1},"hasCompleteKittyQueryResponse"),Jy=o(e=>{let t=[],n=0;for(;n<e.length;){let r=uc(e,n);if(r?.state==="complete"){n=r.endIndex+1;continue}if(r?.state==="partial")break;t.push(e[n]),n++}return t},"stripKittyQueryResponsesAndTrailingPartial"),Wr=o(e=>e instanceof Error||Object.prototype.toString.call(e)==="[object Error]","isErrorInput"),Qy=class{static{o(this,"Ink")}isConcurrent;options;cursorPosition;isScreenReaderEnabled;isUnmounted;isUnmounting;lastOutput;lastOutputToRender;lastOutputHeight;lastTerminalWidth;container;rootNode;fullStaticOutput;exitPromise;exitResult;beforeExitHandler;restoreConsole;restoreStreamWriteGuard;rawStdoutWrite;rawStderrWrite;internalStreamWriteDepth=0;unsubscribeResize;throttledOnRender;hasPendingThrottledRender=!1;kittyProtocolEnabled=!1;cancelKittyDetection;altScreenActive=!1;shellMode;mouseTrackingActive=!1;shellTransitionPhase=void 0;cursorHidden=!1;constructor(t){$y(this),this.options=t,this.rawStdoutWrite=t.stdout.write.bind(t.stdout),this.rawStderrWrite=t.stderr.write.bind(t.stderr),this.rootNode=rn("ink-root"),this.rootNode.onComputeLayout=this.calculateLayout,this.isScreenReaderEnabled=t.isScreenReaderEnabled??Pe.env.INK_SCREEN_READER==="true";let n=t.debug||this.isScreenReaderEnabled,r=t.maxFps??30,i=r>0?Math.max(1,Math.ceil(1e3/r)):0;if(n)this.rootNode.onRender=this.onRender,this.throttledOnRender=void 0;else{let a=Ny(this.onRender,i,{leading:!0,trailing:!0});this.rootNode.onRender=()=>{this.hasPendingThrottledRender=!0,a()},this.throttledOnRender=a}this.rootNode.onImmediateRender=this.onRender,this.cellLogUpdate=new mn({isTTY:!!t.stdout.isTTY}),this.prevFrame=St(t.stdout.rows??24,t.stdout.columns??80),this.cursorPosition=void 0,this.isUnmounted=!1,this.isUnmounting=!1,this.installExternalStreamWriteGuard(),this.isConcurrent=t.concurrent??!1,this.lastOutput="",this.lastOutputToRender="",this.lastOutputHeight=0,this.lastTerminalWidth=this.getTerminalWidth(),this.fullStaticOutput="",this.shellMode=t.shellMode??"virtual";let s=t.concurrent?jy:Fy;this.container=se.createContainer(this.rootNode,s,null,!1,null,"id",()=>{},()=>{},()=>{},()=>{}),this.unsubscribeExit=Dy(this.unmount,{alwaysLast:!1}),tn()&&se.injectIntoDevTools(),t.patchConsole&&this.patchConsole(),fe||(t.stdout.on("resize",this.resized),this.unsubscribeResize=()=>{t.stdout.off("resize",this.resized)}),this.initKittyKeyboard()}getTerminalWidth=o(()=>this.options.stdout.columns?this.options.stdout.columns:Xy()?.columns??80,"getTerminalWidth");resized=o(()=>{let t=this.getTerminalWidth();if(t<this.lastTerminalWidth){this.returnCursorToRest();let n=this.altScreenActive?this.lastOutputHeight>0?B.eraseLines(this.lastOutputHeight):"":this.eraseInlineLiveBlock();n.length>0&&this.writeStdout(n),this.lastOutput="",this.lastOutputToRender="",this.cellLogUpdate.reset(),this.prevFrame=St(this.options.stdout.rows??24,t)}this.calculateLayout(),this.onRender(),this.lastTerminalWidth=t},"resized");resolveExitPromise=o(()=>{},"resolveExitPromise");rejectExitPromise=o(()=>{},"rejectExitPromise");unsubscribeExit=o(()=>{},"unsubscribeExit");handleAppExit=o(t=>{if(!(this.isUnmounted||this.isUnmounting)){if(Wr(t)){this.unmount(t);return}this.exitResult=t,this.unmount()}},"handleAppExit");setCursorPosition=o(t=>{if(t===void 0){this.cursorPosition=void 0;return}let n=this.getTerminalWidth(),r=this.options.stdout.rows??24;if(n<=0||r<=0){this.cursorPosition=void 0;return}let i=Math.max(0,Math.min(t.x|0,n-1)),s=Math.max(0,Math.min(t.y|0,r-1));this.cursorPosition={x:i,y:s}},"setCursorPosition");resetOutputTracking=o(()=>{this.lastOutput="",this.lastOutputToRender="",this.lastOutputHeight=0,this.cursorPosition=void 0,this.invalidateCellFrame()},"resetOutputTracking");usesVirtualShellOwnership=o((t={})=>t.altScreenActive??this.altScreenActive,"usesVirtualShellOwnership");beginShellTransition(t){this.shellTransitionPhase=t}setShellMode(t,n){let r=this.shellMode,i=this.mouseTrackingActive,s=this.usesVirtualShellOwnership(),a=n??!1;this.shellMode=t,this.mouseTrackingActive=a;let c=this.usesVirtualShellOwnership();(r!==t&&(s||c)||i!==a&&c)&&this.resetOutputTracking()}setAltScreenActive(t,n){let r=this.altScreenActive,i=this.mouseTrackingActive,s=this.usesVirtualShellOwnership(),a=n??!1;this.altScreenActive=t,this.mouseTrackingActive=a,this.shellTransitionPhase=void 0;let c=this.usesVirtualShellOwnership();(r!==t||i!==a&&(s||c))&&this.resetOutputTracking()}clearTextSelection(){}installExternalStreamWriteGuard(){if(this.options.debug||fe)return;let t=this.options.stdout,n=this.options.stderr,r=t.write,i=n.write,s=o((...c)=>{let d=this.rawStdoutWrite(...c);return this.internalStreamWriteDepth===0&&this.handleExternalStreamWrite(),d},"guardedStdoutWrite"),a=o((...c)=>{let d=this.rawStderrWrite(...c);return this.internalStreamWriteDepth===0&&this.handleExternalStreamWrite(),d},"guardedStderrWrite");t.write=s,n.write=a,this.restoreStreamWriteGuard=()=>{t.write===s&&(t.write=r),n.write===a&&(n.write=i)}}handleExternalStreamWrite(){this.isUnmounted||this.invalidateCellFrame()}withInternalStreamWrite(t){this.internalStreamWriteDepth+=1;try{return t()}finally{this.internalStreamWriteDepth-=1}}writeStdout(t,...n){return this.withInternalStreamWrite(()=>this.rawStdoutWrite(t,...n))}writeStderr(t,...n){return this.withInternalStreamWrite(()=>this.rawStderrWrite(t,...n))}restoreLastOutput=o(()=>{if(this.prevFrame.screen.height===0)return;let t=St(this.options.stdout.rows??24,this.getTerminalWidth()),n=this.cellLogUpdate.render(t,this.prevFrame);this.withInternalStreamWrite(()=>hn(this.options.stdout,n))},"restoreLastOutput");shouldRestoreManagedShellAfterExternalWrite=o(()=>this.altScreenActive,"shouldRestoreManagedShellAfterExternalWrite");calculateLayout=o(()=>{let t=this.getTerminalWidth();this.rootNode.yogaNode.setWidth(t),this.rootNode.yogaNode.calculateLayout(void 0,void 0,Ky.DIRECTION_LTR)},"calculateLayout");onRender=o(()=>{if(this.hasPendingThrottledRender=!1,this.isUnmounted)return;let t=performance.now(),n={rows:this.options.stdout.rows??24,columns:this.getTerminalWidth()},{output:r,outputHeight:i,staticOutput:s,frame:a}=Mr(this.rootNode,this.isScreenReaderEnabled,n);this.options.onRender?.({renderTime:performance.now()-t}),!fe&&!this.options.debug&&!this.isScreenReaderEnabled&&!this.cursorHidden&&(this.writeStdout(B.cursorHide),this.cursorHidden=!0);let c=s&&s!==`
|
|
568
|
+
`;if(this.options.debug){c&&(this.fullStaticOutput+=s),this.writeStdout(this.fullStaticOutput+r);return}if(fe){c&&this.writeStdout(s),this.lastOutput=r,this.lastOutputToRender=r+`
|
|
569
|
+
`,this.lastOutputHeight=i;return}if(this.isScreenReaderEnabled){let w=ue(this.options.stdout);if(w&&this.writeStdout(de),c){let b=this.lastOutputHeight>0?B.eraseLines(this.lastOutputHeight):"";this.writeStdout(b+s),this.lastOutputHeight=0}if(r===this.lastOutput&&!c){w&&this.writeStdout(ee);return}let y=this.getTerminalWidth(),h=By(r,y,{trim:!1,hard:!0});if(c)this.writeStdout(h);else{let b=this.lastOutputHeight>0?B.eraseLines(this.lastOutputHeight):"";this.writeStdout(b+h)}this.lastOutput=r,this.lastOutputToRender=h,this.lastOutputHeight=h===""?0:h.split(`
|
|
570
|
+
`).length,w&&this.writeStdout(ee);return}c&&(this.fullStaticOutput+=s);let u=!this.altScreenActive&&!!(a&&a.inputCursor)?[]:null,l=o(w=>{w&&(u?u.push(w):this.writeStdout(w))},"emit"),f=u?{write:l}:null;l(this.computeReturnToRestSeq());let m=this.altScreenActive,g=this.options.stdout.isTTY&&i>=this.options.stdout.rows&&m?r:r+`
|
|
571
|
+
`;if(this.lastOutputHeight>=this.options.stdout.rows&&m){if(Pe.env.KODAX_FULLSCREEN_CELLDIFF!=="0"&&this.altScreenActive&&this.fullStaticOutput===""){let h=ue(this.options.stdout);h&&this.writeStdout(de),this.applyCellFrame(a),h&&this.writeStdout(ee),this.lastOutput=r,this.lastOutputToRender=g,this.lastOutputHeight=i;return}let w=ue(this.options.stdout);w&&this.writeStdout(de);let y=this.fullStaticOutput+g;if(this.altScreenActive){let h=this.lastOutputHeight>0?B.eraseLines(this.lastOutputHeight):"";this.writeStdout(h+y)}else this.writeStdout(B.clearTerminal+this.fullStaticOutput+r);this.lastOutput=r,this.lastOutputToRender=this.altScreenActive?y:g,this.lastOutputHeight=i,this.invalidateCellFrame(),w&&this.writeStdout(ee);return}let v=!u&&ue(this.options.stdout);try{if(c?(v&&l(de),l(this.eraseInlineLiveBlock()+s),this.invalidateCellFrame(),this.applyCellFrame(a,f),v&&l(ee)):!this.altScreenActive&&this.prevFrame&&this.prevFrame.screen.height!==a.screen.height&&this.lastOutputHeight>0&&i<=this.options.stdout.rows&&this.lastOutputHeight<this.options.stdout.rows?(v&&l(de),l(this.eraseInlineLiveBlock()),this.invalidateCellFrame(),this.applyCellFrame(a,f),v&&l(ee)):this.applyCellFrame(a,f),a?.inputCursor){let w=Ur(a,!this.altScreenActive),y=w(a.cursor),h=w(a.inputCursor),b=Xr(h.x-y.x,h.y-y.y);l(b),this.displayCursor=h}}finally{u&&this.flushCursorTxn(u)}this.lastOutput=r,this.lastOutputToRender=g,this.lastOutputHeight=i},"onRender");applyCellFrame=o((t,n=null)=>{let r={cellLogUpdate:this.cellLogUpdate,prevFrame:this.prevFrame,stdout:n??this.options.stdout},i=ue(this.options.stdout),s={altScreen:this.altScreenActive,decstbmSafe:i,synchronized:n?!1:i,inlineBottomAnchored:!this.altScreenActive},a=this.withInternalStreamWrite(()=>Ka(r,t,s));return this.prevFrame=r.prevFrame,a},"applyCellFrame");invalidateCellFrame=o(()=>{this.cellLogUpdate.reset(),this.prevFrame=St(this.options.stdout.rows??24,this.getTerminalWidth())},"invalidateCellFrame");eraseInlineLiveBlock=o(()=>this.lastOutputHeight>0?B.eraseLines(this.lastOutputHeight):"","eraseInlineLiveBlock");commitInlineScrollback=o(({mode:t,text:n})=>{if(this.altScreenActive||this.isUnmounted)return;let r=[],i=o(c=>{c&&r.push(c)},"emit"),s={write:i};i(this.computeReturnToRestSeq());let a=t==="rebuild"?"\x1B[2J\x1B[3J\x1B[H":this.eraseInlineLiveBlock();i(a+(n??"")),this.lastOutput="",this.lastOutputToRender="",this.lastOutputHeight=0,this.fullStaticOutput="",this.invalidateCellFrame();try{this.calculateLayout();let c={rows:this.options.stdout.rows??24,columns:this.getTerminalWidth()},{output:d,outputHeight:u,frame:l}=Mr(this.rootNode,this.isScreenReaderEnabled,c);if(this.applyCellFrame(l,s),l?.inputCursor){let f=Ur(l,!this.altScreenActive),m=f(l.cursor),p=f(l.inputCursor),g=Xr(p.x-m.x,p.y-m.y);i(g),this.displayCursor=p}this.lastOutput=d,this.lastOutputToRender=d,this.lastOutputHeight=u}finally{this.flushCursorTxn(r)}},"commitInlineScrollback");flushCursorTxn(t){let n=t.join("");if(!n)return;let r=ue(this.options.stdout);this.writeStdout(r?de+n+ee:n)}render(t){let n=dc.createElement(Be.Provider,{value:{isScreenReaderEnabled:this.isScreenReaderEnabled}},dc.createElement(ac,{stdin:this.options.stdin,stdout:this.options.stdout,stderr:this.options.stderr,exitOnCtrlC:this.options.exitOnCtrlC,writeToStdout:this.writeToStdout,writeToStderr:this.writeToStderr,setCursorPosition:this.setCursorPosition,onExit:this.handleAppExit},t));this.options.concurrent?se.updateContainer(n,this.container,null,wn):(se.updateContainerSync(n,this.container,null,wn),se.flushSyncWork())}computeReturnToRestSeq(){if(this.displayCursor&&this.prevFrame){let t=Ur(this.prevFrame,!this.altScreenActive)(this.prevFrame.cursor),n=Xr(t.x-this.displayCursor.x,t.y-this.displayCursor.y);return this.displayCursor=null,n}return""}returnCursorToRest(){let t=this.computeReturnToRestSeq();t&&this.writeStdout(t)}writeToStdout(t){if(this.isUnmounted)return;if(this.options.debug){this.writeStdout(t+this.fullStaticOutput+this.lastOutput);return}if(fe){this.writeStdout(t);return}if(!this.shouldRestoreManagedShellAfterExternalWrite()){this.returnCursorToRest(),this.writeStdout(t),this.invalidateCellFrame();return}let n=ue(this.options.stdout);n&&this.writeStdout(de),this.returnCursorToRest();let r=this.lastOutputHeight>0?B.eraseLines(this.lastOutputHeight):"";this.writeStdout(r+t),this.restoreLastOutput(),this.invalidateCellFrame(),n&&this.writeStdout(ee)}writeToStderr(t){if(this.isUnmounted)return;if(this.options.debug){this.writeStderr(t),this.writeStdout(this.fullStaticOutput+this.lastOutput);return}if(fe){this.writeStderr(t);return}if(!this.shouldRestoreManagedShellAfterExternalWrite()){this.returnCursorToRest(),this.writeStderr(t),this.invalidateCellFrame();return}let n=ue(this.options.stdout);n&&this.writeStdout(de),this.returnCursorToRest();let r=this.lastOutputHeight>0?B.eraseLines(this.lastOutputHeight):"";r.length>0&&this.writeStdout(r),this.writeStderr(t),this.restoreLastOutput(),this.invalidateCellFrame(),n&&this.writeStdout(ee)}unmount(t){if(this.isUnmounted||this.isUnmounting)return;this.isUnmounting=!0,this.beforeExitHandler&&(Pe.off("beforeExit",this.beforeExitHandler),this.beforeExitHandler=void 0);let n=this.options.stdout,r=!n.destroyed&&!n.writableEnded&&(n.writable??!0);if(o(u=>{typeof u.flush=="function"&&(r?u.flush():typeof u.cancel=="function"&&u.cancel())},"settleThrottle")(this.throttledOnRender??{}),r&&(!this.throttledOnRender||!this.hasPendingThrottledRender&&this.fullStaticOutput==="")&&(this.calculateLayout(),this.onRender()),this.isUnmounted=!0,this.unsubscribeExit(),typeof this.restoreConsole=="function"&&this.restoreConsole(),typeof this.restoreStreamWriteGuard=="function"&&(this.restoreStreamWriteGuard(),this.restoreStreamWriteGuard=void 0),typeof this.unsubscribeResize=="function"&&this.unsubscribeResize(),this.cancelKittyDetection&&this.cancelKittyDetection(),r){if(this.kittyProtocolEnabled)try{this.writeStdout("\x1B[<u")}catch{}fe&&this.writeStdout(this.lastOutput+`
|
|
572
|
+
`)}this.kittyProtocolEnabled=!1,this.shellTransitionPhase=void 0,this.options.concurrent?se.updateContainer(null,this.container,null,wn):(se.updateContainerSync(null,this.container,null,wn),se.flushSyncWork()),Ba.delete(this.options.stdout);let{exitResult:s}=this,a=o(()=>{Wr(t)?this.rejectExitPromise(t):this.resolveExitPromise(s)},"resolveOrReject"),c=t!==void 0&&!Wr(t),d=n._writableState!==void 0||n.writableLength!==void 0;c?a():r&&d?this.writeStdout("",a):setImmediate(a)}async waitUntilExit(){return this.exitPromise||=new Promise((t,n)=>{this.resolveExitPromise=t,this.rejectExitPromise=n}),this.beforeExitHandler||(this.beforeExitHandler=()=>{this.unmount()},Pe.once("beforeExit",this.beforeExitHandler)),this.exitPromise}clear(){if(!fe&&!this.options.debug){this.returnCursorToRest();let t=this.altScreenActive?this.lastOutputHeight>0?B.eraseLines(this.lastOutputHeight):"":this.eraseInlineLiveBlock();t.length>0&&this.writeStdout(t),this.lastOutput="",this.lastOutputToRender="",this.lastOutputHeight=0,this.invalidateCellFrame()}}patchConsole(){this.options.debug||(this.restoreConsole=Ly((t,n)=>{t==="stdout"&&this.writeToStdout(n),t==="stderr"&&(n.startsWith("The above error occurred")||this.writeToStderr(n))}))}initKittyKeyboard(){if(!this.options.kittyKeyboard)return;let t=this.options.kittyKeyboard,n=t.mode??"auto";if(n==="disabled"||!this.options.stdin.isTTY||!this.options.stdout.isTTY)return;let r=t.flags??["disambiguateEscapeCodes"];if(n==="enabled"){this.enableKittyProtocol(r);return}let i=Pe.env.TERM??"",s=Pe.env.TERM_PROGRAM??"",a="KITTY_WINDOW_ID"in Pe.env||i==="xterm-kitty"||s==="WezTerm"||s==="ghostty";!fe&&a&&this.confirmKittySupport(r)}confirmKittySupport(t){let{stdin:n}=this.options,r=[],i=o(()=>{this.cancelKittyDetection=void 0,clearTimeout(a),n.removeListener("data",s);let c=Jy(r);r=[],c.length>0&&n.unshift(Buffer.from(c))},"cleanup"),s=o(c=>{let d=typeof c=="string"?Buffer.from(c):c;for(let u of d)r.push(u);Yy(r)&&(i(),this.isUnmounted||this.enableKittyProtocol(t))},"onData");n.on("data",s);let a=setTimeout(i,200);this.cancelKittyDetection=i,this.writeStdout("\x1B[?u")}enableKittyProtocol(t){this.writeStdout(`\x1B[>${cc(t)}u`),this.kittyProtocolEnabled=!0}},lc=Qy;var It=class{static{o(this,"KodaXRenderer")}engineInstance;isConcurrent;constructor(t){this.engineInstance=new lc(t),this.isConcurrent=this.engineInstance.isConcurrent}render=o(t=>{this.engineInstance.render(t)},"render");unmount=o(t=>{this.engineInstance.unmount(t)},"unmount");waitUntilExit=o(()=>this.engineInstance.waitUntilExit(),"waitUntilExit");clear=o(()=>{this.engineInstance.clear()},"clear");setAltScreenActive=o((t,n)=>{this.engineInstance.setAltScreenActive?.(t,n)},"setAltScreenActive");setShellMode=o((t,n)=>{this.engineInstance.setShellMode?.(t,n)},"setShellMode");beginShellTransition=o(t=>{this.engineInstance.beginShellTransition?.(t)},"beginShellTransition");clearTextSelection=o(()=>{this.engineInstance.clearTextSelection?.()},"clearTextSelection");commitInlineScrollback=o(t=>{this.engineInstance.commitInlineScrollback?.(t)},"commitInlineScrollback")};var ve=null;function pc(){if(ve===-1)return null;if(ve!==null)return ve;let e=process.env.KODAX_RENDER_TRACE;if(!e||e==="0"||e==="false")return ve=-1,null;let t=e==="1"||e==="true"?rw(nw(),`kodax-render-trace-${process.pid}.log`):e;try{return ve=ew(t,"a"),fc(ve,`=== KODAX render trace pid=${process.pid} ${new Date().toISOString()} platform=${process.platform} node=${process.version} ===
|
|
573
|
+
`),ve}catch{return ve=-1,null}}o(pc,"resolveTraceFd");function ow(e){let t=pc();if(t!==null)try{fc(t,e)}catch{}}o(ow,"traceLine");var Hr=new WeakMap,iw={isTTY:!1,columns:80,rows:24,write:o(()=>!0,"write"),on:o(()=>{},"on"),off:o(()=>{},"off")},sw={isTTY:!1,write:o(()=>!0,"write"),on:o(()=>{},"on"),off:o(()=>{},"off")},aw={isTTY:!1,isRaw:!1,on:o(()=>{},"on"),off:o(()=>{},"off"),pause:o(()=>{},"pause"),resume:o(()=>{},"resume"),setRawMode:o(()=>{},"setRawMode")};function cw(e={}){return e instanceof Zy?{stdout:e}:e}o(cw,"getOptions");function dw(e,t,n){let r=Hr.get(e);return r?r.isConcurrent!==n&&console.warn(`Warning: render() was called with concurrent: ${n}, but the existing renderer for this stdout uses concurrent: ${r.isConcurrent}. The concurrent option only takes effect on the first render. Call unmount() first if you need to change the rendering mode.`):(r=t(),Hr.set(e,r)),r}o(dw,"getInstance");function zr(e,t){let n={stdout:iw,stdin:aw,stderr:sw,debug:!1,exitOnCtrlC:!0,patchConsole:!1,maxFps:30,concurrent:!1,...cw(t)};if(pc()!==null){let s=n.stdout,a=s.write.bind(s),c=0,d=0;s.write=((m,...p)=>(c+=1,d+=typeof m=="string"?Buffer.byteLength(m,"utf8"):m?.length??0,a(m,...p)));let u=0,l=0,f=n.onRender;n.onRender=m=>{let p=tw.now(),g=u===0?0:p-u,v=s,w=v.columns??0,y=v.rows??0;return ow(`frame=${l} renderTime=${m.renderTime.toFixed(2)}ms interval=${g.toFixed(2)}ms writes=${c} bytes=${d} viewport=${w}x${y}
|
|
574
|
+
`),c=0,d=0,u=p,l+=1,f?.(m)}}let i=dw(n.stdout,()=>new It(n),n.concurrent??!1);return i.render(e),{rerender:i.render,unmount(){i.unmount()},waitUntilExit:i.waitUntilExit,cleanup:o(()=>{Hr.delete(n.stdout)},"cleanup"),clear:i.clear}}o(zr,"render");var mc=q,hc=K;import{Buffer as lw}from"node:buffer";var fw=/^(?:\x1b)([a-zA-Z0-9])$/,pw=/^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/,yc={OP:"f1",OQ:"f2",OR:"f3",OS:"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},wc=[...Object.values(yc),"backspace"],mw=o(e=>["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(e),"isShiftKey"),hw=o(e=>["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(e),"isCtrlKey"),vc=/^\x1b\[(\d+)(?:;(\d+)(?::(\d+))?(?:;([\d:]+))?)?u$/,gw=/^\x1b\[(\d+);(\d+):(\d+)([A-Za-z~])$/,yw={A:"up",B:"down",C:"right",D:"left",E:"clear",F:"end",H:"home",P:"f1",Q:"f2",R:"f3",S:"f4"},ww={2:"insert",3:"delete",5:"pageup",6:"pagedown",7:"home",8:"end",11:"f1",12:"f2",13:"f3",14:"f4",15:"f5",17:"f6",18:"f7",19:"f8",20:"f9",21:"f10",23:"f11",24:"f12"},gc={27:"escape",9:"tab",127:"delete",8:"backspace",57358:"capslock",57359:"scrolllock",57360:"numlock",57361:"printscreen",57362:"pause",57363:"menu",57376:"f13",57377:"f14",57378:"f15",57379:"f16",57380:"f17",57381:"f18",57382:"f19",57383:"f20",57384:"f21",57385:"f22",57386:"f23",57387:"f24"},bc=o(e=>e>=0&&e<=1114111&&!(e>=55296&&e<=57343),"isValidCodepoint"),qr=o(e=>bc(e)?String.fromCodePoint(e):"?","safeFromCodePoint");function kc(e){return e===3?"release":e===2?"repeat":"press"}o(kc,"resolveEventType");function xc(e){return{ctrl:!!(e&le.ctrl),shift:!!(e&le.shift),meta:!!(e&le.meta),option:!!(e&le.alt),super:!!(e&le.super),hyper:!!(e&le.hyper),capsLock:!!(e&le.capsLock),numLock:!!(e&le.numLock)}}o(xc,"parseKittyModifiers");function vw(e){let t=vc.exec(e);if(!t)return null;let n=Number.parseInt(t[1],10),r=t[2]?Math.max(0,Number.parseInt(t[2],10)-1):0,i=t[3]?Number.parseInt(t[3],10):1,s=t[4];if(!bc(n))return null;let a;s&&(a=s.split(":").map(u=>qr(Number.parseInt(u,10))).join(""));let c,d;return n===32?(c="space",d=!0):n===13?(c="return",d=!0):gc[n]?(c=gc[n],d=!1):n>=1&&n<=26?(c=String.fromCodePoint(n+96),d=!1):(c=qr(n).toLowerCase(),d=!0),d&&!a&&(a=qr(n)),{name:c,...xc(r),eventType:kc(i),sequence:e,raw:e,isKittyProtocol:!0,isPrintable:d,text:a}}o(vw,"parseKittyKeypress");function bw(e){let t=gw.exec(e);if(!t)return null;let n=Number.parseInt(t[1],10),r=Math.max(0,Number.parseInt(t[2],10)-1),i=Number.parseInt(t[3],10),s=t[4],a=s==="~"?ww[n]:yw[s];return a?{name:a,...xc(r),eventType:kc(i),sequence:e,raw:e,isKittyProtocol:!0,isPrintable:!1}:null}o(bw,"parseKittySpecialKey");var Vr="\x1B[200~",kw="\x1B[201~";function xw(e){if(!e.startsWith(Vr))return null;let t=e.indexOf(kw,Vr.length);return t===-1?null:e.slice(Vr.length,t)}o(xw,"extractBracketedPaste");function Gr(e=""){let t=e,n;if(lw.isBuffer(t)?t[0]>127&&t[1]===void 0?(t[0]-=128,t="\x1B"+String(t)):t=String(t):t!==void 0&&typeof t!="string"?t=String(t):t||(t=""),typeof t=="string"){let a=xw(t);if(a!==null)return{name:"paste",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:t,raw:t,isPaste:!0,isPrintable:!1,text:a}}let r=vw(t);if(r)return r;let i=bw(t);if(i)return i;if(vc.test(t))return{name:"",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:t,raw:t,isKittyProtocol:!0,isPrintable:!1};let s={name:"",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:t,raw:t};if(s.sequence=s.sequence||t||s.name,t==="\r"||t==="\x1B\r")s.raw=void 0,s.name="return",s.option=t.length===2;else if(t===`
|
|
575
|
+
`)s.name="enter";else if(t===" ")s.name="tab";else if(t==="\b"||t==="\x1B\b")s.name="backspace",s.meta=t.charAt(0)==="\x1B";else if(t==="\x7F"||t==="\x1B\x7F")s.name="delete",s.meta=t.charAt(0)==="\x1B";else if(t==="\x1B"||t==="\x1B\x1B")s.name="escape",s.meta=t.length===2;else if(t===" "||t==="\x1B ")s.name="space",s.meta=t.length===2;else if(t.length===1&&t<="")s.name=String.fromCharCode(t.charCodeAt(0)+97-1),s.ctrl=!0;else if(t.length===1&&t>="0"&&t<="9")s.name="number";else if(t.length===1&&t>="a"&&t<="z")s.name=t;else if(t.length===1&&t>="A"&&t<="Z")s.name=t.toLowerCase(),s.shift=!0;else if(n=fw.exec(t))s.meta=!0,s.shift=/^[A-Z]$/.test(n[1]??"");else if(n=pw.exec(t)){let a=[...t];a[0]==="\x1B"&&a[1]==="\x1B"&&(s.option=!0);let c=[n[1],n[2],n[4],n[6]].filter(Boolean).join(""),d=Number(n[3]||n[5]||1)-1;s.ctrl=!!(d&4),s.meta=!!(d&10),s.shift=!!(d&1),s.code=c,s.name=yc[c]??"",s.shift=mw(c)||s.shift,s.ctrl=hw(c)||s.ctrl}return s}o(Gr,"parseKeypress");var Iw=50;function Yr(e){return{columns:e?.columns??80,rows:e?.rows??24}}o(Yr,"resolveTerminalSize");var bn=Sw(null),Cw={isTTY:!1,columns:80,rows:24,write:o(()=>!0,"write"),on:o(()=>{},"on"),off:o(()=>{},"off")};var Cc={isTTY:!1,isRaw:!1,on:o(()=>{},"on"),off:o(()=>{},"off"),pause:o(()=>{},"pause"),resume:o(()=>{},"resume"),setRawMode:o(()=>{},"setRawMode")};function Tw(e){for(let t of e)if(t.rawMode)return!0;return!1}o(Tw,"hasRawModeSubscribers");function Rw({stdin:e,setRawMode:t,isRawModeSupported:n}){let r=new Set,i,s=!1,a=!1,c=o(f=>{for(let m of r)m.listener(f)},"handleData"),d=o(()=>{if(a){try{t(!1)}catch{}a=!1}},"disableRawModeIfOwned"),u=o(()=>{let f=i;f?.off?.("data",c),d(),s&&(f?.unref?.(),s=!1),i=void 0},"detachInput"),l=o(()=>{if(i&&i!==e&&u(),!e||r.size===0){u();return}if(i!==e&&(e.hasRef?.()!==!0&&typeof e.ref=="function"&&(e.ref(),s=!0),e.on?.("data",c),e.resume?.(),i=e),!(n&&Tw(r))){d();return}if(e.isRaw===!1&&!a)try{t(!0),a=!0}catch{a=!1}},"syncInputOwnership");return{subscribe(f,m={}){let p={listener:f,rawMode:m.rawMode!==!1};return r.add(p),l(),()=>{r.delete(p),l()}},dispose(){r.clear(),u()}}}o(Rw,"createTerminalInputController");var _w=o(({children:e,runtime:t})=>{let[n,r]=Ew(()=>t.terminalSize);Ge(()=>{if(r(Yr(t.stdout)),typeof t.stdout?.on!="function"||typeof t.stdout?.off!="function")return;let c=o(()=>{r(Yr(t.stdout))},"handleResize");return t.stdout.on("resize",c),()=>{t.stdout.off?.("resize",c)}},[t.stdout]);let i=Ic(c=>typeof t.stdout?.write!="function"?!1:(t.stdout.write(c),!0),[t.stdout]),s=Sc(()=>Rw({stdin:t.stdin,setRawMode:t.setRawMode,isRawModeSupported:t.isRawModeSupported}),[t.stdin,t.isRawModeSupported,t.setRawMode]);Ge(()=>()=>{s.dispose()},[s]);let a=Sc(()=>({stdout:t.stdout,stdin:t.stdin,setRawMode:t.setRawMode,isRawModeSupported:t.isRawModeSupported,exit:t.exit,terminalSize:n,isTTY:t.stdout?.isTTY===!0,writeRaw:i,subscribeInput:s.subscribe}),[s.subscribe,t.exit,t.isRawModeSupported,t.setRawMode,t.stdin,t.stdout,s.subscribe,n,i]);return Ec(bn.Provider,{value:a,children:e})},"TuiRuntimeProvider");function Aw(e){let t=e?.stdout??Cw,n=e?.stdin??Cc,r=o(s=>{typeof n?.setRawMode=="function"&&n.setRawMode(s)},"setRawMode"),i;return{stdout:t,stdin:n,setRawMode:r,isRawModeSupported:typeof n?.setRawMode=="function",exit:o(()=>{i?.()},"exit"),terminalSize:Yr(t),isTTY:t?.isTTY===!0,writeRaw:o(s=>typeof t?.write!="function"?!1:(t.write(s),!0),"writeRaw"),subscribeInput:o(()=>()=>{},"subscribeInput"),attachExit(s){i=s}}}o(Aw,"createRuntimeValue");function kn(e,t){let n=Aw(t),r=zr(Ec(_w,{runtime:n,children:e}),t);return n.attachExit(r.unmount),r}o(kn,"render");var be=mc,V=hc;function Pw(e){let t={upArrow:e.name==="up",downArrow:e.name==="down",leftArrow:e.name==="left",rightArrow:e.name==="right",pageDown:e.name==="pagedown",pageUp:e.name==="pageup",home:e.name==="home",end:e.name==="end",return:e.name==="return",escape:e.name==="escape",ctrl:e.ctrl,shift:e.shift,tab:e.name==="tab",backspace:e.name==="backspace",delete:e.name==="delete",meta:e.meta||e.name==="escape"||e.option===!0,super:e.super??!1,hyper:e.hyper??!1,capsLock:e.capsLock??!1,numLock:e.numLock??!1,eventType:e.eventType},n="";return e.isKittyProtocol?e.isPrintable?n=e.text??e.name:e.ctrl&&e.name.length===1&&(n=e.name):e.ctrl?n=e.name:n=e.sequence,!e.isKittyProtocol&&wc.includes(e.name)&&(n=""),n.startsWith("\x1B")&&(n=n.slice(1)),n.length===1&&typeof n[0]=="string"&&/[A-Z]/.test(n[0])&&(t.shift=!0),{input:n,key:t}}o(Pw,"createCompatKeypress");function xn(e,t={}){let{isActive:n=!0}=t,r=vn(e),i=vn(null),s=vn(null);Ge(()=>{r.current=e},[e]),Ge(()=>{if(!n){i.current=null,s.current&&(clearTimeout(s.current),s.current=null);return}return i.current=gn(),()=>{i.current?.reset(),i.current=null,s.current&&(clearTimeout(s.current),s.current=null)}},[n]);let a=Ic(c=>{let{input:d,key:u}=Pw(Gr(c));r.current(d,u)},[]);Zr(c=>{if(!n)return;s.current&&(clearTimeout(s.current),s.current=null);let d=i.current,u=typeof c=="string"?c:c.toString("utf8"),l=d?.push(u)??[u];for(let f of l)a(f);u.length>0&&(s.current=setTimeout(()=>{let f=i.current?.flushPendingEscape();f&&a(f)},Iw))},{isActive:n,rawMode:!0})}o(xn,"useInput");function Qr(){let e=Jr(bn),t=e?.stdin??Cc,n=e?.setRawMode??(r=>{typeof t?.setRawMode=="function"&&t.setRawMode(r)});return{stdin:t,setRawMode:n,isRawModeSupported:e?.isRawModeSupported??typeof t?.setRawMode=="function"}}o(Qr,"useStdin");function Sn(){return{exit:Jr(bn)?.exit??(()=>{})}}o(Sn,"useApp");function Zr(e,t={}){let{isActive:n=!0,rawMode:r=!0}=t,i=Jr(bn),{stdin:s,setRawMode:a,isRawModeSupported:c}=Qr(),d=vn(e);Ge(()=>{d.current=e},[e]),Ge(()=>{if(!n||!s)return;if(i)return i.subscribeInput(m=>{d.current(m)},{rawMode:r});let u=s,l=u.isRaw;r&&c&&l===!1&&a(!0);let f=o(m=>{d.current(m)},"handleData");return u.on?.("data",f),()=>{if(u.off?.("data",f),r&&c&&l===!1)try{a(!1)}catch{}}},[i,s,n,r,c,a])}o(Zr,"useTerminalInput");import{jsx as pW}from"react/jsx-runtime";import{useInsertionEffect as hW,useMemo as gW}from"react";import{jsx as eH,jsxs as tH}from"react/jsx-runtime";import{jsx as AW}from"react/jsx-runtime";import MW,{useEffect as OW,useImperativeHandle as NW,useMemo as $W,useRef as DW,useCallback as LW,useState as FW}from"react";var eo=class{static{o(this,"LRUCache")}capacity;cache;constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let n=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,n),n}set(t,n){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(t,n)}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear()}get size(){return this.cache.size}};var Mw=1e3;var WW=new eo(Mw);var Fw=40;function jw(e,t){let n=t.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean);return n.length===0?[...e]:e.filter(r=>{let i=[r.title,r.id,r.surface??"",r.createdAt??"",String(r.msgCount)].join(" ").toLocaleLowerCase();return n.every(s=>i.includes(s))})}o(jw,"filterSessionPickerItems");function Kw(e,t,n){let r=Math.max(1,n),i=e.length===0?0:Math.max(0,Math.min(t,e.length-1)),s=Math.floor(i/r)*r;return{items:e.slice(s,s+r),selectedIndex:i,pageStart:s,pageIndex:Math.floor(s/r),pageCount:Math.max(1,Math.ceil(e.length/r))}}o(Kw,"buildSessionPickerPage");function Bw(e){if(!e)return"unknown time";let t=new Date(e);if(Number.isNaN(t.getTime()))return e;let n=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),s=String(t.getHours()).padStart(2,"0"),a=String(t.getMinutes()).padStart(2,"0");return`${n}-${r}-${i} ${s}:${a}`}o(Bw,"formatTimestamp");function Xw({sessions:e,onSelect:t,onSelectionError:n,onCancel:r,pageSize:i=8}){let{exit:s}=Sn(),[a,c]=to(""),[d,u]=to(0),[l,f]=to(!1),m=Lw(!1),p=Dw(()=>jw(e,a),[e,a]),g=Kw(p,d,i),v=p[g.selectedIndex];return xn((w,y)=>{if(!m.current){if(y.escape||y.ctrl&&w==="c"){r(),s();return}if(y.return){let h=p[g.selectedIndex];h&&(m.current=!0,f(!0),(async()=>{await new Promise(b=>setTimeout(b,Fw));try{await t(h)}catch(b){n(b)}finally{s()}})());return}if(y.upArrow)u(h=>Math.max(0,h-1));else if(y.downArrow)u(h=>Math.min(Math.max(0,p.length-1),h+1));else if(y.pageUp)u(h=>Math.max(0,h-i));else if(y.pageDown)u(h=>Math.min(Math.max(0,p.length-1),h+i));else if(y.home)u(0);else if(y.end)u(Math.max(0,p.length-1));else if(y.tab){let h=p[g.selectedIndex];h&&(c(h.title),u(0))}else y.backspace||y.delete?(c(h=>h.slice(0,-1)),u(0)):w&&!y.ctrl&&!y.meta&&!y.super&&(c(h=>h+w),u(0))}}),Ye(be,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[Ct(V,{bold:!0,color:"cyan",children:"Resume a session"}),Ye(V,{children:["Search: ",Ct(V,{color:"yellow",children:a||"type to filter"})]}),Ct(V,{dimColor:!0,children:l?"Loading selected session...":"\u2191/\u2193 select \xB7 PgUp/PgDn page \xB7 Tab complete \xB7 Enter resume \xB7 Esc cancel"}),Ye(be,{flexDirection:"column",marginTop:1,children:[g.items.length===0?Ct(V,{color:"yellow",children:"No matching sessions."}):null,g.items.map((w,y)=>{let b=g.pageStart+y===g.selectedIndex,I=w.title.trim()||"Untitled session",_=w.surface?` \xB7 ${w.surface}`:"";return Ye(V,{color:b?"cyan":void 0,bold:b,children:[b?"\u276F":" "," ",I," \xB7 ",w.msgCount," msgs",_," \xB7 ",Bw(w.createdAt)," \xB7 ",w.id.slice(0,8)]},w.id)})]}),Ye(V,{dimColor:!0,children:[p.length," matches \xB7 Page ",g.pageIndex+1,"/",g.pageCount]}),Ye(V,{dimColor:!0,children:["Selected ID: ",v?.id??"none"]})]})}o(Xw,"SessionPicker");async function Ac(e,t={}){if(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0)throw new Error("Searchable session resume requires an interactive terminal. Pass an exact session ID or title to -r/--resume instead.");let n,r=!1,i=!1,s,a=Math.max(4,Math.min(12,(process.stdout.rows??24)-8)),c=kn(Ct(Xw,{sessions:e,pageSize:a,onSelect:o(async d=>{n=d,await t.prepareSelection?.(d)},"onSelect"),onSelectionError:o(d=>{i=!0,s=d},"onSelectionError"),onCancel:o(()=>{r=!0},"onCancel")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1,patchConsole:!1});try{await c.waitUntilExit()}finally{c.unmount(),c.cleanup()}if(i)throw s;if(!n&&!r)throw new Error("Session picker exited unexpectedly before selection or cancellation.");return n}o(Ac,"runSessionPicker");var Pc=65536,Mc=48;function Ww(){let e=process.env.KODAX_HOME,t=e&&e.length>0?e:Qe.join(Uw.homedir(),".kodax");return Qe.join(t,"sessions")}o(Ww,"defaultSessionsDir");function Oc(e){return e.endsWith(".jsonl")&&!e.endsWith(".archive.jsonl")&&!e.endsWith(".islands.jsonl")&&!e.startsWith(".")}o(Oc,"isSessionFile");async function Hw(e){let t=[],n;try{n=await Je.readdir(e,{withFileTypes:!0})}catch{return t}for(let r of n){let i=Qe.join(e,r.name);if(r.isFile()&&Oc(r.name)&&!r.name.startsWith("archived-")){t.push(i);continue}if(!(!r.isDirectory()||r.name.startsWith(".")||r.name==="archived"))try{for(let s of await Je.readdir(i,{withFileTypes:!0}))s.isFile()&&Oc(s.name)&&!s.name.startsWith("archived-")&&t.push(Qe.join(i,s.name))}catch{}}return t}o(Hw,"collectActiveSessionFiles");function Nc(e){if(!e?.trim())return;let t=Qe.resolve(e).replace(/\\/g,"/");return process.platform==="win32"||process.platform==="darwin"?t.toLowerCase():t}o(Nc,"normalizeComparableRoot");function zw(e,t){let n=Nc(t);if(!n)return!0;let r=e.runtimeInfo!==null&&typeof e.runtimeInfo=="object"?e.runtimeInfo:void 0;return[typeof r?.canonicalRepoRoot=="string"?r.canonicalRepoRoot:void 0,typeof r?.workspaceRoot=="string"?r.workspaceRoot:void 0,typeof e.gitRoot=="string"?e.gitRoot:void 0].some(s=>Nc(s)===n)}o(zw,"matchesProjectRoot");async function qw(e){let t;try{t=await Je.open(e,"r");let n=Buffer.allocUnsafe(Pc),{bytesRead:r}=await t.read(n,0,Pc,0);if(r===0)return;let i=n.toString("utf8",0,r),s=i.indexOf(`
|
|
576
|
+
`);if(s>=0)return i.slice(0,s).trim();let a=await Je.readFile(e,"utf8"),c=a.indexOf(`
|
|
577
|
+
`);return(c>=0?a.slice(0,c):a).trim()}catch{return}finally{await t?.close()}}o(qw,"readFirstLine");async function Vw(e,t){if(typeof t.activeMessageCount=="number"&&t.activeMessageCount>=0)return t.activeMessageCount;let n=(await Je.readFile(e,"utf8")).trim();if(!n)return 0;let r=typeof t.extensionRecordCount=="number"&&t.extensionRecordCount>0?t.extensionRecordCount:0;return Math.max(0,n.split(`
|
|
578
|
+
`).length-1-r)}o(Vw,"readMessageCount");function Gw(e){if(e.runtimeInfo===null||typeof e.runtimeInfo!="object")return;let t=e.runtimeInfo;return{...typeof t.canonicalRepoRoot=="string"?{canonicalRepoRoot:t.canonicalRepoRoot}:{},...typeof t.workspaceRoot=="string"?{workspaceRoot:t.workspaceRoot}:{},...typeof t.surface=="string"?{surface:t.surface}:{}}}o(Gw,"runtimeSummary");async function Yw(e,t){try{let n=await qw(e);if(!n)return;let r=JSON.parse(n);if(r===null||typeof r!="object")return;let i=r;if(i._type!=="meta"||i.scope==="managed-task-worker"||!zw(i,t))return;let s=await Vw(e,i);if(s<=0)return;let a=typeof i.createdAt=="string"?i.createdAt:void 0,c=Gw(i);return{id:Qe.basename(e,".jsonl"),title:typeof i.title=="string"?i.title:"",msgCount:s,...a!==void 0?{createdAt:a}:{},...c?.surface!==void 0?{surface:c.surface}:{},...a!==void 0?{createdAtMs:Date.parse(a)}:{}}}catch{return}}o(Yw,"readResumeCandidate");async function $c(e){try{let t=e.sessionsDir??Ww();await Ls(t),await Je.mkdir(t,{recursive:!0});let n=await Hw(t),r=[],i=new Set;for(let s=0;s<n.length;s+=Mc){let a=await Promise.all(n.slice(s,s+Mc).map(c=>Yw(c,e.projectRoot)));for(let c of a)c&&!i.has(c.id)&&(i.add(c.id),r.push(c))}return r.sort((s,a)=>Number.isFinite(s.createdAtMs)&&Number.isFinite(a.createdAtMs)&&s.createdAtMs!==a.createdAtMs?a.createdAtMs-s.createdAtMs:Number.isFinite(a.createdAtMs)&&!Number.isFinite(s.createdAtMs)?1:Number.isFinite(s.createdAtMs)&&!Number.isFinite(a.createdAtMs)?-1:a.id.localeCompare(s.id)),r.slice(0,e.limit??1e3).map(({createdAtMs:s,...a})=>a)}catch{return[]}}o($c,"listCliResumeSessions");async function Dc(e,t={}){return Ac(e,t)}o(Dc,"runCliResumePicker");async function Jw(e){let{default:t}=await import("chalk");if(e==="empty"){process.stdout.write(`${t.yellow("No resumable sessions found. Starting a new session...")}
|
|
43
579
|
`);return}process.stdout.write(`${t.dim("Session resume cancelled.")}
|
|
44
|
-
`)}
|
|
580
|
+
`)}o(Jw,"printResumeNotice");async function zH(e={}){let t=e.listSessions??$c,n=e.pickSession??Dc,r=e.notify??Jw,i=await t({projectRoot:e.cwd??process.cwd(),limit:1e3});if(i.length===0)return await r("empty"),{kind:"continue",argv:[]};let s=await n(i,{prepareSelection:e.beforeSelect});return s?{kind:"continue",argv:["-r",s.id]}:(await r("cancelled"),{kind:"exit"})}o(zH,"resolveBareResume");export{zH as resolveBareResume};
|