infra-kit 0.34.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/{boot-LC2ESPY6.js → boot-ST2534PA.js} +2 -2
  2. package/dist/boot-ST2534PA.js.map +7 -0
  3. package/dist/{chunk-5ZBDB3U7.js → chunk-3JFITLZG.js} +2 -2
  4. package/dist/chunk-3JFITLZG.js.map +7 -0
  5. package/dist/{chunk-SAHE3MZJ.js → chunk-55F372Z7.js} +1 -1
  6. package/dist/{chunk-SAHE3MZJ.js.map → chunk-55F372Z7.js.map} +2 -2
  7. package/dist/chunk-BPOPODWW.js +15 -0
  8. package/dist/chunk-BPOPODWW.js.map +7 -0
  9. package/dist/{chunk-I23MDR4X.js → chunk-GCOYOWGH.js} +1 -1
  10. package/dist/{chunk-I23MDR4X.js.map → chunk-GCOYOWGH.js.map} +2 -2
  11. package/dist/{chunk-XES5EOEE.js → chunk-PP44RGIU.js} +2 -2
  12. package/dist/chunk-PP44RGIU.js.map +7 -0
  13. package/dist/{chunk-7A4LVTRJ.js → chunk-QS7RKE5P.js} +2 -2
  14. package/dist/chunk-QS7RKE5P.js.map +7 -0
  15. package/dist/{chunk-AWFGP6GY.js → chunk-REDCBY4O.js} +1 -1
  16. package/dist/{chunk-AWFGP6GY.js.map → chunk-REDCBY4O.js.map} +2 -2
  17. package/dist/{chunk-QCTAEXMN.js → chunk-SBG3HRSC.js} +6 -6
  18. package/dist/{chunk-QCTAEXMN.js.map → chunk-SBG3HRSC.js.map} +2 -2
  19. package/dist/{chunk-U7VGROH3.js → chunk-TCQXTDVZ.js} +2 -2
  20. package/dist/{chunk-U7VGROH3.js.map → chunk-TCQXTDVZ.js.map} +1 -1
  21. package/dist/{chunk-MWGE43QS.js → chunk-TGEAIKD6.js} +2 -2
  22. package/dist/{chunk-MWGE43QS.js.map → chunk-TGEAIKD6.js.map} +2 -2
  23. package/dist/{chunk-DVXTZPQ5.js → chunk-UTQ4KTO6.js} +1 -1
  24. package/dist/{chunk-DVXTZPQ5.js.map → chunk-UTQ4KTO6.js.map} +2 -2
  25. package/dist/{chunk-TVG47UHG.js → chunk-V2ZLQPLI.js} +1 -1
  26. package/dist/{chunk-TVG47UHG.js.map → chunk-V2ZLQPLI.js.map} +2 -2
  27. package/dist/cli.js +145 -127
  28. package/dist/cli.js.map +4 -4
  29. package/dist/dev-server.js +5 -5
  30. package/dist/dev-server.js.map +2 -2
  31. package/dist/{dev-wizard-run-452R76HN.js → dev-wizard-run-PAHX7EMH.js} +2 -2
  32. package/dist/dev-wizard-run-PAHX7EMH.js.map +7 -0
  33. package/dist/{env-load-IXDGWGPV.js → env-load-XBKASGXP.js} +2 -2
  34. package/dist/mcp-proxy.js +1 -1
  35. package/dist/mcp-proxy.js.map +2 -2
  36. package/dist/{persistent-ink-dev-ui-ZSOS3CF4.js → persistent-ink-dev-ui-D6ALK2P3.js} +2 -2
  37. package/dist/update-check.js +1 -1
  38. package/package.json +3 -3
  39. package/dist/boot-LC2ESPY6.js.map +0 -7
  40. package/dist/chunk-467ZSXYU.js +0 -15
  41. package/dist/chunk-467ZSXYU.js.map +0 -7
  42. package/dist/chunk-5ZBDB3U7.js.map +0 -7
  43. package/dist/chunk-7A4LVTRJ.js.map +0 -7
  44. package/dist/chunk-XES5EOEE.js.map +0 -7
  45. package/dist/dev-wizard-run-452R76HN.js.map +0 -7
  46. /package/dist/{env-load-IXDGWGPV.js.map → env-load-XBKASGXP.js.map} +0 -0
  47. /package/dist/{persistent-ink-dev-ui-ZSOS3CF4.js.map → persistent-ink-dev-ui-D6ALK2P3.js.map} +0 -0
@@ -1,2 +1,2 @@
1
- import{a as j}from"./chunk-TVG47UHG.js";import{c as J}from"./chunk-QWVLAZ6N.js";import{b as ee}from"./chunk-WIZJQ57Q.js";import{render as We}from"ink";import X from"node:process";import{Box as U,Text as O,useApp as he,useInput as we,useWindowSize as xe}from"ink";import{useEffect as ne,useState as G}from"react";import{useMemo as de,useState as te}from"react";var F=(t,e)=>{let[r,p]=te(""),[n,a]=te(0),o=de(()=>{let f=r.trim().toLowerCase();return f?t.filter(m=>e(m).toLowerCase().includes(f)):t},[t,r,e]),u=Math.min(n,Math.max(0,o.length-1));return{filtered:o,activeIndex:u,query:r,handleNavigation:(f,m)=>{let b=o.length;return m.upArrow?(b>0&&a((u-1+b)%b),!0):m.downArrow?(b>0&&a((u+1)%b),!0):m.backspace||m.delete?(p(r.slice(0,-1)),a(0),!0):f&&!m.ctrl&&!m.meta?(p(r+f),a(0),!0):!1},clearQuery:()=>r?(p(""),a(0),!0):!1}};var pe=()=>{},q=(t,e=0)=>t<5?{mode:"tiny",chromeRows:0,groups:!1}:t<10?{mode:"compact",chromeRows:4+e,groups:!1}:{mode:"full",chromeRows:6+e,groups:!0},fe=(t,e,r,p)=>{let n=0,a;for(let o=e;o<r;o+=1){let u=t[o];if(!u)break;let w=p(u),g=w!==void 0&&w!==a;n+=1+(g?1:0)+(g&&o>e?1:0),a=w}return n},re=(t,e,r,p)=>{let n=e;for(;n<t.length&&fe(t,e,n+1,p)<=r;)n+=1;return n},$=(t,e,r,p,n)=>{let a=n?.groupOf??pe,o=Math.max(0,p-(n?.chromeRows??6)),u=Math.min(e,r);for(;r>=re(t,u,o,a)&&u<r;)u+=1;let w=re(t,u,o,a);return{visible:t.slice(u,w),start:u,hiddenBefore:u,hiddenAfter:Math.max(0,t.length-w)}};import{jsx as W,jsxs as z}from"react/jsx-runtime";var oe=t=>{let{items:e,onSubmit:r,onCancel:p,required:n=!0,allowSelectAll:a=!0}=t,o=ge,u=e.reduce((s,x)=>Math.max(s,x.label.length),0),{exit:w}=he(),{rows:g}=xe(),{filtered:f,activeIndex:m,query:b,handleNavigation:P,clearQuery:M}=F(e,Te),[v,R]=G(()=>new Set),[E,h]=G(!1),[C,d]=G(0),[l,y]=G(!1);ne(()=>{l&&w()},[l,w]);let _=q(g,1),S=$(f,C,m,g,{chromeRows:_.chromeRows});ne(()=>{S.start!==C&&d(S.start)},[S.start,C]);let H=s=>{R(x=>{let T=new Set(x);return T.has(s)?T.delete(s):T.add(s),T})},k=()=>{R(s=>e.every(T=>s.has(T.value))?new Set:new Set(e.map(T=>T.value)))},i=()=>{p(),y(!0)},c=()=>{if(n&&v.size===0){h(!0);return}r([...v]),y(!0)};return we((s,x)=>{if(!l){if(x.ctrl&&s==="c"){i();return}if(x.escape){M()||i();return}if(x.ctrl&&s==="a"){a&&k();return}if(s===" "){let T=f[m];T&&H(T.value);return}if(x.return){c();return}P(s,x)}}),l?null:_.mode==="tiny"?W(O,{dimColor:!0,wrap:"truncate",children:o.tiny}):z(U,{flexDirection:"column",children:[_.mode==="full"?W(O,{dimColor:!0,wrap:"truncate",children:o.hint}):null,z(U,{children:[W(O,{color:"cyan",children:o.prompt}),W(O,{wrap:"truncate-start",children:b})]}),z(U,{flexDirection:"column",marginTop:_.mode==="full"?1:0,children:[f.length===0?W(O,{dimColor:!0,wrap:"truncate",children:o.empty}):null,S.hiddenBefore>0?W(O,{dimColor:!0,wrap:"truncate",children:`${o.more} ${S.hiddenBefore} above`}):null,S.visible.map((s,x)=>{let T=S.start+x===m,me=v.has(s.value);return z(O,{color:T?"green":void 0,wrap:"truncate",children:[T?"\u203A ":" ",me?"[x] ":"[ ] ",s.label.padEnd(u)," ",W(O,{dimColor:!0,children:s.description??""})]},s.value)}),S.hiddenAfter>0?W(O,{dimColor:!0,wrap:"truncate",children:`${o.more} ${S.hiddenAfter} below`}):null]}),E?W(O,{dimColor:!0,wrap:"truncate",children:o.requiredHint}):null]})};function Te(t){return`${t.label} ${t.description??""}`}var ge={hint:"filter \xB7 \u2191\u2193 move \xB7 Space toggle \xB7 Ctrl-A all \xB7 Enter submit \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick branches",requiredHint:"select at least one",more:"\u2026"};import{Box as Y,Text as I,useApp as be,useInput as Ce,useWindowSize as ye}from"ink";import{useEffect as ie,useState as le}from"react";import{jsx as L,jsxs as D}from"react/jsx-runtime";var se=t=>{let{items:e,onSelect:r,onCancel:p}=t,n=Pe,a=e.reduce((d,l)=>Math.max(d,l.label.length),0),{exit:o}=be(),{rows:u}=ye(),{filtered:w,activeIndex:g,query:f,handleNavigation:m,clearQuery:b}=F(e,Be),[P,M]=le(0),[v,R]=le(!1);ie(()=>{v&&o()},[v,o]);let E=q(u),h=$(w,P,g,u,{chromeRows:E.chromeRows});ie(()=>{h.start!==P&&M(h.start)},[h.start,P]);let C=()=>{p(),R(!0)};return Ce((d,l)=>{if(!v){if(l.ctrl&&d==="c"){C();return}if(l.escape){b()||C();return}if(l.return){let y=w[g];y&&(r(y.value),R(!0));return}m(d,l)}}),v?null:E.mode==="tiny"?L(I,{dimColor:!0,wrap:"truncate",children:n.tiny}):D(Y,{flexDirection:"column",children:[E.mode==="full"?L(I,{dimColor:!0,wrap:"truncate",children:n.hint}):null,D(Y,{children:[L(I,{color:"cyan",children:n.prompt}),L(I,{wrap:"truncate-start",children:f})]}),D(Y,{flexDirection:"column",marginTop:E.mode==="full"?1:0,children:[w.length===0?L(I,{dimColor:!0,wrap:"truncate",children:n.empty}):null,h.hiddenBefore>0?L(I,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenBefore} above`}):null,h.visible.map((d,l)=>{let y=h.start+l===g;return D(I,{color:Se(d.type,y),wrap:"truncate",children:[y?"\u203A ":" ",d.label.padEnd(a)," ",L(I,{dimColor:!0,children:d.description??""})]},d.value)}),h.hiddenAfter>0?L(I,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenAfter} below`}):null]})]})};function Se(t,e){return t==="hotfix"?"red":e?"green":void 0}function Be(t){return`${t.label} ${t.description??""}`}var Pe={hint:"type to filter \xB7 \u2191\u2193 move \xB7 Enter select \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick a branch",more:"\u2026"};import{Box as Q,Text as B,useApp as ve,useInput as Re,useWindowSize as Oe}from"ink";import{useEffect as ae,useMemo as Ae,useState as K}from"react";import{jsx as A,jsxs as N}from"react/jsx-runtime";var ce=t=>{let{items:e,onSelect:r,onCancel:p,onSuspend:n}=t,a={hint:Ee(!!n),prompt:"\u276F ",empty:"No matching commands",tiny:"terminal too short \u2014 resize to pick a command",more:"\u2026"},o=24,{exit:u,suspendTerminal:w}=ve(),{rows:g}=Oe(),[f,m]=K(""),[b,P]=K(0),[M,v]=K(0),[R,E]=K(!1);ae(()=>{R&&u()},[R,u]);let h=Ae(()=>{let i=f.trim().toLowerCase();return i?e.filter(c=>`${c.name} ${c.description}`.toLowerCase().includes(i)):e},[e,f]),C=Math.min(b,Math.max(0,h.length-1)),d=q(g),l=$(h,M,C,g,{chromeRows:d.chromeRows,groupOf:d.groups?i=>i.group:void 0});ae(()=>{l.start!==M&&v(l.start)},[l.start,M]);let y=()=>{p(),E(!0)},_=()=>{n&&w(n).catch(()=>{})},S=i=>i==="c"||i==="d"?(y(),!0):i==="z"?(_(),!0):!1,H=i=>{let c=h.length;c>0&&P((C+i+c)%c)};if(Re((i,c)=>{if(!R&&!(c.ctrl&&S(i))){if(c.escape){m(""),P(0);return}if(c.return){let s=h[C];s&&(r(s.name),E(!0));return}if(c.upArrow){H(-1);return}if(c.downArrow){H(1);return}if(c.backspace||c.delete){m(f.slice(0,-1)),P(0);return}i&&!c.ctrl&&!c.meta&&(m(f+i),P(0))}}),R)return null;if(d.mode==="tiny")return A(B,{dimColor:!0,wrap:"truncate",children:a.tiny});let k="";return N(Q,{flexDirection:"column",children:[d.mode==="full"?A(B,{dimColor:!0,wrap:"truncate",children:a.hint}):null,N(Q,{children:[A(B,{color:"cyan",children:a.prompt}),A(B,{wrap:"truncate-start",children:f})]}),N(Q,{flexDirection:"column",marginTop:d.mode==="full"?1:0,children:[h.length===0?A(B,{dimColor:!0,wrap:"truncate",children:a.empty}):null,l.hiddenBefore>0?A(B,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenBefore} above`}):null,l.visible.map((i,c)=>{let s=l.start+c===C,x=d.groups&&i.group!==k;return k=i.group,N(Q,{flexDirection:"column",children:[x&&c>0?A(B,{children:" "}):null,x?A(B,{color:"yellow",wrap:"truncate",children:`\u2014 ${i.group} \u2014`}):null,N(B,{color:s?"green":void 0,wrap:"truncate",children:[s?"\u203A ":" ",i.name.padEnd(o)," ",A(B,{dimColor:!0,children:i.description})]})]},i.name)}),l.hiddenAfter>0?A(B,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenAfter} below`}):null]})]})},ue={suspend:"filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear \xB7 Ctrl-C quit \xB7 Ctrl-Z suspend",plain:"type to filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear \xB7 Ctrl-C quit"},Ee=t=>t?ue.suspend:ue.plain;import{jsx as V}from"react/jsx-runtime";var Z=async t=>{let e=ee(),{waitUntilExit:r}=We(t,{stdout:e,exitOnCtrlC:!1,interactive:!!e.isTTY});try{await r()}catch{}finally{J()>0?X.stdin.ref():X.stdin.pause()}},lt=async t=>{let e=null;return await Z(V(ce,{items:t,onSelect:r=>{e=r},onCancel:()=>{e=null},onSuspend:X.platform==="win32"?void 0:()=>{j()}})),e},st=async t=>{let e=null;return await Z(V(se,{items:t,onSelect:r=>{e=r},onCancel:()=>{e=null}})),e},at=async(t,e)=>{let r=null;return await Z(V(oe,{items:t,required:e?.required,allowSelectAll:e?.allowSelectAll,onSubmit:p=>{r=p},onCancel:()=>{r=null}})),r};export{at as runBranchMultiPicker,st as runBranchPicker,lt as runCommandPalette};
2
- //# sourceMappingURL=boot-LC2ESPY6.js.map
1
+ import{a as j}from"./chunk-V2ZLQPLI.js";import{c as J}from"./chunk-QWVLAZ6N.js";import{b as ee}from"./chunk-WIZJQ57Q.js";import{render as We}from"ink";import X from"node:process";import{Box as U,Text as O,useApp as he,useInput as we,useWindowSize as xe}from"ink";import{useEffect as ne,useState as G}from"react";import{useMemo as de,useState as te}from"react";var F=(t,e)=>{let[r,p]=te(""),[n,a]=te(0),o=de(()=>{let f=r.trim().toLowerCase();return f?t.filter(m=>e(m).toLowerCase().includes(f)):t},[t,r,e]),u=Math.min(n,Math.max(0,o.length-1));return{filtered:o,activeIndex:u,query:r,handleNavigation:(f,m)=>{let b=o.length;return m.upArrow?(b>0&&a((u-1+b)%b),!0):m.downArrow?(b>0&&a((u+1)%b),!0):m.backspace||m.delete?(p(r.slice(0,-1)),a(0),!0):f&&!m.ctrl&&!m.meta?(p(r+f),a(0),!0):!1},clearQuery:()=>r?(p(""),a(0),!0):!1}};var pe=()=>{},q=(t,e=0)=>t<5?{mode:"tiny",chromeRows:0,groups:!1}:t<10?{mode:"compact",chromeRows:4+e,groups:!1}:{mode:"full",chromeRows:6+e,groups:!0},fe=(t,e,r,p)=>{let n=0,a;for(let o=e;o<r;o+=1){let u=t[o];if(!u)break;let w=p(u),g=w!==void 0&&w!==a;n+=1+(g?1:0)+(g&&o>e?1:0),a=w}return n},re=(t,e,r,p)=>{let n=e;for(;n<t.length&&fe(t,e,n+1,p)<=r;)n+=1;return n},$=(t,e,r,p,n)=>{let a=n?.groupOf??pe,o=Math.max(0,p-(n?.chromeRows??6)),u=Math.min(e,r);for(;r>=re(t,u,o,a)&&u<r;)u+=1;let w=re(t,u,o,a);return{visible:t.slice(u,w),start:u,hiddenBefore:u,hiddenAfter:Math.max(0,t.length-w)}};import{jsx as W,jsxs as z}from"react/jsx-runtime";var oe=t=>{let{items:e,onSubmit:r,onCancel:p,required:n=!0,allowSelectAll:a=!0}=t,o=ge,u=e.reduce((s,x)=>Math.max(s,x.label.length),0),{exit:w}=he(),{rows:g}=xe(),{filtered:f,activeIndex:m,query:b,handleNavigation:P,clearQuery:M}=F(e,Te),[v,R]=G(()=>new Set),[E,h]=G(!1),[C,d]=G(0),[l,y]=G(!1);ne(()=>{l&&w()},[l,w]);let _=q(g,1),S=$(f,C,m,g,{chromeRows:_.chromeRows});ne(()=>{S.start!==C&&d(S.start)},[S.start,C]);let H=s=>{R(x=>{let T=new Set(x);return T.has(s)?T.delete(s):T.add(s),T})},k=()=>{R(s=>e.every(T=>s.has(T.value))?new Set:new Set(e.map(T=>T.value)))},i=()=>{p(),y(!0)},c=()=>{if(n&&v.size===0){h(!0);return}r([...v]),y(!0)};return we((s,x)=>{if(!l){if(x.ctrl&&s==="c"){i();return}if(x.escape){M()||i();return}if(x.ctrl&&s==="a"){a&&k();return}if(s===" "){let T=f[m];T&&H(T.value);return}if(x.return){c();return}P(s,x)}}),l?null:_.mode==="tiny"?W(O,{dimColor:!0,wrap:"truncate",children:o.tiny}):z(U,{flexDirection:"column",children:[_.mode==="full"?W(O,{dimColor:!0,wrap:"truncate",children:o.hint}):null,z(U,{children:[W(O,{color:"cyan",children:o.prompt}),W(O,{wrap:"truncate-start",children:b})]}),z(U,{flexDirection:"column",marginTop:_.mode==="full"?1:0,children:[f.length===0?W(O,{dimColor:!0,wrap:"truncate",children:o.empty}):null,S.hiddenBefore>0?W(O,{dimColor:!0,wrap:"truncate",children:`${o.more} ${S.hiddenBefore} above`}):null,S.visible.map((s,x)=>{let T=S.start+x===m,me=v.has(s.value);return z(O,{color:T?"green":void 0,wrap:"truncate",children:[T?"\u203A ":" ",me?"[x] ":"[ ] ",s.label.padEnd(u)," ",W(O,{dimColor:!0,children:s.description??""})]},s.value)}),S.hiddenAfter>0?W(O,{dimColor:!0,wrap:"truncate",children:`${o.more} ${S.hiddenAfter} below`}):null]}),E?W(O,{dimColor:!0,wrap:"truncate",children:o.requiredHint}):null]})};function Te(t){return`${t.label} ${t.description??""}`}var ge={hint:"filter \xB7 \u2191\u2193 move \xB7 Space toggle \xB7 Ctrl-A all \xB7 Enter submit \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick branches",requiredHint:"select at least one",more:"\u2026"};import{Box as Y,Text as I,useApp as be,useInput as Ce,useWindowSize as ye}from"ink";import{useEffect as ie,useState as le}from"react";import{jsx as L,jsxs as D}from"react/jsx-runtime";var se=t=>{let{items:e,onSelect:r,onCancel:p}=t,n=Pe,a=e.reduce((d,l)=>Math.max(d,l.label.length),0),{exit:o}=be(),{rows:u}=ye(),{filtered:w,activeIndex:g,query:f,handleNavigation:m,clearQuery:b}=F(e,Be),[P,M]=le(0),[v,R]=le(!1);ie(()=>{v&&o()},[v,o]);let E=q(u),h=$(w,P,g,u,{chromeRows:E.chromeRows});ie(()=>{h.start!==P&&M(h.start)},[h.start,P]);let C=()=>{p(),R(!0)};return Ce((d,l)=>{if(!v){if(l.ctrl&&d==="c"){C();return}if(l.escape){b()||C();return}if(l.return){let y=w[g];y&&(r(y.value),R(!0));return}m(d,l)}}),v?null:E.mode==="tiny"?L(I,{dimColor:!0,wrap:"truncate",children:n.tiny}):D(Y,{flexDirection:"column",children:[E.mode==="full"?L(I,{dimColor:!0,wrap:"truncate",children:n.hint}):null,D(Y,{children:[L(I,{color:"cyan",children:n.prompt}),L(I,{wrap:"truncate-start",children:f})]}),D(Y,{flexDirection:"column",marginTop:E.mode==="full"?1:0,children:[w.length===0?L(I,{dimColor:!0,wrap:"truncate",children:n.empty}):null,h.hiddenBefore>0?L(I,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenBefore} above`}):null,h.visible.map((d,l)=>{let y=h.start+l===g;return D(I,{color:Se(d.type,y),wrap:"truncate",children:[y?"\u203A ":" ",d.label.padEnd(a)," ",L(I,{dimColor:!0,children:d.description??""})]},d.value)}),h.hiddenAfter>0?L(I,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenAfter} below`}):null]})]})};function Se(t,e){return t==="hotfix"?"red":e?"green":void 0}function Be(t){return`${t.label} ${t.description??""}`}var Pe={hint:"type to filter \xB7 \u2191\u2193 move \xB7 Enter select \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick a branch",more:"\u2026"};import{Box as Q,Text as B,useApp as ve,useInput as Re,useWindowSize as Oe}from"ink";import{useEffect as ae,useMemo as Ae,useState as K}from"react";import{jsx as A,jsxs as N}from"react/jsx-runtime";var ce=t=>{let{items:e,onSelect:r,onCancel:p,onSuspend:n}=t,a={hint:Ee(!!n),prompt:"\u276F ",empty:"No matching commands",tiny:"terminal too short \u2014 resize to pick a command",more:"\u2026"},o=24,{exit:u,suspendTerminal:w}=ve(),{rows:g}=Oe(),[f,m]=K(""),[b,P]=K(0),[M,v]=K(0),[R,E]=K(!1);ae(()=>{R&&u()},[R,u]);let h=Ae(()=>{let i=f.trim().toLowerCase();return i?e.filter(c=>`${c.name} ${c.description}`.toLowerCase().includes(i)):e},[e,f]),C=Math.min(b,Math.max(0,h.length-1)),d=q(g),l=$(h,M,C,g,{chromeRows:d.chromeRows,groupOf:d.groups?i=>i.group:void 0});ae(()=>{l.start!==M&&v(l.start)},[l.start,M]);let y=()=>{p(),E(!0)},_=()=>{n&&w(n).catch(()=>{})},S=i=>i==="c"||i==="d"?(y(),!0):i==="z"?(_(),!0):!1,H=i=>{let c=h.length;c>0&&P((C+i+c)%c)};if(Re((i,c)=>{if(!R&&!(c.ctrl&&S(i))){if(c.escape){m(""),P(0);return}if(c.return){let s=h[C];s&&(r(s.name),E(!0));return}if(c.upArrow){H(-1);return}if(c.downArrow){H(1);return}if(c.backspace||c.delete){m(f.slice(0,-1)),P(0);return}i&&!c.ctrl&&!c.meta&&(m(f+i),P(0))}}),R)return null;if(d.mode==="tiny")return A(B,{dimColor:!0,wrap:"truncate",children:a.tiny});let k="";return N(Q,{flexDirection:"column",children:[d.mode==="full"?A(B,{dimColor:!0,wrap:"truncate",children:a.hint}):null,N(Q,{children:[A(B,{color:"cyan",children:a.prompt}),A(B,{wrap:"truncate-start",children:f})]}),N(Q,{flexDirection:"column",marginTop:d.mode==="full"?1:0,children:[h.length===0?A(B,{dimColor:!0,wrap:"truncate",children:a.empty}):null,l.hiddenBefore>0?A(B,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenBefore} above`}):null,l.visible.map((i,c)=>{let s=l.start+c===C,x=d.groups&&i.group!==k;return k=i.group,N(Q,{flexDirection:"column",children:[x&&c>0?A(B,{children:" "}):null,x?A(B,{color:"yellow",wrap:"truncate",children:`\u2014 ${i.group} \u2014`}):null,N(B,{color:s?"green":void 0,wrap:"truncate",children:[s?"\u203A ":" ",i.name.padEnd(o)," ",A(B,{dimColor:!0,children:i.description})]})]},i.name)}),l.hiddenAfter>0?A(B,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenAfter} below`}):null]})]})},ue={suspend:"filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear \xB7 Ctrl-C quit \xB7 Ctrl-Z suspend",plain:"type to filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear \xB7 Ctrl-C quit"},Ee=t=>t?ue.suspend:ue.plain;import{jsx as V}from"react/jsx-runtime";var Z=async t=>{let e=ee(),{waitUntilExit:r}=We(t,{stdout:e,exitOnCtrlC:!1,interactive:!!e.isTTY});try{await r()}catch{}finally{J()>0?X.stdin.ref():X.stdin.pause()}},lt=async t=>{let e=null;return await Z(V(ce,{items:t,onSelect:r=>{e=r},onCancel:()=>{e=null},onSuspend:X.platform==="win32"?void 0:()=>{j()}})),e},st=async t=>{let e=null;return await Z(V(se,{items:t,onSelect:r=>{e=r},onCancel:()=>{e=null}})),e},at=async(t,e)=>{let r=null;return await Z(V(oe,{items:t,required:e?.required,allowSelectAll:e?.allowSelectAll,onSubmit:p=>{r=p},onCancel:()=>{r=null}})),r};export{at as runBranchMultiPicker,st as runBranchPicker,lt as runCommandPalette};
2
+ //# sourceMappingURL=boot-ST2534PA.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/tui/boot.tsx", "../src/tui/screens/branch-multi-picker.tsx", "../src/tui/hooks/use-list-filter.ts", "../src/tui/screens/palette-window.ts", "../src/tui/screens/branch-picker.tsx", "../src/tui/screens/command-palette.tsx"],
4
+ "sourcesContent": ["import { render } from 'ink'\nimport process from 'node:process'\nimport type { ReactElement } from 'react'\n\nimport { stdinReaderCount } from 'src/lib/prompts/stdin-ref'\nimport type { BranchPickerItem } from 'src/lib/prompts/types'\nimport { suspendForeground } from 'src/lib/session/suspend-foreground'\n\nimport { safeStderr } from './safe-stderr'\nimport { BranchMultiPicker } from './screens/branch-multi-picker'\nimport { BranchPicker } from './screens/branch-picker'\nimport { CommandPalette } from './screens/command-palette'\nimport type { PaletteItem } from './types'\n\n/**\n * Entry point for the Ink TUI. This module (and everything under `src/tui/`) is\n * the ONLY place allowed to import `ink`/`react`; it is reached exclusively via a\n * dynamic `await import('src/tui/boot')` from the TTY branch of entry/cli.ts, so\n * React never loads on the `--agent` / `--json` / non-TTY paths. Build splitting keeps\n * it in a separate lazy chunk (see scripts/build.js).\n */\n\n/**\n * Render an Ink element to stderr and resolve once it tears down. Frames are\n * written to stderr so stdout stays clean for the command that runs afterwards\n * (mirrors the previous Inquirer menu).\n *\n * STDIN \u2014 Ink is self-balancing (it refs when it arms raw mode, unrefs on teardown), so the common\n * paths need nothing from here. The re-assert below is CONDITIONAL on the reader counter and is a\n * net for the one case Ink cannot see: an Ink screen rendered INSIDE a `withEscape` callback, whose\n * teardown would unref the handle the outer prompt is still reading from and kill it with exit 13.\n * See lib/prompts/stdin-ref.\n */\n// Where the balance comes from: ink/build/components/App.js:225 (`ref` on raw mode) and :137\n// (`unref` on teardown). A later Ink render refs itself again on mount, and an `@inquirer/*`\n// prompt \u2014 which refs nothing on its own \u2014 gets its ref from `withEscape`. The re-assert is a net\n// for a boundary nothing structurally enforces, not the mechanism that keeps prompts alive.\n//\n// It replaces an UNCONDITIONAL `process.stdin.ref()`, whose stated premise \u2014 \"an idle ref'd stdin\n// does not block exit\" \u2014 is simply false: a ref'd tty ReadStream holds the event loop open whether\n// or not anything is listening to it. That re-ref bought the next prompt its handle and cost the\n// session shell its exit, so every quit key in the palette tore the frame down correctly and then\n// hung forever.\nconst renderToStderr = async (element: ReactElement): Promise<void> => {\n const stdout = safeStderr()\n\n const { waitUntilExit } = render(element, {\n stdout,\n // Ink's default is `exitOnCtrlC: true`, which intercepts the 0x03 byte in its own App and calls\n // `handleExit()` BEFORE it ever reaches `useInput`. That makes every screen's own ctrl+c branch\n // dead code, and \u2014 worse \u2014 it tears down on the CURRENT frame, so `log.done()` freezes the drawn\n // command list into the scrollback instead of erasing it (Esc, which goes through the screens'\n // own quit path, erases correctly; Ctrl-C left a corpse). Every screen rendered here already\n // handles ctrl+c itself, so hand them the key.\n exitOnCtrlC: false,\n // Ink's default is `!isInCi && stdout.isTTY`. We drop the isInCi term: a developer with CI\n // exported in their shell would otherwise get a NON-interactive Ink on a real terminal, and Ink\n // skips ALL terminal management in that mode \u2014 `beginSuspend` returns before it can drop raw mode\n // or erase the frame, and `endSuspend` never redraws. Ctrl-Z would hand the shell a raw-mode tty\n // with a stranded frame and a hidden cursor, and `fg` would come back to nothing. Whether we own\n // the terminal is a question about the tty, and only about the tty.\n interactive: Boolean(stdout.isTTY),\n })\n\n try {\n await waitUntilExit()\n } catch {\n // Swallow a teardown rejection: the caller reports cancellation via its own\n // captured sentinel (which stays at its initial value), not via a throw.\n } finally {\n if (stdinReaderCount() > 0) {\n process.stdin.ref()\n } else {\n // STOP READING, not just \"stop holding the loop open\". `unref()` answers \"may node exit?\", not\n // \"is anyone still consuming this fd?\" \u2014 and Ink's teardown only drops its `readable` listener\n // and unrefs (App.js:136-137). The session shell then spawns the next command with\n // `stdio: 'inherit'`, so parent and child hold the SAME tty and each keystroke goes to exactly\n // one of them. Left unpaused, the parent wins often enough to eat the user's Esc; the child then\n // never cancels, `waitForExit` never resolves, and `childOwnsSigint` (lib/session/run-session)\n // swallows every Ctrl-C that follows. That is the \"Esc worked, then nothing does\" wedge.\n //\n // WHY `pause()` REACHES libuv AT ALL \u2014 it looks inert, and on a generic stream it is. The chain:\n // 1. `Readable.prototype.pause()` (node internal/streams/readable.js) emits `'pause'` ONLY IF\n // `readableFlowing !== false`.\n // 2. `process.stdin` \u2014 and ONLY `process.stdin`, ONLY on the main thread \u2014 carries a `'pause'`\n // listener installed by node's bootstrap (internal/bootstrap/switches/is_main_thread.js:263).\n // 3. That listener defers to `onpause` (:267), which calls `stdin._handle.readStop()` (:273).\n // `net.Socket.prototype.pause` never calls `readStop` itself (it does so only under `kBuffer`,\n // which is unset here), so a harness built on a CONSTRUCTED `tty.ReadStream`, or run in a worker\n // thread, measures a stream with ZERO `'pause'` listeners and correctly reports no effect. That\n // is a false negative about a different object, not evidence against this line.\n //\n // THE PRECONDITION, AND WHY THIS CALL SITE MEETS IT \u2014 Ink reads via a `readable` listener\n // (App.js:206, removed at :126), where `readableFlowing === false`, which would fail step 1 and\n // make this a silent no-op. It does not, because `removeListener('readable')` schedules\n // `updateReadableListening` on the NEXTTICK queue (clearing flowing to `null`), while this\n // `finally` runs in the PROMISE MICROTASK behind `await waitUntilExit()` above \u2014 and node drains\n // nextTick before microtasks. Ink resolves no earlier than it detaches (App.js:126 <- unmount\n // ink.js:300 <- resolveExitPromise ink.js:580). Measured on a pty: synchronous call => 0 `'pause'`\n // events, 0 readStops; behind the await => 1 and 1, flowing `null`, 3/3.\n //\n // SO: KEEP THIS BEHIND THE `await`. Making it synchronous silently disarms it with every test\n // still green \u2014 which is what src/tui/__tests__/stdin-pause-semantics.test.ts exists to catch.\n // Deferring it by a tick is NOT a hardening: `readStop` already lands after the `spawn` in\n // run-session.ts (pause -> spawn -> readStop) and deferring only widens that window. Verified\n // against ink 7.1.0; if Ink ever resolves before detaching, this reverts to a no-op.\n process.stdin.pause()\n }\n }\n}\n\n/**\n * Render the command palette and resolve to the chosen command name, or `null`\n * if the user cancels. A Ctrl-Z suspends the job and resolves nothing \u2014 the same\n * palette redraws, filter and all, when the user brings it back with `fg`.\n */\nexport const runCommandPalette = async (items: PaletteItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <CommandPalette\n items={items}\n onSelect={(name) => {\n selected = name\n }}\n onCancel={() => {\n selected = null\n }}\n // This module is the platform authority: `undefined` tells the palette that suspending is\n // impossible here, so it neither binds Ctrl-Z nor advertises it in the footer. (`suspendForeground`\n // guards win32 again on its own \u2014 the palette itself must stay free of `process`.)\n onSuspend={\n process.platform === 'win32'\n ? undefined\n : () => {\n suspendForeground()\n }\n }\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable single-select branch picker and resolve to the chosen\n * value, or `null` if the user cancels.\n */\nexport const runBranchPicker = async (items: BranchPickerItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <BranchPicker\n items={items}\n onSelect={(value) => {\n selected = value\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable multi-select branch picker and resolve to the chosen\n * values, or `null` if the user cancels. The captured variable starts as `null`\n * and is only assigned an array in `onSubmit`, so a cancel is distinguishable\n * from an empty submit.\n */\nexport const runBranchMultiPicker = async (\n items: BranchPickerItem[],\n opts?: { required?: boolean; allowSelectAll?: boolean },\n): Promise<string[] | null> => {\n let selected: string[] | null = null\n\n await renderToStderr(\n <BranchMultiPicker\n items={items}\n required={opts?.required}\n allowSelectAll={opts?.allowSelectAll}\n onSubmit={(values) => {\n selected = values\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface BranchMultiPickerProps {\n items: BranchPickerItem[]\n /** Called with the selected item values; the app then exits. */\n onSubmit: (values: string[]) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n /** When true (default), Enter with an empty selection is ignored. */\n required?: boolean\n /** When true (default), Ctrl-A toggles select-all across all items. */\n allowSelectAll?: boolean\n}\n\n/**\n * Searchable multi-select branch picker rendered with Ink. Same filter/move/cancel\n * behaviour as `BranchPicker`, plus a selection `Set` keyed by item *value* so the\n * selection survives filter changes. Space toggles the active row; Ctrl-A toggles\n * select-all across all items; Enter submits the selected values.\n *\n * The list is WINDOWED to the terminal height for the same safety reason as the\n * palette and the single picker: an overflowing Ink frame corrupts the cursor and\n * welds later output onto the transcript. See `palette-window.ts`.\n */\nexport const BranchMultiPicker = (props: BranchMultiPickerProps) => {\n const { items, onSubmit, onCancel, required = true, allowSelectAll = true } = props\n\n const T = BRANCH_MULTI_PICKER_TEXT\n\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { rows } = useWindowSize()\n const { filtered, activeIndex, query, handleNavigation, clearQuery } = useListFilter(items, filterText)\n\n // Selection keyed by value so it persists across filter changes.\n const [selected, setSelected] = useState<Set<string>>(() => {\n return new Set()\n })\n\n const [showRequiredHint, setShowRequiredHint] = useState(false)\n // First branch in the visible window; kept in state so the list scrolls by the minimum needed.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n // The extra chrome row is this screen's `select at least one` hint: counted unconditionally, because\n // it appears on a keystroke and a budget that shrinks mid-frame is a budget that overflows.\n const layout = listLayout(rows, 1)\n // No `groupOf`: a branch list has no headers, so every branch costs exactly one row.\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, { chromeRows: layout.chromeRows })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n const toggleValue = (value: string) => {\n setSelected((prev) => {\n const next = new Set(prev)\n\n if (next.has(value)) {\n next.delete(value)\n } else {\n next.add(value)\n }\n\n return next\n })\n }\n\n const toggleSelectAll = () => {\n setSelected((prev) => {\n // Clear only when every item (all, not just filtered) is already selected.\n const allSelected = items.every((item) => {\n return prev.has(item.value)\n })\n\n if (allSelected) {\n return new Set()\n }\n\n return new Set(\n items.map((item) => {\n return item.value\n }),\n )\n })\n }\n\n const cancel = () => {\n onCancel()\n setSubmitted(true)\n }\n\n const submit = () => {\n if (required && selected.size === 0) {\n setShowRequiredHint(true)\n\n return\n }\n\n onSubmit([...selected])\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.ctrl && input === 'c') {\n cancel()\n\n return\n }\n\n // Esc pops the innermost stateful thing: the typed filter first, the picker only once\n // there is no filter left to clear. It never touches `selected` \u2014 a filter keystroke is\n // not a selection, so clearing one must not discard the other. Stage 2 discards it, as before.\n if (key.escape) {\n if (!clearQuery()) {\n cancel()\n }\n\n return\n }\n\n if (key.ctrl && input === 'a') {\n if (allowSelectAll) {\n toggleSelectAll()\n }\n\n return\n }\n\n if (input === ' ') {\n const active = filtered[activeIndex]\n\n if (active) {\n toggleValue(active.value)\n }\n\n return\n }\n\n if (key.return) {\n submit()\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one branch row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START: overflow must eat the head of the filter, never the character being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n const isChecked = selected.has(item.value)\n\n // `wrap=\"truncate\"` keeps one branch = one row at any width. Ink reads the wrap style off the\n // OUTER <Text> only, so it must live here, not on the nested description.\n return (\n <Text color={isActive ? 'green' : undefined} key={item.value} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {isChecked ? '[x] ' : '[ ] '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n {showRequiredHint ? (\n <Text dimColor wrap=\"truncate\">\n {T.requiredHint}\n </Text>\n ) : null}\n </Box>\n )\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n\n/**\n * Static screen copy. Module-scoped and exported so the hint-width guard can measure it:\n * these strings render under `wrap=\"truncate\"`, so a hint of \u226580 columns silently loses\n * its tail at the common terminal width \u2014 and the tail is where the Esc hint lives.\n */\nexport const BRANCH_MULTI_PICKER_TEXT = {\n hint: 'filter \u00B7 \u2191\u2193 move \u00B7 Space toggle \u00B7 Ctrl-A all \u00B7 Enter submit \u00B7 Esc clear/cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n tiny: 'terminal too short \u2014 resize to pick branches',\n requiredHint: 'select at least one',\n more: '\u2026',\n}\n", "import type { Key } from 'ink'\nimport { useMemo, useState } from 'react'\n\ninterface ListFilter<T> {\n /** Items matching the current query (all items when the query is empty). */\n filtered: T[]\n /** Active row index, always clamped into `filtered`'s bounds. */\n activeIndex: number\n /** Current filter query. */\n query: string\n /**\n * Handle the shared navigation/filter keys (\u2191\u2193 wrap-around, backspace/delete,\n * printable chars). Returns true when the key was consumed so the caller can\n * `return` early; false leaves the key for the component's own handlers.\n */\n handleNavigation: (input: string, key: Key) => boolean\n /**\n * Stage 1 of the Esc ladder: clears a non-empty query (back to the first row) and\n * returns true. Returns false when the query is already empty \u2014 the boolean IS the\n * ladder, and a false tells the caller there is nothing left to cancel but the screen.\n *\n * Deliberately NOT folded into `handleNavigation`: the two pickers want different\n * stage-2 actions, so the escape branch belongs to each screen, not to the shared handler.\n */\n clearQuery: () => boolean\n}\n\n/**\n * Shared list-filter state for the branch pickers: substring filtering,\n * wrap-around \u2191\u2193 movement, and query editing. Extracted so each `useInput`\n * handler stays under the sonarjs cognitive-complexity \u226415 gate.\n */\nexport const useListFilter = <T>(items: T[], toText: (item: T) => string): ListFilter<T> => {\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return toText(item).toLowerCase().includes(q)\n })\n }, [items, query, toText])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n const handleNavigation = (input: string, key: Key): boolean => {\n const n = filtered.length\n\n if (key.upArrow) {\n // `+ n` sidesteps JS negative modulo (e.g. -1 % 5 === -1, not 4).\n if (n > 0) {\n setIndex((activeIndex - 1 + n) % n)\n }\n\n return true\n }\n\n if (key.downArrow) {\n if (n > 0) {\n setIndex((activeIndex + 1) % n)\n }\n\n return true\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return true\n }\n\n // Printable character: append to the filter and reset to the first row.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n\n return true\n }\n\n return false\n }\n\n const clearQuery = (): boolean => {\n if (!query) {\n return false\n }\n\n setQuery('')\n setIndex(0)\n\n return true\n }\n\n return { filtered, activeIndex, query, handleNavigation, clearQuery }\n}\n", "/**\n * @fileoverview\n *\n * Pure viewport arithmetic shared by every Ink list screen (the command palette and both branch\n * pickers): which slice of the (already filtered) list fits the terminal, and how much chrome the\n * screen may spend around it.\n *\n * This is a SAFETY guard, not a readability one. Ink's cleanup walks the cursor upward one line at a\n * time (`ESC[2K ESC[1A` per row) and `ESC[1A` SATURATES AT ROW 0. So the moment a frame is taller than\n * the viewport, the terminal scrolls while Ink draws, the upward walk erases the wrong rows, and the\n * cursor is left parked ABOVE live content \u2014 after which every later write (the session's status\n * footer, the next palette frame) is deposited on top of the transcript. That is the \"welded rows\" bug:\n * `\u276F ` printed over the head of `ERROR: \u2026`, leaving `ROR: \u2026` behind.\n *\n * The invariant this module exists to enforce, for every (columns, rows):\n *\n * rendered frame height < terminal rows\n *\n * Hold that, and Ink never takes its overflow path: `clearTerminal` never fires, `eraseLines` never\n * saturates, the cursor stays below the transcript, and a fresh (cold) Ink instance \u2014 which erases\n * NOTHING before its first frame \u2014 simply appends below the transcript like any other CLI. No new\n * escape bytes required.\n *\n * Two things make the row count knowable at all:\n * - Every list row is rendered `wrap=\"truncate\"`, so one item is always exactly one row. Without that\n * a long description wraps to two rows and this arithmetic silently under-counts (Ink wraps text\n * itself and measures the WRAPPED height, so it, not us, would be right).\n * - Chrome is counted unconditionally, even when a given row is not drawn (see `CHROME_ROWS`). Over-\n * counting shrinks the list; under-counting overflows. Only one of those is a bug.\n *\n * `src/tui/safe-stderr.ts` (the `ESC[3J` byte filter) remains the last-resort backstop for the case\n * this cannot cover \u2014 a SIGWINCH that invalidates a frame's height retroactively.\n */\nimport type { PaletteItem } from '../types'\n\n/**\n * Reads an item's group label. Omitted by the branch pickers, whose lists have no headers at all.\n * (Passed as an accessor rather than constrained with a `{ group?: string }` marker interface: a type\n * whose properties are ALL optional is \"weak\", and TypeScript refuses to match a `BranchPickerItem`\n * against it \u2014 inference silently falls back to the constraint and every field access breaks.)\n */\nexport type GroupOf<T> = (item: T) => string | undefined\n\n/** The slice to render, plus how many rows fell off each end (for the `\u2026 n more` affordances). */\nexport interface ListWindow<T> {\n visible: T[]\n /** Index the window starts at \u2014 the component stores it so the list does not jump between frames. */\n start: number\n hiddenBefore: number\n hiddenAfter: number\n}\n\n/** Back-compat alias: the command palette's window is a window of `PaletteItem`s. */\nexport type PaletteWindow = ListWindow<PaletteItem>\n\n/**\n * Rows a screen spends on everything that is not a list row, counted UNCONDITIONALLY (a `\u2026 n above`\n * that is not drawn today may be drawn on the next keystroke, and re-deriving the budget mid-frame is\n * how you get an off-by-one that only bites on a full list):\n * hint, `\u276F` prompt, the list's `marginTop`, `\u2026 n above`, `\u2026 n below`, and one row of headroom.\n *\n * The headroom row is what makes the frame strictly SHORTER than the viewport: Ink treats a frame\n * exactly as tall as the terminal as fullscreen and clears the screen.\n */\nexport const CHROME_ROWS = 6\n\n/** Compact chrome: the hint and the list's `marginTop` are dropped. Prompt + affordances + headroom. */\nexport const COMPACT_CHROME_ROWS = 4\n\n/** Below this many rows a screen drops its hint, its `marginTop`, and its group headers. */\nexport const COMPACT_BELOW_ROWS = 10\n\n/** Below this many rows no usable list fits at all; the screen renders a single-line notice instead. */\nexport const TINY_BELOW_ROWS = 5\n\n/** How a screen must lay itself out to keep its frame shorter than `rows`. */\nexport type ListLayoutMode = 'full' | 'compact' | 'tiny'\n\nexport interface ListLayout {\n mode: ListLayoutMode\n /** Rows reserved for chrome. Pass to `paletteWindow` as `chromeRows`. */\n chromeRows: number\n /** Whether group headers may be drawn (they cost a row each, so a compact frame drops them). */\n groups: boolean\n}\n\n/** A list with no group headers: every item costs exactly one row. */\nconst NO_GROUPS = (): undefined => {\n return undefined\n}\n\n/**\n * The layout a screen must use at this terminal height. `extraChromeRows` is for chrome a screen has\n * that the others do not \u2014 the multi-picker's `select at least one` hint is the only one today.\n *\n * A `tiny` frame is one truncated line, which is strictly shorter than any terminal of 2+ rows. (At\n * `rows === 1` nothing can be shorter than the viewport; Ink will clear. That is a degenerate terminal,\n * and `safe-stderr` keeps even that harmless.)\n *\n * @example\n * listLayout(24) // => { mode: 'full', chromeRows: 6, groups: true }\n * listLayout(8) // => { mode: 'compact', chromeRows: 4, groups: false }\n * listLayout(8, 1) // => { mode: 'compact', chromeRows: 5, groups: false } (multi-picker)\n * listLayout(4) // => { mode: 'tiny', chromeRows: 0, groups: false }\n */\nexport const listLayout = (rows: number, extraChromeRows = 0): ListLayout => {\n if (rows < TINY_BELOW_ROWS) {\n return { mode: 'tiny', chromeRows: 0, groups: false }\n }\n\n if (rows < COMPACT_BELOW_ROWS) {\n return { mode: 'compact', chromeRows: COMPACT_CHROME_ROWS + extraChromeRows, groups: false }\n }\n\n return { mode: 'full', chromeRows: CHROME_ROWS + extraChromeRows, groups: true }\n}\n\n/**\n * How many rows rendering `items[start..end)` costs: one per item (guaranteed by `wrap=\"truncate\"`),\n * plus, when `groups` is on, one for each group header and one for the blank line between groups (the\n * first rendered group gets a header but no blank \u2014 it mirrors the `showGroup && position > 0` rule in\n * the components). A list whose items carry no `group` never spends a header row.\n */\nconst heightOf = <T>(items: T[], start: number, end: number, groupOf: GroupOf<T>): number => {\n let height = 0\n let previousGroup: string | undefined\n\n for (let index = start; index < end; index += 1) {\n const item = items[index]\n\n if (!item) break\n\n const group = groupOf(item)\n const startsGroup = group !== undefined && group !== previousGroup\n\n height += 1 + (startsGroup ? 1 : 0) + (startsGroup && index > start ? 1 : 0)\n previousGroup = group\n }\n\n return height\n}\n\n/** The last index (exclusive) that still fits `budget` rows when rendering from `start`. */\nconst endThatFits = <T>(items: T[], start: number, budget: number, groupOf: GroupOf<T>): number => {\n let end = start\n\n while (end < items.length && heightOf(items, start, end + 1, groupOf) <= budget) {\n end += 1\n }\n\n return end\n}\n\n/**\n * The window of items to render: the largest slice starting at or after `start` that fits the terminal\n * while still containing `activeIndex`. Scrolls by the minimum needed \u2014 the caller keeps `start` in\n * state, so the list only moves when the cursor would otherwise leave the window.\n *\n * An empty `visible` is a legitimate result on a terminal too short to hold even one row. It is NOT\n * clamped up to one item: forcing a row that does not fit is exactly how the frame overflows and the\n * cursor corruption starts. A screen that gets nothing back renders its `tiny` notice instead \u2014 see\n * `listLayout`.\n *\n * @example\n * const window = paletteWindow(items, 0, 12, 24)\n * window.visible.length // => however many commands fit 18 rows\n * window.hiddenAfter // => the rest, surfaced as '\u2026 n below'\n */\nexport const paletteWindow = <T>(\n items: T[],\n start: number,\n activeIndex: number,\n rows: number,\n opts?: { chromeRows?: number; groupOf?: GroupOf<T> },\n): ListWindow<T> => {\n const groupOf = opts?.groupOf ?? NO_GROUPS\n const budget = Math.max(0, rows - (opts?.chromeRows ?? CHROME_ROWS))\n\n // Scroll up only if the cursor moved above the window; otherwise scroll down just far enough.\n let first = Math.min(start, activeIndex)\n\n while (activeIndex >= endThatFits(items, first, budget, groupOf) && first < activeIndex) {\n first += 1\n }\n\n const end = endThatFits(items, first, budget, groupOf)\n\n return {\n visible: items.slice(first, end),\n start: first,\n hiddenBefore: first,\n hiddenAfter: Math.max(0, items.length - end),\n }\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface BranchPickerProps {\n items: BranchPickerItem[]\n /** Called with the chosen item's value; the app then exits. */\n onSelect: (value: string) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n}\n\n/**\n * Searchable single-select branch picker rendered with Ink. Mirrors\n * `CommandPalette` minus the group headers: type-to-filter over label +\n * description, \u2191\u2193 wrap-around, Enter selects the active item's *value*.\n *\n * Like the palette, the list is WINDOWED to the terminal height. That is a safety\n * requirement, not a nicety: a repo with ~20 open releases produced a frame taller\n * than an 80x24 window, and an overflowing Ink frame corrupts the cursor and welds\n * the next frame onto the command's own output. See `palette-window.ts`.\n */\nexport const BranchPicker = (props: BranchPickerProps) => {\n const { items, onSelect, onCancel } = props\n\n const T = BRANCH_PICKER_TEXT\n\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { rows } = useWindowSize()\n const { filtered, activeIndex, query, handleNavigation, clearQuery } = useListFilter(items, filterText)\n // First branch in the visible window; kept in state so the list scrolls by the minimum needed.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const layout = listLayout(rows)\n // No `groupOf`: a branch list has no headers, so every branch costs exactly one row.\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, { chromeRows: layout.chromeRows })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n const cancel = () => {\n onCancel()\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.ctrl && input === 'c') {\n cancel()\n\n return\n }\n\n // Esc pops the innermost stateful thing: a typed filter first, the picker only once\n // there is no filter left to clear. `clearQuery` returning false IS that ladder.\n if (key.escape) {\n if (!clearQuery()) {\n cancel()\n }\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.value)\n setSubmitted(true)\n }\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one branch row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START: overflow must eat the head of the filter, never the character being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n\n // `wrap=\"truncate\"` keeps one branch = one row at any width (a long branch name would\n // otherwise wrap and make the frame taller than this component believes). Ink reads the wrap\n // style off the OUTER <Text> only, so it must live here, not on the nested description.\n return (\n <Text color={labelColor(item.type, isActive)} key={item.value} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n </Box>\n )\n}\n\n/**\n * Colour for a row's label, derived from the release type. Kept a plain lookup so\n * an unknown/absent type simply falls through to the default (green when active).\n */\nfunction labelColor(type: string | undefined, isActive: boolean): string | undefined {\n if (type === 'hotfix') {\n return 'red'\n }\n\n return isActive ? 'green' : undefined\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n\n/**\n * Static screen copy. Module-scoped and exported so the hint-width guard can measure it:\n * these strings render under `wrap=\"truncate\"`, so a hint of \u226580 columns silently loses\n * its tail at the common terminal width \u2014 and the tail is where the Esc hint lives.\n */\nexport const BRANCH_PICKER_TEXT = {\n hint: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter select \u00B7 Esc clear/cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n tiny: 'terminal too short \u2014 resize to pick a branch',\n more: '\u2026',\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useMemo, useState } from 'react'\n\nimport type { PaletteItem } from '../types'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface CommandPaletteProps {\n items: PaletteItem[]\n /** Called with the chosen command name; the app then exits. */\n onSelect: (name: string) => void\n /** Called when the user cancels (Ctrl-C / Ctrl-D); the app then exits. Esc never reaches this. */\n onCancel: () => void\n /**\n * Stop the foreground job (Ctrl-Z). ABSENT means suspend is impossible on this platform \u2014 the\n * palette stays pure presentation and never inspects `process`; boot.tsx is the platform authority.\n */\n onSuspend?: () => void\n}\n\n/**\n * Fuzzy-ish command picker rendered with Ink. Pure presentation: it receives a\n * flat list of commands (already grouped/ordered by the catalog) and returns the\n * selected name. It never executes anything \u2014 the caller runs the command via\n * the existing Commander path.\n *\n * NOTE: this component sits at exactly the sonarjs cognitive-complexity ceiling (15). Any `if` or\n * `?:` added to its BODY breaks `pnpm run qa` \u2014 which is why the hint is picked by the module-scope\n * `hintFor` below and the control keys by `handleCtrlKey`, rather than inline.\n */\nexport const CommandPalette = (props: CommandPaletteProps) => {\n const { items, onSelect, onCancel, onSuspend } = props\n\n const T = {\n hint: hintFor(Boolean(onSuspend)),\n prompt: '\u276F ',\n empty: 'No matching commands',\n tiny: 'terminal too short \u2014 resize to pick a command',\n more: '\u2026',\n }\n\n const nameWidth = 24\n\n const { exit, suspendTerminal } = useApp()\n const { rows } = useWindowSize()\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n // First command in the visible window. Kept in state so the list scrolls by the minimum needed\n // instead of jumping every time the cursor moves.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame (Ink's `log.done()` would otherwise\n // freeze the last drawn frame \u2014 the command list \u2014 into the scrollback).\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return `${item.name} ${item.description}`.toLowerCase().includes(q)\n })\n }, [items, query])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n // The slice that fits this terminal, and how much chrome we may spend around it. A frame taller than\n // the viewport corrupts the cursor (see palette-window.ts) \u2014 every row here is budgeted, and every\n // row below is `wrap=\"truncate\"` so one command is always exactly one row.\n const layout = listLayout(rows)\n\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, {\n chromeRows: layout.chromeRows,\n // A compact frame drops group headers, so they must not be budgeted for either.\n groupOf: layout.groups\n ? (item) => {\n return item.group\n }\n : undefined,\n })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n // Back out with nothing picked (Ctrl-C / Ctrl-D). Esc is NOT a caller: it pops the filter only.\n const quit = () => {\n onCancel()\n setSubmitted(true)\n }\n\n // Hand the terminal back to the user's shell until they `fg`.\n //\n // Ink does all the terminal work for us, in the right order and synchronously: `beginSuspend`\n // settles pending frames, erases the list, restores the cursor and drops raw mode BEFORE our\n // callback runs, and on resume `endSuspend` re-arms raw mode and force-redraws THIS SAME LIVE\n // COMPONENT \u2014 so the typed filter survives the suspend. That is why we must NOT set `submitted`\n // here: unmounting would throw the query away and give us a blank palette on return.\n //\n // The `.catch` is the PRIMARY guard, not a backstop \u2014 never simplify it to `void`. Two 0x1a bytes\n // in one read chunk (a double-tap) are both already queued in Ink's input loop, and `pauseInput`\n // only detaches the stdin listener, so the second one still fires \u2014 into a `beginSuspend` that is\n // already suspended, which throws. Harmless (it throws before flipping its own state, and the first\n // suspension still unwinds), but the rejection must be caught: `void` would make it an unhandled\n // rejection that kills the process mid terminal-restore.\n const suspend = () => {\n if (!onSuspend) {\n return\n }\n\n suspendTerminal(onSuspend).catch(() => {\n // See above: a double Ctrl-Z is a no-op, not a crash.\n })\n }\n\n /**\n * Ctrl-C / Ctrl-Z, hoisted OUT of the `useInput` body. Mandatory, not tidiness: that handler sits at\n * cognitive complexity 14, and an inline `if (key.ctrl && input === 'z' && onSuspend)` costs +2 \u2014\n * 16, over the sonarjs ceiling of 15, and `pnpm run qa` goes red.\n *\n * The palette's Ctrl-Z is a BYTE (0x1a), not a signal: Ink holds stdin in raw mode, which clears\n * termios ISIG, so the tty never generates SIGTSTP here at all. We therefore stop the process GROUP\n * ourselves (kill(0), see ../suspend.ts). The session shell's SIGTSTP handler does the opposite \u2014\n * it self-stops with raise('SIGSTOP') (lib/session/run-session.ts) \u2014 and that is CORRECT there,\n * because while a child command holds the foreground the tty is cooked and has already TSTP'd the\n * whole group, leaving only us to follow. DO NOT UNIFY THE TWO.\n */\n const handleCtrlKey = (input: string): boolean => {\n if (input === 'c') {\n quit()\n\n return true\n }\n\n // Ctrl-D is the REPL/shell convention for \"end of input\", and it quits exactly like Ctrl-C above.\n // UNCONDITIONAL, unlike anything Esc does: it ends the session with a filter typed as readily as\n // without one. It is no longer the key the footer names \u2014 Ctrl-C is, because that is the one a\n // hand reaches for to abandon a picker \u2014 but a shell user's fingers know this one, so it stays.\n if (input === 'd') {\n quit()\n\n return true\n }\n\n if (input === 'z') {\n suspend()\n\n return true\n }\n\n return false\n }\n\n // Move the active row by `delta`, wrapping. The `+ n` sidesteps JS negative modulo\n // (e.g. -1 % 5 === -1, not 4). No-op on an empty list.\n const step = (delta: number) => {\n const n = filtered.length\n\n if (n > 0) {\n setIndex((activeIndex + delta + n) % n)\n }\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n // Ctrl-C quits, Ctrl-Z suspends (see handleCtrlKey). Esc pops one level and this palette has\n // exactly one \u2014 the filter \u2014 so an empty filter makes it a no-op, NOT a quit. Popping the root\n // would leave nowhere to land: the session shell has no screen behind the palette, so an Esc that\n // quit would be a quit wearing a back-out's clothes. Quitting is Ctrl-C / Ctrl-D, and only those.\n // No emptiness check: clearing an already-empty query is a React no-op.\n if (key.ctrl && handleCtrlKey(input)) {\n return\n }\n\n if (key.escape) {\n setQuery('')\n setIndex(0)\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.name)\n setSubmitted(true)\n }\n\n return\n }\n\n if (key.upArrow) {\n step(-1)\n\n return\n }\n\n if (key.downArrow) {\n step(1)\n\n return\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return\n }\n\n // Printable character: append to the filter.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n }\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one command row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n let lastGroup = ''\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START on the input: overflow must eat the head of the filter, never the character\n being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n const showGroup = layout.groups && item.group !== lastGroup\n\n lastGroup = item.group\n\n return (\n <Box flexDirection=\"column\" key={item.name}>\n {/* Blank line between groups (not before the first row of the window). */}\n {showGroup && position > 0 ? <Text> </Text> : null}\n {showGroup ? <Text color=\"yellow\" wrap=\"truncate\">{`\u2014 ${item.group} \u2014`}</Text> : null}\n {/* `wrap=\"truncate\"` is load-bearing, not cosmetic: it is what makes \"one command = one\n row\" true at any width, which is what keeps the frame shorter than the viewport. Ink\n reads the wrap style off the OUTER <Text> only \u2014 it squashes the nested <Text> into\n this one's string \u2014 so it must live here. */}\n <Text color={isActive ? 'green' : undefined} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {item.name.padEnd(nameWidth)} <Text dimColor>{item.description}</Text>\n </Text>\n </Box>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n </Box>\n )\n}\n\n/**\n * Footer copy. Kept out of the component's `T` because picking between the two is a conditional.\n *\n * Exported so the hint-width guard can measure these strings: they render under `wrap=\"truncate\"`,\n * so a hint of \u226580 columns silently loses its TAIL \u2014 and the tail is where the newest keybinding\n * always lands. `Esc clear` is the whole truth, not an abbreviation of one: Esc pops the filter and\n * never quits, so the `quit` beside it is the only advertised way out.\n *\n * That advertised key is Ctrl-C, though Ctrl-D quits identically (see `handleCtrlKey`). Naming only\n * one is a width decision, and Ctrl-C wins it: it is what a hand reaches for to abandon a picker, and\n * it went UNADVERTISED here for as long as the palette existed.\n *\n * The slack this leaves is NOT spendable: restoring `type to filter` to the suspend variant would\n * measure 79 against the guard's `toBeLessThan(80)`, i.e. one column from silently truncating again.\n */\nexport const HINTS = {\n suspend: 'filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc clear \u00B7 Ctrl-C quit \u00B7 Ctrl-Z suspend',\n plain: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc clear \u00B7 Ctrl-C quit',\n}\n\n/**\n * The footer hint, which advertises Ctrl-Z only where suspending is possible.\n *\n * Module scope for two reasons, both load-bearing. It cannot live in the component: a `?:` in\n * `CommandPalette`'s body pushes it from 15 to 16, over the sonarjs cognitive-complexity ceiling. And\n * it cannot sit above the component either: `@wl/component-file-order` pins this file to\n * imports \u2192 props interface \u2192 component with nothing in between. Below is the only legal home.\n *\n * Both strings are SHORTER than the hint they replace, on purpose \u2014 the footer renders with\n * `wrap=\"truncate\"`, so anything longer silently loses its tail on a narrow terminal, and the tail is\n * exactly where a newly-added key would land.\n *\n * @example\n * hintF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AAW,IACb,EACF,CACF,EAEOA,CACT,EAQaO,GAAuB,MAClCR,EACAS,IAC6B,CAC7B,IAAIR,EAA4B,KAEhC,aAAMV,EACJD,EAACoB,GAAA,CACC,MAAOV,EACP,SAAUS,GAAM,SAChB,eAAgBA,GAAM,eACtB,SAAWE,GAAW,CACpBV,EAAWU,CACb,EACA,SAAU,IAAM,CACdV,EAAW,IACb,EACF,CACF,EAEOA,CACT",
6
+ "names": ["render", "process", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useState", "useMemo", "useState", "useListFilter", "items", "toText", "query", "setQuery", "index", "setIndex", "filtered", "q", "item", "activeIndex", "input", "key", "n", "NO_GROUPS", "listLayout", "rows", "extraChromeRows", "heightOf", "items", "start", "end", "groupOf", "height", "previousGroup", "index", "item", "group", "startsGroup", "endThatFits", "budget", "paletteWindow", "activeIndex", "opts", "first", "jsx", "jsxs", "BranchMultiPicker", "props", "items", "onSubmit", "onCancel", "required", "allowSelectAll", "T", "BRANCH_MULTI_PICKER_TEXT", "labelWidth", "max", "item", "exit", "useApp", "rows", "useWindowSize", "filtered", "activeIndex", "query", "handleNavigation", "clearQuery", "useListFilter", "filterText", "selected", "setSelected", "useState", "showRequiredHint", "setShowRequiredHint", "windowStart", "setWindowStart", "submitted", "setSubmitted", "useEffect", "layout", "listLayout", "view", "paletteWindow", "toggleValue", "value", "prev", "next", "toggleSelectAll", "cancel", "submit", "useInput", "input", "key", "active", "Text", "Box", "position", "isActive", "isChecked", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useState", "jsx", "jsxs", "BranchPicker", "props", "items", "onSelect", "onCancel", "T", "BRANCH_PICKER_TEXT", "labelWidth", "max", "item", "exit", "useApp", "rows", "useWindowSize", "filtered", "activeIndex", "query", "handleNavigation", "clearQuery", "useListFilter", "filterText", "windowStart", "setWindowStart", "useState", "submitted", "setSubmitted", "useEffect", "layout", "listLayout", "view", "paletteWindow", "cancel", "useInput", "input", "key", "selected", "Text", "Box", "position", "isActive", "labelColor", "type", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useMemo", "useState", "jsx", "jsxs", "CommandPalette", "props", "items", "onSelect", "onCancel", "onSuspend", "T", "hintFor", "nameWidth", "exit", "suspendTerminal", "useApp", "rows", "useWindowSize", "query", "setQuery", "useState", "index", "setIndex", "windowStart", "setWindowStart", "submitted", "setSubmitted", "useEffect", "filtered", "useMemo", "q", "item", "activeIndex", "layout", "listLayout", "view", "paletteWindow", "quit", "suspend", "handleCtrlKey", "input", "step", "delta", "n", "useInput", "key", "selected", "Text", "lastGroup", "Box", "position", "isActive", "showGroup", "HINTS", "canSuspend", "jsx", "renderToStderr", "element", "stdout", "safeStderr", "waitUntilExit", "render", "stdinReaderCount", "process", "runCommandPalette", "items", "selected", "CommandPalette", "name", "suspendForeground", "runBranchPicker", "BranchPicker", "value", "runBranchMultiPicker", "opts", "BranchMultiPicker", "values"]
7
+ }
@@ -1,4 +1,4 @@
1
- import{P as f,l as $,r as F}from"./chunk-467ZSXYU.js";import{execFile as te,execFileSync as oe}from"node:child_process";import b from"node:process";var ne=5e3,ae=100,W=2e3,U="/bin/ps",se=1e3,J=["-eo","pid=,ppid=,pgid=,lstart="],V=8<<20,B=e=>e.split(`
1
+ import{P as f,l as $,r as F}from"./chunk-BPOPODWW.js";import{execFile as te,execFileSync as oe}from"node:child_process";import b from"node:process";var ne=5e3,ae=100,W=2e3,U="/bin/ps",se=1e3,J=["-eo","pid=,ppid=,pgid=,lstart="],V=8<<20,B=e=>e.split(`
2
2
  `).flatMap(r=>{let[t,o,n,...i]=r.trim().split(/\s+/);if(t==null||o==null||n==null)return[];let l=Number(t),s=Number(o),c=Number(n);return!Number.isInteger(l)||!Number.isInteger(s)||!Number.isInteger(c)?[]:[{pid:l,ppid:s,pgid:c,lstart:i.join(" ")}]}),H=e=>{let r=new Map;for(let t of e)t.pid===t.pgid&&r.set(t.pgid,t.lstart);return r},ie=(e,r,t)=>{let o=H(r);return j(e,r,t).flatMap(n=>{let i=o.get(n);return i==null||i===""?[]:[{pgid:n,leaderStart:i}]})},K=(e,r)=>{let t=H(r);return e.flatMap(({pgid:o,leaderStart:n})=>t.get(o)===n?[o]:[])},D=(e,r)=>K(e,r).flatMap(t=>{try{b.kill(-t,"SIGKILL")}catch{return[]}return[t]}),j=(e,r,t)=>{let o=new Map;for(let s of r){let c=o.get(s.ppid);c?c.push(s):o.set(s.ppid,[s])}let n=new Set([e]),i=new Set([e]),l=[e];for(let s=0;s<l.length;s+=1)for(let c of o.get(l[s]??-1)??[])i.has(c.pid)||(i.add(c.pid),n.add(c.pgid),l.push(c.pid));return[...n].filter(s=>s>1&&s!==t)},A=()=>{try{return B(oe(U,[...J],{encoding:"utf8",maxBuffer:V}))}catch{return[]}},ce=async()=>new Promise(e=>{te(U,[...J],{encoding:"utf8",maxBuffer:V},(r,t)=>{e(r?[]:B(t))})}),le=(e,r,t)=>t.some(o=>o.pid===e&&o.ppid===r),L=(e,r)=>{let t=r.find(o=>o.pid===b.pid)?.pgid;return j(e,r,t)},q=e=>{try{return b.kill(-e,0),!0}catch{return!1}},C=(e,r)=>{for(let t of e)try{b.kill(-t,r)}catch{}},S=new Set,ue=(e,r,t)=>{let o=L(e,r),n=t.flatMap(i=>K(i,r));return[...new Set([...o,...n])]},z=()=>{let e=A(),r=[...S].map(t=>t());C(ue(b.pid,e,r),"SIGKILL")},pe=async e=>new Promise(r=>{setTimeout(r,e)}),v=async(e,r)=>{let t=Date.now()+r,o=e;for(;o.length>0&&Date.now()<t&&(o=o.filter(q),o.length!==0);)await pe(ae);return o};function or(e,r=ne,t,o=A){e.unref();let n=!1,i=!1,l=[],s=null,c=()=>l;S.add(c);let m=()=>{s&&clearInterval(s),s=null},w=async()=>{await v(l.map(a=>a.pgid),W),S.delete(c)},h=a=>{let u=e.pid;if(u==null||i||n||a.length===0)return;let R=a.find(_=>_.pid===b.pid)?.pgid,x=ie(u,a,R);x.length>0&&(l=x)},y=async()=>{e.pid==null||i||n||h(await ce())};h(A()),s=setInterval(()=>{y()},se),s.unref();let T=a=>{n||t?.(a)};return e.on("exit",(a,u)=>{i=!0,m(),n||(D(l,o()),w()),T(`exited unexpectedly (code=${a??"null"}, signal=${u??"null"})`)}),e.on("error",a=>{T(`failed to spawn: ${a.message}`)}),{kill:async()=>{n=!0,m();let a=e.pid;if(a==null){S.delete(c);return}if(e.exitCode!==null||e.signalCode!==null){D(l,o()),await w();return}let u=o();if(u.length>0&&!le(a,b.pid,u))return;let R=L(a,u);C(R,"SIGTERM");let x=await v(R,r);if(x.length===0){S.delete(c);return}let _=L(a,o()),G=[...new Set([...x,..._])].filter(q);C(G,"SIGKILL"),await v(G,W),S.delete(c)}}}import{constants as de}from"node:os";import k from"node:process";var me=["SIGINT","SIGTERM","SIGHUP"],fe=de.signals,ge=2,N=e=>128+(fe[e]??ge),Oe=2e4,be=e=>{k.exit(e)},we=(e,r)=>{k.on(e,r)},he=(e,r)=>{k.off(e,r)},ye=(e,r)=>{let t=setTimeout(e,r);return t.unref(),()=>{clearTimeout(t)}},I=e=>{try{k.stderr.write(e)}catch{}},Se=(e,r)=>{let t=r instanceof Error?`${r.message}
3
3
  ${r.stack??"(no stack)"}`:String(r);I(`
4
4
  \u2717 Teardown failed while handling ${e}: ${t}
@@ -7,4 +7,4 @@ ${r.stack??"(no stack)"}`:String(r);I(`
7
7
  `),w?.(),n(),y(),r(N(a));return}m=a,w=l(()=>{let u=`
8
8
  \u26A0 Teardown deadline exceeded at stage=${s()} after ${i}ms \u2014 force-quitting.
9
9
  `;I(u),c(u),n(),y(),r(N(a))},i),(async()=>{try{await e(a)}catch(u){Se(a,u)}finally{w?.(),y(),r(N(a))}})()};for(let a of me){let u=()=>T(a);h.set(a,u),t(a,u)}return y};var Pe=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),X=e=>e instanceof Error&&Pe.has(e.name),ur=e=>{if(X(e))return!0;let r=e?.cause;return X(r)};import{$ as xe}from"zx";var d=class extends Error{code;data;constructor(r){super(r.message),this.name="OrcaError",this.code=r.code,this.data=r.data}},P=class extends Error{exitCode;stderrTail;constructor(r,t){super(`orca: stdout is not a JSON envelope (exit ${r??"signal"})`),this.name="OrcaMalformedError",this.exitCode=r,this.stderrTail=t}},g=class extends Error{constructor(){super("orca: command not found \u2014 the CLI is registered from Orca \u2192 Settings \u2192 Experimental \u2192 CLI"),this.name="OrcaAbsentError"}},Te=400,Re=127,ke=e=>typeof e=="object"&&e!==null&&e.code==="ENOENT",Ee=async e=>{try{return await xe({nothrow:!0,quiet:!0})`orca ${e} --json`}catch(r){throw ke(r)?new g:r}},_e=e=>{try{let r=JSON.parse(e);return typeof r=="object"&&r!==null&&typeof r.ok=="boolean"?r:null}catch{return null}},p=async e=>{let r=await Ee(e),t=_e(r.stdout);if(f.debug({argv:e,ok:t?.ok,code:t?.error?.code,exitCode:r.exitCode},"orca"),!t)throw r.exitCode===Re?new g:new P(r.exitCode,r.stderr.slice(-Te));if(!t.ok)throw new d(t.error??{code:"unknown",message:"orca: ok:false without an error payload"});return t.result};var ve=async()=>{try{let e=await p(["status"]);return f.debug({appVersion:e.runtime?.appVersion},"orca: status"),e.app?.running===!0&&e.runtime?.reachable===!0?"ready":"unreachable"}catch(e){return e instanceof g?"absent":(f.debug({error:e},"orca: status probe failed"),"unreachable")}};import{realpath as Ae}from"node:fs/promises";var O=async e=>{try{return await Ae(e)}catch{return e}};var Le=async e=>{let[{repos:r=[]},t]=await Promise.all([p(["repo","list"]),O(e)]);for(let o of r)if(await O(o.path)===t)return{registered:!0,visibility:o.externalWorktreeVisibility};return{registered:!1}},Ce=async e=>{let{repo:r}=await p(["repo","add","--path",e]);return{visibility:r?.externalWorktreeVisibility}};var Ne="500",Ie=async(e,r)=>{let[{worktrees:t=[]},o]=await Promise.all([p(["worktree","list","--repo",`path:${e}`,"--limit",Ne]),O(r)]);for(let n of t)if(await O(n.path)===o)return!0;return!1};import Me from"node:process";var Y="::",Ge=e=>{let r=e.ORCA_WORKTREE_ID;if(!r)return null;let t=r.indexOf(Y);if(t<0)return null;let o=r.slice(t+Y.length);return o.length>0?o:null},$e=async(e,r=Me.env)=>{let t=Ge(r);if(t===null)return null;let o=await O(t);for(let n of e)if(await O(n)===o)return n;return null};var Q="200",M=async e=>{try{let r=await p(["terminal","list","--worktree",`path:${e}`,"--limit",Q]),t=r.truncated===!0;return t&&f.debug({cwd:e,limit:Q},"orca: terminal list truncated"),{terminals:r.terminals??[],truncated:t}}catch(r){if(r instanceof d&&r.code==="selector_not_found")return{terminals:[],truncated:!1};throw r}};var Fe=async e=>{try{return await p(["terminal","close","--worktree",`path:${e}`,"--all"]),"retired"}catch(r){if(r instanceof d&&r.code==="selector_not_found")return"not_found";if(r instanceof d&&r.code==="terminal_close_incomplete")return f.debug({cwd:e,error:r},"orca: surfaces not retired"),"retired";throw r}},We=async e=>{let{terminals:r}=await M(e);for(let o of r)await p(["terminal","close","--terminal",o.handle]);let t=await Fe(e);return r.length===0&&t==="not_found"?{closed:!1,skipped:"not_found"}:{closed:!0,count:r.length}},De=(e,r)=>r instanceof g?{closed:!1,skipped:"absent"}:r instanceof d?{closed:!1,error:r}:r instanceof P?{closed:!1,error:new d({code:"orca_malformed_output",message:r.message,data:{exitCode:r.exitCode,stderrTail:r.stderrTail}})}:(f.debug({cwd:e,error:r},"orca: close failed outside the Orca contract"),{closed:!1,error:new d({code:"orca_close_failed",message:r instanceof Error?r.message:String(r)})}),Ue=async(e,r)=>{if(r!=="ready")return{closed:!1,skipped:r};try{return await We(e)}catch(t){return De(e,t)}};import{setTimeout as Je}from"node:timers/promises";var Ve=3,Be=300,ee=(e={})=>({attempts:e.attempts??Ve,delayMs:e.delayMs??Be,exhausted:!1}),He=async e=>{try{return{created:await p(e)}}catch(r){if(r instanceof d&&r.code==="selector_not_found")return{notSelectable:r};throw r}},Ke=async(e,r,t)=>{let o=t.exhausted?1:t.attempts,n=Array.from({length:o},(l,s)=>s+1),i;for(let l of n){let s=await He(e);if("created"in s)return s.created.terminal.handle;i=s.notSelectable,l<o&&await Je(t.delayMs)}throw t.exhausted=!0,new d({code:"orca_worktree_not_selectable",message:`orca: worktree ${r} is not selectable after ${o} attempt(s): ${i?.message??""}`,data:{cwd:r,attempts:o,cause:i?.data}})},Z=async(e,r)=>(await p(["terminal","split","--terminal",e,"--direction",r])).split.handle,je=async e=>{let{cwd:r,title:t,focus:o,layout:n,panes:i,poll:l=ee()}=e,s=["terminal","create","--worktree",`path:${r}`,"--title",t,...o?["--focus"]:[]],c=await Ke(s,r,l),m=[c];return n==="full"&&(m.push(await Z(c,"horizontal")),i==="three-pane"&&m.push(await Z(c,"vertical"))),{handles:m,layout:n}};var qe=e=>{let{branch:r}=e,t=$(r);return t?F(t):r};var Yr=e=>typeof e=="object",E=async e=>(await e.body?.cancel(),{kind:"foreign",status:e.status,contentType:e.headers.get("content-type")}),Qr=(e,r)=>{let t=r.contentType?.split(";")[0]?.trim(),o=t==null||t===""?`${r.status}`:`${r.status} ${t}`;return`port ${e} answered ${o}, not vite's ping \u2014 liveness cannot be verified`};var re={accept:"text/x-vite-ping"},ze=e=>e.kind==="api"?`http://127.0.0.1:${e.port}/__health`:`http://127.0.0.1:${e.port}/`,Xe=(e,r)=>{try{return new URL(e,r)}catch{return null}},Ye=async(e,r)=>{let t=await fetch(e,{signal:r});return t.ok?(await t.body?.cancel(),"ok"):E(t)},Qe=async(e,r)=>{let t=await fetch(e,{headers:re,redirect:"manual",signal:r});if(t.status===204)return"ok";if(t.status<300||t.status>=400)return E(t);let o=t.headers.get("location"),n=o==null?null:Xe(o,e);if(n==null||n.origin!==new URL(e).origin)return E(t);await t.body?.cancel();let i=await fetch(n,{headers:re,redirect:"manual",signal:r});return i.status!==204?E(i):(await i.body?.cancel(),"ok")},Zr=async e=>{let r=ze(e),t=AbortSignal.timeout(1500);try{return e.kind==="api"?await Ye(r,t):await Qe(r,t)}catch{return"refused"}};import{readRelease as Ze}from"@slip-stream-kit/config/internal";var er=e=>Ze(e);export{z as a,or as b,N as c,cr as d,d as e,p as f,ve as g,$e as h,M as i,Ue as j,Le as k,Ce as l,Ie as m,ee as n,je as o,qe as p,Yr as q,Qr as r,Zr as s,er as t,ur as u};
10
- //# sourceMappingURL=chunk-5ZBDB3U7.js.map
10
+ //# sourceMappingURL=chunk-3JFITLZG.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/dev/managed-child.ts", "../src/dev/signal-shutdown.ts", "../src/lib/errors/is-prompt-cancellation.ts", "../src/integrations/orca/run-orca.ts", "../src/integrations/orca/availability.ts", "../src/integrations/orca/realpath-for-orca-cwd.ts", "../src/integrations/orca/ensure-repo.ts", "../src/integrations/orca/is-worktree-listed.ts", "../src/integrations/orca/caller-inside-target.ts", "../src/integrations/orca/list-terminals-by-cwd.ts", "../src/integrations/orca/close-worktree-terminals.ts", "../src/integrations/orca/open-worktree-terminals.ts", "../src/integrations/orca/terminal-title.ts", "../src/dev/health-probe.ts", "../src/lib/app-release/app-release.ts"],
4
+ "sourcesContent": ["/**\n * @fileoverview\n *\n * Shared supervision for the dev-server's long-lived, detached child processes\n * (`turbo watch build`, `turbo run dev`). Both are deep trees\n * (`sh \u2192 pnpm \u2192 node \u2192 turbo \u2192 \u2026`) spawned `detached` so they form their own process\n * group; teardown signals the whole GROUP (`process.kill(-pid, \u2026)`), not just the wrapper.\n *\n * Signalling turbo's group is NOT enough on its own: turbo puts every task it runs\n * (`vite`, `tsc -b`, \u2026) into a process group of its OWN, so `kill(-turboPid, \u2026)` reaches\n * turbo but never its tasks. Turbo normally forwards the signal and reaps them, but when it\n * is slower than the grace window a bare `SIGKILL` on turbo's group kills the only process\n * that knows the task groups \u2014 stranding orphaned vite servers that hold their ports until\n * the next run fails with `EADDRINUSE`.\n *\n * So teardown snapshots the descendant process groups BEFORE signalling (once turbo dies its\n * children reparent to init and can no longer be found by walking `ppid`), waits for the whole\n * set to exit, and only then force-kills whatever is left.\n *\n * The same fact \u2014 reparenting blinds the `ppid` walk \u2014 is why a snapshot taken only at teardown is not\n * enough. When turbo dies on its OWN (a crash, an OOM kill) there is no teardown to snapshot from, and\n * the tasks it never reaped are already unreachable. So the snapshot is instead kept ROLLING for the\n * child's whole life, and each group is stamped with its leader's `lstart`: a pgid is a bare integer the\n * kernel will happily recycle, and the leader's start time is the only proof that the group we are about\n * to SIGKILL is still the one we saw.\n *\n * That rolling snapshot lives in a per-child closure, which is exactly what the SECOND-SIGNAL force path\n * (`killDescendantGroupsNow`, used by both `signal-shutdown`'s force-quit and `crash-barrier`'s fatal\n * path) cannot reach on its own \u2014 it only ever does a live `ppid` walk from `process.pid`, the same walk\n * that goes blind the moment a child dies. So every supervised child's snapshot is also published to a\n * module-level `registry` (see below), letting that force path find a descendant which reparented to init\n * before ITS parent's `exit` even fired \u2014 the one case a live walk structurally cannot cover.\n */\nimport { execFile, execFileSync } from 'node:child_process'\nimport type { ChildProcess } from 'node:child_process'\nimport process from 'node:process'\n\n/** Handle to a supervised child; `kill()` reaps its whole process tree and resolves when gone. */\nexport interface ManagedChild {\n kill: () => Promise<void>\n}\n\n/**\n * Grace before escalating SIGTERM \u2192 SIGKILL. Long enough for turbo to stop its tasks itself\n * (typically well under a second) and short enough that Ctrl-C still feels immediate. Escalating\n * is safe now that every task group is killed as a set, so this need not cover the worst case.\n * The happy path never waits the full window \u2014 teardown returns as soon as the groups are gone.\n */\nconst DEFAULT_GRACE_MS = 5000\n\n/** Poll interval while waiting for the doomed process groups to exit. */\nconst POLL_MS = 100\n\n/** How long to wait for the kernel to reap a group after SIGKILL before giving up on confirmation. */\nconst REAP_TIMEOUT_MS = 2000\n\n/** Absolute path to `ps` \u2014 present on both macOS and Linux, and immune to `PATH` substitution. */\nconst PS_BIN = '/bin/ps'\n\n/**\n * How often the live process table is sampled while a supervised child is alive, to keep\n * {@link ManagedChild}'s group snapshot current. See {@link superviseChild} for why a snapshot taken\n * only at kill-time is too late. Async (`execFile`, not `execFileSync`), so it never blocks the event\n * loop the in-process backends share.\n */\nconst SAMPLE_INTERVAL_MS = 1000\n\n/** `ps` columns: the `ppid` walk needs pid/ppid/pgid, and the reuse guard needs the leader's `lstart`. */\nconst PS_ARGS = ['-eo', 'pid=,ppid=,pgid=,lstart='] as const\n\n/** Cap on `ps` output; a busy machine's full process table stays far below this. */\nconst PS_MAX_BUFFER = 8 << 20\n\n/** One row of `ps -eo pid=,ppid=,pgid=,lstart=`. */\nexport interface ProcRow {\n pid: number\n ppid: number\n pgid: number\n /** The process's start time as `ps` prints it (`Mon Jul 13 13:21:14 2026`); `''` when unavailable. */\n lstart: string\n}\n\n/**\n * The subset of a {@link ProcRow} that describes the process TREE. The `ppid` walk needs nothing else,\n * so the functions that only walk take this \u2014 `lstart` is the reuse guard's concern, not the topology's.\n */\nexport type TopologyRow = Pick<ProcRow, 'pid' | 'ppid' | 'pgid'>\n\n/**\n * Parse `ps -eo pid=,ppid=,pgid=,lstart=`, skipping any line that doesn't start with three integers.\n * `lstart` is whitespace-separated and multi-token, so it is everything after the third column.\n */\nexport const parseProcRows = (raw: string): ProcRow[] => {\n return raw.split('\\n').flatMap((line) => {\n const [rawPid, rawPpid, rawPgid, ...rest] = line.trim().split(/\\s+/)\n\n if (rawPid == null || rawPpid == null || rawPgid == null) return []\n\n const pid = Number(rawPid)\n const ppid = Number(rawPpid)\n const pgid = Number(rawPgid)\n\n if (!Number.isInteger(pid) || !Number.isInteger(ppid) || !Number.isInteger(pgid)) return []\n\n return [{ pid, ppid, pgid, lstart: rest.join(' ') }]\n })\n}\n\n/**\n * A process group, stamped with its LEADER's start time at the moment the group was observed.\n *\n * The start time is the whole point. A pgid on its own is a bare integer: by the time we come to reap\n * it the kernel may have recycled it onto an unrelated process, and `kill(-pgid, \u2026)` would then destroy\n * a stranger's group. The leader's `lstart` is the identity that survives \u2014 a recycled pgid necessarily\n * has a NEWER birth time than the one recorded, so it is refused.\n */\nexport interface GroupSnapshot {\n pgid: number\n leaderStart: string\n}\n\n/** Map every process group in `rows` to its leader's start time (the leader is the pid equal to the pgid). */\nconst leaderStarts = (rows: ProcRow[]): Map<number, string> => {\n const starts = new Map<number, string>()\n\n for (const row of rows) {\n if (row.pid === row.pgid) starts.set(row.pgid, row.lstart)\n }\n\n return starts\n}\n\n/**\n * {@link collectDoomedGroups}, but each group is stamped with its leader's start time so it can be\n * validated later. Groups whose leader is not in `rows` are dropped: with no leader there is nothing to\n * stamp, so nothing could prove the group is still the one we saw, and the reuse guard must fail closed.\n *\n * @example\n * const rows = [\n * { pid: 10, ppid: 1, pgid: 10, lstart: 'Mon Jul 13 13:00:00 2026' },\n * { pid: 20, ppid: 10, pgid: 20, lstart: 'Mon Jul 13 13:00:01 2026' },\n * ]\n * snapshotGroups(10, rows) // => [{ pgid: 10, leaderStart: '\u202613:00:00\u2026' }, { pgid: 20, leaderStart: '\u202613:00:01\u2026' }]\n */\nexport const snapshotGroups = (rootPid: number, rows: ProcRow[], excludePgid?: number): GroupSnapshot[] => {\n const starts = leaderStarts(rows)\n\n return collectDoomedGroups(rootPid, rows, excludePgid).flatMap((pgid) => {\n const leaderStart = starts.get(pgid)\n\n if (leaderStart == null || leaderStart === '') return []\n\n return [{ pgid, leaderStart }]\n })\n}\n\n/**\n * pgids in `snapshot` whose leader's start time still matches `rows` \u2014 the reuse guard shared by every\n * path that reaps from a snapshot instead of a live walk: {@link reapSnapshot} (the per-child crash/kill\n * reap) and {@link collectForceReapTargets} (the force-reap path, reaping every REGISTERED child's\n * snapshot). Extracted so the two can never drift apart \u2014 a registry-sourced pgid must clear the exact\n * same check a per-child reap does before either signals it.\n */\nconst validSnapshotPgids = (snapshot: readonly GroupSnapshot[], rows: ProcRow[]): number[] => {\n const starts = leaderStarts(rows)\n\n return snapshot.flatMap(({ pgid, leaderStart }) => {\n return starts.get(pgid) === leaderStart ? [pgid] : []\n })\n}\n\n/**\n * SIGKILL every snapshotted group whose leader is STILL the same process, and return the pgids killed.\n *\n * A group whose leader has since exited is skipped (nothing to kill, and no way to prove ownership of\n * whatever else may share the pgid). A group whose leader's start time no longer matches is a recycled\n * pgid belonging to a stranger \u2014 skipped, loudly and deliberately. This is the guard that makes reaping\n * from a stale snapshot safe, and it is why the snapshot records `lstart` at all.\n */\nexport const reapSnapshot = (snapshot: readonly GroupSnapshot[], rows: ProcRow[]): number[] => {\n return validSnapshotPgids(snapshot, rows).flatMap((pgid) => {\n try {\n process.kill(-pgid, 'SIGKILL')\n } catch {\n // Raced us to exit (ESRCH) \u2014 nothing to kill.\n return []\n }\n\n return [pgid]\n })\n}\n\n/**\n * Distinct process groups of every transitive descendant of `rootPid`, plus `rootPid`'s own\n * group. Group `0`/`1` and `excludePgid` (our own group \u2014 a detached child can never share it,\n * but a mis-parsed row must never make us signal ourselves) are filtered out.\n *\n * @example\n * const rows = [{ pid: 10, ppid: 1, pgid: 10 }, { pid: 20, ppid: 10, pgid: 20 }]\n * collectDoomedGroups(10, rows, 5) // => [10, 20]\n */\nexport const collectDoomedGroups = (rootPid: number, rows: TopologyRow[], excludePgid?: number): number[] => {\n const childrenOf = new Map<number, TopologyRow[]>()\n\n for (const row of rows) {\n const siblings = childrenOf.get(row.ppid)\n\n if (siblings) siblings.push(row)\n else childrenOf.set(row.ppid, [row])\n }\n\n const groups = new Set<number>([rootPid])\n const seen = new Set<number>([rootPid])\n const queue = [rootPid]\n\n for (let i = 0; i < queue.length; i += 1) {\n for (const child of childrenOf.get(queue[i] ?? -1) ?? []) {\n if (seen.has(child.pid)) continue\n seen.add(child.pid)\n groups.add(child.pgid)\n queue.push(child.pid)\n }\n }\n\n return [...groups].filter((pgid) => {\n return pgid > 1 && pgid !== excludePgid\n })\n}\n\n/**\n * Snapshot the live process table; an empty list on failure degrades to group-only teardown.\n * `ps` is invoked by absolute path (not via `PATH`, unlike the `pnpm` the engines shell out to)\n * so a writable `PATH` entry can never substitute the binary we hand a kill list to.\n */\nconst snapshotProcRows = (): ProcRow[] => {\n try {\n return parseProcRows(execFileSync(PS_BIN, [...PS_ARGS], { encoding: 'utf8', maxBuffer: PS_MAX_BUFFER }))\n } catch {\n return []\n }\n}\n\n/**\n * {@link snapshotProcRows}, off the event loop. The rolling sampler runs on a timer for the whole life\n * of a dev session, and the in-process backends share this loop \u2014 a synchronous `ps` every second would\n * stall every request that lands during it. Resolves to `[]` on failure, degrading to the previous\n * snapshot rather than clobbering it.\n */\nconst snapshotProcRowsAsync = async (): Promise<ProcRow[]> => {\n return new Promise((resolve) => {\n execFile(PS_BIN, [...PS_ARGS], { encoding: 'utf8', maxBuffer: PS_MAX_BUFFER }, (error, stdout) => {\n resolve(error ? [] : parseProcRows(stdout))\n })\n })\n}\n\n/** Does `pid` currently exist and name a direct child of `parentPid`? Guards against pid reuse. */\nexport const isChildOf = (pid: number, parentPid: number, rows: TopologyRow[]): boolean => {\n return rows.some((row) => {\n return row.pid === pid && row.ppid === parentPid\n })\n}\n\n/**\n * The groups to signal for `rootPid`'s tree, excluding our own group so a mis-parsed `ps` row can\n * never make the dev-server signal itself.\n */\nconst doomedGroupsOf = (rootPid: number, rows: ProcRow[]): number[] => {\n const ownPgid = rows.find((row) => {\n return row.pid === process.pid\n })?.pgid\n\n return collectDoomedGroups(rootPid, rows, ownPgid)\n}\n\n/** Is the process group led by `pgid` still alive? (`kill(-pgid, 0)` throws ESRCH when gone.) */\nconst groupAlive = (pgid: number): boolean => {\n try {\n process.kill(-pgid, 0)\n\n return true\n } catch {\n return false\n }\n}\n\n/** Send `signal` to every named process group, ignoring groups that already exited. */\nconst signalGroups = (pgids: number[], signal: NodeJS.Signals): void => {\n for (const pgid of pgids) {\n try {\n process.kill(-pgid, signal)\n } catch {\n // Already gone (ESRCH) \u2014 nothing to signal.\n }\n }\n}\n\n/**\n * Live accessors into every currently-supervised child's rolling {@link GroupSnapshot} list \u2014 populated by\n * {@link superviseChild} on spawn, removed only once that child's own groups are CONFIRMED gone (see\n * `deregisterAfter` inside it, not the child's bare `exit` event). This is what lets\n * {@link killDescendantGroupsNow} \u2014 the second-signal force path and the crash-barrier's fatal path \u2014\n * reach a descendant that reparented to init before ITS parent's `exit` fired: a live `ppid` walk from\n * `process.pid` cannot see such a descendant (see the module doc block for why), but a snapshot recorded\n * while the parent was still alive can.\n *\n * INVARIANT \u2014 never regress this: a registry-sourced pgid is signalled ONLY after\n * {@link validSnapshotPgids} confirms its leader's start time still matches a FRESH `ps` snapshot. An\n * ungated union would SIGKILL a recycled pgid \u2014 a hazard the live walk cannot have, since it only ever\n * names processes that are alive right now.\n */\nconst registry = new Set<() => readonly GroupSnapshot[]>()\n\n/**\n * The pgids {@link killDescendantGroupsNow} should signal: every group in the live `ppid` walk from\n * `rootPid` (unchanged semantics \u2014 see {@link doomedGroupsOf}), UNIONED with every registry-sourced\n * snapshot that survives {@link validSnapshotPgids} against the same `rows`. Live-walk pgids are not\n * lstart-gated \u2014 they carry no snapshot to validate against, and are live by construction; only the\n * registry-sourced half needs the reuse guard.\n *\n * Pulled out of `killDescendantGroupsNow` as a pure function so the union/dedupe logic can be tested\n * against a fake process table and fake registry snapshots, without spawning real processes or waiting on\n * a real `ps`.\n *\n * @example\n * // pgid 20 is unreachable from rootPid (reparented to init) but was recorded before its parent died.\n * collectForceReapTargets(1000, freshRows, [[{ pgid: 20, leaderStart: '\u2026' }]]) // => [20]\n */\nexport const collectForceReapTargets = (\n rootPid: number,\n rows: ProcRow[],\n registrySnapshots: readonly (readonly GroupSnapshot[])[],\n): number[] => {\n const live = doomedGroupsOf(rootPid, rows)\n\n const fromRegistry = registrySnapshots.flatMap((snapshot) => {\n return validSnapshotPgids(snapshot, rows)\n })\n\n return [...new Set([...live, ...fromRegistry])]\n}\n\n/**\n * SIGKILL every process group descended from this process, right now \u2014 plus every REGISTERED\n * supervised-child snapshot that still validates, so a group that reparented to init before its parent's\n * `exit` fired is not left behind just because the live `ppid` walk can no longer see it.\n *\n * The force-quit path (a second Ctrl-C) abandons the graceful teardown, but it must not abandon the\n * CHILDREN: they hold the dev ports, and the next start would 502 against their stale portless\n * aliases. So this is the blunt counterpart to {@link superviseChild}'s teardown \u2014 no SIGTERM grace,\n * no escalation, no waiting for the kernel to reap. Straight to SIGKILL.\n *\n * Synchronous by contract: the caller exits the process on the very next line, so anything deferred\n * to a later tick would never run. Cost is one `ps` (tens of ms) plus a `kill` per group; that is the\n * whole latency budget a user who just hit Ctrl-C twice is willing to spend.\n */\nexport const killDescendantGroupsNow = (): void => {\n const rows = snapshotProcRows()\n\n const registrySnapshots = [...registry].map((getGroups) => {\n return getGroups()\n })\n\n signalGroups(collectForceReapTargets(process.pid, rows, registrySnapshots), 'SIGKILL')\n}\n\n/** Resolve after `ms`, used to pace the teardown polling loop. */\nconst sleep = async (ms: number): Promise<void> => {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n\n/** Poll `pgids` until every group has exited or `timeoutMs` elapses; returns the survivors. */\nconst waitForExit = async (pgids: number[], timeoutMs: number): Promise<number[]> => {\n const deadline = Date.now() + timeoutMs\n let alive = pgids\n\n while (alive.length > 0 && Date.now() < deadline) {\n alive = alive.filter(groupAlive)\n if (alive.length === 0) break\n await sleep(POLL_MS)\n }\n\n return alive\n}\n\n/**\n * Called when a supervised child dies on its OWN \u2014 a natural `exit` or a spawn `error` that was\n * NOT initiated by {@link ManagedChild.kill}. `detail` is a short human description of the cause.\n * The runner uses it to surface a silently-dead `turbo watch`/`turbo run dev` engine (which stops\n * rebuilds/HMR with no other signal) instead of leaving the session looking healthy.\n */\nexport type UnexpectedExitHandler = (detail: string) => void\n\n/**\n * Wrap a detached child: `unref()` it (so it never keeps the loop alive) and return a handle\n * whose `kill()` reaps the child AND every process group turbo spawned beneath it.\n *\n * Snapshot first, signal second: after turbo exits its tasks reparent to init, so the `ppid`\n * walk that finds them must run while turbo is still alive. Then SIGTERM every doomed group,\n * poll until all are gone, and SIGKILL the survivors. Resolves once nothing is left.\n *\n * `onUnexpectedExit` (optional) fires when the child dies WITHOUT `kill()` having been called \u2014\n * the \"engine died silently\" case; the exit our own teardown causes never reaches it.\n */\n// The snapshot-first order covers the ORDERLY death, where we choose the moment and can walk the tree\n// first. It does not cover turbo CRASHING, because reparenting happens at termination \u2014 strictly before\n// Node hands us the `exit` event \u2014 so by then the walk is already blind. A rolling snapshot (see `sample`)\n// is therefore kept for the child's whole life, and both the crash path and a `kill()` on an already-dead\n// child reap from it, validating each group against its leader's start time so a recycled pgid is never\n// killed.\n//\n// A `killing` latch, set at the top of `kill()` before any signal goes out, is what suppresses\n// `onUnexpectedExit` for our own teardown, so it reports only genuine crashes.\n//\n// The `error` listener is load-bearing beyond reporting: a ChildProcess that emits `error` (e.g. `pnpm`\n// ENOENT) with no listener throws as an uncaught exception and would take the whole dev session down.\nexport function superviseChild(\n child: ChildProcess,\n graceMs: number = DEFAULT_GRACE_MS,\n onUnexpectedExit?: UnexpectedExitHandler,\n /**\n * Test-only seam: overrides the `ps` snapshot used by this child's own reap ATTEMPTS (the crash-time\n * reap in the `exit` handler, and `kill()`'s reaps) \u2014 never the rolling sampler, which always uses the\n * real one. Defaults to the real synchronous `ps` call for every production caller. Lets a test simulate\n * a transient `ps` failure (an empty read) without needing to race the real one.\n */\n snapshotRowsOverride: () => ProcRow[] = snapshotProcRows,\n): ManagedChild {\n // Don't keep the parent event loop alive on the child; the runner owns lifecycle via kill().\n child.unref()\n\n // Latched by kill() before it signals, so the child's own teardown exit is not misreported as a crash.\n let killing = false\n // Set by the `exit` listener, so a sampler callback still in flight cannot clobber the final snapshot.\n let exited = false\n /** Last known process groups beneath this child, refreshed while it is alive. See the sampler below. */\n let groups: GroupSnapshot[] = []\n let sampler: NodeJS.Timeout | null = null\n\n /** Live accessor registered in {@link registry} for the whole life of this child \u2014 see `deregisterAfter`. */\n const getGroups = (): readonly GroupSnapshot[] => {\n return groups\n }\n\n registry.add(getGroups)\n\n const stopSampling = (): void => {\n if (sampler) clearInterval(sampler)\n sampler = null\n }\n\n /**\n * Drop this child's accessor from {@link registry} once every group it ever recorded is CONFIRMED gone\n * \u2014 never merely because `exit` fired or a reap attempt ran. A reap attempt can fail to kill anything\n * for a legitimate reason (a stale/empty `ps` read) while the descendant is still very much alive, and\n * removing the entry THEN would strand it: nothing else remembers those pgids once this closure is gone.\n * Bounded by `REAP_TIMEOUT_MS` so a group this genuinely cannot reap (a foreign process now holding a\n * recycled pgid) does not pin a dead entry in the registry forever.\n */\n const deregisterAfter = async (): Promise<void> => {\n await waitForExit(\n groups.map((g) => {\n return g.pgid\n }),\n REAP_TIMEOUT_MS,\n )\n registry.delete(getGroups)\n }\n\n /**\n * Turn a fresh `ps` read into an updated {@link groups}. An empty result is discarded rather than\n * stored: `ps` failing, or racing the child's own death, must degrade to the previous snapshot, never\n * erase it. Shared by the synchronous first sample below and the async rolling {@link sample}, so the\n * two can never compute the group set differently.\n */\n const applySample = (rows: ProcRow[]): void => {\n const pid = child.pid\n\n if (pid == null || exited || killing || rows.length === 0) return\n\n const ownPgid = rows.find((row) => {\n return row.pid === process.pid\n })?.pgid\n\n const next = snapshotGroups(pid, rows, ownPgid)\n\n if (next.length > 0) groups = next\n }\n\n /**\n * Refresh {@link groups} while the child is alive.\n *\n * This is what makes a crash survivable. Reaping walks `ppid` from the child \u2014 but a process that\n * dies has ALREADY reparented its children to init by the time Node delivers `exit`, so a walk\n * started from the corpse finds only the corpse's own group. Verified: while turbo is alive the walk\n * yields `[turbo, vite]`; inside the `exit` handler it yields `[turbo]`, and vite (`ppid=1`, still\n * running, still holding its port) is unreachable forever. There is no window to race \u2014 the only way\n * to know vite's group after turbo dies is to have written it down BEFORE turbo died.\n *\n * Async (`snapshotProcRowsAsync`) so the rolling tick never blocks the event loop the in-process\n * backends share \u2014 see the FIRST sample below for why that leaves a narrow window this function alone\n * cannot close.\n */\n const sample = async (): Promise<void> => {\n if (child.pid == null || exited || killing) return\n\n applySample(await snapshotProcRowsAsync())\n }\n\n // Synchronous, not `void sample()`: a child that crashes within `sample()`'s first async `ps` round\n // trip (tens of ms) would otherwise have no snapshot recorded at all, and the `exit` handler's\n // `reapSnapshot(groups, \u2026)` would run against an empty `groups` and reap nothing \u2014 the exact\n // spawn\u2192first-snapshot window W11 closes. One small `ps` exec, before this function ever returns,\n // costs the same one-time block on the shared event loop that `killDescendantGroupsNow`'s synchronous\n // `ps` call already spends on every force-quit \u2014 paid once per spawn instead of once per Ctrl-C.\n applySample(snapshotProcRows())\n\n sampler = setInterval(() => {\n void sample()\n }, SAMPLE_INTERVAL_MS)\n // The timer must never be the reason the process stays alive \u2014 it outlives nothing.\n sampler.unref()\n\n const reportUnexpected = (detail: string): void => {\n if (killing) return\n onUnexpectedExit?.(detail)\n }\n\n child.on('exit', (code, signal) => {\n exited = true\n stopSampling()\n\n // The child died WITHOUT us killing it \u2014 a turbo crash, or an OOM kill. Turbo puts each of its\n // tasks in a process group of its OWN, and a turbo that dies this way reaps none of them, so\n // `vite`/`tsc` survive holding their ports. Nothing can find them by walking (see `sample`), and\n // the `kill()` below would bail on an already-exited child. Reaping from the snapshot here is the\n // only thing standing between a crashed engine and a permanently orphaned dev server.\n //\n // `deregisterAfter` (not a bare delete) \u2014 this reap attempt reading a stale/empty `ps` snapshot must\n // not be mistaken for the descendants actually being gone; the registry entry is the only remaining\n // record of them until a later confirmation (or force-reap) proves they are.\n if (!killing) {\n reapSnapshot(groups, snapshotRowsOverride())\n void deregisterAfter()\n }\n\n reportUnexpected(`exited unexpectedly (code=${code ?? 'null'}, signal=${signal ?? 'null'})`)\n })\n child.on('error', (error: Error) => {\n reportUnexpected(`failed to spawn: ${error.message}`)\n })\n\n return {\n kill: async (): Promise<void> => {\n // Latch FIRST: the child WILL emit `exit` during the reap below, and that exit is ours, not a crash.\n killing = true\n stopSampling()\n\n const pid = child.pid\n\n if (pid == null) {\n // Never spawned a real pid \u2014 nothing was ever tracked, so nothing to confirm.\n registry.delete(getGroups)\n\n return\n }\n\n // Once the child is reaped the OS may recycle `pid` onto an unrelated process, and `kill(-pid, \u2026)`\n // would then destroy a stranger's group \u2014 so an exited child is never walked. It is not simply\n // skipped either: a turbo that CRASHED left its task groups running, and this is the Ctrl-C that\n // has to clear them. The snapshot is the only surviving handle on those groups, and `reapSnapshot`\n // re-validates each one against its leader's start time, so a recycled pgid is refused.\n if (child.exitCode !== null || child.signalCode !== null) {\n reapSnapshot(groups, snapshotRowsOverride())\n await deregisterAfter()\n\n return\n }\n\n const rows = snapshotRowsOverride()\n\n // The cheap check above misses a child reaped just now, so confirm `pid` is still ours: a\n // detached child keeps us as its parent, so a foreign `ppid` means the pid was recycled.\n // Skipped when `ps` failed (empty `rows`) \u2014 then only the guard above stands. The registry entry is\n // deliberately left alone here: this state is genuinely ambiguous (did the pid really get\n // recycled, or did `ps` just fail?), and the safe default is to let a later reap re-decide with a\n // fresh read, not to guess by dropping the one record we have.\n if (rows.length > 0 && !isChildOf(pid, process.pid, rows)) return\n\n const doomed = doomedGroupsOf(pid, rows)\n\n // Negative pid \u2192 the whole group (detached made the child a group leader). Turbo forwards\n // this to its tasks; the extra task groups are signalled directly in case it doesn't.\n signalGroups(doomed, 'SIGTERM')\n\n const stragglers = await waitForExit(doomed, graceMs)\n\n if (stragglers.length === 0) {\n // Every doomed group (this child's own, plus every task group the live walk found) exited\n // within grace \u2014 confirmed by the `waitForExit` above, so no further wait is needed here.\n registry.delete(getGroups)\n\n return\n }\n\n // Re-snapshot before forcing: turbo is still alive (that's why we're here), so its tree is\n // still walkable, and `turbo watch build` may have started a task AFTER the first snapshot.\n // Union with the known stragglers, whose groups may already have left turbo's subtree.\n const late = doomedGroupsOf(pid, snapshotRowsOverride())\n const forced = [...new Set([...stragglers, ...late])].filter(groupAlive)\n\n // Killing turbo's group alone would orphan exactly these, so they are killed as a set.\n signalGroups(forced, 'SIGKILL')\n\n // A SIGKILLed leader lingers as an unreaped zombie for a few ms, and `kill(pgid, 0)` still\n // succeeds against it. Wait for the kernel to finish so callers that exit the process\n // immediately after `kill()` resolves aren't racing the teardown they just awaited.\n await waitForExit(forced, REAP_TIMEOUT_MS)\n registry.delete(getGroups)\n },\n }\n}\n", "/**\n * @fileoverview\n *\n * Signal-driven graceful shutdown, shared by every long-lived dev entry point.\n *\n * Three invariants:\n *\n * 1. Only a REPEAT OF THE SAME SIGNAL is an escape hatch. It is tempting to treat any second\n * signal as \"the user pressed Ctrl-C again, get out now\" \u2014 that was the old rule, and it\n * silently orphaned every child. A process manager in front of us relays its own signal after\n * the TTY's, so ONE Ctrl-C under `pnpm exec` arrives as SIGINT *then* SIGTERM:\n *\n * $ pnpm exec node -e \"process.on('SIGINT',\u2026); process.on('SIGTERM',\u2026)\"\n * ^C GOT SIGINT\n * GOT SIGTERM <- pnpm relaying, NOT a second keypress\n *\n * Under the old rule that relay force-quit the teardown a few hundred ms in and abandoned the\n * turbo/vite children (which sit in their own process groups). Keying the escape on the FIRST\n * signal's type fixes it without losing the hatch: a real second Ctrl-C re-sends SIGINT, and a\n * supervisor escalating SIGTERM -> SIGTERM still force-quits. `npm`/`yarn` relay the same way,\n * so this must live here, in the library, not in one consumer's `dev` script.\n * 2. Force-quitting must still not orphan. Even a genuine double Ctrl-C leaves children holding\n * ports (the next start then 502s), so the force path SIGKILLs the descendant process groups\n * before exiting. Bounded and synchronous \u2014 no grace, no escalation, no waiting for reaping.\n * 3. A signal-terminated process must not report exit code 0. The old handlers ran\n * `finally { process.exit(0) }`, which also swallowed a rejecting teardown without a word.\n * Here the rejection goes to stderr and the code stays `128 + signo` \u2014 even on a failed\n * teardown, because the process genuinely WAS signal-terminated, no conventional code means\n * \"signal-terminated but cleanup failed\", and inventing one would break the SIGTERM -> 143\n * contract supervisors rely on. The failure is surfaced by logging, not by the code.\n */\nimport { constants } from 'node:os'\nimport process from 'node:process'\n\nimport { killDescendantGroupsNow } from 'src/dev/managed-child'\n\n/**\n * The signals a resident dev process tears down on.\n *\n * SIGHUP is here for invariant 2: the terminal going away (window closed, ssh dropped) is delivered to\n * the foreground process group, so `dev` gets it \u2014 but its turbo/vite children DON'T, because they sit\n * in their own detached process groups. Without a handler, `dev` takes SIGHUP's default kill, never runs\n * `killDescendantGroupsNow`, and leaves the whole tree alive holding the dev ports; the next start then\n * 502s. Closing a terminal is the single most common way to walk away from a dev server, so this is the\n * likeliest orphan path, not an exotic one.\n */\nconst HANDLED_SIGNALS: readonly NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP']\n\n/**\n * `os.constants.signals` typed for lookup by an arbitrary {@link NodeJS.Signals}. The platform\n * table omits signals that do not exist on the host, so the index is genuinely partial.\n */\nconst SIGNAL_NUMBERS: Partial<Record<NodeJS.Signals, number>> = constants.signals\n\n/** Fallback signal number when the host table lacks the signal: SIGINT, yielding the usual 130. */\nconst FALLBACK_SIGNO = 2\n\n/**\n * The POSIX exit code for a process terminated by `signal`: `128 + signo`.\n *\n * A shell reports SIGINT as 130 and SIGTERM as 143. Exiting 0 after a signal tells a supervisor\n * the process stopped voluntarily, which is a lie.\n *\n * @example\n * exitCodeForSignal('SIGINT') // 130\n * exitCodeForSignal('SIGTERM') // 143\n */\nexport const exitCodeForSignal = (signal: NodeJS.Signals): number => {\n return 128 + (SIGNAL_NUMBERS[signal] ?? FALLBACK_SIGNO)\n}\n\n/**\n * Seams for {@link registerSignalShutdown}. Each exists because the real implementation is\n * untestable in-process: `process.exit` kills the test runner, and delivering a real POSIX\n * signal to the runner is unsafe and flaky.\n */\nexport interface SignalShutdownDeps {\n /** The context-specific teardown. May reject; the rejection is logged, never swallowed. */\n onSignal: (signal: NodeJS.Signals) => Promise<void>\n /**\n * Terminate the process. Typed as returning `void`, not `never`, so a test can pass a plain\n * recording fake: a `never` fake would have to throw a sentinel, and that throw would reject the\n * in-flight teardown promise. Nothing meaningful runs after a call, so a returning fake is safe.\n */\n exit?: (code: number) => void\n /** Subscribe `handler` to `signal`. Defaults to `process.on`. */\n register?: (signal: NodeJS.Signals, handler: () => void) => void\n /**\n * Unsubscribe `handler` from `signal`. Defaults to `process.off`. Called once the teardown this module\n * owns is over \u2014 graceful completion, the force-quit escape, or the deadline \u2014 so a process whose\n * `exit` seam does not actually terminate (a test, or a caller with its own reasons to keep running)\n * is not left with a dangling SIGINT/SIGTERM/SIGHUP handler from a session that already ended.\n */\n unregister?: (signal: NodeJS.Signals, handler: () => void) => void\n /**\n * Reap surviving descendant process groups on the force-quit path, where the normal teardown is\n * abandoned mid-flight. Synchronous by contract: the process exits on the next line, so anything\n * deferred to a later tick would never run. Defaults to {@link killDescendantGroupsNow}.\n */\n forceReap?: () => void\n /** How long a teardown may run before it is force-quit. See {@link TEARDOWN_DEADLINE_MS}. */\n teardownDeadlineMs?: number\n /**\n * Timer seam, returning its own cancel. Defaults to `setTimeout`/`clearTimeout`; a test injects a fake\n * so the deadline is fired deliberately rather than waited out.\n */\n setTimer?: (handler: () => void, ms: number) => () => void\n /**\n * Name the teardown step still in flight when the deadline trips \u2014 the CLI entry wires this to\n * `runner.shutdownStage`.\n *\n * This module holds NO reference to the runner and so cannot read a stage on its own. Without the seam\n * the deadline degrades into a plain force-quit and the incident's central question (\"`shutdown()`\n * demonstrably ran \u2014 so where did it wedge?\") survives the fix meant to answer it.\n */\n describeStall?: () => string\n /**\n * File the deadline report where it can still be read. The entry routes it into the per-service log sink:\n * on the path this deadline exists for, the terminal is exactly what is gone, so stderr is not a channel.\n * Defaults to a no-op \u2014 library code has no sink to file into.\n */\n fileReport?: (text: string) => void\n}\n\n/**\n * How long a teardown may run before the process force-quits: 20 s, well past a healthy reap (a turbo tree\n * escalates SIGTERM\u2192SIGKILL per child, seconds at worst) and far short of \"forever\".\n *\n * This module used to argue that NO deadline should be armed: *\"any value safe enough not to preempt a\n * legitimate teardown would fire later than a user's second Ctrl-C, and a supervisor sends its own SIGKILL\n * on its own grace.\"* That reasoning quietly ASSUMES A HUMAN IS PRESENT to press Ctrl-C twice \u2014 and the\n * incident that put this here is precisely the case where there is none: the terminal is gone, the operator\n * is not watching, and no supervisor sits above an interactive `ik dev`. Five processes took SIGHUP, ran\n * `shutdown()`, wedged, and spun for five hours writing 455 GB. The escape hatch the old design leaned on\n * cannot be pressed by anyone who has already walked away.\n */\nconst TEARDOWN_DEADLINE_MS = 20_000\n\nconst defaultExit = (code: number): void => {\n process.exit(code)\n}\n\nconst defaultRegister = (signal: NodeJS.Signals, handler: () => void): void => {\n process.on(signal, handler)\n}\n\nconst defaultUnregister = (signal: NodeJS.Signals, handler: () => void): void => {\n process.off(signal, handler)\n}\n\nconst defaultSetTimer = (handler: () => void, ms: number): (() => void) => {\n const timer = setTimeout(handler, ms)\n\n // `unref` so the deadline itself never HOLDS the process open: if the loop empties, the teardown is done\n // and Node exits on its own. A wedged teardown always has live handles (children, listening servers), so\n // the timer phase is still reached \u2014 the probe proved the fault storm does not starve it either.\n timer.unref()\n\n return (): void => {\n clearTimeout(timer)\n }\n}\n\n/**\n * Write to stderr, swallowing a failed write.\n *\n * `stderr.write` can throw (EPIPE, when the parent closed the pipe). Every caller here is on the\n * exit path, and failing to REPORT something must never break that path \u2014 the process still has to\n * die with the right code. A lost message is recoverable; a process that survives its own SIGINT\n * is not.\n */\nconst writeStderr = (message: string): void => {\n try {\n process.stderr.write(message)\n } catch {\n // stderr is gone; there is nowhere left to report to.\n }\n}\n\n/** Report a rejected teardown \u2014 message AND stack, so a wedge is never silent. */\nconst writeTeardownFailure = (signal: NodeJS.Signals, error: unknown): void => {\n const detail = error instanceof Error ? `${error.message}\\n${error.stack ?? '(no stack)'}` : String(error)\n\n writeStderr(`\\n\u2717 Teardown failed while handling ${signal}: ${detail}\\n`)\n}\n\n/**\n * Wire SIGINT/SIGTERM to `onSignal`, then exit `128 + signo`.\n *\n * The first signal runs the teardown. While it is in flight, a signal of a DIFFERENT type is a\n * relay from the process manager above us (`pnpm exec` turns one Ctrl-C into SIGINT + SIGTERM) and\n * is ignored, so the teardown survives to reap its children. A repeat of the FIRST signal is the\n * real escape hatch: it force-quits without touching `onSignal` again, SIGKILLing the descendant\n * groups on the way out so nothing is left holding a port.\n *\n * A {@link TEARDOWN_DEADLINE_MS} deadline IS armed \u2014 read its doc block before removing it.\n *\n * Returns a `detach` function that drops the SIGINT/SIGTERM/SIGHUP listeners this call installed. Every\n * exit path already calls it before exiting, so a real process never needs it.\n *\n * @example\n * registerSignalShutdown({\n * onSignal: async (signal) => {\n * process.stdout.write(`Received ${signal}, shutting down...`)\n * await runner.shutdown()\n * },\n * describeStall: () => runner.shutdownStage,\n * })\n */\n// On the deadline: this module used to explain at length why one should NOT be armed. That explanation\n// assumed a human at the keyboard to press Ctrl-C a second time; the incident it now guards against is the\n// case where nobody is there. Mechanically it depends on `terminal-liveness`: with a fault storm live,\n// teardown competes with ~100k blocking `writeSync` calls per second, and a deadline shipped into a\n// machine that cannot honour it is decoration. The storm is cut at its source first; this is what stops\n// the wedge that follows.\n//\n// On `detach`: it exists for a caller whose `exit` seam does NOT terminate the process (every test in this\n// suite), so a session that already ended does not leave dangling handlers behind for the next one in the\n// same process. In a real process `exit` terminates first.\nexport const registerSignalShutdown = ({\n onSignal,\n exit = defaultExit,\n register = defaultRegister,\n unregister = defaultUnregister,\n forceReap = killDescendantGroupsNow,\n teardownDeadlineMs = TEARDOWN_DEADLINE_MS,\n setTimer = defaultSetTimer,\n describeStall = () => {\n return 'unknown'\n },\n fileReport = () => {},\n}: SignalShutdownDeps): (() => void) => {\n /** The signal that opened the teardown \u2014 `null` until the first one lands. */\n let firstSignal: NodeJS.Signals | null = null\n /** Cancels the armed deadline \u2014 on a completed teardown, and on the second-signal escape. */\n let cancelDeadline: (() => void) | null = null\n /** Every handler this call installed, so `detach` can drop exactly those and nothing else. */\n const handlers = new Map<NodeJS.Signals, () => void>()\n\n /**\n * Drop every listener this call installed. Runs at the end of EVERY exit path below (graceful\n * completion, the second-signal escape, and the deadline) \u2014 not just the happy one \u2014 so a caller whose\n * `exit` seam does not actually terminate the process (a test, or a future non-terminating consumer)\n * is never left holding SIGINT/SIGTERM/SIGHUP handlers from a session that already ended. Idempotent:\n * a second call finds an empty map and does nothing.\n */\n const detach = (): void => {\n for (const [signal, handler] of handlers) {\n unregister(signal, handler)\n }\n handlers.clear()\n }\n\n const handle = (signal: NodeJS.Signals): void => {\n if (firstSignal !== null) {\n // A DIFFERENT signal while tearing down is the process manager in front of us relaying its\n // own (pnpm/npm turn one Ctrl-C into SIGINT + SIGTERM), never a second keypress. Ignoring it\n // is what lets the teardown finish and reap the children. Only a repeat of the signal that\n // STARTED the teardown is the user (or a supervisor) genuinely asking again.\n if (signal !== firstSignal) return\n\n writeStderr(`\\n\u26A0 Received ${signal} again \u2014 force-quitting.\\n`)\n cancelDeadline?.()\n // Abandoning the teardown must still not abandon the children: they hold the dev ports, and\n // the next start would 502 against their stale portless aliases.\n forceReap()\n detach()\n exit(exitCodeForSignal(signal))\n\n return\n }\n\n firstSignal = signal\n\n // The human's escape hatch, armed for the case where there is no human. Same destination as a second\n // Ctrl-C \u2014 reap the descendant groups, exit `128 + signo` \u2014 but it also NAMES the step that wedged, and\n // files that name where it can still be read once the terminal is gone.\n cancelDeadline = setTimer(() => {\n const report = `\\n\u26A0 Teardown deadline exceeded at stage=${describeStall()} after ${teardownDeadlineMs}ms \u2014 force-quitting.\\n`\n\n writeStderr(report)\n fileReport(report)\n forceReap()\n detach()\n exit(exitCodeForSignal(signal))\n }, teardownDeadlineMs)\n\n void (async (): Promise<void> => {\n try {\n await onSignal(signal)\n } catch (error) {\n writeTeardownFailure(signal, error)\n } finally {\n // `finally`, so the exit survives anything the catch body might later throw: a process must\n // never outlive its own signal. Not the old `finally { process.exit(0) }` bug \u2014 that one\n // exited zero without logging; this logs first, then exits the honest code.\n cancelDeadline?.()\n detach()\n exit(exitCodeForSignal(signal))\n }\n })()\n }\n\n for (const signal of HANDLED_SIGNALS) {\n const handler = (): void => {\n return handle(signal)\n }\n\n handlers.set(signal, handler)\n register(signal, handler)\n }\n\n return detach\n}\n", "/**\n * Names of the error classes thrown when an interactive prompt ends without a\n * value. From `@inquirer/core`: `ExitPromptError` (Ctrl-C \u2014 and ONLY Ctrl-C:\n * inquirer binds no escape key, so it raises this from readline's SIGINT) and\n * `AbortPromptError` (the prompt was aborted via an `AbortSignal`, which is how\n * Esc arrives \u2014 see lib/prompts/escapable-context). From our own Ink pickers:\n * `PromptCancelledError` (see ./prompt-cancelled-error), which is registered here\n * rather than impersonating an inquirer class name. All are intentional\n * cancellations, not failures.\n */\nconst CANCELLATION_ERROR_NAMES = new Set(['ExitPromptError', 'AbortPromptError', 'PromptCancelledError'])\n\nconst hasCancellationName = (value: unknown): boolean => {\n return value instanceof Error && CANCELLATION_ERROR_NAMES.has(value.name)\n}\n\n/**\n * True when `error` represents a user (or signal) cancellation of an interactive\n * prompt \u2014 Ctrl-C anywhere, or Esc, which reaches an `@inquirer` prompt as an\n * abort and an Ink picker as a `PromptCancelledError`. Matched by `name` rather\n * than `instanceof` so it stays correct\n * even when pnpm dedupes more than one copy of `@inquirer/core` into the tree\n * (an `instanceof` check fails across realms/duplicate classes).\n *\n * Also unwraps one level of `cause`, so a cancellation re-wrapped in an\n * {@link ./operation-error.OperationError} is still recognised at the top-level\n * error boundary.\n *\n * @example\n * try {\n * await checkbox({ message: 'Select release branches', choices })\n * } catch (err) {\n * if (isPromptCancellation(err)) process.exit(0) // clean back-out, not an error\n * throw err\n * }\n */\nexport const isPromptCancellation = (error: unknown): boolean => {\n if (hasCancellationName(error)) return true\n\n const cause = (error as { cause?: unknown } | null | undefined)?.cause\n\n return hasCancellationName(cause)\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\n/**\n * The only place that spawns `orca`. Everything the driver knows about the CLI is\n * encoded here:\n *\n * - infra-kit owns git; Orca owns windows. The `orca worktree` subcommand's\n * `create` and `rm` verbs are forbidden in this codebase \u2014 `rm` also deletes the\n * local branch, and `create` picks paths/branch names infra-kit's worktree\n * layout does not control (docs/orca-migration-plan.md \u00A71, principle 1).\n * - The JSON envelope is the contract, never the exit code: `ok:false` came back\n * with exit 0 on 1.4.203 and exit 1 on 1.4.204, and the app auto-updates\n * unattended (docs/orca-cli-findings.md, \"Additional facts\").\n */\n\nexport interface OrcaErrorPayload {\n code: string\n message: string\n data?: unknown\n}\n\ninterface OrcaEnvelope<T> {\n ok: boolean\n result?: T\n error?: OrcaErrorPayload\n}\n\n/** Orca answered with `{ ok: false, error }`. */\nexport class OrcaError extends Error {\n readonly code: string\n readonly data: unknown\n\n constructor(payload: OrcaErrorPayload) {\n super(payload.message)\n this.name = 'OrcaError'\n this.code = payload.code\n this.data = payload.data\n }\n}\n\n/** Orca ran but stdout was not an envelope \u2014 a crash, a `--help` fallback, or a CLI too old for `--json`. */\nexport class OrcaMalformedError extends Error {\n readonly exitCode: number | null\n readonly stderrTail: string\n\n constructor(exitCode: number | null, stderrTail: string) {\n super(`orca: stdout is not a JSON envelope (exit ${exitCode ?? 'signal'})`)\n this.name = 'OrcaMalformedError'\n this.exitCode = exitCode\n this.stderrTail = stderrTail\n }\n}\n\n/** The `orca` binary is not on PATH (spawn ENOENT, or the shell's exit 127). */\nexport class OrcaAbsentError extends Error {\n constructor() {\n super('orca: command not found \u2014 the CLI is registered from Orca \u2192 Settings \u2192 Experimental \u2192 CLI')\n this.name = 'OrcaAbsentError'\n }\n}\n\nconst STDERR_TAIL_CHARS = 400\nconst SHELL_COMMAND_NOT_FOUND = 127\n\ninterface SpawnOutput {\n exitCode: number | null\n stdout: string\n stderr: string\n}\n\nconst isEnoent = (error: unknown): boolean => {\n return typeof error === 'object' && error !== null && (error as { code?: unknown }).code === 'ENOENT'\n}\n\nconst spawnOrca = async (argv: string[]): Promise<SpawnOutput> => {\n try {\n // zx runs through a shell, so a missing binary normally surfaces as exit 127 rather than a\n // rejection; the catch covers the shell-less spawn failure shape.\n return await $({ nothrow: true, quiet: true })`orca ${argv} --json`\n } catch (error) {\n if (isEnoent(error)) {\n throw new OrcaAbsentError()\n }\n\n throw error\n }\n}\n\nconst parseEnvelope = <T>(stdout: string): OrcaEnvelope<T> | null => {\n try {\n const parsed: unknown = JSON.parse(stdout)\n\n if (typeof parsed === 'object' && parsed !== null && typeof (parsed as { ok?: unknown }).ok === 'boolean') {\n return parsed as OrcaEnvelope<T>\n }\n\n return null\n } catch {\n return null\n }\n}\n\n/**\n * Run one `orca` command and return its `result`. Throws {@link OrcaError} on an\n * `ok:false` envelope, {@link OrcaMalformedError} when stdout is not an envelope,\n * and {@link OrcaAbsentError} when the binary is missing \u2014 regardless of exit code.\n */\nexport const runOrca = async <T>(argv: string[]): Promise<T> => {\n const output = await spawnOrca(argv)\n const envelope = parseEnvelope<T>(output.stdout)\n\n logger.debug({ argv, ok: envelope?.ok, code: envelope?.error?.code, exitCode: output.exitCode }, 'orca')\n\n if (!envelope) {\n if (output.exitCode === SHELL_COMMAND_NOT_FOUND) {\n throw new OrcaAbsentError()\n }\n\n throw new OrcaMalformedError(output.exitCode, output.stderr.slice(-STDERR_TAIL_CHARS))\n }\n\n if (!envelope.ok) {\n throw new OrcaError(envelope.error ?? { code: 'unknown', message: 'orca: ok:false without an error payload' })\n }\n\n return envelope.result as T\n}\n", "import { logger } from 'src/lib/logger'\n\nimport { OrcaAbsentError, runOrca } from './run-orca'\n\nexport type OrcaProbe = 'absent' | 'unreachable' | 'ready'\n\ninterface OrcaStatus {\n app?: { running?: boolean }\n runtime?: { reachable?: boolean; appVersion?: string }\n}\n\n/**\n * Three-state readiness probe behind every fallback branch and doctor's Orca row.\n * `ready` needs both halves: a headless `orca serve` runtime is reachable but has\n * no UI to adopt a tab, so it reads as `unreachable`. `runtime.appVersion` is the\n * only trustworthy version source (`ORCA_APP_VERSION` is spawn-time stale).\n */\nexport const probeOrca = async (): Promise<OrcaProbe> => {\n try {\n const status = await runOrca<OrcaStatus>(['status'])\n\n logger.debug({ appVersion: status.runtime?.appVersion }, 'orca: status')\n\n return status.app?.running === true && status.runtime?.reachable === true ? 'ready' : 'unreachable'\n } catch (error) {\n if (error instanceof OrcaAbsentError) {\n return 'absent'\n }\n\n logger.debug({ error }, 'orca: status probe failed')\n\n return 'unreachable'\n }\n}\n", "import { realpath } from 'node:fs/promises'\n\n/**\n * Resolve `path` through the filesystem, falling back to the input when it can't\n * be resolved (e.g. the directory was already removed). Both Orca-reported paths\n * and the caller's target are normalized the same way so a macOS\n * `/var`\u2192`/private/var` symlink can't make two equal paths compare unequal.\n *\n * Selectors are NOT built from this \u2014 they take the path as `git worktree list`\n * reports it; realpath is for equality only.\n */\nexport const realpathForOrcaCwd = async (path: string): Promise<string> => {\n try {\n return await realpath(path)\n } catch {\n return path\n }\n}\n", "import { realpathForOrcaCwd } from './realpath-for-orca-cwd'\nimport { runOrca } from './run-orca'\n\nexport type OrcaRepoVisibility = 'show' | 'hide'\n\ninterface OrcaRepoRow {\n path: string\n externalWorktreeVisibility?: OrcaRepoVisibility\n}\n\ninterface OrcaRepoListResult {\n repos?: OrcaRepoRow[]\n}\n\ninterface OrcaRepoAddResult {\n repo?: OrcaRepoRow\n}\n\nexport interface OrcaRepoLookup {\n registered: boolean\n visibility?: OrcaRepoVisibility\n}\n\n/**\n * Whether Orca knows the repo at `mainRepoRoot`, and whether its external\n * worktrees (infra-kit's `<repo>-worktrees/*`) are shown in the sidebar. Split\n * from {@link addOrcaRepo} so a caller can put \"will register <repo> in Orca\" in\n * its confirm preview before mutating \u2014 `repo add` carries hook policy defaults.\n */\nexport const findOrcaRepo = async (mainRepoRoot: string): Promise<OrcaRepoLookup> => {\n const [{ repos = [] }, wanted] = await Promise.all([\n runOrca<OrcaRepoListResult>(['repo', 'list']),\n realpathForOrcaCwd(mainRepoRoot),\n ])\n\n for (const repo of repos) {\n if ((await realpathForOrcaCwd(repo.path)) === wanted) {\n return { registered: true, visibility: repo.externalWorktreeVisibility }\n }\n }\n\n return { registered: false }\n}\n\n/** Registers the repo; the returned visibility is `hide` for a fresh row (measured). */\nexport const addOrcaRepo = async (mainRepoRoot: string): Promise<{ visibility?: OrcaRepoVisibility }> => {\n const { repo } = await runOrca<OrcaRepoAddResult>(['repo', 'add', '--path', mainRepoRoot])\n\n return { visibility: repo?.externalWorktreeVisibility }\n}\n", "import { realpathForOrcaCwd } from './realpath-for-orca-cwd'\nimport { runOrca } from './run-orca'\n\ninterface OrcaWorktreeListResult {\n worktrees?: Array<{ path: string }>\n}\n\nconst WORKTREE_LIST_LIMIT = '500'\n\n/**\n * Whether the sidebar shows the worktree at `cwd`. Distinct from \"the selector\n * resolves it\": a hidden external worktree still answers `terminal create` with a\n * tab nobody can see (docs/orca-cli-findings.md, gate outcome), so callers use\n * this to report `orcaHidden` instead of a silent success.\n */\nexport const isOrcaWorktreeListed = async (mainRepoRoot: string, cwd: string): Promise<boolean> => {\n const [{ worktrees = [] }, wanted] = await Promise.all([\n runOrca<OrcaWorktreeListResult>([\n 'worktree',\n 'list',\n '--repo',\n `path:${mainRepoRoot}`,\n '--limit',\n WORKTREE_LIST_LIMIT,\n ]),\n realpathForOrcaCwd(cwd),\n ])\n\n for (const worktree of worktrees) {\n if ((await realpathForOrcaCwd(worktree.path)) === wanted) {\n return true\n }\n }\n\n return false\n}\n", "import process from 'node:process'\n\nimport { realpathForOrcaCwd } from './realpath-for-orca-cwd'\n\nconst WORKTREE_ID_SEPARATOR = '::'\n\n/**\n * The path half of `ORCA_WORKTREE_ID` (`<repoId>::<abs path>`), or `null` when the\n * caller is not inside an Orca terminal. The id is per-terminal env \u2014 `cd` and\n * `-C` never change it \u2014 which is exactly why it identifies the terminal a\n * removal would destroy, and why \"re-run from elsewhere\" is the only remediation.\n */\nconst orcaCallerWorktreePath = (env: NodeJS.ProcessEnv): string | null => {\n const id = env.ORCA_WORKTREE_ID\n\n if (!id) {\n return null\n }\n\n const separatorAt = id.indexOf(WORKTREE_ID_SEPARATOR)\n\n if (separatorAt < 0) {\n return null\n }\n\n const path = id.slice(separatorAt + WORKTREE_ID_SEPARATOR.length)\n\n return path.length > 0 ? path : null\n}\n\n/**\n * The first of `paths` that is the caller's own Orca worktree, or `null`. Runs in\n * the command preflight of `worktrees remove` / `release-remove` \u2014 before the\n * confirm prompt and before any git call \u2014 because closing that worktree's\n * terminals would kill the shell running infra-kit.\n */\nexport const orcaCallerInsideTargets = async (\n paths: string[],\n env: NodeJS.ProcessEnv = process.env,\n): Promise<string | null> => {\n const callerPath = orcaCallerWorktreePath(env)\n\n if (callerPath === null) {\n return null\n }\n\n const caller = await realpathForOrcaCwd(callerPath)\n\n for (const path of paths) {\n if ((await realpathForOrcaCwd(path)) === caller) {\n return path\n }\n }\n\n return null\n}\n", "import { logger } from 'src/lib/logger'\n\nimport { OrcaError, runOrca } from './run-orca'\n\nexport interface OrcaTerminal {\n handle: string\n title: string\n tabId: string\n connected: boolean\n orphaned: boolean\n}\n\ninterface OrcaTerminalListResult {\n terminals?: OrcaTerminal[]\n truncated?: boolean\n}\n\nconst TERMINAL_LIST_LIMIT = '200'\n\n/**\n * The terminals Orca has open in the worktree at `cwd`. A `selector_not_found`\n * is \"nothing open\" (probe semantics \u2014 the row may not exist yet, or was pruned);\n * any other Orca failure propagates. `truncated` is surfaced, not resolved: a\n * truncated list still proves the worktree is open.\n */\nexport const listOrcaTerminals = async (cwd: string): Promise<{ terminals: OrcaTerminal[]; truncated: boolean }> => {\n try {\n const result = await runOrca<OrcaTerminalListResult>([\n 'terminal',\n 'list',\n '--worktree',\n `path:${cwd}`,\n '--limit',\n TERMINAL_LIST_LIMIT,\n ])\n\n const truncated = result.truncated === true\n\n if (truncated) {\n logger.debug({ cwd, limit: TERMINAL_LIST_LIMIT }, 'orca: terminal list truncated')\n }\n\n return { terminals: result.terminals ?? [], truncated }\n } catch (error) {\n if (error instanceof OrcaError && error.code === 'selector_not_found') {\n return { terminals: [], truncated: false }\n }\n\n throw error\n }\n}\n", "import { logger } from 'src/lib/logger'\n\nimport type { OrcaProbe } from './availability'\nimport { listOrcaTerminals } from './list-terminals-by-cwd'\nimport { OrcaAbsentError, OrcaError, OrcaMalformedError, runOrca } from './run-orca'\n\nexport type CloseOrcaWorktreeTerminalsOutcome =\n | { closed: true; count: number }\n | { closed: false; skipped: 'absent' | 'unreachable' | 'not_found' }\n | { closed: false; error: OrcaError }\n\ntype RetireOutcome = 'retired' | 'not_found'\n\n/**\n * `--all` refuses (`terminal_close_incomplete`) while any terminal is live and\n * on an empty row only retires the tab surfaces and resume records \u2014 so it runs\n * LAST, after every handle was closed one by one, and its refusal is not a\n * failure (docs/orca-cli-findings.md \u00A73.4).\n */\nconst retireSurfaces = async (cwd: string): Promise<RetireOutcome> => {\n try {\n await runOrca(['terminal', 'close', '--worktree', `path:${cwd}`, '--all'])\n\n return 'retired'\n } catch (error) {\n if (error instanceof OrcaError && error.code === 'selector_not_found') {\n return 'not_found'\n }\n\n if (error instanceof OrcaError && error.code === 'terminal_close_incomplete') {\n logger.debug({ cwd, error }, 'orca: surfaces not retired')\n\n return 'retired'\n }\n\n throw error\n }\n}\n\nconst closeEach = async (cwd: string): Promise<CloseOrcaWorktreeTerminalsOutcome> => {\n const { terminals } = await listOrcaTerminals(cwd)\n\n // Sequential on purpose: the tab is torn down pane by pane and Orca serializes these anyway.\n for (const terminal of terminals) {\n await runOrca(['terminal', 'close', '--terminal', terminal.handle])\n }\n\n const retired = await retireSurfaces(cwd)\n\n if (terminals.length === 0 && retired === 'not_found') {\n return { closed: false, skipped: 'not_found' }\n }\n\n return { closed: true, count: terminals.length }\n}\n\nconst asOutcome = (cwd: string, error: unknown): CloseOrcaWorktreeTerminalsOutcome => {\n if (error instanceof OrcaAbsentError) {\n return { closed: false, skipped: 'absent' }\n }\n\n if (error instanceof OrcaError) {\n return { closed: false, error }\n }\n\n if (error instanceof OrcaMalformedError) {\n return {\n closed: false,\n error: new OrcaError({\n code: 'orca_malformed_output',\n message: error.message,\n data: { exitCode: error.exitCode, stderrTail: error.stderrTail },\n }),\n }\n }\n\n logger.debug({ cwd, error }, 'orca: close failed outside the Orca contract')\n\n return {\n closed: false,\n error: new OrcaError({\n code: 'orca_close_failed',\n message: error instanceof Error ? error.message : String(error),\n }),\n }\n}\n\n/**\n * Tears down every Orca terminal of the worktree at `cwd` \u2014 called right before\n * `git worktree remove`, and nowhere else (a closed GUI is never a precondition\n * for anything that survives). Never throws: the caller decides whether an error\n * outcome blocks git, and a probe that is not `ready` skips without spawning.\n * The Orca-side row is pruned by Orca itself once the directory is gone.\n */\nexport const closeOrcaWorktreeTerminals = async (\n cwd: string,\n probe: OrcaProbe,\n): Promise<CloseOrcaWorktreeTerminalsOutcome> => {\n if (probe !== 'ready') {\n return { closed: false, skipped: probe }\n }\n\n try {\n return await closeEach(cwd)\n } catch (error) {\n return asOutcome(cwd, error)\n }\n}\n", "import { setTimeout as sleep } from 'node:timers/promises'\n\nimport { OrcaError, runOrca } from './run-orca'\n\nexport type OrcaPanes = 'two-columns' | 'three-pane'\nexport type OrcaOpenedLayout = 'full' | 'single-pane'\n\n/**\n * Shared per batch (one `worktrees add --all`): a fresh worktree\n * that `git worktree add` created milliseconds ago may not be selectable yet, so\n * `terminal create` is retried on `selector_not_found`. The cause of an\n * exhaustion (Orca not scanning the repo) is per-repo, so after the first one the\n * remaining targets attempt once \u2014 worst case `1 \u00D7 budget + (N\u22121) \u00D7 0`.\n */\nexport interface OrcaOpenPoll {\n attempts: number\n delayMs: number\n exhausted: boolean\n}\n\nconst DEFAULT_POLL_ATTEMPTS = 3\nconst DEFAULT_POLL_DELAY_MS = 300\n\nexport const createOrcaOpenPoll = (\n overrides: Partial<Pick<OrcaOpenPoll, 'attempts' | 'delayMs'>> = {},\n): OrcaOpenPoll => {\n return {\n attempts: overrides.attempts ?? DEFAULT_POLL_ATTEMPTS,\n delayMs: overrides.delayMs ?? DEFAULT_POLL_DELAY_MS,\n exhausted: false,\n }\n}\n\ninterface OpenOrcaWorktreeTerminalsArgs {\n cwd: string\n title: string\n /**\n * `--focus` steals the window; callers pass `false` on every multi-branch\n * `worktrees add` fan-out. It must also stay `false` on a row the sidebar hides \u2014\n * there `--focus` times out after ~10 s (docs/orca-cli-findings.md, axis 1).\n */\n focus: boolean\n layout: OrcaOpenedLayout\n /** The configured pane preset; only consulted when `layout` is `full`. */\n panes: OrcaPanes\n poll?: OrcaOpenPoll\n}\n\nexport interface OrcaTerminalCreateResult {\n terminal: { handle: string }\n}\n\nexport interface OrcaTerminalSplitResult {\n split: { handle: string }\n}\n\ntype CreateOutcome = { created: OrcaTerminalCreateResult } | { notSelectable: OrcaError }\n\nconst tryCreate = async (argv: string[]): Promise<CreateOutcome> => {\n try {\n return { created: await runOrca<OrcaTerminalCreateResult>(argv) }\n } catch (error) {\n if (error instanceof OrcaError && error.code === 'selector_not_found') {\n return { notSelectable: error }\n }\n\n throw error\n }\n}\n\nconst createWithPoll = async (argv: string[], cwd: string, poll: OrcaOpenPoll): Promise<string> => {\n const attempts = poll.exhausted ? 1 : poll.attempts\n\n const schedule = Array.from({ length: attempts }, (_, index) => {\n return index + 1\n })\n\n let lastRefusal: OrcaError | undefined\n\n for (const attempt of schedule) {\n const outcome = await tryCreate(argv)\n\n if ('created' in outcome) {\n return outcome.created.terminal.handle\n }\n\n lastRefusal = outcome.notSelectable\n\n if (attempt < attempts) {\n await sleep(poll.delayMs)\n }\n }\n\n poll.exhausted = true\n\n throw new OrcaError({\n code: 'orca_worktree_not_selectable',\n message: `orca: worktree ${cwd} is not selectable after ${attempts} attempt(s): ${lastRefusal?.message ?? ''}`,\n data: { cwd, attempts, cause: lastRefusal?.data },\n })\n}\n\nconst split = async (handle: string, direction: 'horizontal' | 'vertical'): Promise<string> => {\n const result = await runOrca<OrcaTerminalSplitResult>([\n 'terminal',\n 'split',\n '--terminal',\n handle,\n '--direction',\n direction,\n ])\n\n return result.split.handle\n}\n\n/**\n * Opens terminals for the worktree at `cwd` in one Orca tab and returns their\n * handles (`handles[0]` is the tab's first pane). `full` lays out the preset:\n * `horizontal` on `h0` puts a pane to the RIGHT, and `three-pane` adds a\n * `vertical` split on the same `h0` for the pane BELOW it (measured tree:\n * `horizontal(vertical(h0, h2), h1)`).\n *\n * A background (non-`--focus`) handle is splittable in the same tab, so no\n * layout depends on focus.\n */\nexport const openOrcaWorktreeTerminals = async (\n args: OpenOrcaWorktreeTerminalsArgs,\n): Promise<{ handles: string[]; layout: OrcaOpenedLayout }> => {\n const { cwd, title, focus, layout, panes, poll = createOrcaOpenPoll() } = args\n\n const createArgv = [\n 'terminal',\n 'create',\n '--worktree',\n `path:${cwd}`,\n '--title',\n title,\n ...(focus ? ['--focus'] : []),\n ]\n\n const first = await createWithPoll(createArgv, cwd, poll)\n const handles = [first]\n\n if (layout === 'full') {\n handles.push(await split(first, 'horizontal'))\n\n if (panes === 'three-pane') {\n handles.push(await split(first, 'vertical'))\n }\n }\n\n return { handles, layout }\n}\n", "import { displayLabel, parseBranchName } from 'src/lib/release-id'\n\ninterface BuildOrcaTerminalTitleArgs {\n branch: string\n}\n\n/**\n * The Orca TAB title for a worktree's terminals \u2014 release branches render via\n * their release-id label (`release/v1.48.0` \u2192 `1.48.0`), anything else is the raw\n * branch. It labels the tab only: the sidebar row keeps Orca's automatic branch\n * name, and titles are never an ownership key because Orca programs rewrite the\n * per-terminal title at runtime (`\u2733 Claude Code`).\n */\nexport const buildOrcaTerminalTitle = (args: BuildOrcaTerminalTitleArgs): string => {\n const { branch } = args\n\n const id = parseBranchName(branch)\n\n return id ? displayLabel(id) : branch\n}\n", "/**\n * @fileoverview\n * Loopback liveness probes for the apps `infra-kit dev` runs: a backend's `/__health`, a UI's vite ping.\n * Shared by the dev panel's health dots and by `infra-kit e2e`, which must agree on what \"up\" means.\n */\n\n/** What a probe is aimed at. `kind` picks the endpoint AND the verdict rules \u2014 the two are not separable. */\nexport interface ProbeTarget {\n /** Stream tag (`<app>/api`, `<app>/ui`) \u2014 the key the health map and every log line agree on. */\n tag: string\n /** The port to probe: a backend's ACTUAL bound port, or a UI's runner-assigned vite port. */\n port: number\n kind: 'api' | 'ui'\n}\n\n/**\n * Something answered, but not the thing we asked for \u2014 and WHAT it answered is the whole diagnostic.\n *\n * A UI's `foreign` never paints red (see {@link ProbeOutcome}), so this line is the only thing the user\n * gets, and \"not vite's ping\" alone cannot separate the three causes it exists to tell apart: a\n * `200 text/html` means vite dropped the ping and infra-kit must ship a fix; a `502` means portless or a\n * proxy is shadowing the port; a `404` means a squatter won the free-port race. One glance, three very\n * different next moves \u2014 so the status and content-type travel with the verdict.\n */\nexport interface ForeignAnswer {\n kind: 'foreign'\n status: number\n contentType: string | null\n}\n\n/**\n * Three outcomes, not a boolean:\n * - `ok` \u2014 the endpoint PROVED it is serving (a 2xx on `/__health`; a 204 on vite's ping).\n * - `refused` \u2014 nothing answered (ECONNREFUSED, timeout, transport error).\n * - {@link ForeignAnswer} \u2014 something answered, but not the thing we asked for. For a backend that is a\n * failure (our own fastify returning non-2xx). For a UI it is NOT: a non-204 is equally consistent with a\n * squatter, with a proxy that shadows the ping, and with a future vite that dropped it \u2014 so it can never\n * be allowed to paint red, and it is the reason this is not a boolean.\n */\nexport type ProbeOutcome = 'ok' | 'refused' | ForeignAnswer\n\n/** Narrow a {@link ProbeOutcome} to the one arm that carries data. */\nexport const isForeign = (outcome: ProbeOutcome): outcome is ForeignAnswer => {\n return typeof outcome === 'object'\n}\n\n/** Build the `foreign` verdict from the response that earned it, draining its body so the socket returns. */\nconst foreignFrom = async (res: Response): Promise<ForeignAnswer> => {\n await res.body?.cancel()\n\n return { kind: 'foreign', status: res.status, contentType: res.headers.get('content-type') }\n}\n\n/**\n * The `\u25CD ?` warn. Names what answered instead of vite, because that is the whole actionable content: an\n * `html` body means vite dropped the ping (ours to fix), a 5xx means something is shadowing the port, a 404\n * means a squatter took it. The content-type is trimmed of its `; charset=\u2026` tail \u2014 it is a hint, not a\n * header dump.\n */\nexport const describeForeign = (port: number, answer: ForeignAnswer): string => {\n const type = answer.contentType?.split(';')[0]?.trim()\n const what = type == null || type === '' ? `${answer.status}` : `${answer.status} ${type}`\n\n return `port ${port} answered ${what}, not vite's ping \u2014 liveness cannot be verified`\n}\n\n/** Health-probe seam: resolve one target's liveness. Injectable so the panel stays deterministic in tests. */\nexport type HealthProbe = (target: ProbeTarget) => Promise<ProbeOutcome>\n\n/** One budget for the whole probe \u2014 BOTH hops of a UI redirect share it (see {@link probeUi}). */\nconst PROBE_TIMEOUT_MS = 1500\n\n/**\n * Vite's HMR ping. It is installed unconditionally on every dev server (no plugin, no config) and it sits\n * AHEAD of vite's `htmlFallback` middleware \u2014 which is the whole point: `htmlFallback` answers a plain\n * `GET /` with `200 index.html` even for a vite whose entry module throws, so a naive GET would report a\n * broken app as healthy. The ping cannot be forged that way; a 204 means a vite dev server is listening.\n */\nconst VITE_PING_HEADERS = { accept: 'text/x-vite-ping' } as const\n\n/**\n * Where a target is probed. Always `http://127.0.0.1:<port>`, never the `https://<alias>` the panel prints:\n * the alias adds TLS, a private CA and the portless daemon to the path, so a probe through it would report\n * the PROXY's health, not the app's. And never `localhost` \u2014 ServerlessLocalRun binds v4 loopback only,\n * while `localhost` resolves `[::1]` first on modern Node, which renders a healthy backend `\u25CF down`.\n */\nconst probeUrl = (target: ProbeTarget): string => {\n return target.kind === 'api' ? `http://127.0.0.1:${target.port}/__health` : `http://127.0.0.1:${target.port}/`\n}\n\n/** `new URL(loc, base)`, or `null` when the header is unparseable even relative to the probe URL. */\nconst resolveHop = (location: string, base: string): URL | null => {\n try {\n return new URL(location, base)\n } catch {\n return null\n }\n}\n\n/** A backend: `/__health` must answer 2xx. Anything else IS our own fastify failing, so it is not `ok`. */\nconst probeApi = async (url: string, signal: AbortSignal): Promise<ProbeOutcome> => {\n const res = await fetch(url, { signal })\n\n if (!res.ok) return foreignFrom(res)\n // Drain: undici keeps the socket checked out until an unread body is GC'd, and this runs every 5s per app\n // for the life of the session.\n await res.body?.cancel()\n\n return 'ok'\n}\n\n/**\n * A frontend: vite's ping must answer 204.\n *\n * The redirect hop is the delicate part. Vite serves the ping from its `base`, so a UI configured with\n * `base: '/app/'` answers `/` with a 3xx whose `Location` is RELATIVE (`/app/`) \u2014 which is why the hop is\n * resolved against the probe URL rather than parsed on its own (`new URL('/app/')` throws outright). The\n * accept header is RE-SENT on the second hop: without it the redirected request falls through to vite's\n * html fallback and comes back `200 text/html` \u2014 the exact false green this probe exists to refuse.\n *\n * Exactly one hop, same-origin only. A cross-origin redirect is somebody else's server, and a second hop\n * is a loop we have no budget for; both report `foreign` \u2014 never followed, and never called alive.\n */\nconst probeUi = async (url: string, signal: AbortSignal): Promise<ProbeOutcome> => {\n const res = await fetch(url, { headers: VITE_PING_HEADERS, redirect: 'manual', signal })\n\n if (res.status === 204) return 'ok'\n if (res.status < 300 || res.status >= 400) return foreignFrom(res)\n\n const location = res.headers.get('location')\n const next = location == null ? null : resolveHop(location, url)\n\n if (next == null || next.origin !== new URL(url).origin) return foreignFrom(res)\n\n await res.body?.cancel()\n\n const hop = await fetch(next, { headers: VITE_PING_HEADERS, redirect: 'manual', signal })\n\n if (hop.status !== 204) return foreignFrom(hop)\n await hop.body?.cancel()\n\n return 'ok'\n}\n\n/** Default probe: per-kind, bounded, and loopback-only. A transport error or a timeout is `refused`. */\nexport const defaultHealthProbe: HealthProbe = async (target: ProbeTarget): Promise<ProbeOutcome> => {\n const url = probeUrl(target)\n // ONE signal, shared across both hops: a redirect must not double the budget a wedged server can spend.\n const signal = AbortSignal.timeout(PROBE_TIMEOUT_MS)\n\n try {\n return target.kind === 'api' ? await probeApi(url, signal) : await probeUi(url, signal)\n } catch {\n return 'refused'\n }\n}\n", "import { readRelease } from '@slip-stream-kit/config/internal'\n\n/**\n * Slugified `<release>` for the app's git branch (resolved from the app's own dir), falling back to\n * `DEFAULT_RELEASE_SLUG` outside a git repo / on an empty slug. Never throws.\n *\n * A release ALWAYS resolves because it is the first DNS label of every alias, and every app is reached\n * by hostname. The fallback cannot collide the way a branch can: worktrees are what make two checkouts\n * coexist, and a worktree is by definition inside a git repo. One implementation, in the config package,\n * because the vite and Playwright helpers must name the same host.\n */\nexport const readAppRelease = (cwd: string): string => {\n return readRelease(cwd)\n}\n"],
5
+ "mappings": "sDAiCA,OAAS,YAAAA,GAAU,gBAAAC,OAAoB,qBAEvC,OAAOC,MAAa,eAapB,IAAMC,GAAmB,IAGnBC,GAAU,IAGVC,EAAkB,IAGlBC,EAAS,UAQTC,GAAqB,IAGrBC,EAAU,CAAC,MAAO,0BAA0B,EAG5CC,EAAgB,GAAK,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EAEhB,MALaC,EAAYD,CAAG,CAMrC,EAcME,GAAU,MAAOJ,EAAaC,IAA+C,CACjF,IAAMC,EAAM,MAAM,MAAMF,EAAK,CAAE,QAASP,GAAmB,SAAU,SAAU,OAAAQ,CAAO,CAAC,EAEvF,GAAIC,EAAI,SAAW,IAAK,MAAO,KAC/B,GAAIA,EAAI,OAAS,KAAOA,EAAI,QAAU,IAAK,OAAOC,EAAYD,CAAG,EAEjE,IAAML,EAAWK,EAAI,QAAQ,IAAI,UAAU,EACrCG,EAAOR,GAAY,KAAO,KAAOD,GAAWC,EAAUG,CAAG,EAE/D,GAAIK,GAAQ,MAAQA,EAAK,SAAW,IAAI,IAAIL,CAAG,EAAE,OAAQ,OAAOG,EAAYD,CAAG,EAE/E,MAAMA,EAAI,MAAM,OAAO,EAEvB,IAAMI,EAAM,MAAM,MAAMD,EAAM,CAAE,QAASZ,GAAmB,SAAU,SAAU,OAAAQ,CAAO,CAAC,EAExF,OAAIK,EAAI,SAAW,IAAYH,EAAYG,CAAG,GAC9C,MAAMA,EAAI,MAAM,OAAO,EAEhB,KACT,EAGaC,GAAkC,MAAOZ,GAA+C,CACnG,IAAMK,EAAMN,GAASC,CAAM,EAErBM,EAAS,YAAY,QAAQ,IAAgB,EAEnD,GAAI,CACF,OAAON,EAAO,OAAS,MAAQ,MAAMI,GAASC,EAAKC,CAAM,EAAI,MAAMG,GAAQJ,EAAKC,CAAM,CACxF,MAAQ,CACN,MAAO,SACT,CACF,EC3JA,OAAS,eAAAO,OAAmB,mCAWrB,IAAMC,GAAkBC,GACtBF,GAAYE,CAAG",
6
+ "names": ["execFile", "execFileSync", "process", "DEFAULT_GRACE_MS", "POLL_MS", "REAP_TIMEOUT_MS", "PS_BIN", "SAMPLE_INTERVAL_MS", "PS_ARGS", "PS_MAX_BUFFER", "parseProcRows", "raw", "line", "rawPid", "rawPpid", "rawPgid", "rest", "pid", "ppid", "pgid", "leaderStarts", "rows", "starts", "row", "snapshotGroups", "rootPid", "excludePgid", "collectDoomedGroups", "leaderStart", "validSnapshotPgids", "snapshot", "reapSnapshot", "childrenOf", "siblings", "groups", "seen", "queue", "i", "child", "snapshotProcRows", "snapshotProcRowsAsync", "resolve", "error", "stdout", "isChildOf", "parentPid", "doomedGroupsOf", "ownPgid", "groupAlive", "signalGroups", "pgids", "signal", "registry", "collectForceReapTargets", "registrySnapshots", "live", "fromRegistry", "killDescendantGroupsNow", "getGroups", "sleep", "ms", "waitForExit", "timeoutMs", "deadline", "alive", "superviseChild", "graceMs", "onUnexpectedExit", "snapshotRowsOverride", "killing", "exited", "sampler", "stopSampling", "deregisterAfter", "g", "applySample", "next", "sample", "reportUnexpected", "detail", "code", "doomed", "stragglers", "late", "forced", "constants", "process", "HANDLED_SIGNALS", "SIGNAL_NUMBERS", "constants", "FALLBACK_SIGNO", "exitCodeForSignal", "signal", "TEARDOWN_DEADLINE_MS", "defaultExit", "code", "process", "defaultRegister", "handler", "defaultUnregister", "defaultSetTimer", "ms", "timer", "writeStderr", "message", "writeTeardownFailure", "error", "detail", "registerSignalShutdown", "onSignal", "exit", "register", "unregister", "forceReap", "killDescendantGroupsNow", "teardownDeadlineMs", "setTimer", "describeStall", "fileReport", "firstSignal", "cancelDeadline", "handlers", "detach", "handle", "report", "CANCELLATION_ERROR_NAMES", "hasCancellationName", "value", "isPromptCancellation", "error", "cause", "$", "OrcaError", "payload", "OrcaMalformedError", "exitCode", "stderrTail", "OrcaAbsentError", "STDERR_TAIL_CHARS", "SHELL_COMMAND_NOT_FOUND", "isEnoent", "error", "spawnOrca", "argv", "$", "parseEnvelope", "stdout", "parsed", "runOrca", "output", "envelope", "logger", "probeOrca", "status", "runOrca", "logger", "error", "OrcaAbsentError", "realpath", "realpathForOrcaCwd", "path", "findOrcaRepo", "mainRepoRoot", "repos", "wanted", "runOrca", "realpathForOrcaCwd", "repo", "addOrcaRepo", "WORKTREE_LIST_LIMIT", "isOrcaWorktreeListed", "mainRepoRoot", "cwd", "worktrees", "wanted", "runOrca", "realpathForOrcaCwd", "worktree", "process", "WORKTREE_ID_SEPARATOR", "orcaCallerWorktreePath", "env", "id", "separatorAt", "path", "orcaCallerInsideTargets", "paths", "process", "callerPath", "caller", "realpathForOrcaCwd", "TERMINAL_LIST_LIMIT", "listOrcaTerminals", "cwd", "result", "runOrca", "truncated", "logger", "error", "OrcaError", "retireSurfaces", "cwd", "runOrca", "error", "OrcaError", "logger", "closeEach", "terminals", "listOrcaTerminals", "terminal", "retired", "asOutcome", "OrcaAbsentError", "OrcaMalformedError", "closeOrcaWorktreeTerminals", "probe", "sleep", "DEFAULT_POLL_ATTEMPTS", "DEFAULT_POLL_DELAY_MS", "createOrcaOpenPoll", "overrides", "tryCreate", "argv", "runOrca", "error", "OrcaError", "createWithPoll", "cwd", "poll", "attempts", "schedule", "_", "index", "lastRefusal", "attempt", "outcome", "sleep", "split", "handle", "direction", "openOrcaWorktreeTerminals", "args", "title", "focus", "layout", "panes", "createArgv", "first", "handles", "buildOrcaTerminalTitle", "args", "branch", "id", "parseBranchName", "displayLabel", "isForeign", "outcome", "foreignFrom", "res", "describeForeign", "port", "answer", "type", "what", "VITE_PING_HEADERS", "probeUrl", "target", "resolveHop", "location", "base", "probeApi", "url", "signal", "res", "foreignFrom", "probeUi", "next", "hop", "defaultHealthProbe", "readRelease", "readAppRelease", "cwd"]
7
+ }
@@ -1,2 +1,2 @@
1
1
  import*as o from"node:fs";import*as i from"node:path";function v(e){let t=e;for(let r=0;r<10;r++){let s=i.join(t,"pnpm-workspace.yaml");if(o.existsSync(s))return t;t=i.dirname(t)}throw new Error("Could not find monorepo root (pnpm-workspace.yaml)")}function h(e,t){let r=i.join(e,"package.json");if(!o.existsSync(r))return t;try{let s=JSON.parse(o.readFileSync(r,"utf-8"));return typeof s.name=="string"?s.name:t}catch{return t}}function N(e){let t=i.join(e,"apps"),r=[];if(!o.existsSync(t))throw new Error(`Apps directory not found: ${t}`);let s=o.readdirSync(t,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name);for(let n of s){let a=i.join(t,n,"api"),p=i.join(a,"serverless.yml");o.existsSync(p)&&r.push({name:n,packageName:h(a,n),path:a})}return r}var y=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs"],k=["@slip-stream-kit/vite","@slip-stream-kit/config/vite","infra-kit/vite"];function S(e){for(let t of y){let r=i.join(e,t);if(o.existsSync(r))try{let s=o.readFileSync(r,"utf-8");return k.some(n=>s.includes(n))}catch{return!1}}return!1}function F(e){for(let t of y){let r=i.join(e,t);if(o.existsSync(r))try{return o.readFileSync(r,"utf-8").includes("infraKit(")}catch{return!1}}return!1}function D(e){let t=i.join(e,"package.json");if(!o.existsSync(t))return!1;try{let r=JSON.parse(o.readFileSync(t,"utf-8"));return typeof r.scripts?.dev=="string"&&r.scripts.dev.length>0}catch{return!1}}function G(e){let t=i.join(e,"apps"),r=[];if(!o.existsSync(t))return r;let s=o.readdirSync(t,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name);for(let n of s){let a=i.join(t,n,"ui");o.existsSync(a)&&D(a)&&r.push({name:n,packageName:h(a,n),path:a,managedPort:S(a)})}return r}function K(e){let t=e?.filter(Boolean)??[];return t.length>0?t:null}function L(e){let t=v(e),r=i.relative(i.join(t,"apps"),e),s=r.split(i.sep)[0];if(r===""||r.startsWith("..")||i.isAbsolute(r)||!s)throw new Error(`--self: not inside an apps/<app> directory (cwd: ${e}). Run from an app folder or use --app=<name>.`);return s}var A=new Set(["api","ui"]),d=e=>{let t=i.join(e,"dist");return o.existsSync(t)&&o.statSync(t).isDirectory()?t:void 0},f=e=>o.existsSync(e)?o.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name):[];function O(e){let t=[];for(let s of f(i.join(e,"packages"))){let n=d(i.join(e,"packages",s));n!==void 0&&t.push(n)}let r=i.join(e,"apps");for(let s of f(r))for(let n of f(i.join(r,s))){if(A.has(n))continue;let a=i.join(r,s,n);if(!o.existsSync(i.join(a,"package.json")))continue;let p=d(a);p!==void 0&&t.push(p)}return t}function _(e){return e.map(t=>i.join(t.path,"dist")).filter(t=>o.existsSync(t))}function z(e,t,r){let s=i.normalize(e),n=g=>{let c=i.normalize(g);return s===c||s.startsWith(c+i.sep)},a=r.find(n);return a?{kind:"package",packageDir:a}:{kind:"app",app:t.find(n)}}var j={"*/api":{},"*/ui":{}},R=e=>{let t=e.split("/"),[r,s]=t;return t.length!==2||!r?`invalid target "${e}" (expected "<app>/api" or "<app>/ui")`:s!=="api"&&s!=="ui"?`invalid target part "${s}" in "${e}" (expected "api" or "ui")`:null},b=e=>{let t=R(e);if(t)throw new Error(t);let[r,s]=e.split("/");return{appGlob:r,part:s}},w=(e,t)=>t==="api"?e.api:e.ui,I=e=>[...new Set([...e.api,...e.ui])].sort(),x=(e,t)=>`${e}/${t}`,T=(e,t,r)=>{let{app:s,part:n,isGlob:a}=r;if(!w(t,n).includes(s)){a||e.unmatched.push(x(s,n));return}e.targets.set(x(s,n),{app:s,part:n})},$=(e,t)=>{let r=Object.entries(e.apps??j),s={targets:new Map,proxy:{},unmatched:[]};for(let[p,g]of r){let{appGlob:c,part:m}=b(p),l=c==="*",P=l?I(t):[c];for(let u of P)T(s,t,{app:u,part:m,isGlob:l}),g.proxy&&(s.proxy[u]={...s.proxy[u]??{},...g.proxy})}let n=[...s.targets.values()],a=[...new Set(n.filter(p=>p.part==="api").map(p=>p.app))];return{targets:n,proxy:s.proxy,localApps:a,unmatched:s.unmatched}},U=e=>{if(e.running.length===0)return"nothing";let t=new Set(e.running);return e.discovered.every(s=>t.has(s))?"*":[...t].sort().join(" + ")},C=(e,t)=>Object.keys(e).find(r=>e[r]===t),E=({app:e,route:t,launchedPkgs:r,ctx:s})=>{let n=s.routePkg(e,t);if(n===void 0)return{app:e,route:t,kind:"unknown-route",message:`proxy override "${t}" on "${e}" names a route not declared in ${e}'s infra-kit.config.ts dev.proxy.routes`};if(r.has(n))return null;let a=C(s.apiPkgByApp,n),p=a?`add "${a}/api" to the selection`:`launch the api whose package is "${n}"`;return{app:e,route:t,pkg:n,kind:"backend-not-launched",message:`proxy override "${t}" \u2192 "local" requires backend "${n}" to run locally, but nothing launches it \u2014 ${p}, or set "${t}" to "cloud"`}},V=(e,t)=>{let r=$(e,t.discovered),s=new Set(r.localApps.map(n=>t.apiPkgByApp[n]).filter(n=>n!==void 0));return Object.entries(r.proxy).flatMap(([n,a])=>Object.entries(a).flatMap(([p,g])=>{let c=g==="local"?E({app:n,route:p,launchedPkgs:s,ctx:t}):null;return c?[c]:[]}))};export{v as a,N as b,F as c,G as d,K as e,L as f,O as g,_ as h,z as i,R as j,$ as k,U as l,V as m};
2
- //# sourceMappingURL=chunk-SAHE3MZJ.js.map
2
+ //# sourceMappingURL=chunk-55F372Z7.js.map