infra-kit 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/{chunk-FRBNA6VH.js → chunk-4GXRGHU3.js} +12 -11
  2. package/dist/{chunk-FRBNA6VH.js.map → chunk-4GXRGHU3.js.map} +3 -3
  3. package/dist/{chunk-VDBJ73LS.js → chunk-DVXTZPQ5.js} +1 -1
  4. package/dist/chunk-DVXTZPQ5.js.map +7 -0
  5. package/dist/chunk-GIMZ4GTZ.js +12 -0
  6. package/dist/chunk-GIMZ4GTZ.js.map +7 -0
  7. package/dist/chunk-I23MDR4X.js +5 -0
  8. package/dist/chunk-I23MDR4X.js.map +7 -0
  9. package/dist/{chunk-CMF7HEVU.js → chunk-IT6XJWTW.js} +2 -2
  10. package/dist/chunk-IT6XJWTW.js.map +7 -0
  11. package/dist/{chunk-BQPSXIH2.js → chunk-MH37P7W4.js} +2 -2
  12. package/dist/{chunk-EAUGQ3ZU.js → chunk-NJEEEHUY.js} +2 -2
  13. package/dist/{chunk-MFHYIQ7B.js → chunk-OPYDLPHB.js} +2 -2
  14. package/dist/{chunk-MFHYIQ7B.js.map → chunk-OPYDLPHB.js.map} +1 -1
  15. package/dist/chunk-R6MPHCEI.js +7 -0
  16. package/dist/{chunk-DW2SQ2XU.js.map → chunk-R6MPHCEI.js.map} +3 -3
  17. package/dist/cli.js +129 -111
  18. package/dist/cli.js.map +4 -4
  19. package/dist/dev-server.js +21 -21
  20. package/dist/dev-server.js.map +3 -3
  21. package/dist/{dev-wizard-run-3DNKOVPD.js → dev-wizard-run-OXBPE3BF.js} +2 -2
  22. package/dist/env-load-74P4WMXV.js +2 -0
  23. package/dist/mcp-proxy.js +7 -7
  24. package/dist/mcp-proxy.js.map +3 -3
  25. package/dist/{persistent-ink-dev-ui-P65EJCC6.js → persistent-ink-dev-ui-ZSOS3CF4.js} +2 -2
  26. package/dist/update-check.js +1 -1
  27. package/package.json +3 -3
  28. package/readme.md +6 -3
  29. package/dist/chunk-CMF7HEVU.js.map +0 -7
  30. package/dist/chunk-DW2SQ2XU.js +0 -7
  31. package/dist/chunk-QSTGO43H.js +0 -4
  32. package/dist/chunk-QSTGO43H.js.map +0 -7
  33. package/dist/chunk-UD6VVXUY.js +0 -10
  34. package/dist/chunk-UD6VVXUY.js.map +0 -7
  35. package/dist/chunk-VDBJ73LS.js.map +0 -7
  36. package/dist/env-load-MF26WMDL.js +0 -2
  37. /package/dist/{chunk-BQPSXIH2.js.map → chunk-MH37P7W4.js.map} +0 -0
  38. /package/dist/{chunk-EAUGQ3ZU.js.map → chunk-NJEEEHUY.js.map} +0 -0
  39. /package/dist/{dev-wizard-run-3DNKOVPD.js.map → dev-wizard-run-OXBPE3BF.js.map} +0 -0
  40. /package/dist/{env-load-MF26WMDL.js.map → env-load-74P4WMXV.js.map} +0 -0
  41. /package/dist/{persistent-ink-dev-ui-P65EJCC6.js.map → persistent-ink-dev-ui-ZSOS3CF4.js.map} +0 -0
@@ -3,4 +3,4 @@ import h from"node:process";var p=["\u280B","\u2819","\u2839","\u2838","\u283C",
3
3
  `),this.paintSpinner();return}this.deps.write(`${t}
4
4
  `)}log(t,e="info",r={}){(e!=="debug"||this.deps.verbose)&&this.emit(t),r.tee!==!1&&this.tee(t,e)}narrate(t){this.deps.verbose&&this.emit(t),this.tee(t,"info")}logFn=(t,e="info")=>{this.log(t,e)};paintSpinner(){let t=p[this.spinnerFrame%p.length];this.deps.write(`${d}${this.color(s.teal,t)} ${this.color(s.dim,this.spinnerPhase)}`)}bootStep(t){if(this.tee(t,"info"),this.spinnerPhase=t,!this.deps.isTTY){this.deps.write(`${t}
5
5
  `);return}this.spinnerTimer==null&&(this.spinnerTimer=setInterval(()=>{this.spinnerFrame+=1,this.paintSpinner()},f),this.spinnerTimer.unref?.()),this.paintSpinner()}stopSpinner(){this.spinnerTimer!=null&&(clearInterval(this.spinnerTimer),this.spinnerTimer=null),this.deps.isTTY&&this.deps.write(d)}errorCount(t){let e=`\u26A0 ${t}`;return t>0?this.color(`${s.bold}${s.red}`,e):this.color(s.dim,e)}tagCell(t,e,r){return this.color((r??0)>0?s.red:s.teal,t.padEnd(e))}healthDot(t){switch(t){case"ok":return this.color(s.green,"\u25CF ok");case"down":return this.color(s.red,"\u25CF down");case"starting":return this.color(s.dim,"\u25CC starting");case"unverified":return this.color(s.dim,"\u25CD ?");default:return""}}ready(t){this.stopSpinner();let e=this.formatReadyLines(t);for(let r of e)this.emit(r),this.tee(r,"info")}tagWidth(t){return[...t.endpoints.map(r=>r.tag),...t.uiRefs.map(r=>r.tag),...(t.failed??[]).map(r=>r.tag),...(t.degraded??[]).map(r=>`${r.tag} ${r.route}`)].reduce((r,i)=>Math.max(r,i.length),0)}titleLine(t){let e=[t.target,t.watch?"watch":null,t.release].filter(a=>!!a).join(" \xB7 "),r=t.failed?.length??0,i=v(t.elapsedMs),n=r>0?this.color(s.red,`${r} failed \xB7 started in ${i}`):this.color(s.green,`ready in ${i}`);return` ${this.color(s.bold,"infra-kit dev")} ${this.color(s.dim,e)} ${n}`}legendLines(t){let e=t.watch&&t.watchSummary?`watching ${t.watchSummary}`:"watch off",r=this.hyperlink(t.logHref,t.logPath),i=`${e} logs \u2192 ${r}`,n="\u2500".repeat(60);return[` ${this.color(s.dim,i)}`,` ${this.color(s.dim,n)}`]}uiRefLine(t,e,r){let i=r==null?"":` ${this.errorCount(r)}`;return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.dim,"no managed port (vite prints its own URL)")}${i}`}statusFields(t){let e=[];return t.uptimeMs!=null&&e.push(this.color(s.dim,`up ${c(t.uptimeMs)}`)),t.rpm!=null&&t.rpm>0&&e.push(this.color(s.dim,`${t.rpm}/min`)),t.restarts!=null&&t.restarts>0&&e.push(this.color(s.dim,`\u21BA${t.restarts}`)),t.errors!=null&&e.push(this.errorCount(t.errors)),e.join(" ")}endpointLine(t,e,r){let i=r?this.healthDot(t.health):"",n=this.statusFields(t),a=[i,n].filter(Boolean).join(" ");return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.blue,t.url)}${a?` ${a}`:""}`}failedLine(t,e){return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.red,"\u25CF failed")} ${this.color(s.dim,t.reason)}`}degradedLine(t,e){let r=`${t.tag} ${t.route}`,i=t.fallback==="cloud"?"\u25CF cloud (local backend down)":"\u25CF dead alias (local backend down)",n=t.target?` ${this.color(s.dim,t.target)}`:"";return` ${this.color(s.red,"\u26A0")} ${this.color(s.teal,r.padEnd(e))} ${this.color(s.red,i)}${n}`}proxyLines(t){if(t.length===0)return[];let e=Math.max(...t.map(r=>r.route.length));return t.map((r,i)=>{let n=i===t.length-1?"\u2514":"\u251C",a=r.source==="local"?this.color(s.green,"\u25CF"):this.color(s.dim,"\u25CB"),l=r.target?` ${this.color(s.blue,r.target)}`:"";return` ${this.color(s.dim,n)} ${this.color(s.teal,r.route.padEnd(e))} ${a} ${this.color(s.dim,r.source)}${l}`})}formatLines(t,{withHealthDot:e}){let r=this.tagWidth(t),i=["",this.titleLine(t),""];for(let n of t.endpoints)i.push(this.endpointLine(n,r,e)),n.proxies&&i.push(...this.proxyLines(n.proxies));for(let n of t.failed??[])i.push(this.failedLine(n,r));for(let n of t.uiRefs)i.push(this.uiRefLine(n,r,n.errors)),n.proxies&&i.push(...this.proxyLines(n.proxies));for(let n of t.degraded??[])i.push(this.degradedLine(n,r));return i.push("",...this.legendLines(t)),i}formatHeaderLines(t){return this.formatLines(t,{withHealthDot:!1})}formatFooterLines(t){let e=this.tagWidth(t),r=t.endpoints.map(i=>{let n=this.healthDot(i.health),a=this.statusFields(i),l=[n,a].filter(Boolean).join(" ");return` ${this.tagCell(i.tag,e,i.errors)} ${l}`});for(let i of t.uiRefs)i.errors!=null&&r.push(` ${this.tagCell(i.tag,e,i.errors)} ${this.errorCount(i.errors)}`);for(let i of t.degraded??[])r.push(this.degradedLine(i,e));if(t.sessionUptimeMs!=null){let i=`up ${c(t.sessionUptimeMs)}`;r.push(` ${this.color(s.dim,i)}`)}return r}formatReadyLines(t){return this.formatLines(t,{withHealthDot:!0})}};export{R as a,g as b};
6
- //# sourceMappingURL=chunk-VDBJ73LS.js.map
6
+ //# sourceMappingURL=chunk-DVXTZPQ5.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/dev/render.ts"],
4
+ "sourcesContent": ["/**\n * Terminal renderer for `infra-kit dev` \u2014 a calm-print layer (never a full-screen TUI).\n *\n * The boot collapses into a single transient spinner; the final screen is a STATUS PANEL, one row per\n * server, carrying health, uptime, requests/min, restarts and an error count. There is no log tail:\n * every line \u2014 framework output, request logs, a handler's own `console.log` \u2014 is written to that\n * service's file under `<cacheRoot>/<session>/dev/<pid>/` and never printed. What still appears above\n * the panel is only what the RUNNER says: a restart, an unhealthy app, a dead engine.\n *\n * The panel's live fields are the reason it is a status surface and not a screenshot. With nothing\n * scrolling beside it, a panel whose numbers never move cannot be told apart from a hung process.\n *\n * All I/O is injected (`write` / `appendLog` / `isTTY` / `now`) so every frame is snapshot-testable and\n * the spinner is deterministically disabled in tests (`isTTY: false`).\n */\nimport process from 'node:process'\n\nimport type { DevUi } from './dev-ui.js'\n\nexport type LogLevel = 'info' | 'warn' | 'error' | 'debug'\n\n/**\n * Per-call options for {@link DevRenderer.log}.\n *\n * `tee: false` exists for exactly one caller: `DevServerRunner.reportFault`, which files the fault into the\n * sink ITSELF (at `error` level \u2014 that is what turns the panel row red) and then prints it. Without this\n * opt-out the print tees a SECOND copy into the same `runner.log`, so every fault is filed twice \u2014 a\n * literal 2\u00D7 amplifier sitting at the centre of the loop that wrote 455 GB.\n */\nexport interface LogOptions {\n /** Also append the line to the log file. Default `true`; `false` prints without filing. */\n tee?: boolean\n}\n\n/**\n * A row's liveness, as the runner's probe state machine resolved it.\n *\n * Five arms, not a boolean, because a probe has three outcomes and a row has a history. The two that\n * are neither `ok` nor `down` are the honest ones: a UI that has never answered yet is `starting`\n * (vite is spawned after the ready frame, so red would be a lie for the first seconds), and a port that\n * answers something OTHER than vite's ping is `unverified` \u2014 a squatter, a shadowing proxy, or a future\n * vite that dropped the endpoint are all consistent with that, and only one of them is broken. Red must\n * stay a PROOF of failure, so `unverified` renders a question mark and never a red dot.\n */\nexport type HealthState = 'ok' | 'down' | 'starting' | 'unverified' | 'unknown'\n\n/** Injected I/O seams. Defaults wire to the real stdout + a caller-provided file appender. */\nexport interface DevRendererDeps {\n /** Terminal sink (default: `process.stdout.write`). */\n write: (text: string) => void\n /** File tee \u2014 always receives full detail (default: no-op; the runner passes its log appender). */\n appendLog: (text: string) => void\n /** Whether the terminal is a TTY. Gates the spinner + ANSI color; false in CI / when piped. */\n isTTY: boolean\n /** Clock seam (default: `() => new Date()`), so timestamps + `ready in Xs` are testable. */\n now: () => Date\n /** When true, boot narration reaches the terminal; otherwise it is file-only. */\n verbose: boolean\n}\n\n/**\n * One resolved proxy route on a frontend, painted as an indented line under that app's row: which route,\n * where it lands, and whether it is the local backend or the shared cloud one. This is the \"all proxies \u2014\n * which one and where\" surface: unlike a {@link DegradedRow} it reports the happy path too, so a frontend\n * that proxies `/api` local and `/media` cloud shows both, and nobody has to guess where a route points.\n */\nexport interface ProxyRouteRow {\n /** Route path (e.g. `/api`). */\n route: string\n /** Where the route resolves this run \u2014 the local backend or the shared cloud origin. */\n source: 'local' | 'cloud'\n /**\n * The origin the route lands on. Omitted when it is not knowable (a `local` route whose backend is not\n * up \u2014 a dead alias the degraded row already owns \u2014 or a `cloud` route with no `<env>` sourced).\n */\n target?: string\n}\n\n/**\n * One server's row on the status panel.\n *\n * The live fields below are what make the panel a STATUS surface rather than a screenshot. The terminal\n * no longer carries a log tail, so a static row would leave \"quiet\" indistinguishable from \"hung\" \u2014 the\n * moving numbers are the liveness tell, and they are not decoration.\n */\nexport interface EndpointRow {\n /** Stream tag, e.g. `client/api`. */\n tag: string\n /** The app's `.localhost` alias URL \u2014 the only form, since an app that cannot be aliased never starts. */\n url: string\n /** Liveness, as {@link HealthState} defines it; `unknown` renders no dot at all (nothing to probe). */\n health: HealthState\n /** Milliseconds since this server last (re)started. Omitted on the boot frame. */\n uptimeMs?: number\n /** Watch-triggered restarts so far this session. */\n restarts?: number\n /** Requests served in the last 60s. */\n rpm?: number\n /**\n * Errors this service has declared since boot \u2014 a 5xx, a `console.error`, a framework failure line.\n * This is the ONLY error signal the user gets now that nothing prints, so a row that cannot count is\n * a row that lies. A COUNT, never a classification: it is incremented from the level the emitter\n * declared, never from anything read out of the line's text.\n */\n errors?: number\n /**\n * Resolved proxy routes for a frontend row (a `<app>/ui` endpoint), painted as an indented list under\n * it. Absent on backend rows \u2014 a `<app>/api` endpoint proxies nothing \u2014 and on a frontend with no\n * `dev.proxy` block.\n */\n proxies?: ProxyRouteRow[]\n}\n\n/**\n * A UI app whose URL the runner does not own, so it streams its own below \u2014 referenced, never given a\n * (fabricated) endpoint row. The fallback case only: a UI whose port the runner pre-assigned is an\n * {@link EndpointRow}, proxy or no proxy.\n */\nexport interface UiRef {\n /** Stream tag, e.g. `client/ui`. */\n tag: string\n /**\n * Errors this UI has declared since boot. Present for the same reason an {@link EndpointRow} has one:\n * with nothing printing, a row that cannot count is a row that lies \u2014 and this row belongs to the app\n * whose vite config never wired `infraKitDev()`, i.e. the one most likely to be misconfigured.\n */\n errors?: number\n /** Resolved proxy routes for this frontend, painted as an indented list under its reference line. */\n proxies?: ProxyRouteRow[]\n}\n\n/**\n * An app that was asked for but never came up. It has no URL and no health \u2014 but it MUST still get a\n * row: the header is a report of what the user asked for, and an app that silently vanishes from it\n * reads as \"not requested\" rather than \"broken\".\n */\nexport interface FailedRow {\n /** Stream tag, e.g. `client/api`. */\n tag: string\n /** One-line reason, e.g. `config is missing field: 'connectionURL'`. */\n reason: string\n}\n\n/**\n * A route that wanted a local backend and is falling back to cloud because that backend failed to start.\n *\n * It gets a row of its own \u2014 not a footnote on the failed backend's row \u2014 because the two facts land on\n * different people. `client/api \u25CF failed` says a server is down, which reads as \"that half is broken\".\n * It does NOT say the frontend beside it came up healthy and is now sending every `/api` request to the\n * shared cloud backend. That second fact is the one that gets you writing to the cloud dev database\n * while you believe you are on localhost, and it is invisible everywhere else on the screen: the vite\n * proxy resolved cleanly, so nothing else has anything to complain about.\n *\n * Only rendered under `--watch` \u2014 without it the run is refused outright (see `local-pairing.ts`).\n */\nexport interface DegradedRow {\n /** Route path (e.g. `/api`). */\n route: string\n /** Stream tag of the frontend serving it, e.g. `client/ui`. */\n tag: string\n /**\n * Where the route ACTUALLY resolves now. Not always `cloud`: the helper falls back to\n * `route.default ?? route.from[0]`, so a single-source `from: ['local']` route with no `default` falls\n * back to `local` \u2014 at an alias nothing registered, i.e. a 502 on every request. The row must name the\n * real destination, or it is doing the same lying-by-omission it exists to prevent.\n */\n fallback: 'local' | 'cloud'\n /** The cloud origin it now resolves to. Only ever set when `fallback` is `cloud` and it is knowable. */\n target?: string\n}\n\n/** Everything {@link DevRenderer.ready} needs to paint the final header in one shot. */\nexport interface ReadySummary {\n /** Resolved preset / target label (e.g. `client`, `*`). */\n target: string\n watch: boolean\n /** Slugified release for the header meta; omitted outside a git repo. */\n release?: string\n /** Backend readiness time in ms (UI is fire-and-forget, so this is BE-only \u2014 labeled honestly). */\n elapsedMs: number\n /** Real backend endpoint rows (owned ports + pre-probed health). */\n endpoints: EndpointRow[]\n /** UI apps that print their own URL below. */\n uiRefs: UiRef[]\n /**\n * Apps that failed to start. Optional only so the (many) existing summaries need not restate an\n * empty list; a non-empty one downgrades the title from a green `ready` to an honest `N failed`.\n */\n failed?: FailedRow[]\n /**\n * Routes silently demoted from local to cloud by a backend that failed to start. Recomputed on every\n * repaint, so a route CLEARS from the panel the moment `--watch` gets its backend up (see\n * {@link DegradedRow}).\n */\n degraded?: DegradedRow[]\n /** Human watch summary, e.g. `1 app \u00B7 5 packages`; omitted when not watching. */\n watchSummary?: string\n /**\n * Compact, human-readable log path shown as the `logs \u2192 \u2026` label. A DIRECTORY, not a file\n * (e.g. `~/.cache/infra-kit/<session>/dev/<pid>`): there is one log per service, so a single path\n * would have to pick a favourite.\n */\n logPath: string\n /** Absolute log path backing the clickable OSC-8 hyperlink (wrapped as `file://<logHref>`). */\n logHref: string\n /**\n * Milliseconds since the session became ready \u2014 the panel's HEARTBEAT.\n *\n * Every other live field belongs to a backend: uptime, req/min, restarts. A UI-only session has no\n * backend, so its rows have nothing that moves \u2014 and Ink does not repaint an identical frame, so the\n * screen would sit perfectly still while the session ran. With no log tail left to prove otherwise,\n * a motionless panel is indistinguishable from a hung process. This is the one field that ticks for\n * EVERY session shape. Omitted on the boot frame, where nothing has elapsed yet.\n */\n sessionUptimeMs?: number\n}\n\nconst SPINNER_FRAMES = ['\u280B', '\u2819', '\u2839', '\u2838', '\u283C', '\u2834', '\u2826', '\u2827', '\u2807', '\u280F']\nconst SPINNER_INTERVAL_MS = 80\n\nconst ANSI = {\n reset: '\\x1B[0m',\n dim: '\\x1B[2m',\n bold: '\\x1B[1m',\n teal: '\\x1B[36m',\n green: '\\x1B[32m',\n blue: '\\x1B[34m',\n red: '\\x1B[31m',\n} as const\n\n/** Erase the current line and return the cursor to column 0 (used to clear the spinner). */\nconst CLEAR_LINE = '\\r\\x1B[2K'\n\n/**\n * SGR color codes (`ESC [ \u2026 m`) and OSC-8 hyperlink wrappers (`ESC ] 8 ; ; \u2026 ESC \\`), non-greedy.\n * Matching the ESC control character is the whole point here \u2014 this pattern exists to remove it.\n */\n// eslint-disable-next-line sonarjs/no-control-regex, no-control-regex\nconst ANSI_PATTERN = /\\x1B\\[[0-9;]*m|\\x1B\\]8;;.*?\\x1B\\\\/g\n\n/**\n * Strip SGR colors + OSC-8 hyperlink escapes, keeping the hyperlink's visible label. Applied at the\n * file-tee seam so `logs.txt` stays greppable plain text even though the terminal frames it renders\n * from are colored + hyperlinked (both renderers format once, for a TTY, and tee the same string).\n */\nexport const stripAnsi = (s: string): string => {\n return s.replace(ANSI_PATTERN, '')\n}\n\n/** Zero-pad to 2 digits for `HH:MM:SS`. */\nconst pad2 = (n: number): string => {\n return String(n).padStart(2, '0')\n}\n\n/** `2.4s` for the `ready in \u2026` header. */\nexport const formatElapsed = (ms: number): string => {\n return `${(ms / 1000).toFixed(1)}s`\n}\n\n/**\n * `47s` / `4m12s` / `2h03m` \u2014 the panel's liveness tell.\n *\n * With no log tail on screen, a panel whose numbers never move is indistinguishable from a hung\n * process. This is the field that proves the session is alive even when nothing is happening, so it is\n * always rendered and always advancing.\n */\nexport const formatUptime = (ms: number): string => {\n const total = Math.max(0, Math.floor(ms / 1000))\n const hours = Math.floor(total / 3600)\n const minutes = Math.floor((total % 3600) / 60)\n const seconds = total % 60\n\n if (hours > 0) return `${hours}h${pad2(minutes)}m`\n if (minutes > 0) return `${minutes}m${pad2(seconds)}s`\n\n return `${seconds}s`\n}\n\n/**\n * Resolve the endpoint URL for an app: `https://<alias><prefix>`, where `alias` is the portless hostname\n * the runner registered (e.g. `feat-x.backend-api.hulyo-monorepo.localhost`). The runner refuses to start an app it could\n * not alias, so there is no port-form to fall back to.\n *\n * There is no port and no scheme choice, by construction. The proxy serves TLS on 443 \u2014 the implicit HTTPS\n * port \u2014 so the URL is byte-identical to the `dev.proxy` local template that `infra-kit/vite` proxies to,\n * and what the table prints cannot drift from what the frontend calls. Any port suffix here would mean the\n * proxy is not on 443, which `ensureProxy` has already refused to start.\n */\nexport const resolveEndpointUrl = (input: { prefixUrl: string; alias: string }): string => {\n return `https://${input.alias}${input.prefixUrl}`\n}\n\nexport class DevRenderer implements DevUi {\n private readonly deps: DevRendererDeps\n private spinnerTimer: ReturnType<typeof setInterval> | null = null\n private spinnerPhase = ''\n private spinnerFrame = 0\n\n constructor(deps: Partial<DevRendererDeps> = {}) {\n this.deps = {\n write:\n deps.write ??\n ((text: string): void => {\n process.stdout.write(text)\n }),\n appendLog: deps.appendLog ?? ((): void => {}),\n isTTY: deps.isTTY ?? Boolean(process.stdout.isTTY),\n now:\n deps.now ??\n ((): Date => {\n return new Date()\n }),\n verbose: deps.verbose ?? false,\n }\n }\n\n /** Wrap `s` in an ANSI color on a TTY; return it untouched when piped (deterministic snapshots). */\n private color(code: string, s: string): string {\n return this.deps.isTTY ? `${code}${s}${ANSI.reset}` : s\n }\n\n /**\n * Wrap `label` in an OSC-8 terminal hyperlink to `href` (a filesystem path \u2192 `file://` URI) so the\n * log path is cmd/ctrl-clickable. Returns the bare `label` when piped (deterministic snapshots) or\n * when `href` is empty \u2014 terminals without OSC-8 support silently ignore the escapes anyway.\n */\n private hyperlink(href: string, label: string): string {\n if (!this.deps.isTTY || href === '') return label\n\n // `encodeURI` escapes spaces / non-ASCII but leaves `#` and `?`, which a file URI reads as a\n // fragment / query \u2014 encode those too so a path containing them still resolves to the real file.\n const uri = encodeURI(href).replace(/[#?]/g, (c) => {\n return `%${c.charCodeAt(0).toString(16).toUpperCase()}`\n })\n\n return `\\x1B]8;;file://${uri}\\x1B\\\\${label}\\x1B]8;;\\x1B\\\\`\n }\n\n /**\n * Append one line to the log file ONLY \u2014 the canonical `[iso] [LEVEL] msg` shape, no terminal write.\n * The single source of the file-tee format: the private {@link tee} and the Ink boot UI both route\n * here, so the log file stays identical whichever renderer is live.\n */\n teeOnly(message: string, level: LogLevel): void {\n this.deps.appendLog(`[${this.deps.now().toISOString()}] [${level.toUpperCase()}] ${stripAnsi(message)}\\n`)\n }\n\n /** File tee for a line that is ALSO written to the terminal; delegates the format to {@link teeOnly}. */\n private tee(message: string, level: LogLevel): void {\n this.teeOnly(message, level)\n }\n\n /**\n * No-op for the plain renderer: it owns no Ink / raw-mode terminal state to release. Present to\n * satisfy {@link DevUi} so the runner can call `dispose()` uniformly. Idempotent by construction.\n */\n dispose(): void {\n // Nothing to release \u2014 the plain renderer never seizes the terminal.\n }\n\n /**\n * Write one terminal line spinner-safely: if the spinner is live on a TTY, erase it, print the\n * line, then repaint the spinner, so a mid-boot message never shreds the `\\r`-based spinner.\n */\n private emit(line: string): void {\n if (this.spinnerTimer != null && this.deps.isTTY) {\n this.deps.write(`${CLEAR_LINE}${line}\\n`)\n this.paintSpinner()\n\n return\n }\n\n this.deps.write(`${line}\\n`)\n }\n\n /** A general message routed by level (terminal + file tee). Debug is terminal-only in verbose. */\n log(message: string, level: LogLevel = 'info', options: LogOptions = {}): void {\n if (level !== 'debug' || this.deps.verbose) {\n this.emit(message)\n }\n if (options.tee !== false) {\n this.tee(message, level)\n }\n }\n\n /** A boot-narration step: terminal only when `--verbose`, but always tee'd to the log. */\n narrate(message: string): void {\n if (this.deps.verbose) {\n this.emit(message)\n }\n this.tee(message, 'info')\n }\n\n /** `LogFn`-shaped adapter for the build runner seam (which passes `(msg, level)`). */\n readonly logFn = (message: string, level: LogLevel = 'info'): void => {\n this.log(message, level)\n }\n\n // ---- boot spinner -------------------------------------------------------\n\n /** Paint the current spinner frame in place (TTY only). */\n private paintSpinner(): void {\n const frame = SPINNER_FRAMES[this.spinnerFrame % SPINNER_FRAMES.length]!\n\n this.deps.write(`${CLEAR_LINE}${this.color(ANSI.teal, frame)} ${this.color(ANSI.dim, this.spinnerPhase)}`)\n }\n\n /**\n * Update the boot phase. On a TTY this drives a single transient spinner line; when piped it\n * prints one plain phase line (no ANSI, deterministic). Always tee'd to the log.\n */\n bootStep(phase: string): void {\n this.tee(phase, 'info')\n this.spinnerPhase = phase\n\n if (!this.deps.isTTY) {\n this.deps.write(`${phase}\\n`)\n\n return\n }\n\n if (this.spinnerTimer == null) {\n this.spinnerTimer = setInterval(() => {\n this.spinnerFrame += 1\n this.paintSpinner()\n }, SPINNER_INTERVAL_MS)\n // Never keep the event loop alive for the spinner alone.\n this.spinnerTimer.unref?.()\n }\n this.paintSpinner()\n }\n\n /** Stop + erase the spinner line (idempotent). Called before the ready header prints. */\n stopSpinner(): void {\n if (this.spinnerTimer != null) {\n clearInterval(this.spinnerTimer)\n this.spinnerTimer = null\n }\n if (this.deps.isTTY) {\n this.deps.write(CLEAR_LINE)\n }\n }\n\n // ---- the ready header ---------------------------------------------------\n\n /**\n * The error counter, shared by endpoint rows and UI reference rows.\n *\n * Zero is rendered, not omitted: with nothing else printing, this is the only failure signal on the\n * screen, so a dim `\u26A0 0` is a claim worth making.\n *\n * Non-zero is BOLD red, and that is not decoration. A frontend that fails to compile still serves and\n * still answers vite's ping, so its dot stays green \u2014 the dot is liveness, and the app IS alive. This\n * counter is the only thing on the screen that says the app is nevertheless broken, so it has to win a\n * glance against a green dot sitting two columns away.\n */\n private errorCount(errors: number): string {\n const text = `\u26A0 ${errors}`\n\n return errors > 0 ? this.color(`${ANSI.bold}${ANSI.red}`, text) : this.color(ANSI.dim, text)\n }\n\n /**\n * The padded tag gutter for a PANEL row \u2014 red once the row has declared an error, teal otherwise.\n *\n * Footer only, never {@link formatHeaderLines}. The header is committed once through Ink's `<Static>`,\n * so a tag reddened there would be a photograph of the boot: it could never turn red later, and \u2014 far\n * worse \u2014 could never turn back. The panel repaints, so the color tracks the fact.\n */\n private tagCell(tag: string, tagWidth: number, errors: number | undefined): string {\n return this.color((errors ?? 0) > 0 ? ANSI.red : ANSI.teal, tag.padEnd(tagWidth))\n }\n\n /** Format the health dot for an endpoint row \u2014 one arm per {@link HealthState}; `unknown` prints nothing. */\n private healthDot(health: HealthState): string {\n switch (health) {\n case 'ok':\n return this.color(ANSI.green, '\u25CF ok')\n case 'down':\n return this.color(ANSI.red, '\u25CF down')\n case 'starting':\n return this.color(ANSI.dim, '\u25CC starting')\n // Answering, but not with vite's ping. Dim, never red: a non-204 is equally consistent with a\n // broken squatter and a perfectly healthy vite behind something that shadows the ping, and a red\n // dot on a coin-flip is how a dot stops being read at all.\n case 'unverified':\n return this.color(ANSI.dim, '\u25CD ?')\n default:\n return ''\n }\n }\n\n /**\n * Collapse the boot and print the final header in one shot: title line, one endpoint row per\n * backend server (with health dot), a reference line per UI app, the watch line, the clickable\n * log path, and a separator rule. Synchronous \u2014 health is pre-probed by the caller.\n */\n ready(summary: ReadySummary): void {\n this.stopSpinner()\n\n const lines = this.formatReadyLines(summary)\n\n for (const line of lines) {\n this.emit(line)\n this.tee(line, 'info')\n }\n }\n\n /** Column width for the aligned `tag` gutter \u2014 the widest endpoint/UI/failed tag. */\n private tagWidth(summary: ReadySummary): number {\n const tags = [\n ...summary.endpoints.map((e) => {\n return e.tag\n }),\n ...summary.uiRefs.map((u) => {\n return u.tag\n }),\n ...(summary.failed ?? []).map((f) => {\n return f.tag\n }),\n // A degraded row's gutter is `<tag> <route>`, which is wider than any bare tag \u2014 measure the label\n // it actually prints or its `\u25CF cloud \u2026` cell would sit out of column with every row above it.\n ...(summary.degraded ?? []).map((d) => {\n return `${d.tag} ${d.route}`\n }),\n ]\n\n return tags.reduce((w, t) => {\n return Math.max(w, t.length)\n }, 0)\n }\n\n /**\n * The `infra-kit dev \u00B7 <meta> ready in Xs` title line.\n *\n * A green `ready` is a claim about the whole session, so it is spent only when the whole session\n * is up. With anything in `failed` the status turns red and counts the casualties instead \u2014 the\n * boot time alone, next to a green word, is exactly how a half-dead session used to pass for a\n * healthy one.\n */\n private titleLine(summary: ReadySummary): string {\n const meta = [summary.target, summary.watch ? 'watch' : null, summary.release]\n .filter((s): s is string => {\n return Boolean(s)\n })\n .join(' \u00B7 ')\n\n const failedCount = summary.failed?.length ?? 0\n const elapsed = formatElapsed(summary.elapsedMs)\n const status =\n failedCount > 0\n ? this.color(ANSI.red, `${failedCount} failed \u00B7 started in ${elapsed}`)\n : this.color(ANSI.green, `ready in ${elapsed}`)\n\n return ` ${this.color(ANSI.bold, 'infra-kit dev')} ${this.color(ANSI.dim, meta)} ${status}`\n }\n\n /** The static legend tail: watch line + clickable log path, then a separator rule. */\n private legendLines(summary: ReadySummary): string[] {\n const watchText = summary.watch && summary.watchSummary ? `watching ${summary.watchSummary}` : 'watch off'\n const logLink = this.hyperlink(summary.logHref, summary.logPath)\n const watchLine = `${watchText} logs \u2192 ${logLink}`\n const rule = '\u2500'.repeat(60)\n\n return [` ${this.color(ANSI.dim, watchLine)}`, ` ${this.color(ANSI.dim, rule)}`]\n }\n\n /**\n * A UI reference row \u2014 used when infra-kit could not claim the UI's port, so it has no URL to print.\n *\n * It STILL carries an error count. That is the whole point: this row is exactly the misconfigured app\n * (its vite config never wired `infraKitDev()`), which is the app most likely to be broken \u2014 and with\n * no log tail on screen, a row with no error field is a row that cannot report the breakage. It used\n * to be a bare reference line, so its errors were counted into a file nobody had a reason to open.\n */\n private uiRefLine(ref: UiRef, tagWidth: number, errors: number | undefined): string {\n const errText = errors == null ? '' : ` ${this.errorCount(errors)}`\n\n return ` ${this.color(ANSI.teal, ref.tag.padEnd(tagWidth))} ${this.color(\n ANSI.dim,\n 'no managed port (vite prints its own URL)',\n )}${errText}`\n }\n\n /**\n * The live half of an endpoint row: `up 4m12s 18/min \u21BA2 \u26A0 3`.\n *\n * Empty on the boot frame (no field is set yet). Each field is omitted individually when absent \u2014 a\n * server with no restarts should not have to say so.\n */\n private statusFields(endpoint: ReadySummary['endpoints'][number]): string {\n const parts: string[] = []\n\n if (endpoint.uptimeMs != null) parts.push(this.color(ANSI.dim, `up ${formatUptime(endpoint.uptimeMs)}`))\n if (endpoint.rpm != null && endpoint.rpm > 0) parts.push(this.color(ANSI.dim, `${endpoint.rpm}/min`))\n if (endpoint.restarts != null && endpoint.restarts > 0) parts.push(this.color(ANSI.dim, `\u21BA${endpoint.restarts}`))\n // Errors are the exception to \"omit when zero\" \u2014 see {@link errorCount}.\n if (endpoint.errors != null) {\n parts.push(this.errorCount(endpoint.errors))\n }\n\n return parts.join(' ')\n }\n\n /** One endpoint row (`client/api https://\u2026 \u25CF ok up 4m12s 18/min \u26A0 0`). */\n private endpointLine(endpoint: ReadySummary['endpoints'][number], tagWidth: number, withHealthDot: boolean): string {\n const dot = withHealthDot ? this.healthDot(endpoint.health) : ''\n const status = this.statusFields(endpoint)\n const suffix = [dot, status].filter(Boolean).join(' ')\n\n return ` ${this.color(ANSI.teal, endpoint.tag.padEnd(tagWidth))} ${this.color(ANSI.blue, endpoint.url)}${\n suffix ? ` ${suffix}` : ''\n }`\n }\n\n /** One failed row (`client/api \u25CF failed <reason>`) \u2014 no URL, because there is nothing listening. */\n private failedLine(failed: FailedRow, tagWidth: number): string {\n return ` ${this.color(ANSI.teal, failed.tag.padEnd(tagWidth))} ${this.color(\n ANSI.red,\n '\u25CF failed',\n )} ${this.color(ANSI.dim, failed.reason)}`\n }\n\n /**\n * One degraded-route row (`\u26A0 /api \u25CF cloud (local backend failed) https://dev.hulyo.co.il`).\n *\n * Tagged by ROUTE, not by app, and deliberately so: the app rows above already say what is up and what\n * is down, and neither of them can say \"the frontend that came up healthy is talking to cloud\". The\n * route is the thing that got redirected, so the route is what the row is about.\n */\n private degradedLine(row: DegradedRow, tagWidth: number): string {\n const label = `${row.tag} ${row.route}`\n // A `local` fallback is not a cloud proxy \u2014 it is a dead alias that 502s. Saying \"cloud\" there would\n // name a destination the traffic never reaches.\n const state = row.fallback === 'cloud' ? '\u25CF cloud (local backend down)' : '\u25CF dead alias (local backend down)'\n const target = row.target ? ` ${this.color(ANSI.dim, row.target)}` : ''\n\n return ` ${this.color(ANSI.red, '\u26A0')} ${this.color(ANSI.teal, label.padEnd(tagWidth))} ${this.color(\n ANSI.red,\n state,\n )}${target}`\n }\n\n /**\n * The indented proxy lines painted under a frontend's row: ` \u251C /api \u25CF local https://\u2026`. One per\n * resolved route, so \"which one and where\" is answered inline instead of left to guess. A filled dot is\n * the local backend, a hollow one the shared cloud origin \u2014 the same local=\u25CF/cloud=\u25CB language the rest\n * of the panel uses. The last route gets a `\u2514` elbow so the group reads as one block belonging to the\n * app above it. Empty when the frontend declares no routes.\n */\n private proxyLines(proxies: ProxyRouteRow[]): string[] {\n if (proxies.length === 0) return []\n\n const routeWidth = Math.max(\n ...proxies.map((p) => {\n return p.route.length\n }),\n )\n\n return proxies.map((p, i) => {\n const elbow = i === proxies.length - 1 ? '\u2514' : '\u251C'\n const dot = p.source === 'local' ? this.color(ANSI.green, '\u25CF') : this.color(ANSI.dim, '\u25CB')\n const where = p.target ? ` ${this.color(ANSI.blue, p.target)}` : ''\n\n return ` ${this.color(ANSI.dim, elbow)} ${this.color(ANSI.teal, p.route.padEnd(routeWidth))} ${dot} ${this.color(\n ANSI.dim,\n p.source,\n )}${where}`\n })\n }\n\n /**\n * Shared header layout: blank, title line, blank, one endpoint row per backend, a reference row per\n * UI app, then the watch/log legend. `withHealthDot` is the ONLY difference between the static Ink\n * header (false \u2014 health is live, the footer owns it) and the ready/boot frame (true).\n */\n private formatLines(summary: ReadySummary, { withHealthDot }: { withHealthDot: boolean }): string[] {\n const tagWidth = this.tagWidth(summary)\n const lines: string[] = ['', this.titleLine(summary), '']\n\n for (const e of summary.endpoints) {\n lines.push(this.endpointLine(e, tagWidth, withHealthDot))\n // A frontend's proxy routes hang directly off its own row, so \"where does /api go\" reads as a\n // property of the app rather than a footnote somewhere below it.\n if (e.proxies) lines.push(...this.proxyLines(e.proxies))\n }\n // Failures sit with the live rows, not in the scrollback above: the log line announcing the crash\n // is metres up the terminal by now, and the header is the only thing the user actually reads.\n for (const f of summary.failed ?? []) {\n lines.push(this.failedLine(f, tagWidth))\n }\n for (const u of summary.uiRefs) {\n lines.push(this.uiRefLine(u, tagWidth, u.errors))\n if (u.proxies) lines.push(...this.proxyLines(u.proxies))\n }\n // Below the app rows, because it is a consequence of one of them \u2014 a `\u25CF failed` backend is WHY a\n // route went to cloud, and the two read as cause and effect only in that order.\n for (const d of summary.degraded ?? []) {\n lines.push(this.degradedLine(d, tagWidth))\n }\n\n lines.push('', ...this.legendLines(summary))\n\n return lines\n }\n\n /**\n * Static reference lines for the persistent Ink header, committed ONCE via `<Static>`: title,\n * endpoint URLs WITHOUT the health dot (health is live \u2192 the footer owns it), UI reference rows,\n * watch line, clickable log path, separator. Pure; colors follow `isTTY`.\n */\n formatHeaderLines(summary: ReadySummary): string[] {\n return this.formatLines(summary, { withHealthDot: false })\n }\n\n /**\n * The live status rows \u2014 THE PANEL. Re-rendered in place on every tick; never committed to `<Static>`.\n *\n * This is the only part of the screen that can change after `ready`, and that makes it the only place\n * live fields can live. The header is committed once through `<Static>`, so anything painted there is\n * a photograph: an uptime or an error count rendered into the header would be frozen at its boot value\n * for the whole session, looking live and being a lie. (It was: the live fields went into the shared\n * endpoint line first, the header picked them up, the footer kept printing a bare health dot, and a\n * real run showed a panel with no uptime, no req/min and no error count at all. No unit test saw it \u2014\n * only the rendered terminal did.)\n *\n * Every row is rendered, including an endpoint that was never probed and a UI with no backend at all:\n * with no log tail on screen this panel is the entire signal, and a row that is absent cannot report\n * that its service is broken.\n */\n formatFooterLines(summary: ReadySummary): string[] {\n const tagWidth = this.tagWidth(summary)\n const rows = summary.endpoints.map((e) => {\n const dot = this.healthDot(e.health)\n const status = this.statusFields(e)\n const cells = [dot, status].filter(Boolean).join(' ')\n\n return ` ${this.tagCell(e.tag, tagWidth, e.errors)} ${cells}`\n })\n\n // A UI whose port infra-kit could not claim has no endpoint row \u2014 but its errors still have to land\n // somewhere the user can see, and it is precisely the app most likely to be misconfigured.\n for (const ref of summary.uiRefs) {\n if (ref.errors == null) continue\n rows.push(` ${this.tagCell(ref.tag, tagWidth, ref.errors)} ${this.errorCount(ref.errors)}`)\n }\n\n // Degraded routes live in the PANEL, not only in the header. The header is committed once through\n // `<Static>` \u2014 a photograph \u2014 so a degraded row painted only there would still be on screen after\n // `--watch` brought the backend back and the route went local again: a permanent warning about a\n // condition that has been fixed, which trains the user to ignore it. The caller re-derives this list\n // from the running set on every tick, so the row survives exactly as long as the problem does.\n for (const d of summary.degraded ?? []) {\n rows.push(this.degradedLine(d, tagWidth))\n }\n\n // The heartbeat. Without it a UI-only session \u2014 whose rows carry no backend uptime and no req/min \u2014\n // would render an identical frame every tick, and Ink does not repaint an identical frame. The panel\n // would be genuinely, verifiably alive and look exactly like a hung process.\n if (summary.sessionUptimeMs != null) {\n const beat = `up ${formatUptime(summary.sessionUptimeMs)}`\n\n rows.push(` ${this.color(ANSI.dim, beat)}`)\n }\n\n return rows\n }\n\n /**\n * Build the ready-header lines with NO side effects (no terminal write, no tee), so both\n * {@link ready} (which writes + tees them) and the Ink boot UI (which commits them via `<Static>`\n * and tee-only's them) share one layout. Colors follow `isTTY` exactly like every other line.\n */\n formatReadyLines(summary: ReadySummary): string[] {\n return this.formatLines(summary, { withHealthDot: true })\n }\n}\n"],
5
+ "mappings": "AAeA,OAAOA,MAAa,eA0MpB,IAAMC,EAAiB,CAAC,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,QAAG,EAClEC,EAAsB,GAEtBC,EAAO,CACX,MAAO,UACP,IAAK,UACL,KAAM,UACN,KAAM,WACN,MAAO,WACP,KAAM,WACN,IAAK,UACP,EAGMC,EAAa,YAObC,EAAe,qCAORC,EAAaC,GACjBA,EAAE,QAAQF,EAAc,EAAE,EAI7BG,EAAQC,GACL,OAAOA,CAAC,EAAE,SAAS,EAAG,GAAG,EAIrBC,EAAiBC,GACrB,IAAIA,EAAK,KAAM,QAAQ,CAAC,CAAC,IAUrBC,EAAgBD,GAAuB,CAClD,IAAME,EAAQ,KAAK,IAAI,EAAG,KAAK,MAAMF,EAAK,GAAI,CAAC,EACzCG,EAAQ,KAAK,MAAMD,EAAQ,IAAI,EAC/BE,EAAU,KAAK,MAAOF,EAAQ,KAAQ,EAAE,EACxCG,EAAUH,EAAQ,GAExB,OAAIC,EAAQ,EAAU,GAAGA,CAAK,IAAIN,EAAKO,CAAO,CAAC,IAC3CA,EAAU,EAAU,GAAGA,CAAO,IAAIP,EAAKQ,CAAO,CAAC,IAE5C,GAAGA,CAAO,GACnB,EAYaC,EAAsBC,GAC1B,WAAWA,EAAM,KAAK,GAAGA,EAAM,SAAS,GAGpCC,EAAN,KAAmC,CACvB,KACT,aAAsD,KACtD,aAAe,GACf,aAAe,EAEvB,YAAYC,EAAiC,CAAC,EAAG,CAC/C,KAAK,KAAO,CACV,MACEA,EAAK,QACHC,GAAuB,CACvBrB,EAAQ,OAAO,MAAMqB,CAAI,CAC3B,GACF,UAAWD,EAAK,YAAc,IAAY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AMmB,EAAM,KAAK,UAAUnB,EAAE,MAAM,EAC7BS,EAAS,KAAK,aAAaT,CAAC,EAC5B+B,EAAQ,CAACZ,EAAKV,CAAM,EAAE,OAAO,OAAO,EAAE,KAAK,IAAI,EAErD,MAAO,KAAK,KAAK,QAAQT,EAAE,IAAKJ,EAAUI,EAAE,MAAM,CAAC,KAAK+B,CAAK,EAC/D,CAAC,EAID,QAAWjB,KAAOhB,EAAQ,OACpBgB,EAAI,QAAU,MAClBgB,EAAK,KAAK,KAAK,KAAK,QAAQhB,EAAI,IAAKlB,EAAUkB,EAAI,MAAM,CAAC,KAAK,KAAK,WAAWA,EAAI,MAAM,CAAC,EAAE,EAQ9F,QAAWX,KAAKL,EAAQ,UAAY,CAAC,EACnCgC,EAAK,KAAK,KAAK,aAAa3B,EAAGP,CAAQ,CAAC,EAM1C,GAAIE,EAAQ,iBAAmB,KAAM,CACnC,IAAMkC,EAAO,MAAM1D,EAAawB,EAAQ,eAAe,CAAC,GAExDgC,EAAK,KAAK,KAAK,KAAK,MAAMjE,EAAK,IAAKmE,CAAI,CAAC,EAAE,CAC7C,CAEA,OAAOF,CACT,CAOA,iBAAiBhC,EAAiC,CAChD,OAAO,KAAK,YAAYA,EAAS,CAAE,cAAe,EAAK,CAAC,CAC1D,CACF",
6
+ "names": ["process", "SPINNER_FRAMES", "SPINNER_INTERVAL_MS", "ANSI", "CLEAR_LINE", "ANSI_PATTERN", "stripAnsi", "s", "pad2", "n", "formatElapsed", "ms", "formatUptime", "total", "hours", "minutes", "seconds", "resolveEndpointUrl", "input", "DevRenderer", "deps", "text", "code", "href", "label", "c", "message", "level", "line", "options", "frame", "phase", "errors", "tag", "tagWidth", "health", "summary", "lines", "e", "u", "f", "d", "w", "t", "meta", "failedCount", "elapsed", "status", "watchText", "logLink", "watchLine", "rule", "ref", "errText", "endpoint", "parts", "withHealthDot", "dot", "suffix", "failed", "row", "state", "target", "proxies", "routeWidth", "p", "elbow", "where", "rows", "cells", "beat"]
7
+ }
@@ -0,0 +1,12 @@
1
+ import{a as x,e as ne,h as S,i as se,j as p}from"./chunk-R6MPHCEI.js";import{P as c,S as oe,d,da as b,e as _,f as re,ga as m,h as D,i as te,w as P}from"./chunk-4GXRGHU3.js";import{a as Z,c as U,d as T,f as G,g as H,h as B,i as Y,j as Q,o as X,p as K,q as ee}from"./chunk-I23MDR4X.js";import He from"@inquirer/select";import{readRepoIdentity as Be}from"@slip-stream-kit/config/internal";import{Buffer as Ye}from"node:buffer";import Qe from"node:fs";import J from"node:path";import $ from"node:process";import{z as k}from"zod";import{$ as I}from"zx";var _e="Could not find requested project",De="Could not find requested config",ie="Invalid Auth token",ae="does not have access to requested config",A=e=>e.includes(ie)||e.includes(ae)?"auth":e.includes(_e)?"project":e.includes(De)?"config":"unknown",R=e=>e.includes(ae)?"mis-scoped":e.includes(ie)?"revoked":null;var ce=e=>[`Doppler rejected the service token for env "${e}" \u2014 it is invalid, revoked, or scoped to a different config.`,`Fix: run \`infra-kit env-token-set ${e}\` with a token scoped to that config.`,"CI / agents: set INFRA_KIT_ENV_TOKEN to a token scoped to that config."].join(`
2
+ `),f=class extends S{authKind;constructor(r,t=null,o){super(o??ce(r),r),this.name="DopplerAuthError",this.authKind=t}};var L=({kind:e,project:r,config:t,available:o})=>{let n=e==="project"?[`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${t}" not found in project "${r}".`];if(o&&o.length>0){let s=e==="project"?"Available projects":`Available configs in "${r}"`;n.push(`${s}: ${o.join(", ")}.`)}return n.push(e==="project"?"Fix: update envManagement.config.name to an existing project, or create it in Doppler.":"Fix: pass an existing config, or create it in Doppler."),n.join(`
3
+ `)};import{$ as N}from"zx";var be=5e3,xe="DOPPLER_CONFIG",g=async()=>{let{envManagement:e}=await b();return e.config.name},Se=async({childEnv:e,project:r,config:t})=>{let o=N.quiet;N.quiet=!0;try{let s=(await N({env:e})`doppler secrets get ${xe} --plain --project ${r} --config ${t}`.timeout(be)).stdout.trim();return s!==t?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(n){return{outcome:Ne(n)}}finally{N.quiet=o}},Ne=e=>{let r=D(e)??(e instanceof Error?e.message:String(e));return A(r)!=="auth"?"unreachable":R(r)??"unreachable"};import Oe from"node:process";var l="INFRA_KIT_ENV_TOKEN",C=async e=>{let r=Oe.env[l];if(r)return{token:r,source:"env"};let o=(await p())?.envs[e];if(o)return{token:o,source:"store"};throw new S(je(e,await se()),e)},je=(e,r)=>[`No Doppler service token for env "${e}".`,`Mint one at https://dashboard.doppler.com \u2014 this project \u2192 config "${e}" \u2192 Access tab \u2192 "Generate Service Token".`,`Fix: run \`infra-kit env-token-set ${e}\` and paste it.`,`It is stored in ${oe(r)} (mode 0600, never in the repo).`,`CI / agents: set ${l} instead \u2014 it takes precedence and needs no home config.`].join(`
4
+ `);import Ee from"node:process";import{z as ve}from"zod";import ze from"node:process";import{z as u}from"zod";var le=["prod"],v={allowed:!1,reason:"disallow"},h=e=>le.includes(e),Fe=["dev","stage"],Ie=e=>Fe.includes(e)||h(e),$e=(e,r=v)=>r.allowed?e:e.filter(t=>!h(t)),Ke=(e,r,t=v)=>{if(!t.allowed&&h(e))throw t.reason==="agent-blocked"?new m({status:"refused",env:e,agentMode:d.source},2,{operation:r,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e}" is withheld from agents in this project (protectedEnvs: "cli-only")`}):new te(void 0,{operation:r,remediation:`use \`infra-kit release deliver\` \u2014 it merges the release to main, opens the RC PR, deploys from main, and releases the Jira version. To allow ad-hoc deploys to "${e}" in this project, set \`protectedEnvs\` to "allow" or "cli-only" in infra-kit.json`,stderrExcerpt:`"${e}" is delivered, not deployed ad-hoc`})};var Le=async()=>{let e;try{e=(await b()).protectedEnvs??"disallow"}catch{return v}return e==="disallow"?v:e==="cli-only"&&_()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var Ce=e=>{let{env:r,branch:t}=e;h(r)&&c.warn([`\u26A0\uFE0F "${r}" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,`Dispatching from "${t}" ships ${r} from a ref that is not merged to main, and skips:`," \u2022 the squash-merge of the release branch into main"," \u2022 the RC pull request"," \u2022 the Jira fix-version release","Run `infra-kit release deliver` instead if you want those."].join(`
5
+ `))};import pe from"node:fs/promises";import M from"node:path";import Me from"yaml";var ue=".github/workflows",Ve=async e=>{let r=await P();return de(M.resolve(r,ue,e))},V=async()=>{let e=await P(),r=M.resolve(e,ue),t;try{t=await pe.readdir(r)}catch{return[]}let o=t.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),n=await Promise.all(o.map(s=>de(M.resolve(r,s))));return[...new Set(n.flat())]},de=async e=>{let r;try{r=Me.parse(await pe.readFile(e,"utf-8"))}catch{return[]}let t=E(r,"on")??E(r,"true"),o=E(E(E(E(t,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(o)?o.filter(n=>typeof n=="string"&&n.length>0):[]},E=(e,r)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[r]};var w=async()=>{let e=await V(),r=await p(),t=e.map(s=>({env:s,source:"gh-workflow"})),o=new Set(e),n=Object.keys(r?.envs??{}).filter(s=>!o.has(s)).sort().map(s=>({env:s,source:"token-only"}));return[...t,...n]},z=async()=>(await w()).map(r=>r.env);var O=e=>[{type:"text",text:e}],j=e=>e;var F=(e,r,t)=>e.map(({env:o,source:n})=>({env:o,source:n,hasToken:!!(t||r[o])})),me=["Environment","Source","Token"],qe=e=>{let r=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),t=me.map((s,i)=>Math.max(s.length,...r.map(a=>(a[i]??"").length))),o=s=>s.map((i,a)=>i.padEnd(t[a]??0)).join(" | ").trimEnd(),n=t.map(s=>"\u2500".repeat(s)).join("\u2500\u253C\u2500");return["Environments:","",o(me),n,...r.map(o)]},ge=async()=>{let e=await g(),r=await w(),t=await p(),o=ze.env[l],n=F(r,t?.envs??{},o);if(c.info(`Doppler project: ${e}
6
+ `),n.length===0)return c.info("No environments found."),c.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),c.info(" or add a token for one manually."),fe({project:e,envs:n});for(let s of qe(n))c.info(s);return fe({project:e,envs:n})},fe=({project:e,envs:r})=>{let t={project:e,configs:r.map(o=>o.env),tokens:r};return{content:O(JSON.stringify(t,null,2)),structuredContent:t}},Je=j({name:"env-list",description:"List the environments this project has. The list is the union of two local sources: every environment declared in a GitHub workflow's `workflow_dispatch` `environment.options` (source `gh-workflow`), and every environment the local token store holds a token for (source `token-only`). Not a live fetch from Doppler \u2014 a Doppler service token is config-scoped and cannot enumerate sibling configs. Also returns the Doppler project name, and reports per environment whether a service token resolves locally (from the token store or INFRA_KIT_ENV_TOKEN) \u2014 presence only, never the token value, and never a live Doppler probe. Read-only.",inputSchema:{},outputSchema:{project:u.string().describe("Detected Doppler project name"),configs:u.array(u.string()).describe("Every environment name known to this project"),tokens:u.array(u.object({env:u.string().describe("Environment / Doppler config name"),source:u.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:u.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:ge});var he=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),We=async e=>{try{return await e}catch{return[]}},Ze=async e=>{let r=await p().catch(()=>null);return F(e,r?.envs??{},Ee.env[l]).filter(t=>!t.hasToken).map(t=>t.env)},q=()=>({get message(){return`Choose the environment to load into terminal session ${Ee.env[T]??`UNKNOWN \u2014 ${T} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>he(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await We(w());if(e.length===0)return c.info({msg:"Tool execution form options empty: env-load"}),null;let r=e.map(o=>o.env),t=await Ze(e);return ve.object({config:ve.enum(r).describe(`The environment to load. ${t.length===0?"A service token is stored for every one of them.":`NO stored token for: ${t.join(", ")} \u2014 choosing one of those fails until you run \`infra-kit env-token-set <env>\`.`} The list is what env-list knows: workflow-declared environments first, then token-only ones.`)})},toArgs:(e,r)=>{let{config:t}=e;return typeof t!="string"||t.length===0?null:{...he(r)?r:{},config:t}}});import{z as Ue}from"zod";var Ge=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(r){return c.debug({err:r,operation:e.operation},"argument form builder threw; refusing without choices"),null}},we=async e=>{if(!re()||!e.provider.isFormable(e.params))return;let r=await Ge(e),t=typeof e.params=="object"&&e.params!==null?e.params:{},o=(r===null?[]:Object.keys(r.shape)).filter(i=>t[i]===void 0||t[i]===""),n=typeof e.argument=="string"?e.argument:e.argument(o),s=r===null?void 0:Ue.toJSONSchema(r);throw new m({status:"argument_required",argument:n,...s===void 0?{}:{choices:s},agentMode:d.source},2,{operation:e.operation,remediation:s===void 0?`pass --${n} on the re-run \u2014 nothing could be listed to choose from`:`ask the human to pick from "choices", then pass --${n} on the re-run`,stderrExcerpt:`--${n} was not given and there is no human to ask`})};var Xe="DOPPLER_CONFIG",ke=new Set(["DOPPLER_TOKEN",l]),ye=!1,er=e=>{e.length===0||ye||(ye=!0,c.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},rr=({pairs:e,config:r,project:t,projectRoot:o,loadedAt:n})=>{let s=e.filter(([i])=>!ke.has(i));return er(e.filter(([i])=>ke.has(i)).map(([i])=>i)),["set -a",...s.map(([i,a])=>`${i}=${y(a)}`),`${G}=${y(r)}`,`${H}=${y(r)}`,`${B}=${y(t)}`,`${Y}=${y(o)}`,`${Q}=${y(n)}`,"set +a"]},tr=async()=>{try{return await P()}catch{return""}},or=(e,r=$.cwd())=>{if(e==="")return[J.resolve(r)];let t=Be(e).root??e;return[...new Set([t,`${t}${ee}`,e])]},nr=async({config:e})=>{let r=await g(),t=await tr(),o=await Ae(r,e),n=new Date().toISOString(),i=`${rr({pairs:o,config:e,project:r,projectRoot:t,loadedAt:n}).join(`
7
+ `)}
8
+ `,a=X(),W=J.resolve(a,Z);Qe.mkdirSync(a,{recursive:!0,mode:448});let Re=or(t);return K(J.resolve(a,U),`${Re.join(`
9
+ `)}
10
+ `,384),K(W,i,384),{filePath:W,variableCount:o.length,project:r,config:e}},Pe=q(),sr=async e=>{let{config:r}=e;await we({provider:Pe,params:e,operation:"env-load",argument:"config"});let t="";if(r)t=r;else{if(_())throw new m({status:"argument_required",argument:"config",agentMode:d.source},2,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let s=await z();x.setInteractive(),t=await ne(i=>He({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:$.stderr,whenHeadless:"refuse"})}x.addOption("--config",t);let o=await nr({config:t});x.print();let n={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config,sessionId:$.env[T]??null};return{content:O(JSON.stringify(n,null,2)),structuredContent:n}},Te=1024*1024,ir=3e4,ar=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],cr=(e,r=$.env)=>{let t={...r};for(let o of ar)delete t[o];return t.DOPPLER_TOKEN=e,t},eo=async e=>new Map(await Ae(await g(),e)),Ae=async(e,r)=>{let{token:t}=await C(r),o=cr(t),n=I.quiet;I.quiet=!0;try{let s;try{s=await I({env:o})`doppler secrets download --no-file --format json --project ${e} --config ${r}`.timeout(ir)}catch(a){throw pr(a,e,r)}ur(s.stdout);let i=mr(s.stdout);return lr(i,r),i}finally{I.quiet=n}},lr=(e,r)=>{let t=e.find(([o])=>o===Xe)?.[1];if(!(t===void 0||t===r))throw new f(r,null,`Doppler returned secrets for config "${t}" but "${r}" was requested \u2014 the service token for env "${r}" is scoped to the wrong config. Refusing to load another environment's secrets.
11
+ Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},pr=(e,r,t)=>{let o=D(e)??(e instanceof Error?e.message:String(e)),n=A(o);return n==="auth"?new f(t,R(o)):n==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(L({kind:n,project:r,config:t,available:null}))},ur=e=>{let r=Ye.byteLength(e,"utf-8");if(r>Te)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Te}) \u2014 refusing to write to disk`)},y=e=>`'${e.replaceAll("'","'\\''")}'`,dr=/^[A-Z_]\w*$/i,mr=e=>{let r;try{r=JSON.parse(e)}catch{throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(e.slice(0,80))})`)}if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)");let t=[];for(let[o,n]of Object.entries(r)){if(!dr.test(o))throw new Error(`doppler returned an invalid env var name for env-load (got: ${JSON.stringify(o.slice(0,80))})`);if(typeof n!="string")throw new TypeError(`doppler returned a non-string value for "${o}" (got ${typeof n})`);t.push([o,n])}if(t.length===0)throw new Error("doppler returned empty output for env-load");return t},ro=j({name:"env-load",description:'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. This server picks the file up on its next tool call, so a tool that needs the variables can be called right after. Omit "config" and this server offers the human a form listing every environment env-list knows, token-less ones marked; a client that cannot render one gets a refusal naming the missing field \u2014 call env-list and ask the human, never guess.',inputSchema:{config:k.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to have the human choose from a form.')},formProvider:Pe,outputSchema:{filePath:k.string().describe("Path to the file that must be sourced to apply variables"),variableCount:k.number().describe("Number of variables loaded"),project:k.string().describe("Doppler project name"),config:k.string().describe("Doppler config name"),sessionId:k.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:sr});export{O as a,j as b,A as c,R as d,g as e,Se as f,l as g,C as h,h as i,Ie as j,$e as k,Ke as l,Le as m,Ce as n,Ve as o,w as p,z as q,ge as r,Je as s,we as t,rr as u,or as v,nr as w,sr as x,Te as y,cr as z,eo as A,lr as B,pr as C,ur as D,y as E,mr as F,ro as G};
12
+ //# sourceMappingURL=chunk-GIMZ4GTZ.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/commands/env-load/env-load.ts", "../src/integrations/doppler/doppler-errors.ts", "../src/integrations/doppler/doppler-project.ts", "../src/integrations/doppler/token-resolver.ts", "../src/lib/env-load-form/env-load-form.ts", "../src/commands/env-list/env-list.ts", "../src/lib/workflow-envs/protected-envs.ts", "../src/lib/workflow-envs/protected-env-access.ts", "../src/lib/workflow-envs/protected-env-warning.ts", "../src/lib/workflow-envs/workflow-envs.ts", "../src/lib/project-envs/project-envs.ts", "../src/types.ts", "../src/lib/prompts/refuse-missing-arguments.ts"],
4
+ "sourcesContent": ["import select from '@inquirer/select'\nimport { readRepoIdentity } from '@slip-stream-kit/config/internal'\nimport { Buffer } from 'node:buffer'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { z } from 'zod'\nimport { $ } from 'zx'\n\nimport {\n DopplerAuthError,\n INFRA_KIT_ENV_TOKEN_VAR,\n buildDopplerNotFoundMessage,\n classifyDopplerAuthFailure,\n classifyDopplerFailure,\n getDopplerProject,\n resolveEnvToken,\n} from 'src/integrations/doppler'\nimport { agentMode, isAgentMode } from 'src/lib/agent-mode'\nimport { commandEcho } from 'src/lib/command-echo'\nimport {\n ENV_LOAD_FILE,\n ENV_LOAD_ROOT_FILE,\n INFRA_KIT_ENV_CONFIG_VAR,\n INFRA_KIT_ENV_LOADED_AT_VAR,\n INFRA_KIT_ENV_PROJECT_ROOT_VAR,\n INFRA_KIT_ENV_PROJECT_VAR,\n INFRA_KIT_ENV_VAR,\n INFRA_KIT_SESSION_VAR,\n WORKTREES_DIR_SUFFIX,\n atomicWriteFileSync,\n getSessionCacheDir,\n} from 'src/lib/constants'\nimport { createEnvLoadFormProvider } from 'src/lib/env-load-form'\nimport { extractStderr } from 'src/lib/errors/operation-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { getProjectRoot } from 'src/lib/git-utils'\nimport { logger } from 'src/lib/logger'\nimport { listProjectEnvNames } from 'src/lib/project-envs'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\nimport { refuseMissingArguments } from 'src/lib/prompts/refuse-missing-arguments'\nimport { defineMcpTool, textContent } from 'src/types'\n\ninterface EnvLoadArgs {\n config?: string\n}\n\ninterface WriteEnvLoadFileArgs {\n /** Resolved Doppler config / environment name (no interactive picker here). */\n config: string\n}\n\nexport interface EnvLoadFileResult {\n filePath: string\n variableCount: number\n project: string\n config: string\n}\n\ninterface EnvLoadFileLinesArgs {\n pairs: Array<[string, string]>\n config: string\n project: string\n projectRoot: string\n loadedAt: string\n}\n\n/** The payload key that carries the token's scope \u2014 the one {@link assertTokenScope} compares. */\nconst DOPPLER_CONFIG_KEY = 'DOPPLER_CONFIG'\n\n/**\n * Secret names that must NEVER be written into the sourced file. A Doppler project can hold a secret\n * called `DOPPLER_TOKEN` (or `INFRA_KIT_ENV_TOKEN`), and `env-load.sh` is sourced into EVERY shell \u2014\n * exporting one would hand a live credential to every child process forever, and (per SPIKE-0 Q5) an\n * exported `DOPPLER_TOKEN` would then hijack the next download's auth.\n *\n * `DOPPLER_CONFIG` / `DOPPLER_PROJECT` are deliberately NOT filtered: they are not credentials, they\n * are the scope evidence {@link assertTokenScope} and `doctor` read back.\n */\nconst CREDENTIAL_SECRET_KEYS = new Set<string>(['DOPPLER_TOKEN', INFRA_KIT_ENV_TOKEN_VAR])\n\n/** Warn at most once per process: a project carrying a token secret would otherwise warn on every load. */\nlet credentialFilterWarned = false\n\n/**\n * Tell the user we dropped a credential-bearing secret from their shell env \u2014 silently swallowing a\n * key they can see in the Doppler dashboard would read as a bug. Names the KEY only, never the value.\n */\nconst warnFilteredCredentialKeys = (keys: string[]): void => {\n if (keys.length === 0 || credentialFilterWarned) return\n\n credentialFilterWarned = true\n\n logger.warn(\n `infra-kit: not exporting ${keys.join(', ')} from Doppler into your shell \u2014 ` +\n 'a service token must not be sourced into every process.',\n )\n}\n\n/**\n * Build the dotenv-format shell lines for env-load.sh. Pure apart from the one-shot credential\n * warning, so callers can assert the exact file contents. `set -a`/`set +a` auto-export every\n * assignment when the file is sourced.\n */\nexport const buildEnvLoadFileLines = ({\n pairs,\n config,\n project,\n projectRoot,\n loadedAt,\n}: EnvLoadFileLinesArgs): string[] => {\n const emitted = pairs.filter(([key]) => {\n return !CREDENTIAL_SECRET_KEYS.has(key)\n })\n\n warnFilteredCredentialKeys(\n pairs\n .filter(([key]) => {\n return CREDENTIAL_SECRET_KEYS.has(key)\n })\n .map(([key]) => {\n return key\n }),\n )\n\n return [\n 'set -a',\n ...emitted.map(([key, value]) => {\n return `${key}=${shellSingleQuote(value)}`\n }),\n // Purpose-named env-name handle for non-shell tooling (e.g. infra-kit/vite's\n // `<env>` proxy interpolation). Single-quoted like every sourced value.\n `${INFRA_KIT_ENV_VAR}=${shellSingleQuote(config)}`,\n `${INFRA_KIT_ENV_CONFIG_VAR}=${shellSingleQuote(config)}`,\n `${INFRA_KIT_ENV_PROJECT_VAR}=${shellSingleQuote(project)}`,\n `${INFRA_KIT_ENV_PROJECT_ROOT_VAR}=${shellSingleQuote(projectRoot)}`,\n `${INFRA_KIT_ENV_LOADED_AT_VAR}=${shellSingleQuote(loadedAt)}`,\n 'set +a',\n ]\n}\n\n/**\n * Project root (git top-level) the loaded env belongs to. Returns '' when this isn't\n * a git checkout so a non-git infra-kit project still loads instead of the whole\n * load breaking on `git rev-parse` throwing.\n */\nconst resolveProjectRootSafe = async (): Promise<string> => {\n try {\n return await getProjectRoot()\n } catch {\n return ''\n }\n}\n\n/**\n * The directories the loaded env applies in ({@link ENV_LOAD_ROOT_FILE}): the repo's own directory (the\n * same `readRepoIdentity` that names the dev alias's `<repo>`) and its `-worktrees` container, so every\n * worktree of the repo shares one load, plus the loading worktree itself in case it lives elsewhere.\n * Outside git, just `cwd`.\n */\nexport const resolveEnvLoadRoots = (projectRoot: string, cwd = process.cwd()): string[] => {\n if (projectRoot === '') return [path.resolve(cwd)]\n\n const repoRoot = readRepoIdentity(projectRoot).root ?? projectRoot\n\n return [...new Set([repoRoot, `${repoRoot}${WORKTREES_DIR_SUFFIX}`, projectRoot])]\n}\n\n/**\n * Download Doppler secrets for a resolved config and atomically write env-load.sh\n * to the session cache dir. Does NOT print to stdout \u2014 the path line belongs to the\n * CLI action in `lib/program`.\n */\nexport const writeEnvLoadFile = async ({ config }: WriteEnvLoadFileArgs): Promise<EnvLoadFileResult> => {\n const project = await getDopplerProject()\n const projectRoot = await resolveProjectRootSafe()\n\n const pairs = await downloadDopplerSecrets(project, config)\n\n const loadedAt = new Date().toISOString()\n const envFileLines = buildEnvLoadFileLines({ pairs, config, project, projectRoot, loadedAt })\n const fileContents = `${envFileLines.join('\\n')}\\n`\n\n const cacheDir = getSessionCacheDir()\n const envFilePath = path.resolve(cacheDir, ENV_LOAD_FILE)\n\n fs.mkdirSync(cacheDir, { recursive: true, mode: 0o700 })\n // The scope lands first: a shell reading between the two writes then never sees the new env unscoped.\n const roots = resolveEnvLoadRoots(projectRoot)\n\n atomicWriteFileSync(path.resolve(cacheDir, ENV_LOAD_ROOT_FILE), `${roots.join('\\n')}\\n`, 0o600)\n atomicWriteFileSync(envFilePath, fileContents, 0o600)\n\n return {\n filePath: envFilePath,\n variableCount: pairs.length,\n project,\n config,\n }\n}\n\n/**\n * Load environment variables from Doppler for the given config\n */\n// ONE provider instance for the tool definition (`envLoadMcpTool.formProvider`) and the agent-mode\n// refusal below, so the rows an agent is handed as `choices` are the form the schema describes.\nconst envLoadForm = createEnvLoadFormProvider()\n\nexport const envLoad = async (args: EnvLoadArgs) => {\n const { config } = args\n\n // Before the picker: an agent / `--json` run without `config` gets the form's env list as `choices`.\n await refuseMissingArguments({ provider: envLoadForm, params: args, operation: 'env-load', argument: 'config' })\n\n let selectedConfig = ''\n\n if (config) {\n selectedConfig = config\n } else {\n // No auth pre-probe before the picker: under token-only auth there is no account\n // to validate, and the per-env token is only knowable AFTER a config is chosen.\n // A missing/rejected token surfaces from the download with an actionable message.\n //\n // The choices are every env this project has \u2014 workflow-declared and token-only alike (see\n // `lib/project-envs`). Deliberately NOT filtered to the envs we hold a token for: an env you cannot\n // yet load is exactly the one you need to SEE, so that picking it tells you to run\n // `infra-kit env-token-set <env>` rather than leaving you to wonder where it went.\n //\n // An agent that omits `config` is refused with `choices` by `refuseMissingArguments` above; landing\n // here headless means the provider judged the arguments unformable, and the refusal has to name the\n // source.\n if (isAgentMode()) {\n throw new StructuredRefusalError(\n { status: 'argument_required', argument: 'config', agentMode: agentMode.source },\n 2,\n {\n operation: 'env-load',\n remediation: 'call env-list, ask the human which environment, and re-call env-load with \"config\"',\n },\n )\n }\n\n const envs = await listProjectEnvNames()\n\n commandEcho.setInteractive()\n selectedConfig = await withEscape(\n (context) => {\n return select(\n {\n message: 'Select environment config',\n choices: envs.map((env) => {\n return { name: env, value: env }\n }),\n },\n context,\n )\n },\n // Render to stderr so the prompt is visible when stdout is captured via $() in the shell function.\n // Only env-load and env-clear use the $() stdout-capture shell pattern.\n { output: process.stderr, whenHeadless: 'refuse' },\n )\n }\n\n commandEcho.addOption('--config', selectedConfig)\n\n const result = await writeEnvLoadFile({ config: selectedConfig })\n\n // The path the zsh wrapper captures is printed by the CLI action in `lib/program`, not here: the\n // handler's stdout stays empty so a `--json` caller gets exactly one document; `emitSourcePath` in\n // `lib/program` owns the path line and its ordering. Logs go to stderr for the same reason.\n commandEcho.print()\n\n const structuredContent = {\n filePath: result.filePath,\n variableCount: result.variableCount,\n project: result.project,\n config: result.config,\n // The terminal session the file was written FOR. A Bash-driven agent inherits the session id but\n // never sees the shell that sources the file; naming it here is how it can tell which terminal\n // just got the variables (and notice when there was none).\n sessionId: process.env[INFRA_KIT_SESSION_VAR] ?? null,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n/**\n * Cap the Doppler stdout we're willing to accept. A well-formed env bundle is\n * O(10 KB); megabytes would indicate a service regression or the wrong stream\n * being captured, and we don't want to write that to disk or source it.\n */\nexport const DOPPLER_MAX_OUTPUT_BYTES = 1024 * 1024\n\n/**\n * Hard upper bound for the Doppler subprocess. Well under zx's default so a\n * hung call surfaces quickly instead of blocking an interactive shell.\n */\nconst DOPPLER_DOWNLOAD_TIMEOUT_MS = 30_000\n\n/**\n * Doppler env vars we refuse to inherit into the download child. SPIKE-0 Q5: an inherited\n * `DOPPLER_TOKEN` OVERRIDES everything else the CLI would use \u2014 and `env-load` itself exports a whole\n * Doppler project into the shell, so a project that happens to hold a secret named `DOPPLER_TOKEN`\n * would silently hijack the NEXT download. `DOPPLER_PROJECT` / `DOPPLER_CONFIG` are scrubbed for the\n * same reason: they are the payload's own scope evidence, and an inherited copy could shadow the\n * `--project` / `--config` we pass in argv.\n */\nconst INHERITED_DOPPLER_VARS = ['DOPPLER_TOKEN', 'DOPPLER_PROJECT', 'DOPPLER_CONFIG'] as const\n\n/**\n * The child environment for `doppler secrets download`: the caller's env with the inherited Doppler\n * vars scrubbed and OUR resolved token set explicitly.\n *\n * The token travels by ENV, never by argv: `ps` shows argv to every user on the box, and\n * `commandEcho` prints option values back to the terminal. Pure (takes the base env) so the scrub is\n * unit-testable without touching `process.env`.\n *\n * @example\n * buildDopplerChildEnv('dp.st.x', { PATH: '/bin', DOPPLER_CONFIG: 'prod' })\n * // => { PATH: '/bin', DOPPLER_TOKEN: 'dp.st.x' } (DOPPLER_CONFIG dropped)\n */\nexport const buildDopplerChildEnv = (token: string, baseEnv: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv => {\n const childEnv: NodeJS.ProcessEnv = { ...baseEnv }\n\n for (const name of INHERITED_DOPPLER_VARS) {\n delete childEnv[name]\n }\n\n childEnv.DOPPLER_TOKEN = token\n\n return childEnv\n}\n\n/**\n * One Doppler config's secrets, downloaded with the token stored for it \u2014 `env-load`'s own fetch, for a\n * caller that needs a few values of an env without loading the whole env into a shell.\n */\nexport const downloadEnvSecrets = async (config: string): Promise<Map<string, string>> => {\n return new Map(await downloadDopplerSecrets(await getDopplerProject(), config))\n}\n\nconst downloadDopplerSecrets = async (project: string, config: string): Promise<Array<[string, string]>> => {\n const { token } = await resolveEnvToken(config)\n\n const childEnv = buildDopplerChildEnv(token)\n\n const prevQuiet = $.quiet\n\n $.quiet = true\n try {\n let result\n\n try {\n result = await $({\n env: childEnv,\n })`doppler secrets download --no-file --format json --project ${project} --config ${config}`.timeout(\n DOPPLER_DOWNLOAD_TIMEOUT_MS,\n )\n } catch (error: unknown) {\n throw translateDopplerDownloadError(error, project, config)\n }\n\n assertDopplerOutputSize(result.stdout)\n\n const pairs = parseDopplerSecretsJson(result.stdout)\n\n assertTokenScope(pairs, config)\n\n return pairs\n } finally {\n $.quiet = prevQuiet\n }\n}\n\n/**\n * Defense in depth against a MIS-SCOPED token: the payload always carries `DOPPLER_CONFIG` as an\n * ordinary secret, and it echoes the `--config` we asked for (SPIKE-0 Q2 \u2014 it is the CONFIG, not\n * `DOPPLER_ENVIRONMENT`, which can differ: config `dev_personal` lives in environment `dev`).\n *\n * ABSENT \u21D2 PROCEED, deliberately. The Doppler CLI already refuses a real mismatch on the wire\n * (SPIKE-0 Q1: exit 1, \"does not have access to requested config\"), so it \u2014 not this \u2014 is the\n * load-bearing guard. An absent `DOPPLER_CONFIG` therefore means Doppler changed what it injects,\n * and failing closed here would blank every developer's shell at once.\n *\n * @example\n * assertTokenScope([['DOPPLER_CONFIG', 'dev']], 'dev') // ok\n * assertTokenScope([['FOO', 'bar']], 'dev') // ok (absent \u21D2 proceed)\n * assertTokenScope([['DOPPLER_CONFIG', 'prod']], 'dev') // throws: token is scoped to \"prod\"\n */\nexport const assertTokenScope = (pairs: Array<[string, string]>, config: string): void => {\n const actual = pairs.find(([key]) => {\n return key === DOPPLER_CONFIG_KEY\n })?.[1]\n\n if (actual === undefined || actual === config) return\n\n // A DopplerAuthError, not a plain Error: this IS an auth failure, and callers classify by TYPE\n // (`isEnvAuthFailure`), so a plain Error would read as transient. The message stays richer than the\n // generic one: we know the token's real config.\n throw new DopplerAuthError(\n config,\n null,\n `Doppler returned secrets for config \"${actual}\" but \"${config}\" was requested \u2014 the service token for ` +\n `env \"${config}\" is scoped to the wrong config. Refusing to load another environment's secrets.\\n` +\n `Fix: run \\`infra-kit env-token-set ${config}\\` with a token scoped to \"${config}\".`,\n )\n}\n\n/**\n * Turn a raw `doppler secrets download` failure into an actionable error. An AUTH-class failure (the\n * token is invalid, revoked, or mis-scoped) becomes a {@link DopplerAuthError} carrying the\n * env-token-set message; a recognized project/config not-found points at the exact infra-kit.json\n * field. Anything else \u2014 network, timeout \u2014 is rethrown untouched so it degrades to the existing\n * behavior, never worse.\n *\n * This is THE boundary where Doppler's raw stderr is read: the markers exist only here, and the\n * classification leaves as a TYPE (`DopplerAuthError`), never as prose for a downstream module to\n * re-parse. Exported so a seam test can drive the REAL error a caller sees.\n *\n * @example\n * translateDopplerDownloadError({ stderr: 'Doppler Error: Invalid Auth token' }, 'p', 'dev')\n * // => DopplerAuthError { authKind: 'revoked', message: '\u2026 `infra-kit env-token-set <env>` \u2026' }\n * translateDopplerDownloadError(new Error('connect ETIMEDOUT'), 'p', 'dev')\n * // => the same Error, untouched\n */\n// Why a type and not prose: a caller that text-matched the raw Doppler markers on the error this\n// function had already rewritten found them long gone, and a revoked token went silent.\n//\n// The not-found message no longer lists the AVAILABLE names: `listDopplerProjects` /\n// `listDopplerConfigs` require an ACCOUNT login, which token-only auth deleted, so that probe\n// could only ever return `null` now. `buildDopplerNotFoundMessage` already treats `null` as\n// \"couldn't tell\" and omits the suggestion line rather than misreporting \"none exist\".\nexport const translateDopplerDownloadError = (error: unknown, project: string, config: string): Error => {\n const stderr = extractStderr(error) ?? (error instanceof Error ? error.message : String(error))\n const kind = classifyDopplerFailure(stderr)\n\n if (kind === 'auth') return new DopplerAuthError(config, classifyDopplerAuthFailure(stderr))\n\n if (kind === 'unknown') return error instanceof Error ? error : new Error(String(error))\n\n return new Error(buildDopplerNotFoundMessage({ kind, project, config, available: null }))\n}\n\nexport const assertDopplerOutputSize = (stdout: string): void => {\n const bytes = Buffer.byteLength(stdout, 'utf-8')\n\n if (bytes > DOPPLER_MAX_OUTPUT_BYTES) {\n throw new Error(\n `doppler returned unexpectedly large output (${bytes} bytes > ${DOPPLER_MAX_OUTPUT_BYTES}) \u2014 refusing to write to disk`,\n )\n }\n}\n\nexport const shellSingleQuote = (value: string): string => {\n const escaped = value.replaceAll(\"'\", \"'\\\\''\")\n\n return `'${escaped}'`\n}\n\n/** A valid POSIX env-var name: a letter or underscore, then word characters. */\nconst ENV_VAR_NAME_PATTERN = /^[A-Z_]\\w*$/i\n\n/**\n * Parse the `doppler secrets download --format json` output (a flat\n * `{\"KEY\":\"value\"}` map) into ordered `[key, value]` pairs, validating the shape\n * and every name/value. Values are returned RAW \u2014 callers must single-quote them\n * before emitting shell (an unquoted `a$(cmd)b` would execute on `source`).\n *\n * @example\n * parseDopplerSecretsJson('{\"FOO\":\"bar\",\"BAZ\":\"a$(x)\"}')\n * // => [['FOO', 'bar'], ['BAZ', 'a$(x)']]\n */\nexport const parseDopplerSecretsJson = (stdout: string): Array<[string, string]> => {\n let parsed: unknown\n\n try {\n parsed = JSON.parse(stdout)\n } catch {\n throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(stdout.slice(0, 80))})`)\n }\n\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)')\n }\n\n const pairs: Array<[string, string]> = []\n\n for (const [key, value] of Object.entries(parsed)) {\n if (!ENV_VAR_NAME_PATTERN.test(key)) {\n throw new Error(\n `doppler returned an invalid env var name for env-load (got: ${JSON.stringify(key.slice(0, 80))})`,\n )\n }\n\n if (typeof value !== 'string') {\n throw new TypeError(`doppler returned a non-string value for \"${key}\" (got ${typeof value})`)\n }\n\n pairs.push([key, value])\n }\n\n if (pairs.length === 0) {\n throw new Error('doppler returned empty output for env-load')\n }\n\n return pairs\n}\n\n// MCP Tool Registration\nexport const envLoadMcpTool = defineMcpTool({\n name: 'env-load',\n description:\n 'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced (\"source <filePath>\") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. This server picks the file up on its next tool call, so a tool that needs the variables can be called right after. Omit \"config\" and this server offers the human a form listing every environment env-list knows, token-less ones marked; a client that cannot render one gets a refusal naming the missing field \u2014 call env-list and ask the human, never guess.',\n inputSchema: {\n config: z\n .string()\n .optional()\n .describe(\n 'Doppler config / environment name to load (e.g. \"dev\", \"arthur\"). Omit it to have the human choose from a form.',\n ),\n },\n formProvider: envLoadForm,\n outputSchema: {\n filePath: z.string().describe('Path to the file that must be sourced to apply variables'),\n variableCount: z.number().describe('Number of variables loaded'),\n project: z.string().describe('Doppler project name'),\n config: z.string().describe('Doppler config name'),\n sessionId: z\n .string()\n .nullable()\n .describe('The INFRA_KIT_SESSION the file was written for; null when the process had no session'),\n },\n handler: envLoad,\n})\n", "/**\n * @fileoverview\n *\n * Translate Doppler `secrets download` not-found failures into actionable,\n * point-at-the-fix guidance. Pure (no I/O) so the classification + message policy\n * is unit-testable without spawning the Doppler CLI \u2014 mirroring the pure-helper\n * pattern in `commands/env-load/env-load.ts`.\n *\n * Observed Doppler output on a not-found download (verified 2026-06-27, doppler\n * v3.76.0), exit 1, written to STDERR (stdout empty):\n * Unable to download secrets\n * Doppler Error: Could not find requested project 'name'\n * Doppler Error: Could not find requested config 'name'\n * Only the \"Doppler Error:\" prefix is ANSI-colored; the \"Could not find requested\n * ...\" text is plain, so substring matching is color-safe. zx's\n * `ProcessOutput.message` also concatenates stdout+stderr, so the same markers are\n * matchable off `.message` when `.stderr` is unavailable.\n */\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\n\n/** Which kind of Doppler not-found a download failure represents (`unknown` = not a not-found error). */\nexport type DopplerNotFoundKind = 'project' | 'config' | 'unknown'\n\n/**\n * Every class of `secrets download` failure we act on. `'auth'` is the token-only addition: the\n * service token is absent, revoked, garbage, or scoped to a DIFFERENT config. It is deliberately\n * distinct from the not-found kinds (the name is wrong) and from `'unknown'` (network, timeout,\n * Doppler down) \u2014 only `'auth'` is a durable, user-fixable state.\n */\nexport type DopplerFailureKind = 'auth' | DopplerNotFoundKind\n\nconst PROJECT_NOT_FOUND_MARKER = 'Could not find requested project'\nconst CONFIG_NOT_FOUND_MARKER = 'Could not find requested config'\n\n/**\n * The REAL auth-class stderr markers, captured from a live Doppler CLI v3.76.0 (SPIKE-0 Q1/Q4):\n * - `Invalid Auth token` \u2014 revoked / garbage token\n * - `This token does not have access to requested config 'x'` \u2014 mis-scoped token\n * Both are plain (uncolored) text, so substring matching is ANSI-safe. The second one is the CLI\n * ENFORCING the token's scope for us \u2014 it is the primary mis-scope guard, not our payload assert.\n */\nconst INVALID_TOKEN_MARKER = 'Invalid Auth token'\nconst TOKEN_SCOPE_MARKER = 'does not have access to requested config'\n\n/**\n * Classify a Doppler `secrets download` failure from its stderr/message text. The full lattice:\n * auth-class first (a mis-scoped token's message names a config but is NOT a not-found), then the\n * two not-found kinds, then `'unknown'` for everything else so the caller can rethrow the original\n * untouched (degrades to status quo, never worse).\n *\n * @example\n * classifyDopplerFailure('Doppler Error: Invalid Auth token') // => 'auth'\n * classifyDopplerFailure(\"This token does not have access to requested config 'dev'\") // => 'auth'\n * classifyDopplerFailure(\"Doppler Error: Could not find requested project 'x'\") // => 'project'\n * classifyDopplerFailure('connect ETIMEDOUT') // => 'unknown'\n */\nexport const classifyDopplerFailure = (stderr: string): DopplerFailureKind => {\n if (stderr.includes(INVALID_TOKEN_MARKER) || stderr.includes(TOKEN_SCOPE_MARKER)) return 'auth'\n\n if (stderr.includes(PROJECT_NOT_FOUND_MARKER)) return 'project'\n\n if (stderr.includes(CONFIG_NOT_FOUND_MARKER)) return 'config'\n\n return 'unknown'\n}\n\n/**\n * The two auth-class failures, told apart. Both are `'auth'` to\n * {@link classifyDopplerFailure} \u2014 they share one fix (a new token) \u2014 but they are DIFFERENT\n * diagnoses, and `doctor` must not conflate them: \"your token was revoked\" sends a user to the\n * Doppler dashboard, \"your token is scoped to the wrong config\" sends them to re-issue it against\n * the right one.\n */\nexport type DopplerAuthKind = 'revoked' | 'mis-scoped'\n\n/**\n * Split an auth-class failure into its two diagnoses, or `null` when the text is not auth-class at\n * all (network, timeout, not-found) \u2014 the caller must not read `null` as \"the token is fine\", only\n * as \"this failure says nothing about the token\".\n *\n * @example\n * classifyDopplerAuthFailure(\"This token does not have access to requested config 'dev'\") // => 'mis-scoped'\n * classifyDopplerAuthFailure('Doppler Error: Invalid Auth token') // => 'revoked'\n * classifyDopplerAuthFailure('connect ETIMEDOUT') // => null\n */\nexport const classifyDopplerAuthFailure = (stderr: string): DopplerAuthKind | null => {\n if (stderr.includes(TOKEN_SCOPE_MARKER)) return 'mis-scoped'\n\n if (stderr.includes(INVALID_TOKEN_MARKER)) return 'revoked'\n\n return null\n}\n\n/**\n * Is this failure text an auth-class Doppler failure (bad / absent / mis-scoped service token)\n * rather than a transient one (network, timeout, Doppler down)? The single source of truth\n * callers classify on.\n *\n * @example\n * isDopplerAuthFailure('Doppler Error: Invalid Auth token') // => true\n * isDopplerAuthFailure('network unreachable') // => false\n */\nexport const isDopplerAuthFailure = (stderr: string): boolean => {\n return classifyDopplerFailure(stderr) === 'auth'\n}\n\n/**\n * Classify a Doppler download failure into the NOT-FOUND lattice only. Auth-class failures collapse\n * to `'unknown'` here on purpose: this predicate's whole contract is \"is this a wrong-NAME error\",\n * and its callers enrich with project/config listings that an auth failure must never trigger. Use\n * {@link classifyDopplerFailure} when you need the full lattice.\n *\n * @example\n * classifyDopplerDownloadError(\"Doppler Error: Could not find requested project 'x'\") // => 'project'\n * classifyDopplerDownloadError(\"Doppler Error: Could not find requested config 'dev'\") // => 'config'\n * classifyDopplerDownloadError('Doppler Error: Invalid Auth token') // => 'unknown'\n */\nexport const classifyDopplerDownloadError = (stderr: string): DopplerNotFoundKind => {\n const kind = classifyDopplerFailure(stderr)\n\n return kind === 'auth' ? 'unknown' : kind\n}\n\n/**\n * The actionable body for an auth-class download failure: Doppler REFUSED the token we sent, so the\n * fix is always a new token for this env \u2014 never `doppler login` (account auth no longer exists).\n *\n * Deliberately does not interpolate the raw stderr: this message is user-facing, and the one rule a\n * credential path cannot bend is that nothing token-adjacent gets rendered by accident.\n *\n * @example\n * buildDopplerAuthFailureMessage('dev')\n * // => 'Doppler rejected the service token for env \"dev\" \u2026 run `infra-kit env-token-set <env>` \u2026'\n */\nexport const buildDopplerAuthFailureMessage = (env: string): string => {\n return [\n `Doppler rejected the service token for env \"${env}\" \u2014 it is invalid, revoked, or scoped to a different config.`,\n `Fix: run \\`infra-kit env-token-set ${env}\\` with a token scoped to that config.`,\n 'CI / agents: set INFRA_KIT_ENV_TOKEN to a token scoped to that config.',\n ].join('\\n')\n}\n\n/**\n * An auth-class `secrets download` failure, as a TYPE rather than a string. This is the error\n * `env-load`'s `translateDopplerDownloadError` throws for the auth class, and it is what every\n * DOWNSTREAM consumer classifies on.\n *\n * It is the DOPPLER-REFUSED-US subset of {@link EnvAuthError}, the durable/user-fixable env-auth\n * class. Downstream policy therefore classifies on `isEnvAuthFailure`; `isDopplerAuthError`\n * remains for the callers who genuinely mean \"the token was SENT and Doppler\n * rejected it\". The message is unchanged \u2014 {@link buildDopplerAuthFailureMessage} still renders\n * it \u2014 so a human who only ever sees `error.message` sees precisely what they saw before.\n *\n * @example\n * throw new DopplerAuthError('dev', 'revoked')\n * // message: 'Doppler rejected the service token for env \"dev\" \u2026 `infra-kit env-token-set <env>` \u2026'\n */\n// WHY a class and not \"match the message\": the moment the raw Doppler stderr is translated into a\n// human-facing message the markers it was classified by are GONE. A consumer that re-derives the\n// class by re-parsing that message is coupled to prose owned by another module \u2014 and the coupling\n// is SILENT: reword the message and the auth channel simply stops firing, with every unit test on\n// both sides still green (exactly the defect this type exists to make impossible). The\n// classification now travels WITH the error.\n//\n// Why the subset framing: a missing token never reaches Doppler, and a corrupt token store never\n// reaches the resolver, yet all three are equally durable and equally the user's to fix.\n//\n// The @example names the command as `infra-kit env-token-set <env>` rather than with a literal arg\n// for `program.test.ts`'s benefit: to that scan an `<env>` placeholder ENDS the command, but a\n// literal `dev` is indistinguishable from a subcommand and would be reported as a dead one.\nexport class DopplerAuthError extends EnvAuthError {\n /**\n * The env (= Doppler config) whose service token Doppler refused. Names the fix, carries no token.\n *\n * `declare` NARROWS the base's `string | null` (a Doppler refusal always names one env) without\n * re-declaring the field: under `useDefineForClassFields` a real re-declaration would `defineProperty`\n * it back to `undefined` AFTER `super()` had set it.\n */\n declare readonly env: string\n /**\n * Which of the two auth diagnoses the raw stderr indicated, or `null` when it was not stated\n * (e.g. the payload-scope assert, which never sees Doppler's stderr). Diagnostic only \u2014 every\n * auth kind shares one fix.\n */\n readonly authKind: DopplerAuthKind | null\n\n /**\n * `message` overrides the rendered text for a caller that knows MORE than the generic diagnosis \u2014\n * the payload-scope assert can name the config the token actually belongs to, which Doppler's own\n * refusal cannot. It never changes the CLASS: every auth failure must remain type-detectable, or it\n * degrades to the transient 30s marker and the user is never told (the defect this type exists to\n * make impossible).\n */\n constructor(env: string, authKind: DopplerAuthKind | null = null, message?: string) {\n super(message ?? buildDopplerAuthFailureMessage(env), env)\n this.name = 'DopplerAuthError'\n this.authKind = authKind\n }\n}\n\n/**\n * The NARROW type guard: \"we sent Doppler a token and Doppler refused it\". Not text-matching \u2014 that\n * is how a caller asks \"was this the token?\" without re-parsing a rendered message.\n *\n * Use {@link isEnvAuthFailure} instead when the question is the POLICY one \u2014 \"is this durable and the\n * user's to fix?\" \u2014 because a missing token and a corrupt token store are both of those and neither is\n * a Doppler refusal; narrowing policy to this guard silently drops both cases.\n *\n * @example\n * isDopplerAuthError(new DopplerAuthError('dev')) // => true\n * isDopplerAuthError(new Error('Doppler Error: Invalid Auth token')) // => false (untranslated: not ours to claim)\n */\nexport const isDopplerAuthError = (error: unknown): error is DopplerAuthError => {\n return error instanceof DopplerAuthError\n}\n\ninterface DopplerNotFoundMessageArgs {\n /** Whether the missing entity is the project or the config within it. */\n kind: 'project' | 'config'\n project: string\n config: string\n /**\n * Names to suggest. `null` = lookup failed/unavailable, `[]` = none exist; both\n * omit the suggestion line so a failed enrichment probe is never misreported as\n * a definitive \"none available\".\n */\n available?: string[] | null\n}\n\n/**\n * Build the actionable, multi-line error body for a Doppler not-found failure:\n * states what's missing, points at the exact infra-kit.json field, lists available\n * names when known, and gives a concrete fix.\n *\n * @example\n * buildDopplerNotFoundMessage({ kind: 'project', project: 'infra-kit', config: 'dev', available: ['nomadream'] })\n * // => 'Doppler project \"infra-kit\" not found (set in infra-kit.json \u2192 envManagement.config.name).\\nAvailable projects: nomadream.\\nFix: ...'\n */\nexport const buildDopplerNotFoundMessage = ({\n kind,\n project,\n config,\n available,\n}: DopplerNotFoundMessageArgs): string => {\n const lines: string[] =\n kind === 'project'\n ? [`Doppler project \"${project}\" not found (set in infra-kit.json \u2192 envManagement.config.name).`]\n : [`Doppler config \"${config}\" not found in project \"${project}\".`]\n\n if (available && available.length > 0) {\n const label = kind === 'project' ? 'Available projects' : `Available configs in \"${project}\"`\n\n lines.push(`${label}: ${available.join(', ')}.`)\n }\n\n // The config half no longer points at a config file: there IS no declared env list any more. The name\n // came from a workflow, a token, or the `--config` flag, and the only place to fix a genuinely missing\n // one is Doppler itself.\n lines.push(\n kind === 'project'\n ? 'Fix: update envManagement.config.name to an existing project, or create it in Doppler.'\n : 'Fix: pass an existing config, or create it in Doppler.',\n )\n\n return lines.join('\\n')\n}\n", "import { $ } from 'zx'\n\nimport { classifyDopplerAuthFailure, classifyDopplerFailure } from 'src/integrations/doppler/doppler-errors'\nimport { extractStderr } from 'src/lib/errors/operation-error'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\n\n/**\n * Hard upper bound for the Doppler probe. It runs only on the diagnostic path (`doctor`), but a hung\n * VPN/connection must not stall it.\n */\nconst DOPPLER_PROBE_TIMEOUT_MS = 5_000\n\n/**\n * The one secret every Doppler payload carries, whose value is the config the token is scoped to\n * (SPIKE-0 Q2 \u2014 the CONFIG, not `DOPPLER_ENVIRONMENT`, which can differ: config `dev_personal` lives\n * in environment `dev`). Reading it back is what turns a liveness probe into a SCOPE probe.\n */\nconst SCOPE_KEY = 'DOPPLER_CONFIG'\n\n/**\n * Resolve Doppler project name from infra-kit.json at the project root\n */\nexport const getDopplerProject = async (): Promise<string> => {\n const { envManagement } = await getInfraKitConfig()\n\n return envManagement.config.name\n}\n\n/**\n * What a service token turned out to be, once Doppler was asked.\n *\n * `'unreachable'` is the load-bearing one and it means \"COULDN'T TELL\", never \"bad\": network,\n * timeout, VPN, Doppler down, a CLI that isn't installed. A caller that renders it as a definitive\n * verdict would tell a developer on a plane that their token was revoked. (Same `null`-vs-`[]`\n * contract the deleted `listDopplerProjects` carried, in enum form.)\n */\nexport type EnvTokenProbeOutcome = 'valid' | 'revoked' | 'mis-scoped' | 'unreachable'\n\nexport interface EnvTokenProbe {\n outcome: EnvTokenProbeOutcome\n /** The config the token actually resolved to, when Doppler told us. Never a token value. */\n scopedTo?: string\n}\n\ninterface EnvTokenProbeArgs {\n /**\n * The child environment carrying the token \u2014 built by `buildDopplerChildEnv`, which scrubs the\n * inherited `DOPPLER_*` vars and sets ours. Passed in rather than built here so the token travels\n * by ENV and never by argv (`ps` shows argv to every user on the box), and so this module stays\n * free of a cycle back through `commands/env-load`.\n */\n childEnv: NodeJS.ProcessEnv\n project: string\n config: string\n}\n\n/**\n * The cheapest combined VALIDITY + SCOPE probe of a Doppler service token (SPIKE-0): read one secret\n * back \u2014 the payload's own `DOPPLER_CONFIG` \u2014 and compare it to the config we asked for.\n *\n * `doppler me` is NOT enough: it works under a service token but returns no project/config, so it can\n * only prove the token is alive, never that it points where we think. One `secrets get` answers both\n * questions in one round trip, and the CLI enforces the scope for us on the wire.\n *\n * Never throws. Every failure becomes an outcome, and an unrecognized one becomes `'unreachable'`\n * (\"couldn't tell\") rather than a guess \u2014 the caller is `doctor`, whose whole value is that its\n * verdicts are true.\n *\n * @example\n * await probeEnvToken({ childEnv, project: 'api', config: 'dev' })\n * // => { outcome: 'valid', scopedTo: 'dev' }\n * // revoked token => { outcome: 'revoked' }\n * // token for prod => { outcome: 'mis-scoped' }\n * // offline => { outcome: 'unreachable' }\n */\nexport const probeEnvToken = async ({ childEnv, project, config }: EnvTokenProbeArgs): Promise<EnvTokenProbe> => {\n const prevQuiet = $.quiet\n\n $.quiet = true\n try {\n const result = await $({\n env: childEnv,\n })`doppler secrets get ${SCOPE_KEY} --plain --project ${project} --config ${config}`.timeout(\n DOPPLER_PROBE_TIMEOUT_MS,\n )\n const scopedTo = result.stdout.trim()\n\n // Exit 0 with a DIFFERENT config would mean the CLI's own scope enforcement let a mis-scoped token\n // through \u2014 belt and braces, but this is the check that would catch it.\n if (scopedTo !== config) return { outcome: 'mis-scoped', scopedTo }\n\n return { outcome: 'valid', scopedTo }\n } catch (error: unknown) {\n return { outcome: classifyProbeFailure(error) }\n } finally {\n $.quiet = prevQuiet\n }\n}\n\n/**\n * Turn a failed probe into an outcome. Only the two auth-class markers are definitive; a\n * project/config not-found is a config bug rather than a token verdict, so it collapses to\n * `'unreachable'` too \u2014 the token check must not claim a token is bad because the PROJECT name is.\n */\nconst classifyProbeFailure = (error: unknown): EnvTokenProbeOutcome => {\n const stderr = extractStderr(error) ?? (error instanceof Error ? error.message : String(error))\n\n if (classifyDopplerFailure(stderr) !== 'auth') return 'unreachable'\n\n return classifyDopplerAuthFailure(stderr) ?? 'unreachable'\n}\n", "import process from 'node:process'\n\nimport { getTokenStorePath, readTokenStore } from 'src/lib/env-tokens'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * The ONE environment variable that carries a Doppler service token into infra-kit (the CI / agent\n * path: no home directory, no token store, no interactive `env-token-set`).\n *\n * Deliberately NOT named `DOPPLER_TOKEN`. That name is contaminated on both ends: a Doppler project\n * may itself hold a secret called `DOPPLER_TOKEN`, and `env-load` exports the WHOLE project into the\n * shell \u2014 so a `DOPPLER_TOKEN` in the environment cannot be trusted to be the token WE were handed\n * (SPIKE-0 Q5: an inherited `DOPPLER_TOKEN` silently overrides everything else the CLI would use).\n * A private name keeps the input channel ours.\n */\nexport const INFRA_KIT_ENV_TOKEN_VAR = 'INFRA_KIT_ENV_TOKEN'\n\n/** Where a resolved token came from. Surfaced by `env-token-list`; never carries the token itself. */\nexport type EnvTokenSource = 'env' | 'store'\n\nexport interface ResolvedEnvToken {\n /** The Doppler service token. NEVER log, echo, or write this into a sourced file. */\n token: string\n source: EnvTokenSource\n}\n\n/**\n * Resolve the Doppler service token for one environment (= one Doppler config).\n *\n * Precedence, highest first:\n * 1. `INFRA_KIT_ENV_TOKEN` \u2014 the CI / agent channel. Checked BEFORE the store so a machine with no\n * home config (or a deliberately corrupted one) still loads, and so nothing on that path can\n * throw on a store it never needed.\n * 2. `envs[env]` from `~/.infra-kit/projects/<repo>/tokens.json` \u2014 the developer channel.\n * 3. Nothing \u21D2 THROW an {@link EnvAuthError}. Token-only auth has no fallback: there is no\n * `doppler login` account to degrade to, so a missing token is a hard, actionable stop rather than\n * a mysterious empty env. The CLASS matters as much as the message \u2014 see the throw below.\n *\n * An EMPTY `INFRA_KIT_ENV_TOKEN` is a MISS, not an empty token: `export INFRA_KIT_ENV_TOKEN=` (or an\n * unset var expanded by a CI template) must fall through to the store, not authenticate as \"\".\n *\n * @example\n * await resolveEnvToken('dev') // => { token: 'dp.st.dev.xxxx', source: 'store' }\n * // with INFRA_KIT_ENV_TOKEN set => { token: <that value>, source: 'env' }\n * // with neither => throws 'No Doppler service token for env \"dev\". \u2026'\n */\nexport const resolveEnvToken = async (env: string): Promise<ResolvedEnvToken> => {\n const fromEnv = process.env[INFRA_KIT_ENV_TOKEN_VAR]\n\n if (fromEnv) return { token: fromEnv, source: 'env' }\n\n const store = await readTokenStore()\n const fromStore = store?.envs[env]\n\n if (fromStore) return { token: fromStore, source: 'store' }\n\n // An EnvAuthError, not a plain Error: \"no token\" is the DURABLE, user-fixable auth failure \u2014 see\n // EnvAuthError's own doc for why the class, not the message, is what downstream callers classify on.\n throw new EnvAuthError(buildMissingTokenMessage(env, await getTokenStorePath()), env)\n}\n\n/**\n * The no-token refusal. It is the first thing an un-migrated user sees at update time, so it must be\n * fixable without reading any docs: it names the env, where to mint a token, the exact command, where\n * the token lands (and that it is NOT the repo), and the CI escape hatch.\n *\n * The fix command is a BACKTICK code span \u2014 the repo convention for naming a command to a human, and\n * the anchor `program.test.ts` scans to prove every command we print is a command we accept.\n *\n * (The @example names the command as `infra-kit env-token-set <env>` rather than with a literal arg\n * for that scan's benefit: a `<env>` placeholder ENDS the command, but a literal `dev` is\n * indistinguishable from a subcommand and would be reported as a dead one.)\n *\n * @example\n * buildMissingTokenMessage('dev', '/Users/x/.infra-kit/projects/api/tokens.json')\n * // => 'No Doppler service token for env \"dev\". Mint one at https://dashboard.doppler.com \u2026 run `infra-kit env-token-set <env>` \u2026'\n */\nconst buildMissingTokenMessage = (env: string, storePath: string): string => {\n return [\n `No Doppler service token for env \"${env}\".`,\n `Mint one at https://dashboard.doppler.com \u2014 this project \u2192 config \"${env}\" \u2192 Access tab \u2192 \"Generate Service Token\".`,\n `Fix: run \\`infra-kit env-token-set ${env}\\` and paste it.`,\n `It is stored in ${tildify(storePath)} (mode 0600, never in the repo).`,\n `CI / agents: set ${INFRA_KIT_ENV_TOKEN_VAR} instead \u2014 it takes precedence and needs no home config.`,\n ].join('\\n')\n}\n", "import process from 'node:process'\nimport { z } from 'zod'\n\nimport { buildEnvTokenStatus } from 'src/commands/env-list'\nimport { INFRA_KIT_ENV_TOKEN_VAR } from 'src/integrations/doppler/token-resolver'\nimport { INFRA_KIT_SESSION_VAR } from 'src/lib/constants'\nimport { readTokenStore } from 'src/lib/env-tokens'\nimport { logger } from 'src/lib/logger'\nimport type { ProjectEnv } from 'src/lib/project-envs'\nimport { listProjectEnvs } from 'src/lib/project-envs'\nimport type { ArgumentFormProvider } from 'src/types'\n\n/**\n * @fileoverview\n *\n * The argument form `env-load` offers when `config` is omitted: pick the environment to load into\n * the calling terminal session, from the same list `env-list` reports.\n *\n * Same seam as `lib/deploy-form`, same silent failure modes \u2014 the tests assert `!== null` on the\n * wire shape for that reason.\n */\n\n/** A plain object \u2014 not an array, not `null`, not a primitive. */\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Collapse a failed enumeration into an empty one \u2014 the provider's own contract is never-throws. */\nconst orEmpty = async (work: Promise<ProjectEnv[]>): Promise<ProjectEnv[]> => {\n try {\n return await work\n } catch {\n return []\n }\n}\n\n/**\n * The envs no token resolves for. An unreadable store reports every env as token-less: the load\n * would fail on the same read, so the form says so up front rather than pretending otherwise.\n */\nconst tokenlessEnvs = async (envs: ProjectEnv[]): Promise<string[]> => {\n const store = await readTokenStore().catch(() => {\n return null\n })\n\n return buildEnvTokenStatus(envs, store?.envs ?? {}, process.env[INFRA_KIT_ENV_TOKEN_VAR])\n .filter((status) => {\n return !status.hasToken\n })\n .map((status) => {\n return status.env\n })\n}\n\n/**\n * Build the `formProvider` for the `env-load` tool.\n *\n * @example\n * envLoadMcpTool.formProvider = createEnvLoadFormProvider()\n */\nexport const createEnvLoadFormProvider = (): ArgumentFormProvider => {\n return {\n // A getter, not a string: `envLoadMcpTool` is a module-scope constant, so a plain string would\n // freeze the session id at import time. Production never changes it after boot; tests set it\n // after the import. Satisfies `message: string` structurally.\n get message(): string {\n const session =\n process.env[INFRA_KIT_SESSION_VAR] ?? `UNKNOWN \u2014 ${INFRA_KIT_SESSION_VAR} is not set, the load will fail`\n\n return `Choose the environment to load into terminal session ${session}. Picking one LOADS it; there is no further prompt.`\n },\n\n isFormable: (params: unknown): boolean => {\n return isRecord(params) && (params.config === undefined || params.config === '')\n },\n\n buildRequestedSchema: async (): Promise<z.ZodObject<z.ZodRawShape> | null> => {\n const envs = await orEmpty(listProjectEnvs())\n\n // `null` with a log line, never `z.enum([])`: the latter throws inside `elicit()` and degrades\n // to a gate that looks exactly like a client which cannot render forms.\n if (envs.length === 0) {\n logger.info({ msg: 'Tool execution form options empty: env-load' })\n\n return null\n }\n\n const names = envs.map((env) => {\n return env.env\n })\n const tokenless = await tokenlessEnvs(envs)\n\n // The token annotation rides in the field prose: the elicitation wire shape carries no\n // per-option labels, so the description is the only place the human can be told before they pick.\n return z.object({\n config: z\n .enum(names)\n .describe(\n `The environment to load. ${\n tokenless.length === 0\n ? 'A service token is stored for every one of them.'\n : `NO stored token for: ${tokenless.join(', ')} \u2014 choosing one of those fails until you run \\`infra-kit env-token-set <env>\\`.`\n } The list is what env-list knows: workflow-declared environments first, then token-only ones.`,\n ),\n })\n },\n\n toArgs: (content: Record<string, unknown>, params: unknown): Record<string, unknown> | null => {\n const { config } = content\n\n if (typeof config !== 'string' || config.length === 0) return null\n\n return { ...(isRecord(params) ? params : {}), config }\n },\n }\n}\n", "import process from 'node:process'\nimport { z } from 'zod'\n\nimport { getDopplerProject } from 'src/integrations/doppler/doppler-project'\nimport { INFRA_KIT_ENV_TOKEN_VAR } from 'src/integrations/doppler/token-resolver'\nimport { readTokenStore } from 'src/lib/env-tokens'\nimport { logger } from 'src/lib/logger'\nimport type { ProjectEnv, ProjectEnvSource } from 'src/lib/project-envs'\nimport { listProjectEnvs } from 'src/lib/project-envs'\nimport { defineMcpTool, textContent } from 'src/types'\n\n/** One row of the token column: an env, where we learned it exists, and whether a token resolves. */\nexport interface EnvTokenStatus {\n env: string\n /** `gh-workflow` \u2014 declared in a workflow's dispatch options. `token-only` \u2014 we hold a token, no workflow names it. */\n source: ProjectEnvSource\n hasToken: boolean\n}\n\n/**\n * Build the token column: one row per known environment, reporting only WHETHER a token resolves \u2014\n * never the token itself. Mirrors `resolveEnvToken`'s precedence (`INFRA_KIT_ENV_TOKEN` shadows the\n * store for every env) without importing it, so this stays a pure, no-I/O function the same way\n * `buildEnvTokenRows` in `env-token-list` is.\n *\n * @example\n * buildEnvTokenStatus([{ env: 'dev', source: 'gh-workflow' }], { dev: 'dp.st.dev.xxxx' }, undefined)\n * // => [{ env: 'dev', source: 'gh-workflow', hasToken: true }]\n */\nexport const buildEnvTokenStatus = (\n envs: ProjectEnv[],\n storeTokens: Record<string, string>,\n envToken: string | undefined,\n): EnvTokenStatus[] => {\n return envs.map(({ env, source }) => {\n return { env, source, hasToken: Boolean(envToken || storeTokens[env]) }\n })\n}\n\n/** Column headers for the environments table, in render order. */\nconst ENV_TABLE_HEADERS = ['Environment', 'Source', 'Token'] as const\n\n/**\n * Render the environments as an aligned, vertical-bar-separated table \u2014 the same columnar shape as\n * `gh-release-list`, with explicit `|` column rules. Display only: the `--json` payload is built\n * separately in {@link buildResult} from the same rows, so the machine contract never depends on this\n * formatting. Deliberately prints no fix command \u2014 setting a token is a manual `env-token-set` step,\n * not something this read-only listing spells out.\n *\n * @example\n * formatEnvTable([{ env: 'dev', source: 'gh-workflow', hasToken: true }])\n * // => ['Environments:', '', 'Environment | Source | Token', '\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2026', 'dev | gh-workflow | set']\n */\nconst formatEnvTable = (rows: EnvTokenStatus[]): string[] => {\n const cells = rows.map((row) => {\n return [row.env, row.source, row.hasToken ? 'set' : 'not set']\n })\n\n const widths = ENV_TABLE_HEADERS.map((header, col) => {\n return Math.max(\n header.length,\n ...cells.map((cell) => {\n return (cell[col] ?? '').length\n }),\n )\n })\n\n const renderRow = (values: readonly string[]): string => {\n return values\n .map((value, col) => {\n return value.padEnd(widths[col] ?? 0)\n })\n .join(' | ')\n .trimEnd()\n }\n\n const separator = widths\n .map((width) => {\n return '\u2500'.repeat(width)\n })\n .join('\u2500\u253C\u2500')\n\n return ['Environments:', '', renderRow(ENV_TABLE_HEADERS), separator, ...cells.map(renderRow)]\n}\n\n/**\n * List the environments this project has, alongside whether a service token resolves for each one.\n *\n * Purely local: reads the repo's workflows and the local token store, and does not call Doppler \u2014 so\n * it works before any service token exists, which is exactly when a user needs to see the env names\n * they have to run `infra-kit env-token-set <env>` for. (A Doppler SERVICE token could not answer this\n * anyway: it is config-scoped and enumerates only its own config.) The token PRESENCE check is a local\n * file read, not a network probe \u2014 validating that a stored token is still accepted stays\n * `env-token-list --check`'s job.\n *\n * @example\n * await envList()\n * // logs an aligned table: 'dev | gh-workflow | set', 'stage | gh-workflow | not set'\n */\nexport const envList = async () => {\n const project = await getDopplerProject()\n const envs = await listProjectEnvs()\n const store = await readTokenStore()\n const envToken = process.env[INFRA_KIT_ENV_TOKEN_VAR]\n\n const tokens = buildEnvTokenStatus(envs, store?.envs ?? {}, envToken)\n\n logger.info(`Doppler project: ${project}\\n`)\n\n if (tokens.length === 0) {\n // Not an error \u2014 a repo can legitimately declare no dispatchable environment. But an empty list with\n // no explanation is the one thing this command must never print: it is read precisely by the person\n // who does not yet know what the env names ARE.\n logger.info('No environments found.')\n logger.info(` Declare them in a workflow's \\`workflow_dispatch\\` \\`environment.options\\`,`)\n logger.info(' or add a token for one manually.')\n\n return buildResult({ project, envs: tokens })\n }\n\n for (const line of formatEnvTable(tokens)) {\n logger.info(line)\n }\n\n return buildResult({ project, envs: tokens })\n}\n\n/** Shared tail for both exits above \u2014 the empty state is a first-class result, not an error. */\nconst buildResult = ({ project, envs }: { project: string; envs: EnvTokenStatus[] }) => {\n const structuredContent = {\n project,\n configs: envs.map((row) => {\n return row.env\n }),\n tokens: envs,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n// MCP Tool Registration\nexport const envListMcpTool = defineMcpTool({\n name: 'env-list',\n description:\n \"List the environments this project has. The list is the union of two local sources: every environment declared in a GitHub workflow's `workflow_dispatch` `environment.options` (source `gh-workflow`), and every environment the local token store holds a token for (source `token-only`). Not a live fetch from Doppler \u2014 a Doppler service token is config-scoped and cannot enumerate sibling configs. Also returns the Doppler project name, and reports per environment whether a service token resolves locally (from the token store or INFRA_KIT_ENV_TOKEN) \u2014 presence only, never the token value, and never a live Doppler probe. Read-only.\",\n inputSchema: {},\n outputSchema: {\n project: z.string().describe('Detected Doppler project name'),\n configs: z.array(z.string()).describe('Every environment name known to this project'),\n tokens: z\n .array(\n z.object({\n env: z.string().describe('Environment / Doppler config name'),\n source: z\n .enum(['gh-workflow', 'token-only'])\n .describe('Where we learned this environment exists \u2014 a workflow declaration, or a token we hold'),\n hasToken: z.boolean().describe('Whether a service token resolves locally for this environment'),\n }),\n )\n .describe('Per-environment token presence \u2014 never the token value'),\n },\n handler: envList,\n})\n", "import { agentMode } from 'src/lib/agent-mode'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\n\n/**\n * Environments that are NOT ordinary ad-hoc deploy targets by default.\n *\n * This is the DEFAULT, not an immovable policy: a project opts out with `protectedEnvs` in its\n * `infra-kit.json` (`'disallow' | 'allow' | 'cli-only'`, absent meaning `'disallow'`), resolved by\n * `protected-env-access.ts`. The LIST stays in code because it answers \"what is delivery-shaped in\n * this org\", which no single repo owns; the config answers \"may this repo reach it\", which each\n * repo does.\n */\n// `prod` is not a deploy target \u2014 it is a DELIVERY target. `gh-release-deliver` is the sanctioned\n// path to it, and it is a whole flow, not a dispatch: squash-merge the release branch to `main`,\n// open and merge the RC PR, dispatch `deploy-all.yml --ref main -f environment=prod` (see\n// `gh-release-deliver.ts`), then release the matching Jira fix version. A `gh-release-deploy-all\n// --env prod` straight from a release branch skips every one of those steps and ships production\n// from an unmerged ref.\n//\n// `stage` is deliberately NOT here. The old per-repo allowlists excluded it, but nothing delivers\n// to it either \u2014 so it was simply unreachable, which was an oversight rather than a policy. It is\n// an ad-hoc deploy target like any other.\n//\n// What is deliberately NOT rebuilt here is the deleted `environments` key \u2014 a hand-maintained\n// per-repo copy of each workflow's own `environment.options` that drifted from them and turned\n// that drift into a REFUSAL to deploy.\nexport const DEFAULT_PROTECTED_ENVS = ['prod']\n\n/**\n * A project's resolved access to {@link DEFAULT_PROTECTED_ENVS}, and WHY.\n *\n * The reason is not decoration: a refusal because the project disallows protected envs and a refusal\n * because the caller is an agent under `'cli-only'` need opposite remediation. Collapsed to a bare\n * boolean, the second case emits \"prod is delivered, not deployed\" and sends an agent off to run the\n * delivery flow, or to report that prod is unconfigured for the project.\n *\n * Declared here, in the pure leaf, so `protected-env-access.ts` depends on this module and never the\n * reverse.\n */\nexport interface ProtectedEnvAccess {\n allowed: boolean\n reason: 'disallow' | 'agent-blocked' | 'allowed'\n}\n\n/**\n * No access \u2014 the DEFAULT for every function below.\n *\n * That default is the safety property of this module: a call site that forgets to thread the resolved\n * access refuses rather than permits, so a seventh caller is fail-closed until someone deliberately\n * opts it in.\n */\nexport const PROTECTED_ENV_DENIED: ProtectedEnvAccess = { allowed: false, reason: 'disallow' }\n\n/** Whether an environment is delivery-shaped by default, before any project opt-out. */\nexport const isProtectedEnv = (env: string): boolean => {\n return DEFAULT_PROTECTED_ENVS.includes(env)\n}\n\n/**\n * Environments the whole team shares. Everything else in a deploy picker is somebody's personal\n * account (`arthur`, `renana`, \u2026), where a dirty tree is the normal case rather than a hazard.\n */\nconst SHARED_ENVS = ['dev', 'stage']\n\n/**\n * Whether this environment belongs to other people \u2014 the input to `local-deploy`'s confirmation\n * prompt and, via `runPreflight`, its dirty-tree refusal, and to the argument form's `env` prose.\n *\n * A delivery-shaped env is shared by definition, more so than `dev`, yet it is deliberately NOT in\n * {@link SHARED_ENVS}: until a project could reach `prod` at all the question never arose, because\n * `assertDeployable` refused first. Now that a project can allow it, resolving from the list alone\n * would hand production the WEAKER treatment of a personal environment \u2014 a y/N prompt and no\n * clean-tree check, i.e. shipping an uncommitted working tree to prod.\n *\n * @example\n * isSharedEnv('dev') // => true\n * isSharedEnv('prod') // => true \u2014 protected, therefore shared\n * isSharedEnv('arthur') // => false\n */\n// Lives in this leaf rather than in `local-deploy.ts`, where it was written, because the deploy\n// argument form partitions its env dropdown's `.describe()` with it. The form provider is wired into\n// `local-deploy`'s own tool definitions, so importing it from there would close a cycle \u2014 and a\n// second hand-written list of shared envs in the provider is exactly the drift the plan requires the\n// prose be derived to avoid. Extracted rather than inlined so the resolution stays testable:\n// asserting `assertCleanTreeForSharedEnv({ isShared: true, \u2026 })` hand-passes the value under test and\n// passes whether or not the bug exists.\nexport const isSharedEnv = (env: string): boolean => {\n return SHARED_ENVS.includes(env) || isProtectedEnv(env)\n}\n\n/**\n * The ad-hoc deploy picker: a workflow's declared options, minus what this project may not reach.\n *\n * @example\n * deployableEnvs(['dev', 'prod']) // => ['dev']\n * deployableEnvs(['dev', 'prod'], { allowed: true, reason: 'allowed' }) // => ['dev', 'prod']\n */\nexport const deployableEnvs = (options: string[], access: ProtectedEnvAccess = PROTECTED_ENV_DENIED): string[] => {\n if (access.allowed) return options\n\n return options.filter((env) => {\n return !isProtectedEnv(env)\n })\n}\n\n/**\n * Refuse a protected environment this project may not reach, naming the fix for THIS refusal.\n *\n * GitHub cannot enforce either rule for us \u2014 from its side `-f environment=prod` is a perfectly valid\n * choice \u2014 so both are ours. Note what is NOT vetoed: an env absent from the local YAML still\n * dispatches, because that read is of the working tree while the run targets `--ref <branch>`, and\n * GitHub validates the choice itself.\n *\n * @example\n * assertDeployable('dev', 'launch deploy-all workflow') // ok\n * assertDeployable('prod', 'launch deploy-all workflow') // throws \u2014 use `infra-kit release deliver`\n */\nexport const assertDeployable = (\n env: string,\n operation: string,\n access: ProtectedEnvAccess = PROTECTED_ENV_DENIED,\n): void => {\n if (access.allowed) return\n if (!isProtectedEnv(env)) return\n\n // Structured (exit 2, nothing ran): the agent that reads it needs the env named and the fact that no\n // flag of its own opens this door \u2014 it is an agent-side withholding, not a transport one.\n if (access.reason === 'agent-blocked') {\n throw new StructuredRefusalError({ status: 'refused', env, agentMode: agentMode.source }, 2, {\n operation,\n remediation: `a human runs it from their own terminal \u2014 this project sets \\`protectedEnvs: \"cli-only\"\\``,\n stderrExcerpt: `\"${env}\" is withheld from agents in this project (protectedEnvs: \"cli-only\")`,\n })\n }\n\n throw new OperationError(undefined, {\n operation,\n remediation:\n `use \\`infra-kit release deliver\\` \u2014 it merges the release to main, opens the RC PR, ` +\n `deploys from main, and releases the Jira version. To allow ad-hoc deploys to \"${env}\" in this ` +\n `project, set \\`protectedEnvs\\` to \"allow\" or \"cli-only\" in infra-kit.json`,\n stderrExcerpt: `\"${env}\" is delivered, not deployed ad-hoc`,\n })\n}\n", "import { isAgentMode } from 'src/lib/agent-mode'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\n\nimport { PROTECTED_ENV_DENIED } from './protected-envs'\nimport type { ProtectedEnvAccess } from './protected-envs'\n\n/**\n * Resolve whether THIS project may reach the delivery-shaped environments, and why not when it may\n * not. The single place the three-value `protectedEnvs` setting is interpreted \u2014 every call site\n * downstream sees the resolved {@link ProtectedEnvAccess} and nothing else.\n *\n * NEVER THROWS. A repo with no `infra-kit.json`, an unreadable one, or one the merge chain rejects\n * all resolve to denied.\n *\n * @example\n * await resolveProtectedEnvAccess() // no `protectedEnvs` key => { allowed: false, reason: 'disallow' }\n */\n// The only impure member of the protected-env pair: it reads the merged config and the agent-mode\n// flag, so `protected-envs.ts` stays a dependency-free policy leaf with a mock-free unit test.\n//\n// Refusing a protected env on a config we cannot read is correct; turning every deploy into a\n// config-parse error is not \u2014 and `getInfraKitConfig` genuinely throws for a missing file.\n//\n// `isAgentMode()` is called INSIDE this function on purpose. `agentMode` is a mutable object read at\n// call time, and the source is assigned in the CLI's `preAction` hook, which runs after this module\n// is imported. Hoisting the read to module\n// scope \u2014 `const inAgent = agentMode.source !== null` at the top \u2014 would freeze `false` and silently\n// degrade `'cli-only'` into `'allow'` for every agent.\nexport const resolveProtectedEnvAccess = async (): Promise<ProtectedEnvAccess> => {\n let setting\n\n try {\n setting = (await getInfraKitConfig()).protectedEnvs ?? 'disallow'\n } catch {\n return PROTECTED_ENV_DENIED\n }\n\n if (setting === 'disallow') return PROTECTED_ENV_DENIED\n\n if (setting === 'cli-only' && isAgentMode()) {\n return { allowed: false, reason: 'agent-blocked' }\n }\n\n return { allowed: true, reason: 'allowed' }\n}\n", "import { logger } from 'src/lib/logger'\n\nimport { isProtectedEnv } from './protected-envs'\n\n/**\n * Warn, at selection time, about what an ad-hoc dispatch to a delivery-shaped environment SKIPS.\n *\n * This is the knowledge the refusal in `assertDeployable` used to carry. A project that sets\n * `protectedEnvs` to `\"allow\"` removes the block, and the block was the only place in the codebase\n * recording WHY `prod` was special \u2014 so the sentence has to outlive it, or the next person learns the\n * hard way that `release deploy-all --env prod` is `release deliver` minus its bookkeeping.\n *\n * Deliberately a warning and not a second confirmation: the project already decided, and a prompt the\n * user cannot act on differently is just friction. The dispatch commands run their own `confirmDeploy`\n * immediately after this.\n *\n * Shared by both dispatch commands rather than copied: `gh-release-deploy-selected` already carries a\n * cognitive-complexity suppression, and this must not add to it.\n *\n * @example\n * warnProtectedEnvDispatch({ env: 'prod', branch: 'release/1.9.0' }) // logs the skipped steps\n * warnProtectedEnvDispatch({ env: 'dev', branch: 'release/1.9.0' }) // no-op\n */\nexport const warnProtectedEnvDispatch = (args: { env: string; branch: string }): void => {\n const { env, branch } = args\n\n if (!isProtectedEnv(env)) return\n\n logger.warn(\n [\n `\u26A0\uFE0F \"${env}\" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,\n `Dispatching from \"${branch}\" ships ${env} from a ref that is not merged to main, and skips:`,\n ' \u2022 the squash-merge of the release branch into main',\n ' \u2022 the RC pull request',\n ' \u2022 the Jira fix-version release',\n 'Run `infra-kit release deliver` instead if you want those.',\n ].join('\\n'),\n )\n}\n", "import fs from 'node:fs/promises'\nimport path from 'node:path'\nimport yaml from 'yaml'\n\nimport { getProjectRoot } from 'src/lib/git-utils'\n\n/** Where GitHub keeps dispatchable workflows. The only place we look for environment declarations. */\nconst WORKFLOWS_DIR = '.github/workflows'\n\n/**\n * The environment list a workflow will accept, read from its own `workflow_dispatch` `choice`\n * input.\n *\n * ADVISORY ONLY: it sources the interactive picker, and callers must NOT veto against it. The value\n * comes from the WORKING TREE while the dispatch targets `--ref <branch>`, so the two can\n * legitimately differ and an explicit `--env` must always win.\n *\n * Never throws. A repo with no such workflow (bridge has none), a `type: string` input, an absent\n * `options:` key, or malformed YAML all yield `[]` \u2014 an empty picker, never a dead command.\n *\n * @example\n * await readWorkflowEnvOptions('deploy-all.yml') // => ['dev', 'arthur', 'stage', 'prod']\n * await readWorkflowEnvOptions('absent.yml') // => []\n */\n// This replaces `infra-kit.json \u2192 environments`, which was a THIRD copy of a fact GitHub already\n// owns and already enforces: a `choice` input is validated server-side on dispatch, so an\n// out-of-range value is rejected by GitHub whether or not we check it here. The copy had drifted \u2014\n// hulyo declared 6 envs while every hulyo workflow declared 8, and the CLI's client-side check\n// turned that drift into a REFUSAL to deploy to `stage` and `prod`. Vetoing on a local read of a\n// remote fact is what created the bug this function exists to remove.\nexport const readWorkflowEnvOptions = async (workflowFile: string): Promise<string[]> => {\n const projectRoot = await getProjectRoot()\n\n return parseEnvOptions(path.resolve(projectRoot, WORKFLOWS_DIR, workflowFile))\n}\n\n/**\n * Every environment this repo declares anywhere \u2014 the union across ALL workflows.\n *\n * Deliberately a UNION, and deliberately not `deploy-all.yml` alone. Two repos prove why: travelist's\n * `deploy-all` omits `eliran` and `roman` (who both hold live tokens and ARE deployable via\n * `deploy-selected-services`), and bridge has no `deploy-all.yml` at all, so a single-file read would\n * report that it has zero environments.\n *\n * Note the asymmetry with {@link readWorkflowEnvOptions}, and keep it: this answers the REPO-scoped\n * question (\"what environments exist here?\") and so unions; the deploy pickers answer the\n * WORKFLOW-scoped question (\"where can THIS workflow deploy?\") and so must not.\n *\n * Never throws \u2014 an unreadable workflows directory yields `[]`.\n *\n * @example\n * await listWorkflowEnvs() // => ['dev', 'arthur', 'eliran', 'renana', 'roman', 'oriana', 'stage', 'prod']\n */\nexport const listWorkflowEnvs = async (): Promise<string[]> => {\n const projectRoot = await getProjectRoot()\n const workflowsDir = path.resolve(projectRoot, WORKFLOWS_DIR)\n\n let entries: string[]\n\n try {\n entries = await fs.readdir(workflowsDir)\n } catch {\n return []\n }\n\n const workflows = entries\n .filter((entry) => {\n return entry.endsWith('.yml') || entry.endsWith('.yaml')\n })\n .sort()\n\n const perWorkflow = await Promise.all(\n workflows.map((file) => {\n return parseEnvOptions(path.resolve(workflowsDir, file))\n }),\n )\n\n // First-seen order, de-duped: the picker reads best when `dev` leads, as it does in every workflow.\n return [...new Set(perWorkflow.flat())]\n}\n\n/**\n * Pull `on.workflow_dispatch.inputs.environment.options` out of one workflow, or `[]`.\n *\n * `yaml.parse` is untyped, and every hop here is a place a real workflow legitimately differs (a\n * `push`-only workflow has no `workflow_dispatch`; a reusable `_jobs.yml` takes `environment` as a\n * `type: string`). Hence the guards rather than a schema: absence is normal, not an error.\n *\n * @example\n * await parseEnvOptions('/repo/.github/workflows/deploy-all.yml') // => ['dev', 'prod']\n * await parseEnvOptions('/repo/.github/workflows/code-quality.yml') // => []\n */\nconst parseEnvOptions = async (workflowPath: string): Promise<string[]> => {\n let parsed: unknown\n\n try {\n parsed = yaml.parse(await fs.readFile(workflowPath, 'utf-8'))\n } catch {\n return []\n }\n\n // `on` is the YAML 1.1 boolean `true` under some parsers; `yaml@2` keeps it a string, but read\n // defensively \u2014 a wrong key here would silently empty every picker.\n const on = pick(parsed, 'on') ?? pick(parsed, 'true')\n const options = pick(pick(pick(pick(on, 'workflow_dispatch'), 'inputs'), 'environment'), 'options')\n\n if (!Array.isArray(options)) return []\n\n return options.filter((option): option is string => {\n return typeof option === 'string' && option.length > 0\n })\n}\n\n/** One safe hop into an unknown object graph. Returns `undefined` for anything that is not a record. */\nconst pick = (value: unknown, key: string): unknown => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n\n return (value as Record<string, unknown>)[key]\n}\n", "import { readTokenStore } from 'src/lib/env-tokens'\nimport { listWorkflowEnvs } from 'src/lib/workflow-envs'\n\n/** Where the knowledge that an environment EXISTS came from. Never says anything about credentials. */\nexport type ProjectEnvSource = 'gh-workflow' | 'token-only'\n\nexport interface ProjectEnv {\n env: string\n source: ProjectEnvSource\n}\n\n/**\n * Every environment this project has, as the union of the two authorities that actually own the\n * answer: `gh-workflow` (declared in a `workflow_dispatch` `environment.options` list) and\n * `token-only` (we hold a token for it, but no workflow mentions it \u2014 real and reachable, just not\n * deployable from here).\n *\n * @example\n * await listProjectEnvs()\n * // => [{ env: 'dev', source: 'gh-workflow' }, \u2026, { env: 'prod_observability', source: 'token-only' }]\n */\n// `gh-workflow` is what a repo says about itself, in git, reviewed, and enforced by GitHub on\n// dispatch. It is the ONLY source that works on a fresh clone with zero credentials, which is\n// exactly when a new developer needs to be told the env names they have to run\n// `infra-kit env-token-set <env>` for. hulyo's `prod_observability` is exactly a token-only env.\n//\n// The union is the point. Neither source alone is the truth: the token store is a per-DEVELOPER\n// cache (a teammate's holds one entry; a fresh clone's holds none), and the workflows cannot know\n// about an env that exists only to be read from. Reading them together is what replaced\n// `infra-kit.json \u2192 environments`, which was a hand-maintained third copy of both and had drifted\n// from both.\nexport const listProjectEnvs = async (): Promise<ProjectEnv[]> => {\n const workflowEnvs = await listWorkflowEnvs()\n const store = await readTokenStore()\n\n const declared: ProjectEnv[] = workflowEnvs.map((env) => {\n return { env, source: 'gh-workflow' }\n })\n\n const known = new Set(workflowEnvs)\n\n const tokenOnly: ProjectEnv[] = Object.keys(store?.envs ?? {})\n .filter((env) => {\n return !known.has(env)\n })\n .sort()\n .map((env) => {\n return { env, source: 'token-only' }\n })\n\n // Workflow envs first, in the order the workflows declare them (`dev` leads everywhere), then the\n // strays. A picker reads best when the common choice is at the top.\n return [...declared, ...tokenOnly]\n}\n\n/** The env names alone, for the callers that only need choices. Same order as {@link listProjectEnvs}. */\nexport const listProjectEnvNames = async (): Promise<string[]> => {\n const envs = await listProjectEnvs()\n\n return envs.map((entry) => {\n return entry.env\n })\n}\n", "import type { z } from 'zod'\n\nexport interface ToolsExecutionResult<TStructured = Record<string, unknown>> {\n [x: string]: unknown\n content: {\n type: 'text'\n text: string\n }[]\n structuredContent?: TStructured\n}\n\nexport interface RequiredConfirmedOptionArg {\n confirmedCommand: boolean\n}\n\n/**\n * The per-tool seam that lets the domain-blind `refuseMissingArguments` describe a tool's arguments\n * as a form \u2014 the `choices` an agent's refusal carries \u2014 without learning anything about the tool's\n * domain. It asks only \"is there a provider?\" and \"is this input formable?\"; every domain-specific\n * answer lives behind these three members.\n */\nexport interface ArgumentFormProvider {\n /** Human-facing prompt rendered above the form. */\n message: string\n /**\n * Whether a form is WORTH opening for THESE arguments. Pure, synchronous, never\n * throws; `false` sends the call straight to the gate with its arguments intact.\n * Defaults to `false` on anything it does not recognise.\n *\n * NOT load-bearing for TRUNCATION: the chokepoint's non-narrowing check\n * catches top-level key removal and any array length change \u2014 shortening OR\n * growth \u2014 which no provider can weaken. The check is load-bearing for NOTHING\n * ELSE: it does not look at nested keys or at values, so it does NOT cover a\n * form that drops `releases[0].type`. Do not read this as \"the chokepoint has\n * it covered\": for anything below the top level, `toArgs`'s merge is the only\n * control.\n */\n isFormable: (params: unknown) => boolean\n /**\n * Candidate values for THIS tool's arguments, as a zod object (a Standard\n * Schema \u2014 `inputRequired.elicit` accepts one). Returned rather than inlined so\n * the SAME schema validates the response on re-entry.\n *\n * Contract: never throws, never blocks past the caller's deadline, and returns\n * `null` when it cannot offer real values \u2014 which the handler reads as \"no\n * form\" and falls to the gate.\n *\n * Also: **validates SYNCHRONOUSLY \u2014 no `.refine(async \u2026)` anywhere in the\n * object.** `acceptedContent`'s schema-aware overload throws a `TypeError` on an\n * asynchronously-validating schema, and the declared return type\n * `z.ZodObject<z.ZodRawShape>` cannot express that constraint \u2014 so it is stated\n * here and backstopped by a wrap at the call site.\n */\n buildRequestedSchema: (params: unknown) => Promise<z.ZodObject<z.ZodRawShape> | null>\n /**\n * MERGES validated form content over the round-1 `params` \u2014 never constructs a\n * fresh argument object. The form overwrites field-by-field and only where the\n * human supplied a value; untouched fields keep their round-1 value.\n *\n * Contract: TOTAL over anything `buildRequestedSchema`'s own schema accepts,\n * and NEVER THROWS \u2014 it is the one member called on client-supplied input, and\n * a throw here escapes the chokepoint's catch as a tool error where a gate was\n * owed. It returns `null` if it cannot map, which the handler treats exactly as\n * a validation failure: gate, with the round-1 arguments.\n */\n toArgs: (content: Record<string, unknown>, params: unknown) => Record<string, unknown> | null\n}\n\nexport interface McpTool<TIn extends z.ZodRawShape = z.ZodRawShape, TOut extends z.ZodRawShape = z.ZodRawShape> {\n name: string\n description: string\n inputSchema: TIn\n outputSchema: TOut\n /**\n * The catalog's own \"this mutation is gated by `confirmOrExit`\" declaration \u2014 the only machine-readable\n * link between the catalog's `mutating` flag and `confirmOrExit`: a run without `--yes` previews its\n * plan and exits, and only a re-run carrying `--yes` executes. Set only on genuinely destructive\n * tools; the default-deny catalog test enforces coverage.\n */\n requiresHumanConfirm?: boolean\n /**\n * Optional per-tool {@link ArgumentFormProvider}. Present means \"this command can describe a form for\n * its arguments\", which `refuseMissingArguments` renders as the `choices` of an agent's refusal. It is\n * ORTHOGONAL to `requiresHumanConfirm`: a form answer is an ARGUMENT, not consent \u2014 the re-run still\n * meets `confirmOrExit`, and the form path can execute nothing a direct call with the same arguments\n * could not.\n */\n formProvider?: ArgumentFormProvider\n handler: (\n params: z.infer<z.ZodObject<TIn>> & RequiredConfirmedOptionArg,\n ) => Promise<ToolsExecutionResult<z.infer<z.ZodObject<TOut>>>>\n}\n\n/**\n * Build the `content` half of a handler result. Narrows the literal `type: 'text'`\n * so handlers can use inferred return types without TS widening `type` to\n * `string` \u2014 the shape is the retired server's, kept because every handler and\n * every handler test is written against it and `--json` reads only\n * `structuredContent`.\n *\n * @example\n * return {\n * content: textContent(JSON.stringify(structuredContent, null, 2)),\n * structuredContent,\n * }\n */\nexport const textContent = (text: string): ToolsExecutionResult['content'] => {\n return [{ type: 'text', text }]\n}\n\n/**\n * Factory that ties the handler's return type to the declared `outputSchema`\n * so `structuredContent` is checked against the schema at compile time. If a\n * handler accidentally drops or renames a field, TS errors at the declaration\n * site rather than in whatever parses the `--json` document.\n *\n * @example\n * export const envLoadMcpTool = defineMcpTool({\n * name: 'env-load',\n * description: '...',\n * inputSchema: { config: z.string() },\n * outputSchema: { filePath: z.string(), variableCount: z.number() },\n * handler: envLoad,\n * })\n */\nexport const defineMcpTool = <TIn extends z.ZodRawShape, TOut extends z.ZodRawShape>(\n tool: McpTool<TIn, TOut>,\n): McpTool<TIn, TOut> => {\n return tool\n}\n", "import { z } from 'zod'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { logger } from 'src/lib/logger'\nimport type { ArgumentFormProvider } from 'src/types'\n\n/**\n * @fileoverview\n * The form-backed twin of `resolveHeadless`: where a human would be shown the command's picker, an\n * agent (or a `--json` run) is refused with `argument_required` AND `choices` \u2014 the form's requested\n * schema rendered as JSON Schema, i.e. exactly the rows the `src/lib/*-form/` builders already\n * produce. No command invents a row shape of its own; the skill turns `choices` into a question and\n * re-runs with the pick.\n *\n * Runs at the TOP of the six form-backed handlers, before their pickers, because a picker only knows\n * its own field while the provider knows every field round 1 omitted (`deploy-selected` can be\n * missing `version`, `env` and `services` at once \u2014 one refusal lists all three).\n */\n\nexport interface RefuseMissingArgumentsInput {\n provider: ArgumentFormProvider\n /** The handler's arguments as received \u2014 what `isFormable` and `buildRequestedSchema` inspect. */\n params: unknown\n operation: string\n /**\n * The CLI flag to name \u2014 a string when one flag answers the whole form (`release-create`'s four\n * fields all fold into `--release <spec>`), or a function of the form's fields that `params` left\n * EMPTY, for the tools whose flags mirror their fields (`deploy-selected` names `env` when\n * `version` was given, although the form re-offers `version` too). The function sees `[]` when\n * the builder had nothing to offer.\n */\n argument: string | ((missing: string[]) => string)\n}\n\n/** The provider contract says never-throw; a programming error inside it must not become a crash here. */\nconst requestedSchema = async (input: RefuseMissingArgumentsInput): Promise<z.ZodObject<z.ZodRawShape> | null> => {\n try {\n return await input.provider.buildRequestedSchema(input.params)\n } catch (error) {\n logger.debug({ err: error, operation: input.operation }, 'argument form builder threw; refusing without choices')\n\n return null\n }\n}\n\n/**\n * Refuse, naming the first argument the form would have asked for and carrying the whole form as\n * `choices`, when an agent / `--json` run omitted a picker argument. A no-op for a human at a TTY\n * and when the provider says the arguments are already complete.\n *\n * @example\n * await refuseMissingArguments({ provider, params: args, operation: 'env-load', argument: 'config' })\n * // agent, `config` omitted \u2192 throws { status: 'argument_required', argument: 'config', choices: {...} }\n */\nexport const refuseMissingArguments = async (input: RefuseMissingArgumentsInput): Promise<void> => {\n if (!isHeadless() || !input.provider.isFormable(input.params)) return\n\n const schema = await requestedSchema(input)\n const params =\n typeof input.params === 'object' && input.params !== null ? (input.params as Record<string, unknown>) : {}\n // A form may re-offer a field round 1 already carried (the deploy form keeps `version` editable);\n // the flag named is the first one the caller actually left out.\n const missing = (schema === null ? [] : Object.keys(schema.shape)).filter((field) => {\n return params[field] === undefined || params[field] === ''\n })\n const argument = typeof input.argument === 'string' ? input.argument : input.argument(missing)\n const choices = schema === null ? undefined : z.toJSONSchema(schema)\n\n throw new StructuredRefusalError(\n {\n status: 'argument_required',\n argument,\n ...(choices === undefined ? {} : { choices }),\n agentMode: agentMode.source,\n },\n 2,\n {\n operation: input.operation,\n remediation:\n choices === undefined\n ? `pass --${argument} on the re-run \u2014 nothing could be listed to choose from`\n : `ask the human to pick from \"choices\", then pass --${argument} on the re-run`,\n stderrExcerpt: `--${argument} was not given and there is no human to ask`,\n },\n )\n}\n"],
5
+ "mappings": "4RAAA,OAAOA,OAAY,mBACnB,OAAS,oBAAAC,OAAwB,mCACjC,OAAS,UAAAC,OAAc,cACvB,OAAOC,OAAQ,UACf,OAAOC,MAAU,YACjB,OAAOC,MAAa,eACpB,OAAS,KAAAC,M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FA,EAAS,KAAK,MAAMJ,CAAM,CAC5B,MAAQ,CACN,MAAM,IAAI,MAAM,uDAAuD,KAAK,UAAUA,EAAO,MAAM,EAAG,EAAE,CAAC,CAAC,GAAG,CAC/G,CAEA,GAAII,IAAW,MAAQ,OAAOA,GAAW,UAAY,MAAM,QAAQA,CAAM,EACvE,MAAM,IAAI,MAAM,8FAA8F,EAGhH,IAAMpF,EAAiC,CAAC,EAExC,OAAW,CAACM,EAAKC,CAAK,IAAK,OAAO,QAAQ6E,CAAM,EAAG,CACjD,GAAI,CAACD,GAAqB,KAAK7E,CAAG,EAChC,MAAM,IAAI,MACR,+DAA+D,KAAK,UAAUA,EAAI,MAAM,EAAG,EAAE,CAAC,CAAC,GACjG,EAGF,GAAI,OAAOC,GAAU,SACnB,MAAM,IAAI,UAAU,4CAA4CD,CAAG,UAAU,OAAOC,CAAK,GAAG,EAG9FP,EAAM,KAAK,CAACM,EAAKC,CAAK,CAAC,CACzB,CAEA,GAAIP,EAAM,SAAW,EACnB,MAAM,IAAI,MAAM,4CAA4C,EAG9D,OAAOA,CACT,EAGaqF,GAAiBC,EAAc,CAC1C,KAAM,WACN,YACE,+sBACF,YAAa,CACX,OAAQC,EACL,OAAO,EACP,SAAS,EACT,SACC,iHACF,CACJ,EACA,aAAcpD,GACd,aAAc,CACZ,SAAUoD,EAAE,OAAO,EAAE,SAAS,0DAA0D,EACxF,cAAeA,EAAE,OAAO,EAAE,SAAS,4BAA4B,EAC/D,QAASA,EAAE,OAAO,EAAE,SAAS,sBAAsB,EACnD,OAAQA,EAAE,OAAO,EAAE,SAAS,qBAAqB,EACjD,UAAWA,EACR,OAAO,EACP,SAAS,EACT,SAAS,sFAAsF,CACpG,EACA,QAASlD,EACX,CAAC",
6
+ "names": ["select", "readRepoIdentity", "Buffer", "fs", "path", "process", "z", "$", "PROJECT_NOT_FOUND_MARKER", "CONFIG_NOT_FOUND_MARKER", "INVALID_TOKEN_MARKER", "TOKEN_SCOPE_MARKER", "classifyDopplerFailure", "stderr", "classifyDopplerAuthFailure", "buildDopplerAuthFailureMessage", "env", "DopplerAuthError", "EnvAuthError", "authKind", "message", "buildDopplerNotFoundMessage", "kind", "project", "config", "available", "lines", "label", "$", "DOPPLER_PROBE_TIMEOUT_MS", "SCOPE_KEY", "getDopplerProject", "envManagement", "getInfraKitConfig", "probeEnvToken", "childEnv", "project", "config", "prevQuiet", "$", "scopedTo", "error", "classifyProbeFailure", "stderr", "extractStderr", "classifyDopplerFailure", "classifyDopplerAuthFailure", "process", "INFRA_KIT_ENV_TOKEN_VAR", "resolveEnvToken", "env", "fromEnv", "process", "fromStore", "readTokenStore", "EnvAuthError", "buildMissingTokenMessage", "getTokenStorePath", "storePath", "tildify", "process", "z", "process", "z", "DEFAULT_PROTECTED_ENVS", "PROTECTED_ENV_DENIED", "isProtectedEnv", "env", "SHARED_ENVS", "isSharedEnv", "deployableEnvs", "options", "access", "assertDeployable", "operation", "StructuredRefusalError", "agentMode", "OperationError", "resolveProtectedEnvAccess", "setting", "getInfraKitConfig", "PROTECTED_ENV_DENIED", "isAgentMode", "warnProtectedEnvDispatch", "args", "env", "branch", "isProtectedEnv", "logger", "fs", "path", "yaml", "WORKFLOWS_DIR", "readWorkflowEnvOptions", "workflowFile", "projectRoot", "getProjectRoot", "parseEnvOptions", "path", "listWorkflowEnvs", "workflowsDir", "entries", "fs", "workflows", "entry", "perWorkflow", "file", "workflowPath", "parsed", "yaml", "on", "pick", "options", "option", "value", "key", "listProjectEnvs", "workflowEnvs", "listWorkflowEnvs", "store", "readTokenStore", "declared", "env", "known", "tokenOnly", "listProjectEnvNames", "entry", "textContent", "text", "defineMcpTool", "tool", "buildEnvTokenStatus", "envs", "storeTokens", "envToken", "env", "source", "ENV_TABLE_HEADERS", "formatEnvTable", "rows", "cells", "row", "widths", "header", "col", "cell", "renderRow", "values", "value", "separator", "width", "envList", "project", "getDopplerProject", "listProjectEnvs", "store", "readTokenStore", "process", "INFRA_KIT_ENV_TOKEN_VAR", "tokens", "logger", "buildResult", "line", "structuredContent", "textContent", "envListMcpTool", "defineMcpTool", "z", "isRecord", "value", "orEmpty", "work", "tokenlessEnvs", "envs", "store", "readTokenStore", "buildEnvTokenStatus", "process", "INFRA_KIT_ENV_TOKEN_VAR", "status", "createEnvLoadFormProvider", "INFRA_KIT_SESSION_VAR", "params", "listProjectEnvs", "logger", "names", "env", "tokenless", "z", "content", "config", "z", "requestedSchema", "input", "error", "logger", "refuseMissingArguments", "isHeadless", "schema", "params", "missing", "field", "argument", "choices", "z", "StructuredRefusalError", "agentMode", "DOPPLER_CONFIG_KEY", "CREDENTIAL_SECRET_KEYS", "INFRA_KIT_ENV_TOKEN_VAR", "credentialFilterWarned", "warnFilteredCredentialKeys", "keys", "logger", "buildEnvLoadFileLines", "pairs", "config", "project", "projectRoot", "loadedAt", "emitted", "key", "value", "shellSingleQuote", "INFRA_KIT_ENV_VAR", "INFRA_KIT_ENV_CONFIG_VAR", "INFRA_KIT_ENV_PROJECT_VAR", "INFRA_KIT_ENV_PROJECT_ROOT_VAR", "INFRA_KIT_ENV_LOADED_AT_VAR", "resolveProjectRootSafe", "getProjectRoot", "resolveEnvLoadRoots", "cwd", "process", "path", "repoRoot", "readRepoIdentity", "WORKTREES_DIR_SUFFIX", "writeEnvLoadFile", "getDopplerProject", "downloadDopplerSecrets", "fileContents", "cacheDir", "getSessionCacheDir", "envFilePath", "ENV_LOAD_FILE", "fs", "roots", "atomicWriteFileSync", "ENV_LOAD_ROOT_FILE", "envLoadForm", "createEnvLoadFormProvider", "envLoad", "args", "refuseMissingArguments", "selectedConfig", "isAgentMode", "StructuredRefusalError", "agentMode", "envs", "listProjectEnvNames", "commandEcho", "withEscape", "context", "select", "env", "result", "structuredContent", "INFRA_KIT_SESSION_VAR", "textContent", "DOPPLER_MAX_OUTPUT_BYTES", "DOPPLER_DOWNLOAD_TIMEOUT_MS", "INHERITED_DOPPLER_VARS", "buildDopplerChildEnv", "token", "baseEnv", "childEnv", "name", "downloadEnvSecrets", "resolveEnvToken", "prevQuiet", "$", "error", "translateDopplerDownloadError", "assertDopplerOutputSize", "parseDopplerSecretsJson", "assertTokenScope", "actual", "DopplerAuthError", "stderr", "extractStderr", "kind", "classifyDopplerFailure", "classifyDopplerAuthFailure", "buildDopplerNotFoundMessage", "stdout", "bytes", "Buffer", "ENV_VAR_NAME_PATTERN", "parsed", "envLoadMcpTool", "defineMcpTool", "z"]
7
+ }
@@ -0,0 +1,5 @@
1
+ import _ from"node:fs";import V from"node:os";import E from"node:path";import p from"node:process";var h="env-load.sh",O="env-clear.sh",S="env-load.root",A="INFRA_KIT_SESSION",f=".infra-kit",d="INFRA_KIT_ENV",v="INFRA_KIT_ENV_CONFIG",x="INFRA_KIT_ENV_PROJECT",K="INFRA_KIT_ENV_PROJECT_ROOT",C="INFRA_KIT_ENV_LOADED_AT",T=/^([A-Z_]\w*)=/i,D=/^unset ([A-Z_]\w*)$/i,a=(t,e)=>{let r=e;for(let n=0;n<t.length;n++){if(!r&&t[n]==="\\"){n++;continue}t[n]==="'"&&(r=!r)}return r},L=t=>{let e=t.startsWith("'")?t.slice(1):t;return(e.endsWith("'")?e.slice(0,-1):e).split("'\\''").join("'")},l=t=>{try{return _.readFileSync(t,"utf-8")}catch{return""}},F=(t,e,r)=>{let n=t.split(`
2
+ `).map(o=>o.endsWith("\r")?o.slice(0,-1):o),s=0,i=!1;for(;s<n.length;){let o=n[s];if(i){i=a(o,i),s+=1;continue}let I=T.exec(o);if(!I){let c=D.exec(o);c&&r?.(c[1]),i=a(o,!1),s+=1;continue}let g=I[1],R=o.slice(I[0].length);if(!R.startsWith("'")){e({name:g,value:R}),i=a(o,!1),s+=1;continue}let u=[R],N=a(R,!1);for(;N&&s+1<n.length;){s+=1;let c=n[s];u.push(c),N=a(c,!0)}e({name:g,value:L(u.join(`
3
+ `))}),i=N,s+=1}},y=t=>{let e=[];return F(l(t),({name:r})=>{e.push(r)}),e},W=t=>{let e={};return F(l(t),({name:r,value:n})=>{e[r]=n}),e},w=t=>{let e=[];return F(l(t),()=>{},r=>{e.push(r)}),e},m=()=>{let t=p.env.XDG_CACHE_HOME,e=t&&t.length>0?t:E.join(V.homedir(),".cache");return E.join(e,"infra-kit")},P=()=>{let t=p.env[A];if(!t)throw new Error(`${A} is not set. Run \`infra-kit setup --skip-tools\` then \`source ~/.zshrc\`.`);return E.join(m(),t)},U=(t,e,r)=>{let n=`${t}.tmp.${p.pid}`;_.writeFileSync(n,e,{mode:r});try{_.renameSync(n,t)}catch(s){throw _.rmSync(n,{force:!0}),s}},b="-worktrees",G=(t,e)=>{let r;try{r=_.readFileSync(t,"utf-8")}catch{return!0}let n=J(e);return r.split(`
4
+ `).filter(Boolean).some(s=>n===s||n.startsWith(`${s}${E.sep}`))},J=t=>{try{return _.realpathSync(t)}catch{return E.resolve(t)}},$={release:"release",feature:"feature",mergeDev:"merge-dev"};export{h as a,O as b,S as c,A as d,f as e,d as f,v as g,x as h,K as i,C as j,y as k,W as l,w as m,m as n,P as o,U as p,b as q,G as r,$ as s};
5
+ //# sourceMappingURL=chunk-I23MDR4X.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/constants/constants.ts"],
4
+ "sourcesContent": ["import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nexport const ENV_LOAD_FILE = 'env-load.sh'\nexport const ENV_CLEAR_FILE = 'env-clear.sh'\n/**\n * Sidecar of `env-load.sh`: the directories, one per line, the loaded env belongs to. The session is\n * per terminal, not per repo, so without it a shell or agent in repo A sourced repo B's env.\n */\nexport const ENV_LOAD_ROOT_FILE = 'env-load.root'\n\nexport const INFRA_KIT_SESSION_VAR = 'INFRA_KIT_SESSION'\n/**\n * Directory under the user's home that holds all machine-local infra-kit config:\n * the runtime `infra-kit.json` merge layer, per-project overrides, the factory\n * registry (`vendor.json`), and the `portless` package link. Single source of\n * truth for `.infra-kit`.\n *\n * Defined HERE, not in `lib/infra-kit-config`, because that module pulls in zod\n * and the `ik-mcp` proxy bundle must stay Node-builtins-only (guarded in\n * `entry/__tests__/dist-shebang.test.ts`); `lib/infra-kit-config` re-exports it\n * for its existing consumers.\n */\nexport const USER_CONFIG_DIR_NAME = '.infra-kit'\n/**\n * The active environment/config NAME (e.g. `dev`, `arthur`), exported plainly so\n * non-shell consumers can read it from `process.env`. Notably `infra-kit/vite`'s\n * `infraKitDev()` reads this to interpolate the `<env>` placeholder in cloud proxy\n * targets. Mirrors {@link INFRA_KIT_ENV_CONFIG_VAR} (same value) but is the stable,\n * purpose-named handle for tooling rather than the shell session-metadata var.\n */\nexport const INFRA_KIT_ENV_VAR = 'INFRA_KIT_ENV'\nexport const INFRA_KIT_ENV_CONFIG_VAR = 'INFRA_KIT_ENV_CONFIG'\nexport const INFRA_KIT_ENV_PROJECT_VAR = 'INFRA_KIT_ENV_PROJECT'\n/**\n * Absolute project root (git top-level) the loaded env belongs to, so a shell can\n * tell whose secrets it is carrying after a `cd` into another project.\n */\nexport const INFRA_KIT_ENV_PROJECT_ROOT_VAR = 'INFRA_KIT_ENV_PROJECT_ROOT'\nexport const INFRA_KIT_ENV_LOADED_AT_VAR = 'INFRA_KIT_ENV_LOADED_AT'\n\n/**\n * Matches a line of the form `KEY=...` where KEY is an env-var identifier\n * (letter or underscore, then word chars). Capture group 1 is the name. Shared\n * between env-load (validation, var counting) and parseVarNamesFromEnvFile.\n */\nexport const ENV_VAR_LINE_PATTERN = /^([A-Z_]\\w*)=/i\n\n/**\n * The `unset NAME` line env-clear.sh is made of. Anchored at both ends so a value that merely\n * starts with the word is not a match.\n */\nconst UNSET_LINE_PATTERN = /^unset ([A-Z_]\\w*)$/i\n\n/**\n * Track whether a physical line leaves us inside an open single-quoted value,\n * mirroring how `shellSingleQuote` emits values (`'\u2026'`, with literal quotes as\n * `'\\''`). Outside a quote a backslash escapes the next char; inside a quote a\n * `'` closes it. Lets the parser skip the continuation lines of a multiline value.\n */\nconst advanceSingleQuoteState = (line: string, startInQuote: boolean): boolean => {\n let inQuote = startInQuote\n\n for (let i = 0; i < line.length; i++) {\n if (!inQuote && line[i] === '\\\\') {\n i++\n continue\n }\n\n if (line[i] === \"'\") {\n inQuote = !inQuote\n }\n }\n\n return inQuote\n}\n\n/** One `KEY=value` assignment recovered from an env file, value already unescaped. */\nexport interface EnvAssignment {\n name: string\n value: string\n}\n\n/**\n * Undo {@link shellSingleQuote}: drop the wrapping quotes, then turn each `'\\''`\n * back into a literal `'`. Order matters \u2014 unescaping first would let an embedded\n * `'\\''` be mistaken for the closing quote.\n */\nconst decodeSingleQuoted = (raw: string): string => {\n const withoutOpen = raw.startsWith(\"'\") ? raw.slice(1) : raw\n const body = withoutOpen.endsWith(\"'\") ? withoutOpen.slice(0, -1) : withoutOpen\n\n return body.split(\"'\\\\''\").join(\"'\")\n}\n\n/** File contents, or '' when the path is absent, a directory, or unreadable. */\nconst readEnvFileContent = (filePath: string): string => {\n try {\n return fs.readFileSync(filePath, 'utf-8')\n } catch {\n return ''\n }\n}\n\n/**\n * Walk every assignment in an env-load.sh body, skipping the continuation lines of\n * multiline values. {@link parseVarNamesFromEnvFile}, {@link parseVarsFromEnvFile}\n * and {@link parseUnsetNamesFromEnvFile} all go through here, so they can never\n * disagree about where a value ends \u2014 an `unset X` inside a quoted value is a\n * continuation line to every one of them.\n */\nconst forEachAssignment = (\n content: string,\n visit: (assignment: EnvAssignment) => void,\n visitUnset?: (name: string) => void,\n): void => {\n // A trailing CR is stripped per line: a CRLF file would otherwise hand back values\n // ending in '\\r' \u2014 a token that looks right in a diff and fails every request.\n const lines = content.split('\\n').map((line) => {\n return line.endsWith('\\r') ? line.slice(0, -1) : line\n })\n let index = 0\n let inQuote = false\n\n while (index < lines.length) {\n const line = lines[index]!\n\n // Only a line that starts OUTSIDE a quoted value can be a real assignment;\n // continuation lines of a multiline secret value are skipped.\n if (inQuote) {\n inQuote = advanceSingleQuoteState(line, inQuote)\n index += 1\n continue\n }\n\n const match = ENV_VAR_LINE_PATTERN.exec(line)\n\n if (!match) {\n const unset = UNSET_LINE_PATTERN.exec(line)\n\n if (unset) visitUnset?.(unset[1]!)\n\n inQuote = advanceSingleQuoteState(line, false)\n index += 1\n continue\n }\n\n const name = match[1]!\n const rest = line.slice(match[0].length)\n\n // An unquoted value cannot span lines (`CONNECTION_STRING=host=db;user=admin`).\n if (!rest.startsWith(\"'\")) {\n visit({ name, value: rest })\n inQuote = advanceSingleQuoteState(line, false)\n index += 1\n continue\n }\n\n const parts = [rest]\n let open = advanceSingleQuoteState(rest, false)\n\n while (open && index + 1 < lines.length) {\n index += 1\n const continuation = lines[index]!\n\n parts.push(continuation)\n open = advanceSingleQuoteState(continuation, true)\n }\n\n visit({ name, value: decodeSingleQuoted(parts.join('\\n')) })\n inQuote = open\n index += 1\n }\n}\n\nexport const parseVarNamesFromEnvFile = (filePath: string): string[] => {\n const names: string[] = []\n\n forEachAssignment(readEnvFileContent(filePath), ({ name }) => {\n names.push(name)\n })\n\n return names\n}\n\n/**\n * Same walk as {@link parseVarNamesFromEnvFile}, but keeping the values. Later\n * assignments win, matching what `source`ing the file would do.\n */\nexport const parseVarsFromEnvFile = (filePath: string): Record<string, string> => {\n const vars: Record<string, string> = {}\n\n forEachAssignment(readEnvFileContent(filePath), ({ name, value }) => {\n vars[name] = value\n })\n\n return vars\n}\n\n/**\n * The names the file `unset`s \u2014 everything env-clear.sh does. Absent file \u2192 `[]`, like\n * its siblings.\n */\nexport const parseUnsetNamesFromEnvFile = (filePath: string): string[] => {\n const names: string[] = []\n\n forEachAssignment(\n readEnvFileContent(filePath),\n () => {},\n (name) => {\n names.push(name)\n },\n )\n\n return names\n}\n\n/**\n * Root cache dir for infra-kit across all sessions. Resolved from\n * $XDG_CACHE_HOME when set, falling back to ~/.cache/infra-kit. Keep in sync\n * with the shell block emitted by `infra-kit setup` (src/commands/init/init.ts).\n */\nexport const getCacheRoot = (): string => {\n const xdg = process.env.XDG_CACHE_HOME\n const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), '.cache')\n\n return path.join(base, 'infra-kit')\n}\n\nexport const getSessionCacheDir = (): string => {\n const session = process.env[INFRA_KIT_SESSION_VAR]\n\n if (!session) {\n throw new Error(\n `${INFRA_KIT_SESSION_VAR} is not set. Run \\`infra-kit setup --skip-tools\\` then \\`source ~/.zshrc\\`.`,\n )\n }\n\n return path.join(getCacheRoot(), session)\n}\n\n/**\n * Write content atomically: write to a pid-suffixed temp file in the same\n * directory, then rename. fs.renameSync is atomic on a single filesystem, so\n * concurrent writers can't produce a half-written secret file.\n */\nexport const atomicWriteFileSync = (filePath: string, content: string, mode: number): void => {\n const tmpPath = `${filePath}.tmp.${process.pid}`\n\n fs.writeFileSync(tmpPath, content, { mode })\n\n try {\n fs.renameSync(tmpPath, filePath)\n } catch (error) {\n fs.rmSync(tmpPath, { force: true })\n throw error\n }\n}\n\nexport const WORKTREES_DIR_SUFFIX = '-worktrees'\n\n/**\n * Whether `cwd` is one of the directories in an {@link ENV_LOAD_ROOT_FILE}, or under one. Mirrors the\n * `~/.zshenv` check in `init.ts`, symlinks resolved on both sides. No sidecar is in scope everywhere:\n * that is an `env-load.sh` written before the sidecar existed, and it stays usable until the next load.\n */\nexport const isInEnvLoadScope = (rootFile: string, cwd: string): boolean => {\n let content: string\n\n try {\n content = fs.readFileSync(rootFile, 'utf-8')\n } catch {\n return true\n }\n\n const realCwd = safeRealpath(cwd)\n\n return content\n .split('\\n')\n .filter(Boolean)\n .some((root) => {\n return realCwd === root || realCwd.startsWith(`${root}${path.sep}`)\n })\n}\n\nconst safeRealpath = (target: string): string => {\n try {\n return fs.realpathSync(target)\n } catch {\n return path.resolve(target)\n }\n}\n\n/**\n * Canonical `<repo>-worktrees` subdirectory names, shared by every command that lays worktrees\n * out under it (`init`'s scaffold, `worktrees add`) or reasons about that layout (`worktrees\n * sync`/`remove`, `gh merge-dev`'s scratch checkout) \u2014 one literal each, not re-typed per site.\n */\nexport const WORKTREE_SUBDIRS = { release: 'release', feature: 'feature', merge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QAAQ2D,CAAM,CAC5B,CACF,EAOaC,EAAmB,CAAE,QAAS,UAAW,QAAS,UAAW,SAAU,WAAY",
6
+ "names": ["fs", "os", "path", "process", "ENV_LOAD_FILE", "ENV_CLEAR_FILE", "ENV_LOAD_ROOT_FILE", "INFRA_KIT_SESSION_VAR", "USER_CONFIG_DIR_NAME", "INFRA_KIT_ENV_VAR", "INFRA_KIT_ENV_CONFIG_VAR", "INFRA_KIT_ENV_PROJECT_VAR", "INFRA_KIT_ENV_PROJECT_ROOT_VAR", "INFRA_KIT_ENV_LOADED_AT_VAR", "ENV_VAR_LINE_PATTERN", "UNSET_LINE_PATTERN", "advanceSingleQuoteState", "line", "startInQuote", "inQuote", "i", "decodeSingleQuoted", "raw", "withoutOpen", "readEnvFileContent", "filePath", "forEachAssignment", "content", "visit", "visitUnset", "lines", "index", "match", "unset", "name", "rest", "parts", "open", "continuation", "parseVarNamesFromEnvFile", "names", "parseVarsFromEnvFile", "vars", "value", "parseUnsetNamesFromEnvFile", "getCacheRoot", "xdg", "base", "getSessionCacheDir", "session", "atomicWriteFileSync", "mode", "tmpPath", "error", "WORKTREES_DIR_SUFFIX", "isInEnvLoadScope", "rootFile", "cwd", "realCwd", "safeRealpath", "root", "target", "WORKTREE_SUBDIRS"]
7
+ }
@@ -1,3 +1,3 @@
1
- import{j as C,m as O,n as D}from"./chunk-AWFGP6GY.js";import{d as S}from"./chunk-QSTGO43H.js";import k from"node:fs";import{homedir as Te}from"node:os";import{dirname as _,join as W}from"node:path";import d from"node:process";import{fileURLToPath as Fe}from"node:url";import{execFile as re}from"node:child_process";import{createHash as ne}from"node:crypto";import{existsSync as F,readFileSync as h}from"node:fs";import oe from"node:http";import se from"node:https";import ie from"node:net";import{homedir as le}from"node:os";import{dirname as N,join as p}from"node:path";import f from"node:process";import ae from"node:tls";import{fileURLToPath as ce}from"node:url";import{promisify as ue}from"node:util";var ee=/^[\w@%+=:,./-]+$/,te="'\\''",T=e=>ee.test(e)?e:`'${e.replaceAll("'",te)}'`,x=e=>e.map(T).join(" ");var de=ue(re),me=e=>{let t=JSON.parse(h(e,"utf-8")),r=typeof t.bin=="string"?t.bin:t.bin?.portless;return r==null||r===""?null:r},E=()=>{try{let e=N(ce(import.meta.url));for(;;){let t=p(e,"node_modules","portless","package.json");if(F(t)){let n=me(t);return n==null?null:p(N(t),n)}let r=N(e);if(r===e)return null;e=r}}catch{return null}},v,M=()=>(v===void 0&&(v=E()),v),U=(e,t)=>{let r=[t.execPath??f.execPath,t.bin,...e];return(t.sudo===!0?"sudo ":"")+x(r)},pe=1500,L=1500,fe="x-portless",I="127.0.0.1",ge="localhost",Pe="sh.portless.proxy",he=`/Library/LaunchDaemons/${Pe}.plist`,ye="/etc/systemd/system/portless.service",it="portless",Se=(e=F)=>{try{return f.platform==="darwin"?e(he)?"yes":"no":f.platform==="linux"?e(ye)?"yes":"no":"unknown"}catch{return"unknown"}},ke=e=>new Promise(t=>{let r=ie.connect({host:I,port:e}),n=o=>{r.destroy(),t(o)};r.setTimeout(L),r.once("connect",()=>{n(!0)}),r.once("timeout",()=>{n(!1)}),r.once("error",()=>{n(!1)})}),be=(e,t)=>new Promise(r=>{let o=(t?se.request:oe.request)({host:I,port:e,method:"HEAD",path:"/",timeout:L,...t?{rejectUnauthorized:!1,servername:ge}:{}},s=>{s.resume(),r(s.headers[fe]==="1")});o.on("error",()=>{r(!1)}),o.on("timeout",()=>{o.destroy(),r(!1)}),o.end()}),xe=async(e,{timeoutMs:t})=>{let r=M();if(r==null)throw new Error("portless is not installed (not resolvable from node_modules)");await de(f.execPath,[r,...e],{signal:AbortSignal.timeout(t),encoding:"utf-8",env:D(f.env)})},w=()=>f.env.PORTLESS_STATE_DIR??p(le(),".portless"),Ne="ca.pem",ve="ca.trusted",B=()=>p(w(),Ne),lt=()=>{try{let e=h(p(w(),ve),"utf-8").trim();return e===""?!1:ne("sha256").update(h(B())).digest("hex")===e.toLowerCase()}catch{return!1}},at=(e,t)=>new Promise(r=>{let n;try{n=h(B())}catch{r({ok:!1,code:"ENOENT"});return}let o=ae.connect({host:I,port:e,servername:t,ca:[n],rejectUnauthorized:!0},()=>{let s=o.authorizationError,i=o.authorized;o.destroy(),r(i?{ok:!0}:{ok:!1,code:s?.code??s?.message??"UNKNOWN"})});o.setTimeout(L),o.once("timeout",()=>{o.destroy(),r({ok:!1,code:"ETIMEDOUT"})}),o.once("error",s=>{o.destroy(),r({ok:!1,code:s.code??"UNKNOWN"})})}),ct=()=>{try{let e=JSON.parse(h(p(w(),"routes.json"),"utf-8"));return Array.isArray(e)?e.flatMap(t=>{let{hostname:r,port:n}=t??{};return typeof r!="string"||r===""||typeof n!="number"?[]:[{name:r,port:n}]}):[]}catch{return[]}},ut=(e={})=>{let t=e.bin===void 0?M():e.bin,r=e.run??xe,n=e.isListening??ke,o=e.isProxyServing??be,s=e.isServiceInstalled??Se,i=e.timeoutMs??pe,a=null,l=async u=>{try{return await r(u,{timeoutMs:i}),!0}catch{return!1}},c=async()=>(a??=await l(["--version"]),a);return{binPath:()=>t,isAvailable:c,isProxyServing:async(u,P)=>!await c()||!await n(u)?!1:o(u,P),probeProxy:async(u,P)=>await n(u)?await o(u,P)?"serving":"not-portless":"daemon-down",isServiceInstalled:s,registerAlias:async(u,P)=>await c()?l(["alias",u,String(P)]):!1,removeAlias:async u=>{await c()&&await l(["alias","--remove",u])}}};import y from"node:fs";import{basename as z,dirname as $,join as j}from"node:path";import G from"node:process";var R=e=>j(e,S,"node"),H=e=>`${R(e)}.source.json`,Ee=e=>{if(typeof e!="object"||e===null)return!1;let t=e,r=["version","arch","platform","source","refreshedAt","versionChangedAt"];return(t.method==="hardlink"||t.method==="copy")&&r.every(n=>typeof t[n]=="string")&&(t.sourceSize===void 0||typeof t.sourceSize=="number")},Le=y.constants.COPYFILE_FICLONE|y.constants.COPYFILE_EXCL,Ie=493,we=(e,t=y)=>{try{let r=JSON.parse(t.readFileSync(H(e),"utf8"));return Ee(r)?r:null}catch{return null}},J=(e,t)=>e.ino===t.ino&&e.dev===t.dev,K=e=>{let{home:t,execPath:r,fs:n=y}=e,o=R(t);try{let s=n.lstatSync(o,{throwIfNoEntry:!1}),i=n.statSync(r,{throwIfNoEntry:!1});return s===void 0||i===void 0||!s.isFile()?null:J(s,i)?o:null}catch{return null}},Y=(e,t)=>e.version===t.version&&e.arch===t.arch&&e.platform===t.platform,Re=(e,t,r,n)=>Y(r,n)?J(e,t)?!0:r.method==="copy"&&r.sourceSize===t.size:!1,A=(e,t)=>{try{t.unlinkSync(e)}catch{}},Ae=(e,t,r)=>{let n;try{n=r.readdirSync(e)}catch{return}for(let o of n)t.some(i=>o.startsWith(i))&&A(j(e,o),r)},_e=(e,t,r)=>{try{return r.linkSync(e,t),"hardlink"}catch{return r.copyFileSync(e,t,Le),r.chmodSync(t,Ie),"copy"}},Ce=(e,t,r)=>{let n=`${t}.tmp-${G.pid}`;try{let o=_e(e,n,r);return r.renameSync(n,t),o}catch(o){throw A(n,r),o}},Oe=(e,t,r)=>{let n=`${e}.tmp-${G.pid}`;try{r.writeFileSync(n,`${JSON.stringify(t,null,2)}
1
+ import{j as C,m as O,n as D}from"./chunk-AWFGP6GY.js";import{e as S}from"./chunk-I23MDR4X.js";import k from"node:fs";import{homedir as Te}from"node:os";import{dirname as _,join as W}from"node:path";import d from"node:process";import{fileURLToPath as Fe}from"node:url";import{execFile as re}from"node:child_process";import{createHash as ne}from"node:crypto";import{existsSync as F,readFileSync as h}from"node:fs";import oe from"node:http";import se from"node:https";import ie from"node:net";import{homedir as le}from"node:os";import{dirname as N,join as p}from"node:path";import f from"node:process";import ae from"node:tls";import{fileURLToPath as ce}from"node:url";import{promisify as ue}from"node:util";var ee=/^[\w@%+=:,./-]+$/,te="'\\''",T=e=>ee.test(e)?e:`'${e.replaceAll("'",te)}'`,x=e=>e.map(T).join(" ");var de=ue(re),me=e=>{let t=JSON.parse(h(e,"utf-8")),r=typeof t.bin=="string"?t.bin:t.bin?.portless;return r==null||r===""?null:r},E=()=>{try{let e=N(ce(import.meta.url));for(;;){let t=p(e,"node_modules","portless","package.json");if(F(t)){let n=me(t);return n==null?null:p(N(t),n)}let r=N(e);if(r===e)return null;e=r}}catch{return null}},v,M=()=>(v===void 0&&(v=E()),v),U=(e,t)=>{let r=[t.execPath??f.execPath,t.bin,...e];return(t.sudo===!0?"sudo ":"")+x(r)},pe=1500,L=1500,fe="x-portless",I="127.0.0.1",ge="localhost",Pe="sh.portless.proxy",he=`/Library/LaunchDaemons/${Pe}.plist`,ye="/etc/systemd/system/portless.service",it="portless",Se=(e=F)=>{try{return f.platform==="darwin"?e(he)?"yes":"no":f.platform==="linux"?e(ye)?"yes":"no":"unknown"}catch{return"unknown"}},ke=e=>new Promise(t=>{let r=ie.connect({host:I,port:e}),n=o=>{r.destroy(),t(o)};r.setTimeout(L),r.once("connect",()=>{n(!0)}),r.once("timeout",()=>{n(!1)}),r.once("error",()=>{n(!1)})}),be=(e,t)=>new Promise(r=>{let o=(t?se.request:oe.request)({host:I,port:e,method:"HEAD",path:"/",timeout:L,...t?{rejectUnauthorized:!1,servername:ge}:{}},s=>{s.resume(),r(s.headers[fe]==="1")});o.on("error",()=>{r(!1)}),o.on("timeout",()=>{o.destroy(),r(!1)}),o.end()}),xe=async(e,{timeoutMs:t})=>{let r=M();if(r==null)throw new Error("portless is not installed (not resolvable from node_modules)");await de(f.execPath,[r,...e],{signal:AbortSignal.timeout(t),encoding:"utf-8",env:D(f.env)})},w=()=>f.env.PORTLESS_STATE_DIR??p(le(),".portless"),Ne="ca.pem",ve="ca.trusted",B=()=>p(w(),Ne),lt=()=>{try{let e=h(p(w(),ve),"utf-8").trim();return e===""?!1:ne("sha256").update(h(B())).digest("hex")===e.toLowerCase()}catch{return!1}},at=(e,t)=>new Promise(r=>{let n;try{n=h(B())}catch{r({ok:!1,code:"ENOENT"});return}let o=ae.connect({host:I,port:e,servername:t,ca:[n],rejectUnauthorized:!0},()=>{let s=o.authorizationError,i=o.authorized;o.destroy(),r(i?{ok:!0}:{ok:!1,code:s?.code??s?.message??"UNKNOWN"})});o.setTimeout(L),o.once("timeout",()=>{o.destroy(),r({ok:!1,code:"ETIMEDOUT"})}),o.once("error",s=>{o.destroy(),r({ok:!1,code:s.code??"UNKNOWN"})})}),ct=()=>{try{let e=JSON.parse(h(p(w(),"routes.json"),"utf-8"));return Array.isArray(e)?e.flatMap(t=>{let{hostname:r,port:n}=t??{};return typeof r!="string"||r===""||typeof n!="number"?[]:[{name:r,port:n}]}):[]}catch{return[]}},ut=(e={})=>{let t=e.bin===void 0?M():e.bin,r=e.run??xe,n=e.isListening??ke,o=e.isProxyServing??be,s=e.isServiceInstalled??Se,i=e.timeoutMs??pe,a=null,l=async u=>{try{return await r(u,{timeoutMs:i}),!0}catch{return!1}},c=async()=>(a??=await l(["--version"]),a);return{binPath:()=>t,isAvailable:c,isProxyServing:async(u,P)=>!await c()||!await n(u)?!1:o(u,P),probeProxy:async(u,P)=>await n(u)?await o(u,P)?"serving":"not-portless":"daemon-down",isServiceInstalled:s,registerAlias:async(u,P)=>await c()?l(["alias",u,String(P)]):!1,removeAlias:async u=>{await c()&&await l(["alias","--remove",u])}}};import y from"node:fs";import{basename as z,dirname as $,join as j}from"node:path";import G from"node:process";var R=e=>j(e,S,"node"),H=e=>`${R(e)}.source.json`,Ee=e=>{if(typeof e!="object"||e===null)return!1;let t=e,r=["version","arch","platform","source","refreshedAt","versionChangedAt"];return(t.method==="hardlink"||t.method==="copy")&&r.every(n=>typeof t[n]=="string")&&(t.sourceSize===void 0||typeof t.sourceSize=="number")},Le=y.constants.COPYFILE_FICLONE|y.constants.COPYFILE_EXCL,Ie=493,we=(e,t=y)=>{try{let r=JSON.parse(t.readFileSync(H(e),"utf8"));return Ee(r)?r:null}catch{return null}},J=(e,t)=>e.ino===t.ino&&e.dev===t.dev,K=e=>{let{home:t,execPath:r,fs:n=y}=e,o=R(t);try{let s=n.lstatSync(o,{throwIfNoEntry:!1}),i=n.statSync(r,{throwIfNoEntry:!1});return s===void 0||i===void 0||!s.isFile()?null:J(s,i)?o:null}catch{return null}},Y=(e,t)=>e.version===t.version&&e.arch===t.arch&&e.platform===t.platform,Re=(e,t,r,n)=>Y(r,n)?J(e,t)?!0:r.method==="copy"&&r.sourceSize===t.size:!1,A=(e,t)=>{try{t.unlinkSync(e)}catch{}},Ae=(e,t,r)=>{let n;try{n=r.readdirSync(e)}catch{return}for(let o of n)t.some(i=>o.startsWith(i))&&A(j(e,o),r)},_e=(e,t,r)=>{try{return r.linkSync(e,t),"hardlink"}catch{return r.copyFileSync(e,t,Le),r.chmodSync(t,Ie),"copy"}},Ce=(e,t,r)=>{let n=`${t}.tmp-${G.pid}`;try{let o=_e(e,n,r);return r.renameSync(n,t),o}catch(o){throw A(n,r),o}},Oe=(e,t,r)=>{let n=`${e}.tmp-${G.pid}`;try{r.writeFileSync(n,`${JSON.stringify(t,null,2)}
2
2
  `),r.renameSync(n,e)}catch(o){throw A(n,r),o}},De=(e,t,r,n,o)=>{let s=e!==null&&Y(e,n)&&(e.sourceSize===void 0||e.sourceSize===r.size);return{method:t,version:n.version,arch:n.arch,platform:n.platform,source:n.execPath,...t==="copy"?{sourceSize:r.size}:{},refreshedAt:o,versionChangedAt:s?e.versionChangedAt:o}},q=e=>{let{home:t,execPath:r,version:n,fs:o=y,now:s=()=>new Date}=e,i=R(t),a=H(t),l=(c,m)=>({kind:"node",outcome:c,node:i,source:r,version:n,method:m});if(e.platform!=="darwin"&&e.platform!=="linux")return l("skipped-platform",null);if(!e.isGlobal())return l("skipped-local",null);try{o.mkdirSync($(i),{recursive:!0});let c=o.lstatSync(i,{throwIfNoEntry:!1});if(c!==void 0&&!c.isFile())return l("failed",null);let m=o.statSync(r,{throwIfNoEntry:!1});if(m===void 0)return l("failed",null);let g=we(t,o);if(c!==void 0&&g!==null&&Re(c,m,g,e))return l("unchanged",g.method);Ae($(i),[`${z(i)}.tmp-`,`${z(a)}.tmp-`],o);let b=Ce(r,i,o);return Oe(a,De(g,b,m,e,s().toISOString()),o),l(c===void 0?"created":"refreshed",b)}catch{return l("failed",null)}};var Q=e=>W(e,S,"portless"),Me=(e,t=k.existsSync)=>{let r=W(Q(e),"dist","cli.js");return t(r)?r:null},Lt=(e,t)=>{let r=t.execPath??d.execPath,n=t.stableNode===void 0?K({home:t.home,execPath:r}):t.stableNode;return U(["service","install"],{sudo:!0,bin:Me(t.home,t.exists)??e,execPath:n??r})},X=Symbol("absent"),Z=Symbol("not-a-symlink"),Ue=(e,t)=>{let r=t.lstatSync(e,{throwIfNoEntry:!1});return r===void 0?X:r.isSymbolicLink()?t.readlinkSync(e):Z},Be=(e,t,r)=>{let n=`${t}.tmp-${d.pid}`;try{r.unlinkSync(n)}catch{}r.symlinkSync(e,n);try{r.renameSync(n,t)}catch(o){try{r.unlinkSync(n)}catch{}throw o}},ze=e=>{let{resolveBin:t,isGlobal:r,home:n,fs:o=k}=e,s=Q(n),i=t();if(i===null)return{kind:"link",outcome:"skipped-unresolved",target:null,link:s};let a=_(_(i));if(!r())return{kind:"link",outcome:"skipped-local",target:a,link:s};try{o.mkdirSync(_(s),{recursive:!0});let l=Ue(s,o);return l===a?{kind:"link",outcome:"unchanged",target:a,link:s}:l===Z?{kind:"link",outcome:"failed",target:a,link:s}:(Be(a,s,o),{kind:"link",outcome:l===X?"created":"repointed",target:a,link:s})}catch{return{kind:"link",outcome:"failed",target:a,link:s}}},$e=()=>{let e=Te(),t,r=()=>(t??=C({selfRealPath:k.realpathSync(Fe(import.meta.url)),env:d.env,realpath:O,home:e,exists:k.existsSync}),t);return{link:{resolveBin:E,isGlobal:r,home:e},node:{isGlobal:r,home:e,execPath:d.execPath,version:d.version,arch:d.arch,platform:d.platform}}},V=(e,t,r)=>{try{e(r(),t)}catch{}},It=(e,t)=>{let r=t??$e();V(e,"portless link",()=>ze(r.link)),V(e,"portless node",()=>q(r.node))};export{x as a,E as b,U as c,Pe as d,he as e,ye as f,it as g,ke as h,be as i,w as j,B as k,lt as l,at as m,ct as n,ut as o,R as p,we as q,q as r,Q as s,Me as t,Lt as u,ze as v,$e as w,It as x};
3
- //# sourceMappingURL=chunk-CMF7HEVU.js.map
3
+ //# sourceMappingURL=chunk-IT6XJWTW.js.map