infra-kit 0.3.5 → 0.3.7

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 (40) hide show
  1. package/dist/boot-HP5ORQEX.js +2 -0
  2. package/dist/boot-HP5ORQEX.js.map +7 -0
  3. package/dist/chunk-7DL27USH.js +7 -0
  4. package/dist/{chunk-GZNE5CBQ.js.map → chunk-7DL27USH.js.map} +3 -3
  5. package/dist/chunk-IURGCRSN.js +231 -0
  6. package/dist/chunk-IURGCRSN.js.map +7 -0
  7. package/dist/chunk-KAWDTA5H.js +2 -0
  8. package/dist/chunk-KAWDTA5H.js.map +7 -0
  9. package/dist/{chunk-A7FAXZGI.js → chunk-LKKKDB6V.js} +1 -1
  10. package/dist/{chunk-A7FAXZGI.js.map → chunk-LKKKDB6V.js.map} +1 -1
  11. package/dist/{chunk-OS5Z2WME.js → chunk-N6ML3SBF.js} +2 -2
  12. package/dist/{chunk-OS5Z2WME.js.map → chunk-N6ML3SBF.js.map} +1 -1
  13. package/dist/chunk-PZU6BLQR.js +4 -0
  14. package/dist/{chunk-IVWPZEMC.js.map → chunk-PZU6BLQR.js.map} +3 -3
  15. package/dist/chunk-X46DP23W.js +2 -0
  16. package/dist/chunk-X46DP23W.js.map +7 -0
  17. package/dist/chunk-XTRPE4SX.js +2 -0
  18. package/dist/chunk-XTRPE4SX.js.map +7 -0
  19. package/dist/cli.js +6 -6
  20. package/dist/cli.js.map +3 -3
  21. package/dist/dev-server.js +3 -3
  22. package/dist/dev-server.js.map +2 -2
  23. package/dist/dev-wizard-run-KIOSJM4D.js +2 -0
  24. package/dist/dev-wizard-run-KIOSJM4D.js.map +7 -0
  25. package/dist/mcp.js +1 -1
  26. package/dist/mcp.js.map +1 -1
  27. package/dist/update-check.js +1 -1
  28. package/package.json +1 -1
  29. package/dist/boot-EEEVHAMO.js +0 -2
  30. package/dist/boot-EEEVHAMO.js.map +0 -7
  31. package/dist/chunk-GZNE5CBQ.js +0 -7
  32. package/dist/chunk-IVWPZEMC.js +0 -4
  33. package/dist/chunk-K46DOODL.js +0 -231
  34. package/dist/chunk-K46DOODL.js.map +0 -7
  35. package/dist/chunk-S45AAYXO.js +0 -4
  36. package/dist/chunk-S45AAYXO.js.map +0 -7
  37. package/dist/chunk-UO3FYLPX.js +0 -2
  38. package/dist/chunk-UO3FYLPX.js.map +0 -7
  39. package/dist/dev-wizard-run-5ST3BJ4L.js +0 -2
  40. package/dist/dev-wizard-run-5ST3BJ4L.js.map +0 -7
@@ -0,0 +1,2 @@
1
+ import{b as V}from"./chunk-TPVXMJ7N.js";import{c as Z}from"./chunk-X46DP23W.js";import{render as We}from"ink";import me from"node:process";import{Box as J,Text as R,useApp as we,useInput as xe,useWindowSize as ge}from"ink";import{useEffect as te,useState as G}from"react";import{useMemo as pe,useState as j}from"react";var F=(e,t)=>{let[r,m]=j(""),[n,a]=j(0),o=pe(()=>{let f=r.trim().toLowerCase();return f?e.filter(d=>t(d).toLowerCase().includes(f)):e},[e,r,t]),u=Math.min(n,Math.max(0,o.length-1));return{filtered:o,activeIndex:u,query:r,handleNavigation:(f,d)=>{let b=o.length;return d.upArrow?(b>0&&a((u-1+b)%b),!0):d.downArrow?(b>0&&a((u+1)%b),!0):d.backspace||d.delete?(m(r.slice(0,-1)),a(0),!0):f&&!d.ctrl&&!d.meta?(m(r+f),a(0),!0):!1},clearQuery:()=>r?(m(""),a(0),!0):!1}};var fe=()=>{},q=(e,t=0)=>e<5?{mode:"tiny",chromeRows:0,groups:!1}:e<10?{mode:"compact",chromeRows:4+t,groups:!1}:{mode:"full",chromeRows:6+t,groups:!0},he=(e,t,r,m)=>{let n=0,a;for(let o=t;o<r;o+=1){let u=e[o];if(!u)break;let w=m(u),T=w!==void 0&&w!==a;n+=1+(T?1:0)+(T&&o>t?1:0),a=w}return n},ee=(e,t,r,m)=>{let n=t;for(;n<e.length&&he(e,t,n+1,m)<=r;)n+=1;return n},$=(e,t,r,m,n)=>{let a=n?.groupOf??fe,o=Math.max(0,m-(n?.chromeRows??6)),u=Math.min(t,r);for(;r>=ee(e,u,o,a)&&u<r;)u+=1;let w=ee(e,u,o,a);return{visible:e.slice(u,w),start:u,hiddenBefore:u,hiddenAfter:Math.max(0,e.length-w)}};import{jsx as I,jsxs as D}from"react/jsx-runtime";var re=e=>{let{items:t,onSubmit:r,onCancel:m,required:n=!0,allowSelectAll:a=!0}=e,o=be,u=t.reduce((s,x)=>Math.max(s,x.label.length),0),{exit:w}=we(),{rows:T}=ge(),{filtered:f,activeIndex:d,query:b,handleNavigation:v,clearQuery:M}=F(t,Te),[B,O]=G(()=>new Set),[E,h]=G(!1),[C,p]=G(0),[l,S]=G(!1);te(()=>{l&&w()},[l,w]);let _=q(T,1),y=$(f,C,d,T,{chromeRows:_.chromeRows});te(()=>{y.start!==C&&p(y.start)},[y.start,C]);let k=s=>{O(x=>{let g=new Set(x);return g.has(s)?g.delete(s):g.add(s),g})},H=()=>{O(s=>t.every(g=>s.has(g.value))?new Set:new Set(t.map(g=>g.value)))},i=()=>{m(),S(!0)},c=()=>{if(n&&B.size===0){h(!0);return}r([...B]),S(!0)};return xe((s,x)=>{if(!l){if(x.ctrl&&s==="c"){i();return}if(x.escape){M()||i();return}if(x.ctrl&&s==="a"){a&&H();return}if(s===" "){let g=f[d];g&&k(g.value);return}if(x.return){c();return}v(s,x)}}),l?null:_.mode==="tiny"?I(R,{dimColor:!0,wrap:"truncate",children:o.tiny}):D(J,{flexDirection:"column",children:[_.mode==="full"?I(R,{dimColor:!0,wrap:"truncate",children:o.hint}):null,D(J,{children:[I(R,{color:"cyan",children:o.prompt}),I(R,{wrap:"truncate-start",children:b})]}),D(J,{flexDirection:"column",marginTop:_.mode==="full"?1:0,children:[f.length===0?I(R,{dimColor:!0,wrap:"truncate",children:o.empty}):null,y.hiddenBefore>0?I(R,{dimColor:!0,wrap:"truncate",children:`${o.more} ${y.hiddenBefore} above`}):null,y.visible.map((s,x)=>{let g=y.start+x===d,de=B.has(s.value);return D(R,{color:g?"green":void 0,wrap:"truncate",children:[g?"\u203A ":" ",de?"[x] ":"[ ] ",s.label.padEnd(u)," ",I(R,{dimColor:!0,children:s.description??""})]},s.value)}),y.hiddenAfter>0?I(R,{dimColor:!0,wrap:"truncate",children:`${o.more} ${y.hiddenAfter} below`}):null]}),E?I(R,{dimColor:!0,wrap:"truncate",children:o.requiredHint}):null]})};function Te(e){return`${e.label} ${e.description??""}`}var be={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 U,Text as W,useApp as Ce,useInput as Se,useWindowSize as ye}from"ink";import{useEffect as ne,useState as oe}from"react";import{jsx as L,jsxs as z}from"react/jsx-runtime";var ie=e=>{let{items:t,onSelect:r,onCancel:m}=e,n=Be,a=t.reduce((p,l)=>Math.max(p,l.label.length),0),{exit:o}=Ce(),{rows:u}=ye(),{filtered:w,activeIndex:T,query:f,handleNavigation:d,clearQuery:b}=F(t,ve),[v,M]=oe(0),[B,O]=oe(!1);ne(()=>{B&&o()},[B,o]);let E=q(u),h=$(w,v,T,u,{chromeRows:E.chromeRows});ne(()=>{h.start!==v&&M(h.start)},[h.start,v]);let C=()=>{m(),O(!0)};return Se((p,l)=>{if(!B){if(l.ctrl&&p==="c"){C();return}if(l.escape){b()||C();return}if(l.return){let S=w[T];S&&(r(S.value),O(!0));return}d(p,l)}}),B?null:E.mode==="tiny"?L(W,{dimColor:!0,wrap:"truncate",children:n.tiny}):z(U,{flexDirection:"column",children:[E.mode==="full"?L(W,{dimColor:!0,wrap:"truncate",children:n.hint}):null,z(U,{children:[L(W,{color:"cyan",children:n.prompt}),L(W,{wrap:"truncate-start",children:f})]}),z(U,{flexDirection:"column",marginTop:E.mode==="full"?1:0,children:[w.length===0?L(W,{dimColor:!0,wrap:"truncate",children:n.empty}):null,h.hiddenBefore>0?L(W,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenBefore} above`}):null,h.visible.map((p,l)=>{let S=h.start+l===T;return z(W,{color:Pe(p.type,S),wrap:"truncate",children:[S?"\u203A ":" ",p.label.padEnd(a)," ",L(W,{dimColor:!0,children:p.description??""})]},p.value)}),h.hiddenAfter>0?L(W,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenAfter} below`}):null]})]})};function Pe(e,t){return e==="hotfix"?"red":t?"green":void 0}function ve(e){return`${e.label} ${e.description??""}`}var Be={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 P,useApp as Oe,useInput as Re,useWindowSize as Ae}from"ink";import{useEffect as le,useMemo as Ee,useState as K}from"react";import{jsx as A,jsxs as N}from"react/jsx-runtime";var ae=e=>{let{items:t,onSelect:r,onCancel:m,onSuspend:n}=e,a={hint:Ie(!!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}=Oe(),{rows:T}=Ae(),[f,d]=K(""),[b,v]=K(0),[M,B]=K(0),[O,E]=K(!1);le(()=>{O&&u()},[O,u]);let h=Ee(()=>{let i=f.trim().toLowerCase();return i?t.filter(c=>`${c.name} ${c.description}`.toLowerCase().includes(i)):t},[t,f]),C=Math.min(b,Math.max(0,h.length-1)),p=q(T),l=$(h,M,C,T,{chromeRows:p.chromeRows,groupOf:p.groups?i=>i.group:void 0});le(()=>{l.start!==M&&B(l.start)},[l.start,M]);let S=()=>{m(),E(!0)},_=()=>{n&&w(n).catch(()=>{})},y=i=>i==="c"||i==="d"?(S(),!0):i==="z"?(_(),!0):!1,k=i=>{let c=h.length;c>0&&v((C+i+c)%c)};if(Re((i,c)=>{if(!O&&!(c.ctrl&&y(i))){if(c.escape){d(""),v(0);return}if(c.return){let s=h[C];s&&(r(s.name),E(!0));return}if(c.upArrow){k(-1);return}if(c.downArrow){k(1);return}if(c.backspace||c.delete){d(f.slice(0,-1)),v(0);return}i&&!c.ctrl&&!c.meta&&(d(f+i),v(0))}}),O)return null;if(p.mode==="tiny")return A(P,{dimColor:!0,wrap:"truncate",children:a.tiny});let H="";return N(Q,{flexDirection:"column",children:[p.mode==="full"?A(P,{dimColor:!0,wrap:"truncate",children:a.hint}):null,N(Q,{children:[A(P,{color:"cyan",children:a.prompt}),A(P,{wrap:"truncate-start",children:f})]}),N(Q,{flexDirection:"column",marginTop:p.mode==="full"?1:0,children:[h.length===0?A(P,{dimColor:!0,wrap:"truncate",children:a.empty}):null,l.hiddenBefore>0?A(P,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenBefore} above`}):null,l.visible.map((i,c)=>{let s=l.start+c===C,x=p.groups&&i.group!==H;return H=i.group,N(Q,{flexDirection:"column",children:[x&&c>0?A(P,{children:" "}):null,x?A(P,{color:"yellow",wrap:"truncate",children:`\u2014 ${i.group} \u2014`}):null,N(P,{color:s?"green":void 0,wrap:"truncate",children:[s?"\u203A ":" ",i.name.padEnd(o)," ",A(P,{dimColor:!0,children:i.description})]})]},i.name)}),l.hiddenAfter>0?A(P,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenAfter} below`}):null]})]})},se={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"},Ie=e=>e?se.suspend:se.plain;import ue from"node:process";var ce=(e={})=>{let t=e.platform??ue.platform,r=e.kill??((m,n)=>{ue.kill(m,n)});if(t!=="win32")try{r(0,"SIGSTOP")}catch{}};import{jsx as X}from"react/jsx-runtime";var Y=async e=>{let t=V(),{waitUntilExit:r}=We(e,{stdout:t,exitOnCtrlC:!1,interactive:!!t.isTTY});try{await r()}catch{}finally{Z()>0&&me.stdin.ref()}},ut=async e=>{let t=null;return await Y(X(ae,{items:e,onSelect:r=>{t=r},onCancel:()=>{t=null},onSuspend:me.platform==="win32"?void 0:()=>{ce()}})),t},ct=async e=>{let t=null;return await Y(X(ie,{items:e,onSelect:r=>{t=r},onCancel:()=>{t=null}})),t},mt=async(e,t)=>{let r=null;return await Y(X(re,{items:e,required:t?.required,allowSelectAll:t?.allowSelectAll,onSubmit:m=>{r=m},onCancel:()=>{r=null}})),r};export{mt as runBranchMultiPicker,ct as runBranchPicker,ut as runCommandPalette};
2
+ //# sourceMappingURL=boot-HP5ORQEX.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", "../src/tui/suspend.ts"],
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'\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 { suspendForeground } from './suspend'\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 MCP / `--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 `ref()`s when it arms raw mode and `unref()`s when it\n * drops it on teardown (ink/build/components/App.js:225 / :137). A later Ink render refs\n * itself again on mount, and an `@inquirer/*` prompt \u2014 which refs nothing on its own \u2014 now\n * gets its ref from `withEscape` (lib/prompts/stdin-ref). So the common paths need nothing\n * from us here.\n *\n * The one thing Ink's `unref()` cannot know about is a reader that is ALREADY live: an Ink\n * screen rendered inside a `withEscape` callback would, on teardown, unref the handle the\n * outer prompt is still reading from and kill it with exit 13. Hence the re-assert below,\n * conditional on the counter. It is a net for a boundary nothing structurally enforces \u2014\n * see lib/prompts/stdin-ref \u2014 not the mechanism that keeps prompts alive.\n *\n * It replaces an UNCONDITIONAL `process.stdin.ref()`, whose stated premise \u2014 \"an idle\n * ref'd stdin does not block exit\" \u2014 is simply false: a ref'd tty ReadStream holds the\n * event loop open whether or not anything is listening to it. That re-ref bought the next\n * prompt its handle and cost the session shell its exit, so every quit key in the palette\n * tore the frame down correctly and then hung forever.\n */\nconst renderToStderr = async (element: ReactElement): Promise<void> => {\n const stdout = safeStderr()\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) process.stdin.ref()\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 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 // Selection keyed by value so it persists across filter changes.\n const [selected, setSelected] = useState<Set<string>>(() => {\n return new Set()\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 * 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 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 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 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 * hintFor(true).includes('Ctrl-Z') // => true\n */\nconst hintFor = (canSuspend: boolean): string => {\n return canSuspend ? HINTS.suspend : HINTS.plain\n}\n", "import process from 'node:process'\n\n/**\n * Ctrl-Z at the palette, from the process side. React-free on purpose: the palette is pure\n * presentation and must not reach for `node:process`, and this half is worth unit-testing with plain\n * vitest (inject `kill`, assert the signal) rather than through an Ink frame.\n *\n * It lives under `src/tui/` rather than `src/lib/session/` because `boot.tsx` is its only caller and\n * the whole `src/tui/**` tree is the lazily-imported Ink chunk \u2014 the session layer never imports it,\n * and parking it there would drag it into the eager CLI chunk for nothing.\n */\n\n/** Seams for the stop. Production passes nothing; tests inject fakes and assert the signal. */\nexport interface SuspendDeps {\n platform?: NodeJS.Platform\n kill?: (pid: number, signal: NodeJS.Signals) => void\n}\n\n/**\n * Stop the foreground PROCESS GROUP so the user's shell reclaims the tty and prints a prompt.\n * Returns when the job is resumed (`fg` \u2192 SIGCONT): the kill halts JS synchronously, and execution\n * continues at the next statement \u2014 so there is no SIGCONT handler and nothing to re-arm.\n *\n * **pid 0 is the whole process group, and that is load-bearing.** Under `pnpm exec infra-kit`, pnpm's\n * node wrapper shares our pgid and the interactive shell only ever waits on PNPM \u2014 we are a\n * grandchild it never reaps. Stopping only ourselves would leave pnpm blocked in `waitpid`, so the\n * job never reads as stopped, the shell never reclaims the tty, and the terminal wedges with no\n * prompt and no way back. Stopping the group suspends the job as a unit, exactly as the tty's own\n * Ctrl-Z would; on direct-bin invocation it degenerates to a self-stop, so this is one code path.\n *\n * Only ever called from inside Ink's `suspendTerminal`, which has already erased the frame, restored\n * the cursor and dropped raw mode by the time we get here.\n *\n * `bg` is NOT supported: on resume Ink re-arms raw mode, and a `tcsetattr` from a background process\n * group raises SIGTTOU, which stops the job again. Same as vim. Use `fg`.\n *\n * @example\n * const stopped: number[] = []\n * suspendForeground({ platform: 'darwin', kill: (pid) => stopped.push(pid) })\n * stopped // => [0] (the process group, not process.pid)\n */\nexport const suspendForeground = (deps: SuspendDeps = {}): void => {\n const platform = deps.platform ?? process.platform\n const kill =\n deps.kill ??\n ((pid: number, signal: NodeJS.Signals) => {\n process.kill(pid, signal)\n })\n\n // SIGSTOP does not exist on Windows: `process.kill` there goes to uv_kill, which fails with ENOSYS\n // and THROWS. That throw would surface inside an Ink input handler \u2192 the ErrorBoundary \u2192\n // `handleExit(error)` \u2192 the session shell would silently QUIT. And Windows really does reach this\n // code: `sessionGateEnabled` (lib/session/run-session.ts) gates on TTYs only, with no platform\n // check, so Windows Terminal enters the palette like any other. Belt to boot.tsx's braces.\n if (platform === 'win32') {\n return\n }\n\n // No cursor/newline work here, deliberately: Ink's `beginSuspend` has already erased its frame and\n // left the cursor at column 0, so the shell's \"suspended\" line lands on a clean row. Writing a\n // newline first only opens a gratuitous blank gap above it (verified on a real pty).\n try {\n kill(0, 'SIGSTOP')\n } catch {\n // A stop we could not perform must degrade to a no-op, never to a crash: we are called mid\n // terminal-restore, and throwing here would take the session down with the tty half-handed-back.\n }\n}\n"],
5
+ "mappings": "gFAAA,OAAS,UAAAA,OAAc,MACvB,OAAOC,OAAa,eCDpB,OAAS,OAAAC,EAAK,QAAAC,EAAM,UAAAC,GAAQ,YAAAC,GAAU,iBAAAC,OAAqB,MAC3D,OAAS,aAAAC,GAAW,YAAAC,MAAgB,QCApC,OAAS,WAAAC,GAAS,YAAAC,MAAgB,QA+B3B,IAAMC,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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", "process", "suspendForeground", "deps", "platform", "kill", "pid", "signal", "jsx", "renderToStderr", "element", "stdout", "safeStderr", "waitUntilExit", "render", "stdinReaderCount", "process", "runCommandPalette", "items", "selected", "CommandPalette", "name", "suspendForeground", "runBranchPicker", "BranchPicker", "value", "runBranchMultiPicker", "opts", "BranchMultiPicker", "values"]
7
+ }
@@ -0,0 +1,7 @@
1
+ import{P as E,v as l}from"./chunk-PZU6BLQR.js";import{q as w}from"./chunk-CHETBZ6M.js";import{a as k,b as S}from"./chunk-X46DP23W.js";import p from"node:fs/promises";import c from"node:path";import{z as s}from"zod";var i=class extends Error{env;constructor(e,o=null){super(e),this.name="EnvAuthError",this.env=o}},K=t=>t instanceof i;import $ from"node:fs/promises";import C from"node:os";var I=async t=>{try{return await $.access(t),!0}catch{return!1}},f=t=>{let e=C.homedir();return t.startsWith(e)?`~${t.slice(e.length)}`:t};var M="tokens.json",d=1,y=384,T=448,N=s.object({version:s.literal(d).default(d),envs:s.record(s.string().min(1),s.string().min(1))}).strict(),u=async()=>{let t=await E();return c.join(c.dirname(t.userProject),M)},g=async()=>{let t=await u(),e;try{e=await p.readFile(t,"utf-8")}catch{return null}let o;try{o=JSON.parse(e)}catch(n){throw new i(`Invalid JSON in the token store at ${f(t)}: ${n.message}
2
+ Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`)}let r=N.safeParse(o);if(!r.success)throw new i(`Invalid token store at ${f(t)}: ${s.prettifyError(r.error)}
3
+ Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return r.data},h=async t=>{let e=await u(),o=c.dirname(e),r=c.dirname(o),n=c.dirname(r);for(let a of[n,r,o])await p.mkdir(a,{recursive:!0,mode:T}),await p.chmod(a,T);w(e,`${JSON.stringify(t,null,2)}
4
+ `,y),await p.chmod(e,y)},_=async(t,e)=>{let o=await g();await h({version:d,envs:{...o?.envs,[t]:e}})},j=async t=>{let e=await g();if(!e||!(t in e.envs))return;let o={...e.envs};delete o[t],await h({version:d,envs:o})};var D=()=>{let t="",e=[],o=!1;return{start(r){t=r,e=[],o=!1},setInteractive(){o=!0},addOption(r,n){e.push({flag:r,value:n})},formatOptions(){return e.map(r=>typeof r.value=="boolean"?r.value?r.flag:"":Array.isArray(r.value)?`${r.flag} "${r.value.join(", ")}"`:`${r.flag} "${r.value}"`).filter(Boolean).join(" ")},snapshot(){return e.length===0?null:{formattedOptions:this.formatOptions()}},print(){!o||e.length===0||!t||l.info(`\u{1F4DF} Equivalent command:
5
+ pnpm exec infra-kit ${t} ${this.formatOptions()}
6
+ `)},reset(){t="",e=[],o=!1}}},v=D();import P from"node:process";var O={enabled:!1},x=()=>O.enabled;var A=27,b=async(t,e)=>{let o=new AbortController,r={...e,signal:o.signal};if(x()||!P.stdin.isTTY)return t(r);let n=P.stdin,a=m=>{m.length===1&&m[0]===A&&o.abort()};k();try{let m=t(r);return n.on("data",a),await m}finally{n.removeListener("data",a),S()}};import F from"@inquirer/confirm";import R from"node:process";var J=async(t,e)=>{let o=t?!0:await b(r=>F({message:e},r));t||v.setInteractive(),o||(l.info("Operation cancelled. Exiting..."),R.exit(0))};export{i as a,K as b,I as c,f as d,u as e,g as f,_ as g,j as h,v as i,O as j,x as k,b as l,J as m};
7
+ //# sourceMappingURL=chunk-7DL27USH.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/lib/env-tokens/env-tokens.ts", "../src/lib/errors/env-auth-error.ts", "../src/lib/path-display/path-display.ts", "../src/lib/command-echo/command-echo.ts", "../src/lib/prompts/escapable-context.ts", "../src/lib/mcp-mode/mcp-mode.ts", "../src/lib/command-echo/confirm-or-exit.ts"],
4
- "sourcesContent": ["// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n *\n * HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were dropped\n * for it \u2014 do not re-add either without re-deciding that:\n *\n * - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version key,\n * and a store the CLI refuses to read is a store the human cannot write.\n * - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout. That\n * guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so `~/work/api`\n * and `~/oss/api` share ONE token directory and repo B could load (and then overwrite) repo A's\n * credentials. It was removed anyway, knowingly: it also made the CLI refuse every hand-written\n * store, which carries no such field. Hand-authorability wins; the basename-collision risk is\n * ACCEPTED. A weakened version of the guard (warn-and-continue, or \"only check when present\") is\n * NOT the compromise here \u2014 it would re-introduce the same refusal for anyone who did write the\n * field. If you want the guard back, key the store directory on something collision-free instead.\n */\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 it cannot heal on a 30s retry, only a human can fix it \u2014 and env\n // auto-load's sticky marker is keyed on that CLASS. Thrown as a plain Error these were classified\n // TRANSIENT, so a corrupt store went silent on the backgrounded shell-startup spawn and the user's\n // env simply stopped loading with nothing ever said. `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, [env]: token },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): env auto-load must tell a user\n * apart from a TRANSIENT failure (network, timeout, Doppler down \u2014 heals itself, 30s backoff, stay\n * quiet) and a DURABLE one (no token, a corrupt token store, a foreign token store \u2014 never heals, and\n * only a human can fix it). Only the durable class earns the STICKY marker that survives the\n * backgrounded shell-startup spawn and is replayed onto the next interactive command; a durable\n * failure misclassified as transient is TOTAL SILENCE, forever, on the one path the whole feature\n * exists to survive.\n *\n * That classification therefore has to travel WITH the error, not be re-derived by grepping a message\n * some other module owns \u2014 and it has to be throwable from EVERY module that can produce the class.\n * `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a Doppler-owned base type\n * could not be thrown there without a layering inversion and an import cycle. Hence a neutral base\n * here in `lib/errors`, with `DopplerAuthError extends EnvAuthError` for the subset of failures that\n * are specifically \"Doppler refused the token we sent\".\n *\n * The defect class this closes is \"a durable failure that is not type-detectable\". Adding a new\n * durable failure and forgetting to type it is exactly how this shipped silent twice \u2014 so throw this\n * (or a subclass), never a plain `Error`, for anything a user must fix before env-load can work.\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n *\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * This is the default `isAuthFailure` of `lib/env-autoload`'s `runEnvAutoLoad`. It is deliberately\n * WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only one of the\n * durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store never reaches\n * the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n", "import fs from 'node:fs/promises'\nimport os from 'node:os'\n\n/**\n * Shared path-display helpers for CLI output. Extracted from `commands/config`\n * and `commands/init/migrate-config` (which each had private copies) so config\n * surfaces print paths consistently. Keep this dependency-light (node builtins\n * only) \u2014 it is imported by several commands.\n */\n\n/**\n * Resolve whether a file is reachable, suppressing ENOENT (and any access error)\n * into a boolean. Used to render `[\u2713]`/`[ ]` existence markers.\n *\n * @example\n * await fileExists('/etc/hosts') // => true\n * await fileExists('/nope.txt') // => false\n */\nexport const fileExists = async (filePath: string): Promise<boolean> => {\n try {\n await fs.access(filePath)\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Replace the user's home prefix with `~` so logged paths stay short and portable\n * across machines. Leaves non-home paths untouched.\n *\n * @example\n * // os.homedir() === '/Users/arthur'\n * tildify('/Users/arthur/.infra-kit/infra-kit.json') // => '~/.infra-kit/infra-kit.json'\n * tildify('/etc/hosts') // => '/etc/hosts'\n */\nexport const tildify = (filePath: string): string => {\n const home = os.homedir()\n\n return filePath.startsWith(home) ? `~${filePath.slice(home.length)}` : filePath\n}\n", "import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the command ran off the CLI (an MCP tool), where a `pnpm exec` line would be\n * nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { isMcpMode } from 'src/lib/mcp-mode'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\nconst ESC_BYTE = 0x1b\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation.\n *\n * The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal\n * goes into the prompt context, `@inquirer/core` rejects with an `AbortPromptError`\n * when it fires, that name is already in `CANCELLATION_ERROR_NAMES`\n * (lib/errors/is-prompt-cancellation), and `entry/cli.ts` catches it at the top\n * level \u2192 \"Operation cancelled.\" \u2192 exit 0. All this adds is the thing that calls\n * `abort()`.\n *\n * DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b`\n * byte. Deliberately NOT readline `keypress`: that delivers a lone Esc only after its\n * escape-sequence timeout (~523ms measured), and the `escapeCodeTimeout` dial that\n * would shorten it is process-global and first-armer-wins \u2014 a second\n * `emitKeypressEvents` call on `process.stdin` is SILENTLY IGNORED, so the dial\n * degrades to a no-op with no error and no failing test. The raw listener costs ~24ms\n * and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n * (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is\n * involved. Node `data` listeners broadcast, so this one does not steal bytes from\n * readline: arrows and Enter keep working while it is attached.\n *\n * FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk.\n * Focus events (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports\n * (`\\x1b[M\u2026`) are all multi-byte, and inquirer enables none of them.\n *\n * FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE\n * chunk, i.e. Esc immediately followed by another key) is silently dropped and the\n * prompt stays open. The fix would be Ink's 20ms deferred abort \u2014 hold the lone Esc,\n * cancel it if a follow-up chunk lands. That is a logged NON-GOAL; do not pre-build it.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a\n * sufficient guard \u2014 see lib/mcp-mode for why `stdio: 'inherit'` defeats it.\n */\nexport const withEscape = async <T>(run: (context: PromptContext) => Promise<T>, base?: PromptContext): Promise<T> => {\n const controller = new AbortController()\n const context: PromptContext = { ...base, signal: controller.signal }\n\n if (isMcpMode() || !process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n const pending = run(context)\n\n input.on('data', onData)\n\n try {\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n }\n}\n", "/**\n * MCP-mode flag for the CLI. `process.stdin` is the JSON-RPC transport when the\n * binary runs as an MCP server, so anything that would read keystrokes from it\n * (raw `data` listeners, Ink screens, `@inquirer` prompts) must be gated off.\n *\n * This exists because `process.stdin.isTTY` CANNOT answer that question:\n * `commands/mcp/mcp.ts` spawns the server with `stdio: 'inherit'`, so a\n * terminal-launched `infra-kit mcp` hands the child a real TTY stdin and an\n * isTTY-keyed guard does not fire. Piped stdio (how Claude Code spawns it) only\n * makes isTTY look sufficient by coincidence.\n *\n * Set in `createMcpServer()` \u2014 the importable, transport-free entry that every\n * MCP launch goes through \u2014 not in `entry/mcp.ts`, which starts a server at\n * module scope and so can never assert the flag was actually set.\n */\n\n/** Mutable holder (object so `prefer-const` holds while the flag toggles per run). */\nexport const mcpMode = { enabled: false }\n\n/** True when this process is serving MCP, i.e. `process.stdin` carries JSON-RPC. */\nexport const isMcpMode = (): boolean => {\n return mcpMode.enabled\n}\n", "import confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { logger } from 'src/lib/logger'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\n/**\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (CLI `--yes` or an MCP call, which always\n * injects `confirmedCommand: true`) the prompt is skipped and execution\n * proceeds. Otherwise it prompts the user, marks the echo as interactive, and\n * exits cleanly if the user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path, which is\n * unreachable under MCP \u2014 so this stays safe for the long-lived MCP server.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nexport const confirmOrExit = async (confirmedCommand: boolean | undefined, message: string): Promise<void> => {\n const answer = confirmedCommand\n ? true\n : await withEscape((context) => {\n return confirm({ message }, context)\n })\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n"],
5
- "mappings": "uFAKA,OAAOA,MAAQ,mBACf,OAAOC,MAAU,YACjB,OAAS,KAAAC,MAAS,MCuBX,IAAMC,EAAN,cAA2B,KAAM,CAO7B,IAET,YAAYC,EAAiBC,EAAqB,KAAM,CACtD,MAAMD,CAAO,EACb,KAAK,KAAO,eACZ,KAAK,IAAMC,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B,MAAOC,EAAuCC,IAAmC,CAC5G,IAAMC,EAASF,EACX,GACA,MAAMG,EAAYC,GACTC,EAAQ,CAAE,QAAAJ,CAAQ,EAAGG,CAAO,CACpC,EAEAJ,GACHM,EAAY,eAAe,EAGxBJ,IACHK,EAAO,KAAK,iCAAiC,EAC7CC,EAAQ,KAAK,CAAC,EAElB",
6
- "names": ["fs", "path", "z", "EnvAuthError", "message", "env", "isEnvAuthFailure", "error", "fs", "os", "fileExists", "filePath", "tildify", "home", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "setToken", "env", "token", "existing", "removeToken", "envs", "createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "process", "mcpMode", "isMcpMode", "ESC_BYTE", "withEscape", "run", "base", "controller", "context", "isMcpMode", "process", "input", "onData", "chunk", "pending", "confirm", "process", "confirmOrExit", "confirmedCommand", "message", "answer", "withEscape", "context", "confirm", "commandEcho", "logger", "process"]
4
+ "sourcesContent": ["// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n *\n * HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were dropped\n * for it \u2014 do not re-add either without re-deciding that:\n *\n * - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version key,\n * and a store the CLI refuses to read is a store the human cannot write.\n * - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout. That\n * guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so `~/work/api`\n * and `~/oss/api` share ONE token directory and repo B could load (and then overwrite) repo A's\n * credentials. It was removed anyway, knowingly: it also made the CLI refuse every hand-written\n * store, which carries no such field. Hand-authorability wins; the basename-collision risk is\n * ACCEPTED. A weakened version of the guard (warn-and-continue, or \"only check when present\") is\n * NOT the compromise here \u2014 it would re-introduce the same refusal for anyone who did write the\n * field. If you want the guard back, key the store directory on something collision-free instead.\n */\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 it cannot heal on a 30s retry, only a human can fix it \u2014 and env\n // auto-load's sticky marker is keyed on that CLASS. Thrown as a plain Error these were classified\n // TRANSIENT, so a corrupt store went silent on the backgrounded shell-startup spawn and the user's\n // env simply stopped loading with nothing ever said. `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, [env]: token },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): env auto-load must tell a user\n * apart from a TRANSIENT failure (network, timeout, Doppler down \u2014 heals itself, 30s backoff, stay\n * quiet) and a DURABLE one (no token, a corrupt token store, a foreign token store \u2014 never heals, and\n * only a human can fix it). Only the durable class earns the STICKY marker that survives the\n * backgrounded shell-startup spawn and is replayed onto the next interactive command; a durable\n * failure misclassified as transient is TOTAL SILENCE, forever, on the one path the whole feature\n * exists to survive.\n *\n * That classification therefore has to travel WITH the error, not be re-derived by grepping a message\n * some other module owns \u2014 and it has to be throwable from EVERY module that can produce the class.\n * `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a Doppler-owned base type\n * could not be thrown there without a layering inversion and an import cycle. Hence a neutral base\n * here in `lib/errors`, with `DopplerAuthError extends EnvAuthError` for the subset of failures that\n * are specifically \"Doppler refused the token we sent\".\n *\n * The defect class this closes is \"a durable failure that is not type-detectable\". Adding a new\n * durable failure and forgetting to type it is exactly how this shipped silent twice \u2014 so throw this\n * (or a subclass), never a plain `Error`, for anything a user must fix before env-load can work.\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n *\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * This is the default `isAuthFailure` of `lib/env-autoload`'s `runEnvAutoLoad`. It is deliberately\n * WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only one of the\n * durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store never reaches\n * the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n", "import fs from 'node:fs/promises'\nimport os from 'node:os'\n\n/**\n * Shared path-display helpers for CLI output. Extracted from `commands/config`\n * and `commands/init/migrate-config` (which each had private copies) so config\n * surfaces print paths consistently. Keep this dependency-light (node builtins\n * only) \u2014 it is imported by several commands.\n */\n\n/**\n * Resolve whether a file is reachable, suppressing ENOENT (and any access error)\n * into a boolean. Used to render `[\u2713]`/`[ ]` existence markers.\n *\n * @example\n * await fileExists('/etc/hosts') // => true\n * await fileExists('/nope.txt') // => false\n */\nexport const fileExists = async (filePath: string): Promise<boolean> => {\n try {\n await fs.access(filePath)\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Replace the user's home prefix with `~` so logged paths stay short and portable\n * across machines. Leaves non-home paths untouched.\n *\n * @example\n * // os.homedir() === '/Users/arthur'\n * tildify('/Users/arthur/.infra-kit/infra-kit.json') // => '~/.infra-kit/infra-kit.json'\n * tildify('/etc/hosts') // => '/etc/hosts'\n */\nexport const tildify = (filePath: string): string => {\n const home = os.homedir()\n\n return filePath.startsWith(home) ? `~${filePath.slice(home.length)}` : filePath\n}\n", "import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the command ran off the CLI (an MCP tool), where a `pnpm exec` line would be\n * nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { isMcpMode } from 'src/lib/mcp-mode'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\nconst ESC_BYTE = 0x1b\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation.\n *\n * The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal\n * goes into the prompt context, `@inquirer/core` rejects with an `AbortPromptError`\n * when it fires, that name is already in `CANCELLATION_ERROR_NAMES`\n * (lib/errors/is-prompt-cancellation), and `entry/cli.ts` catches it at the top\n * level \u2192 \"Operation cancelled.\" \u2192 exit 0. All this adds is the thing that calls\n * `abort()`.\n *\n * DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b`\n * byte. Deliberately NOT readline `keypress`: that delivers a lone Esc only after its\n * escape-sequence timeout (~523ms measured), and the `escapeCodeTimeout` dial that\n * would shorten it is process-global and first-armer-wins \u2014 a second\n * `emitKeypressEvents` call on `process.stdin` is SILENTLY IGNORED, so the dial\n * degrades to a no-op with no error and no failing test. The raw listener costs ~24ms\n * and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n * (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is\n * involved. Node `data` listeners broadcast, so this one does not steal bytes from\n * readline: arrows and Enter keep working while it is attached.\n *\n * FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk.\n * Focus events (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports\n * (`\\x1b[M\u2026`) are all multi-byte, and inquirer enables none of them.\n *\n * FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE\n * chunk, i.e. Esc immediately followed by another key) is silently dropped and the\n * prompt stays open. The fix would be Ink's 20ms deferred abort \u2014 hold the lone Esc,\n * cancel it if a follow-up chunk lands. That is a logged NON-GOAL; do not pre-build it.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a\n * sufficient guard \u2014 see lib/mcp-mode for why `stdio: 'inherit'` defeats it.\n */\nexport const withEscape = async <T>(run: (context: PromptContext) => Promise<T>, base?: PromptContext): Promise<T> => {\n const controller = new AbortController()\n const context: PromptContext = { ...base, signal: controller.signal }\n\n if (isMcpMode() || !process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // STDIN OWNERSHIP \u2014 this is the seam that keeps stdin alive for inquirer, which refs\n // nothing itself. It must sit BELOW the early return above: a non-TTY run never reads\n // stdin, so acquiring there would ref a handle nobody reads and hang the process. See\n // lib/prompts/stdin-ref for why an unref'd stdin kills a prompt with exit 13.\n acquireStdin()\n\n try {\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n //\n // INSIDE the `try`, both of them: `run` is caller-supplied and `@inquirer/core` runs\n // synchronously up to readline construction, so a SYNCHRONOUS throw here would skip a\n // `finally` placed any lower \u2014 leaking the ref and hanging the CLI, which is the exact\n // failure this module exists to prevent.\n const pending = run(context)\n\n input.on('data', onData)\n\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n // Same `finally` as the listener teardown, and for the same reason: every exit path\n // (answer, Esc abort, throw) must give the ref back, or node never exits.\n releaseStdin()\n }\n}\n", "/**\n * MCP-mode flag for the CLI. `process.stdin` is the JSON-RPC transport when the\n * binary runs as an MCP server, so anything that would read keystrokes from it\n * (raw `data` listeners, Ink screens, `@inquirer` prompts) must be gated off.\n *\n * This exists because `process.stdin.isTTY` CANNOT answer that question:\n * `commands/mcp/mcp.ts` spawns the server with `stdio: 'inherit'`, so a\n * terminal-launched `infra-kit mcp` hands the child a real TTY stdin and an\n * isTTY-keyed guard does not fire. Piped stdio (how Claude Code spawns it) only\n * makes isTTY look sufficient by coincidence.\n *\n * Set in `createMcpServer()` \u2014 the importable, transport-free entry that every\n * MCP launch goes through \u2014 not in `entry/mcp.ts`, which starts a server at\n * module scope and so can never assert the flag was actually set.\n */\n\n/** Mutable holder (object so `prefer-const` holds while the flag toggles per run). */\nexport const mcpMode = { enabled: false }\n\n/** True when this process is serving MCP, i.e. `process.stdin` carries JSON-RPC. */\nexport const isMcpMode = (): boolean => {\n return mcpMode.enabled\n}\n", "import confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { logger } from 'src/lib/logger'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\n/**\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (CLI `--yes` or an MCP call, which always\n * injects `confirmedCommand: true`) the prompt is skipped and execution\n * proceeds. Otherwise it prompts the user, marks the echo as interactive, and\n * exits cleanly if the user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path, which is\n * unreachable under MCP \u2014 so this stays safe for the long-lived MCP server.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nexport const confirmOrExit = async (confirmedCommand: boolean | undefined, message: string): Promise<void> => {\n const answer = confirmedCommand\n ? true\n : await withEscape((context) => {\n return confirm({ message }, context)\n })\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n"],
5
+ "mappings": "sIAKA,OAAOA,MAAQ,mBACf,OAAOC,MAAU,YACjB,OAAS,KAAAC,MAAS,MCuBX,IAAMC,EAAN,cAA2B,KAAM,CAO7B,IAET,YAAYC,EAAiBC,EAAqB,KAAM,CACtD,MAAMD,CAAO,EACb,KAAK,KAAO,eACZ,KAAK,IAAMC,CACb,CACF,EAgBaC,EAAoBC,GACxBA,aAAiBJ,EC7D1B,OAAOK,MAAQ,mBACf,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C,EAASF,EACX,GACA,MAAMG,EAAYC,GACTC,EAAQ,CAAE,QAAAJ,CAAQ,EAAGG,CAAO,CACpC,EAEAJ,GACHM,EAAY,eAAe,EAGxBJ,IACHK,EAAO,KAAK,iCAAiC,EAC7CC,EAAQ,KAAK,CAAC,EAElB",
6
+ "names": ["fs", "path", "z", "EnvAuthError", "message", "env", "isEnvAuthFailure", "error", "fs", "os", "fileExists", "filePath", "tildify", "home", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "setToken", "env", "token", "existing", "removeToken", "envs", "createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "process", "mcpMode", "isMcpMode", "ESC_BYTE", "withEscape", "run", "base", "controller", "context", "isMcpMode", "process", "input", "onData", "chunk", "acquireStdin", "pending", "releaseStdin", "confirm", "process", "confirmOrExit", "confirmedCommand", "message", "answer", "withEscape", "context", "confirm", "commandEcho", "logger", "process"]
7
7
  }