infra-kit 0.14.0 → 0.15.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-MFHYIQ7B.js → chunk-3UE375II.js} +2 -2
  2. package/dist/{chunk-MFHYIQ7B.js.map → chunk-3UE375II.js.map} +1 -1
  3. package/dist/chunk-4RZM53X7.js +7 -0
  4. package/dist/{chunk-DW2SQ2XU.js.map → chunk-4RZM53X7.js.map} +3 -3
  5. package/dist/{chunk-VDBJ73LS.js → chunk-DVXTZPQ5.js} +1 -1
  6. package/dist/chunk-DVXTZPQ5.js.map +7 -0
  7. package/dist/{chunk-FRBNA6VH.js → chunk-EZ4DIT5A.js} +3 -3
  8. package/dist/{chunk-FRBNA6VH.js.map → chunk-EZ4DIT5A.js.map} +1 -1
  9. package/dist/chunk-I23MDR4X.js +5 -0
  10. package/dist/chunk-I23MDR4X.js.map +7 -0
  11. package/dist/{chunk-CMF7HEVU.js → chunk-IT6XJWTW.js} +2 -2
  12. package/dist/chunk-IT6XJWTW.js.map +7 -0
  13. package/dist/{chunk-BQPSXIH2.js → chunk-MH37P7W4.js} +2 -2
  14. package/dist/chunk-PP3ZZKB3.js +12 -0
  15. package/dist/chunk-PP3ZZKB3.js.map +7 -0
  16. package/dist/{chunk-EAUGQ3ZU.js → chunk-ZTAUGYJF.js} +2 -2
  17. package/dist/cli.js +117 -109
  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-6PLC5YEW.js} +2 -2
  22. package/dist/env-load-NURS7WNH.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 +5 -2
  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-ZTAUGYJF.js.map} +0 -0
  39. /package/dist/{dev-wizard-run-3DNKOVPD.js.map → dev-wizard-run-6PLC5YEW.js.map} +0 -0
  40. /package/dist/{env-load-MF26WMDL.js.map → env-load-NURS7WNH.js.map} +0 -0
  41. /package/dist/{persistent-ink-dev-ui-P65EJCC6.js.map → persistent-ink-dev-ui-ZSOS3CF4.js.map} +0 -0
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/dev/proxy/portless-link.ts", "../src/dev/proxy/portless-driver.ts", "../src/lib/shell-quote/shell-quote.ts", "../src/dev/proxy/portless-node.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview\n *\n * `~/.infra-kit/portless` \u2014 a stable symlink to the portless PACKAGE directory bundled with the running\n * infra-kit, kept pointing at the current install by every process boot.\n *\n * Why it exists: `portless service install` bakes `process.execPath` and `process.argv[1]` verbatim into\n * the root launchd plist (`ProgramArguments`), and it offers no `--entry` flag to say otherwise. Under\n * pnpm 12 the script half of that pair is version-unstable \u2014 every `pnpm add -g infra-kit@x` mints a\n * fresh `global/v11/{pid}-{timestamp}/` project and removes the previous one, and the path also embeds\n * `infra-kit@<version>`. With silent auto-update on, the daemon's argv dangles after every release,\n * launchd cannot start it at the next boot, and the \"fix\" is another sudo. Node does NOT realpath\n * `argv[1]` (it keeps whatever string it was given) but DOES realpath `execPath`, so only the script half\n * can be made stable: point the plist at `<link>/dist/cli.js` and keep the link current.\n *\n * Why tmp + rename, never unlink first: `rename(2)` replaces a symlink atomically, so there is no\n * instant at which the path is absent. An unlink-then-symlink sequence has one \u2014 and a reboot inside it\n * leaves launchd with no script at all; `KeepAlive` retries the same dangling path forever, and `:443`\n * stays dark until a human runs `service install` again.\n *\n * Why the boot call must run on `version --json`: that is the exact invocation the background updater\n * spawns to verify a fresh install (`run-update-check.ts`, `readInstalledVersion`: `cwd = homedir()`,\n * `--json`, piped stdio). It is the FIRST process the new binary ever runs \u2014 and the one that re-points\n * the link after an auto-update, before any shell command does. So `bootPortlessLink` must not sit\n * behind `warnIfLocalInstall`'s `--json` guard, and it must not have an env opt-out: the link is state,\n * not advisory output.\n *\n * Every write is guarded by `isGlobalInstall`: a checkout or a project-local dependency never aims the\n * root daemon at itself (that would dangle the moment the worktree is removed). Nothing here spawns a\n * subprocess, touches stdout, or throws \u2014 the `ik-mcp` proxy calls it at boot with stdout carrying the\n * JSON-RPC transport, and the CLI calls it before Commander parses argv.\n */\nimport fs from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { fileURLToPath } from 'node:url'\n\nimport { USER_CONFIG_DIR_NAME } from 'src/lib/constants'\nimport { isGlobalInstall, safeRealpath } from 'src/lib/install-manager'\n\nimport { formatPortlessCommand, resolvePortlessBin } from './portless-driver'\nimport type { ExistsCheck } from './portless-driver'\nimport { ensurePortlessNode, stableNodeCandidate } from './portless-node'\nimport type { EnsurePortlessNodeDeps, PortlessNodeResult } from './portless-node'\n\n/** `<home>/.infra-kit/portless` \u2014 the link path; the same `home` seam the rest of the config layer uses. */\nexport const portlessLinkPath = (home: string): string => {\n return join(home, USER_CONFIG_DIR_NAME, 'portless')\n}\n\n/**\n * `<link>/dist/cli.js` when the link resolves to a portless with that file, else `null` \u2014 the path the\n * printed `service install` command (and the plist it writes) should carry. `exists` follows the\n * symlink, so a dangling link answers `null` and callers fall back to the real path.\n */\nexport const portlessLinkCliPath = (\n home: string,\n exists: (target: string) => boolean = fs.existsSync,\n): string | null => {\n const cliPath = join(portlessLinkPath(home), 'dist', 'cli.js')\n\n return exists(cliPath) ? cliPath : null\n}\n\n/** Where the link is looked up and which node to print; every seam is injectable so tests never read a real `~/.infra-kit`. */\nexport interface ServiceInstallSeams {\n home: string\n exists?: ExistsCheck\n execPath?: string\n /**\n * `~/.infra-kit/node` as a health verdict: a string is \"resolved and healthy \u2014 render through it\"\n * (doctor/setup after their node row), `null` is \"resolved and unhealthy or absent \u2014 render through\n * `execPath`, the node that provably runs\", `undefined` is \"not resolved\" and the inode-only candidate\n * is checked here instead (`dev`, which never spawns on its hot path).\n */\n stableNode?: string | null\n}\n\n/**\n * The one-time, out-of-band, ROOT command that installs the `:443` daemon. infra-kit never runs it \u2014 it\n * only ever prints it (principle 3: infra-kit probes and prints, it never elevates). `doctor`, `setup`\n * and `dev` all print it from here so no two surfaces can disagree about the path that ends up as root.\n *\n * Rendered THROUGH `~/.infra-kit/portless/dist/cli.js` whenever that link resolves: portless bakes the\n * script path it was invoked with into the plist, so the command printed here decides whether the root\n * daemon survives the next `pnpm add -g infra-kit` (the link is re-pointed on every boot; the version-\n * specific path is deleted). `bin` \u2014 the resolved `dist/cli.js`, never a bare `portless` (see\n * {@link formatPortlessCommand}) \u2014 is the fallback only, for a machine where nothing has created the\n * link yet.\n */\nexport const serviceInstallCommand = (bin: string, seams: ServiceInstallSeams): string => {\n // Resolved before the candidate check: `dev` passes `{ home }` only, and the candidate must never stat `undefined`.\n const execPath = seams.execPath ?? process.execPath\n // Written out rather than `??`-chained: a `null` verdict (\"resolved, unhealthy\") must reach `execPath`\n // directly and never fall through to a candidate check that would contradict doctor's spawn.\n const stableNode =\n seams.stableNode === undefined ? stableNodeCandidate({ home: seams.home, execPath }) : seams.stableNode\n\n return formatPortlessCommand(['service', 'install'], {\n sudo: true,\n bin: portlessLinkCliPath(seams.home, seams.exists) ?? bin,\n execPath: stableNode ?? execPath,\n })\n}\n\nexport type PortlessLinkOutcome =\n 'created' | 'repointed' | 'unchanged' | 'skipped-local' | 'skipped-unresolved' | 'failed'\n\nexport interface PortlessLinkResult {\n kind: 'link'\n outcome: PortlessLinkOutcome\n /** The portless package dir the link should point at; `null` only for `'skipped-unresolved'`. */\n target: string | null\n link: string\n}\n\n/**\n * The six fs calls the link needs, as an OBJECT seam. Named `node:fs` imports cannot be intercepted by\n * `vi.spyOn` (the binding is a live import, not a property), so the default export is the injectable\n * shape and tests hand in an in-memory fake instead of touching a real `~/.infra-kit`.\n */\nexport interface PortlessLinkFs {\n mkdirSync: (dir: string, options: { recursive: true }) => unknown\n lstatSync: (target: string, options: { throwIfNoEntry: false }) => { isSymbolicLink: () => boolean } | undefined\n readlinkSync: (target: string) => string\n symlinkSync: (target: string, linkPath: string) => void\n renameSync: (from: string, to: string) => void\n unlinkSync: (target: string) => void\n}\n\nexport interface EnsurePortlessLinkDeps {\n /** `resolvePortlessBin` \u2014 the bundled portless's `dist/cli.js`, or `null` when it is not installed. */\n resolveBin: () => string | null\n /** `isGlobalInstall` bound to this process \u2014 the ONLY gate between a checkout and the root daemon. */\n isGlobal: () => boolean\n home: string\n fs?: PortlessLinkFs\n}\n\n/** What currently sits at the link path, beyond \"a symlink to X\". */\nconst ABSENT = Symbol('absent')\nconst NOT_A_SYMLINK = Symbol('not-a-symlink')\n\nconst readCurrentLink = (link: string, linkFs: PortlessLinkFs): string | typeof ABSENT | typeof NOT_A_SYMLINK => {\n const stat = linkFs.lstatSync(link, { throwIfNoEntry: false })\n\n if (stat === undefined) return ABSENT\n if (!stat.isSymbolicLink()) return NOT_A_SYMLINK\n\n return linkFs.readlinkSync(link)\n}\n\n/**\n * Publish `target` at `link` through a pid-suffixed sibling and one `rename`, so the path never goes\n * absent (see the file header). The sibling is cleared BEFORE the symlink as well as after a failed\n * rename: a crash between the two calls leaves `.tmp-<pid>` behind forever, and pid reuse would then\n * turn a later boot's `symlinkSync` into EEXIST \u2014 a `'failed'` for a link that is fine. The name is\n * ours alone, never user data, so removing whatever sits there is safe; `ENOENT` is the normal case.\n */\nconst writeLink = (target: string, link: string, linkFs: PortlessLinkFs): void => {\n const tmp = `${link}.tmp-${process.pid}`\n\n try {\n linkFs.unlinkSync(tmp)\n } catch {\n // Nothing to clear \u2014 the ordinary path.\n }\n\n linkFs.symlinkSync(target, tmp)\n\n try {\n linkFs.renameSync(tmp, link)\n } catch (error) {\n try {\n linkFs.unlinkSync(tmp)\n } catch {\n // Best effort: the failed rename is the error worth surfacing, not the leftover sibling.\n }\n\n throw error\n }\n}\n\n/**\n * Converge `~/.infra-kit/portless` on the portless bundled with THIS install. Never throws; every\n * outcome is a value so callers can log it without a try/catch of their own.\n *\n * A non-symlink at the link path is `'failed'` and left exactly as found: this code owns a symlink, not\n * whatever a user or another tool put there, and removing a directory to make room would be the one\n * destructive action a boot hook must never take.\n *\n * @example\n * ensurePortlessLink({ resolveBin: () => '/g/node_modules/portless/dist/cli.js', isGlobal: () => true, home: '/Users/x' })\n * // => { kind: 'link', outcome: 'created', target: '/g/node_modules/portless', link: '/Users/x/.infra-kit/portless' }\n */\nexport const ensurePortlessLink = (deps: EnsurePortlessLinkDeps): PortlessLinkResult => {\n const { resolveBin, isGlobal, home, fs: linkFs = fs } = deps\n const link = portlessLinkPath(home)\n const bin = resolveBin()\n\n if (bin === null) return { kind: 'link', outcome: 'skipped-unresolved', target: null, link }\n\n const target = dirname(dirname(bin))\n\n if (!isGlobal()) return { kind: 'link', outcome: 'skipped-local', target, link }\n\n try {\n linkFs.mkdirSync(dirname(link), { recursive: true })\n\n const current = readCurrentLink(link, linkFs)\n\n if (current === target) return { kind: 'link', outcome: 'unchanged', target, link }\n if (current === NOT_A_SYMLINK) return { kind: 'link', outcome: 'failed', target, link }\n\n writeLink(target, link, linkFs)\n\n return { kind: 'link', outcome: current === ABSENT ? 'created' : 'repointed', target, link }\n } catch {\n return { kind: 'link', outcome: 'failed', target, link }\n }\n}\n\n/**\n * `(fields, message)` \u2014 the shape of `logger.debug`, so the CLI can pass it straight through. The two\n * boot results are a union on `kind`: a caller that reads `link`/`target` (the `ik-mcp` stderr line)\n * narrows first.\n */\nexport type PortlessLinkLog = (result: PortlessLinkResult | PortlessNodeResult, message: string) => void\n\n/** The link's seams and the node's, sharing ONE `isGlobal` \u2014 the two are converged together at every boot. */\nexport interface PortlessStableDeps {\n link: EnsurePortlessLinkDeps\n node: EnsurePortlessNodeDeps\n}\n\n/**\n * The real seams. Shared with `setup`, which needs the RESULTS back to report its steps, so the writers\n * can never disagree about which install is \"global\" or where the files go. `isGlobal` is memoised\n * per deps object: it costs a `realpathSync` plus the `.git` walk, and both steps ask it.\n */\nexport const realPortlessStableDeps = (): PortlessStableDeps => {\n const home = homedir()\n let global: boolean | undefined\n\n const isGlobal = (): boolean => {\n global ??= isGlobalInstall({\n selfRealPath: fs.realpathSync(fileURLToPath(import.meta.url)),\n env: process.env,\n realpath: safeRealpath,\n home,\n exists: fs.existsSync,\n })\n\n return global\n }\n\n return {\n link: { resolveBin: resolvePortlessBin, isGlobal, home },\n node: {\n isGlobal,\n home,\n execPath: process.execPath,\n version: process.version,\n arch: process.arch,\n platform: process.platform,\n },\n }\n}\n\nconst logStep = (log: PortlessLinkLog, message: string, run: () => PortlessLinkResult | PortlessNodeResult): void => {\n try {\n log(run(), message)\n } catch {\n // A file that could not be converged is `doctor`'s to report; it must never be a boot failure.\n }\n}\n\n/**\n * The process-boot entry for both bins: the link, then the node \u2014 independent state, so the node step\n * runs whatever the link reported. fs-only, no subprocess, never throws, never exits, never writes to\n * stdout; each outcome goes to `log` and nowhere else. `deps` is injectable so the \"`'failed'` is\n * logged\" contract is testable without a real disk.\n */\nexport const bootPortlessLink = (log: PortlessLinkLog, deps?: PortlessStableDeps): void => {\n const stable = deps ?? realPortlessStableDeps()\n\n logStep(log, 'portless link', () => {\n return ensurePortlessLink(stable.link)\n })\n logStep(log, 'portless node', () => {\n return ensurePortlessNode(stable.node)\n })\n}\n", "/**\n * @fileoverview\n *\n * Thin, injectable driver for the `portless` daemon (Layer B \u2014 see `.omc/plans/dev-https-portless.md`).\n *\n * `infra-kit dev` uses it to register `<release>.<package>.localhost \u2192 127.0.0.1:<port>` routes so the\n * hero URLs resolve over **HTTPS on :443, with no port in the URL**. Every call here is **time-bounded and\n * never throws**: a missing binary, a non-zero exit, or a wedged process resolves to `false`/no-op. That is\n * a reporting contract, not a tolerance one \u2014 portless IS a hard dependency of the dev loop, and\n * `DevServerRunner.ensureProxy` turns a `false` from this driver into a fatal, actionable start error.\n *\n * The binary is NOT resolved from `PATH`: `portless` is a normal npm dependency living in\n * `node_modules/.bin`, which is on `PATH` only when the process was launched via pnpm/npm. Since\n * `infra-kit dev` is often launched otherwise (a global bin, an Orca pane, a foreign cwd), we resolve\n * portless's own `dist/cli.js` by walking `node_modules` from this file (see {@link resolvePortlessBin})\n * and run it with the current `node` (`process.execPath`) \u2014 so it works regardless of how `dev` was\n * invoked. Args are fixed literals plus discovered release/package names + a numeric port, never\n * shell-interpolated.\n *\n * **The daemon is PROBED, never started.** `:443` is privileged, and portless binds it by re-execing\n * itself through `sudo` with an inherited stdio \u2014 which a detached `stdio:'ignore'` child can never\n * satisfy: the password prompt has nowhere to go. Setup is one-time and out-of-band: a root\n * `portless service install`, printed for the user by {@link formatPortlessCommand} (never as a bare\n * `portless`, which no shell can resolve \u2014 see there).\n *\n * All process I/O is injected (`run` for awaited commands, `isProxyServing` for the wire probe) so tests\n * never shell out and can assert the exact portless argv.\n */\nimport type { Buffer } from 'node:buffer'\nimport { execFile } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport http from 'node:http'\nimport https from 'node:https'\nimport net from 'node:net'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport tls from 'node:tls'\nimport { fileURLToPath } from 'node:url'\nimport { promisify } from 'node:util'\n\nimport { withoutPackageManagerEnv } from 'src/lib/pm-env'\nimport { shellLine } from 'src/lib/shell-quote'\n\nconst execFileAsync = promisify(execFile)\n\n/** Read `bin.portless` (the `dist/cli.js` relative path) from a portless `package.json` on disk. */\nconst readBinRel = (pkgJsonPath: string): string | null => {\n const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) as { bin?: string | Record<string, string> }\n const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.portless\n\n return rel == null || rel === '' ? null : rel\n}\n\n/**\n * Resolve the absolute path to portless's CLI entry (`portless/dist/cli.js`) from node_modules,\n * independent of `PATH`. Returns `null` when portless is not installed, degrading the whole driver to\n * a no-op.\n *\n * portless is ESM-only (its `.` export exposes only `import`/`types`, no `require`), so\n * `createRequire().resolve` can't see it. We instead walk `node_modules` upward from this file \u2014 the\n * standard resolution path \u2014 and read the package's `package.json` straight off disk, which bypasses the\n * exports map that would otherwise hide both `package.json` and the main entry.\n */\nexport const resolvePortlessBin = (): string | null => {\n try {\n let dir = dirname(fileURLToPath(import.meta.url))\n\n for (;;) {\n const pkgJsonPath = join(dir, 'node_modules', 'portless', 'package.json')\n\n if (existsSync(pkgJsonPath)) {\n const rel = readBinRel(pkgJsonPath)\n\n return rel == null ? null : join(dirname(pkgJsonPath), rel)\n }\n const parent = dirname(dir)\n\n if (parent === dir) return null\n dir = parent\n }\n } catch {\n return null\n }\n}\n\n/** Resolve portless's CLI once per process \u2014 the on-disk location never changes within a run. */\nlet cachedBin: string | null | undefined\nconst portlessBin = (): string | null => {\n if (cachedBin === undefined) cachedBin = resolvePortlessBin()\n\n return cachedBin\n}\n\n/** Seams for {@link formatPortlessCommand}, injected so tests never depend on the real node_modules layout. */\nexport interface FormatPortlessCommandOptions {\n /**\n * Absolute path to portless's `dist/cli.js`. **Required and non-nullable on purpose.** The caller must\n * have resolved portless before it can describe how to run it, so \"I could not find the binary\" cannot be\n * silently rendered as a plausible-looking command \u2014 the type makes that unwritable rather than merely\n * discouraged. A `null` bin is a different report (\"run `pnpm install`\"), which every caller makes first.\n */\n bin: string\n /** Prefix with `sudo` \u2014 only `service install`, which binds the privileged `:443`, needs it. */\n sudo?: boolean\n execPath?: string\n}\n\n/**\n * Render a portless command the user can actually paste into a shell.\n *\n * Prints what the driver itself runs (see {@link defaultRun}): the current interpreter, by absolute path,\n * invoking portless's `dist/cli.js`, by absolute path. Nothing is resolved from `PATH`, so the command\n * works under `sudo`, from any cwd, and however `infra-kit` was launched.\n *\n * @example\n * formatPortlessCommand(['service', 'install'], { sudo: true, bin })\n * // 'sudo /usr/local/bin/node /repo/node_modules/portless/dist/cli.js service install'\n */\n// This exists because the obvious string is a lie. `portless` is a plain npm dependency living in\n// `node_modules/.bin`, which is on `PATH` only inside a pnpm/npm script \u2014 so printing `sudo portless\n// service install` hands the user a command that dies with `sudo: portless: command not found`. `sudo`\n// makes it strictly worse: it replaces `PATH` with `secure_path`, so even a shell that *could* resolve\n// `portless` loses it the moment the command is elevated.\n//\n// This is not merely cosmetic. portless's `service install` writes the interpreter and script path it was\n// invoked with straight into the launchd plist's `ProgramArguments` (`nodePath: process.execPath` plus\n// `process.argv[1]`), so the command printed here is the command that gets installed as a ROOT SYSTEM\n// DAEMON. Printing a name for the shell to resolve would not just fail \u2014 it would decide what runs as\n// root.\nexport const formatPortlessCommand = (args: string[], options: FormatPortlessCommandOptions): string => {\n const words = [options.execPath ?? process.execPath, options.bin, ...args]\n const prefix = options.sudo === true ? 'sudo ' : ''\n\n return prefix + shellLine(words)\n}\n\n/** Awaited portless invocation. Rejects on non-zero exit / timeout; the driver swallows that into a no-op. */\nexport type PortlessRun = (args: string[], opts: { timeoutMs: number }) => Promise<void>\n\n/** Cheap \"is anything at all accepting TCP here?\" pre-filter in front of the wire probe. */\nexport type IsListening = (port: number) => Promise<boolean>\n\n/**\n * Ground-truth identity: is the process serving `port` actually **portless**, and (when `tls`) is it\n * serving **TLS**? See {@link defaultIsProxyServing} for why this cannot be answered from state files.\n */\nexport type IsProxyServing = (port: number, tls: boolean) => Promise<boolean>\n\nconst DEFAULT_TIMEOUT_MS = 1500\nconst PROBE_TIMEOUT_MS = 1500\n\n/** Response header portless sets on every response it serves. Node lower-cases response header names. */\nconst PORTLESS_HEADER = 'x-portless'\n\n/** IPv4 loopback: portless binds and dials `127.0.0.1`. */\nconst LOOPBACK = '127.0.0.1'\n\n/**\n * SNI for the probe. Node sends **no SNI to an IP literal** (RFC 6066), which would drop portless onto its\n * default certificate \u2014 whose SANs are `localhost`, `*.localhost`, `*.local` and contain **no IP entry**.\n * `localhost` is always in that set, so it is the one name guaranteed to work even on a machine with zero\n * aliases registered.\n */\nconst PROBE_SERVERNAME = 'localhost'\n\n/**\n * Whether portless's OS-level service (the thing `service install` registers) is present on disk.\n * `'unknown'` on a platform this check does not cover (currently anything but macOS/Linux) \u2014 a caller must\n * never read `'unknown'` as `'no'`, since doing so would tell an already-provisioned Windows machine to\n * reinstall.\n */\nexport type ServiceInstalled = 'yes' | 'no' | 'unknown'\n\n/**\n * portless's launchd service label (`sh.portless.proxy`, hard-coded in portless's own CLI) and the two\n * fixed paths its `service install`/`uninstall` write to on macOS and Linux. These are read-only constants\n * of portless's OWN implementation, not ours \u2014 see `dist/cli.js`'s `SERVICE_LABEL`/`buildServiceSpec`. There\n * is no per-user or per-project variant: `service install` always targets exactly one of these two paths.\n * Exported so a test can assert against the exact path this check reads, without hard-coding a second copy.\n */\nexport const DARWIN_SERVICE_LABEL = 'sh.portless.proxy'\nexport const DARWIN_SERVICE_PLIST_PATH = `/Library/LaunchDaemons/${DARWIN_SERVICE_LABEL}.plist`\nexport const LINUX_SERVICE_UNIT_PATH = '/etc/systemd/system/portless.service'\n/** The systemd unit name `service install` registers on Linux \u2014 the `systemctl` argument, not a path. */\nexport const LINUX_SERVICE_UNIT_NAME = 'portless'\n\n/** The `existsSync` seam {@link defaultIsServiceInstalled} takes, injected so tests never touch real root paths. */\nexport type ExistsCheck = (path: string) => boolean\n\n/**\n * Cheap, synchronous, never-throwing check for whether portless's OS service is registered \u2014 a plain\n * `existsSync` on the fixed path `service install` writes to, never a `launchctl`/`systemctl` shell-out. This\n * is what lets {@link createPortlessDriver}'s daemon-down classification tell \"never installed\" apart from\n * \"installed, but not currently answering\" without adding a second process spawn to every failed probe.\n *\n * Deliberately does not attempt Windows detection (a Task Scheduler task, which needs `schtasks` to query) \u2014\n * `'unknown'` there is honest; a guessed `'no'` would send an already-provisioned machine back through\n * `service install` for no reason.\n *\n * `exists` defaults to the real `existsSync` but is a normal parameter (not a named-import spy target) so a\n * test can assert both branches without touching `/Library/LaunchDaemons` \u2014 a root-owned path a dev machine\n * may genuinely have populated, which would make an un-injected assertion true or false depending on the\n * author's own machine state rather than the code under test.\n */\nexport const defaultIsServiceInstalled = (exists: ExistsCheck = existsSync): ServiceInstalled => {\n try {\n if (process.platform === 'darwin') return exists(DARWIN_SERVICE_PLIST_PATH) ? 'yes' : 'no'\n if (process.platform === 'linux') return exists(LINUX_SERVICE_UNIT_PATH) ? 'yes' : 'no'\n\n return 'unknown'\n } catch {\n return 'unknown'\n }\n}\n\n/**\n * Fine-grained outcome of probing the proxy port, distinguishing the two ways \"not serving\" happens so\n * {@link createPortlessDriver}'s caller can print a distinct, actionable fix for each:\n * - `'serving'` \u2014 portless answered on the wire (the old boolean `true`).\n * - `'daemon-down'` \u2014 nothing is even accepting TCP on the port (refused). Combined with\n * {@link ServiceInstalled} this splits into \"never installed\" vs \"installed but crashed/stopped\".\n * - `'not-portless'` \u2014 something IS listening, but it did not answer with `X-Portless: 1` \u2014 a squatter has\n * the port, and installing/trusting portless will not free it.\n */\nexport type ProxyProbeOutcome = 'serving' | 'daemon-down' | 'not-portless'\n\nexport const defaultIsListening: IsListening = (port) => {\n return new Promise((resolve) => {\n const socket = net.connect({ host: LOOPBACK, port })\n const finish = (result: boolean): void => {\n socket.destroy()\n resolve(result)\n }\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('connect', () => {\n finish(true)\n })\n socket.once('timeout', () => {\n finish(false)\n })\n socket.once('error', () => {\n finish(false)\n })\n })\n}\n\n/**\n * Is the listener on `port` portless itself, serving `tls`? Proven **on the wire**, by asking it: portless\n * sets `X-Portless: 1` on every response, before route lookup \u2014 so an unrouted host still answers the probe\n * (a 404 with the header is a pass). This mirrors portless's own `isProxyRunning`.\n *\n * `rejectUnauthorized: false` is deliberate and load-bearing: this probe answers *\"is portless serving\n * here?\"*, **never** *\"is its CA trusted?\"*. Trust is a separate, explicitly-validating probe (doctor's\n * CA check).\n */\n// This replaces the old state-file check (`proxy.port` + `proxy.pid`), which was UNSOUND: portless's\n// `resolveStateDir(_port)` ignores its port argument, so `proxy.port` / `proxy.pid` / `proxy.tls` are\n// process-global singletons shared by every daemon on every port. Starting ANY daemon rewrites them, and\n// stopping ANY daemon DELETES them \u2014 so a second, unrelated daemon (or a stale sibling repo still on the\n// old CLI, falling back to an unprivileged port) makes a perfectly healthy `:443` daemon look dead. Both\n// were reproduced against portless 0.15.1; see `.omc/research/portless-https-spike.md`.\n//\n// Validating the chain here would collapse two different failures \u2014 a daemon that is down, and a CA that\n// was never trusted \u2014 into one indistinguishable error, with two different fixes (a root `service install`\n// vs the sudo-free `trust`).\nexport const defaultIsProxyServing: IsProxyServing = (port, tls) => {\n return new Promise((resolve) => {\n const request = tls ? https.request : http.request\n const req = request(\n {\n host: LOOPBACK,\n port,\n method: 'HEAD',\n path: '/',\n timeout: PROBE_TIMEOUT_MS,\n ...(tls ? { rejectUnauthorized: false, servername: PROBE_SERVERNAME } : {}),\n },\n (res) => {\n res.resume()\n resolve(res.headers[PORTLESS_HEADER] === '1')\n },\n )\n\n req.on('error', () => {\n resolve(false)\n })\n req.on('timeout', () => {\n req.destroy()\n resolve(false)\n })\n req.end()\n })\n}\n\nconst defaultRun: PortlessRun = async (args, { timeoutMs }) => {\n const bin = portlessBin()\n\n if (bin == null) throw new Error('portless is not installed (not resolvable from node_modules)')\n await execFileAsync(process.execPath, [bin, ...args], {\n signal: AbortSignal.timeout(timeoutMs),\n encoding: 'utf-8',\n env: withoutPackageManagerEnv(process.env),\n })\n}\n\n/**\n * portless's state directory. Exported so `doctor` reports on the same directory the driver reads.\n *\n * The default is deliberately **unchanged** (`~/.portless`): portless's `service install` bakes\n * `PORTLESS_STATE_DIR`, resolved from `SUDO_USER`, into the launchd plist \u2014 so the root daemon reads the\n * invoking user's* home. Pointing this anywhere else by default would manufacture the very split it looks\n * like it prevents.\n */\nexport const portlessStateDir = (): string => {\n return process.env.PORTLESS_STATE_DIR ?? join(homedir(), '.portless')\n}\n\n/** portless's local CA certificate \u2014 the root every host cert it mints is signed by. */\nconst CA_CERT_FILE = 'ca.pem'\n\n/**\n * Marker portless's `trust` writes: the **hex sha256 of `ca.pem`'s bytes** that was added to the login\n * keychain (`writeTrustMarker` \u2192 `caFingerprint`, `cli.js:78-101`). It records WHICH CA was trusted, so a\n * regenerated CA leaves a marker that no longer matches.\n */\nconst CA_TRUST_MARKER_FILE = 'ca.trusted'\n\n/** A route portless is serving: `<name> \u2192 127.0.0.1:<port>`. */\nexport interface PortlessRoute {\n /**\n * The registered hostname (e.g. `2-4.client-api.localhost`). Usable verbatim as a\n * `portless alias --remove <name>` argument \u2014 portless strips a trailing TLD off the name it is handed\n * (`parseHostnames`, `chunk-SD2PIWJU.js:68-79`) \u2014 and as a TLS `servername`.\n */\n name: string\n port: number\n}\n\n/** Absolute path to portless's local CA certificate, in whichever state dir {@link portlessStateDir} names. */\nexport const readCaPath = (): string => {\n return join(portlessStateDir(), CA_CERT_FILE)\n}\n\n/**\n * Was `portless trust` run for the CA that is on disk right now? Compares `sha256(ca.pem)` against the\n * fingerprint recorded in `ca.trusted`. `false` when either file is missing; never throws.\n *\n * **This proves the marker was written for THIS fingerprint \u2014 not that the keychain still trusts it.** A\n * user who deletes the certificate from Keychain Access by hand leaves the marker behind and gets a false\n * pass here. That residual is accepted (reading the keychain would mean shelling out to `security` on a\n * check that must stay cheap); it is why this is a *separate* check from the chain handshake\n * ({@link handshakeChainsToCa}), which proves what the daemon actually serves.\n */\nexport const caFingerprintMatches = (): boolean => {\n try {\n const recorded = readFileSync(join(portlessStateDir(), CA_TRUST_MARKER_FILE), 'utf-8').trim()\n\n if (recorded === '') return false\n\n const actual = createHash('sha256').update(readFileSync(readCaPath())).digest('hex')\n\n return actual === recorded.toLowerCase()\n } catch {\n return false\n }\n}\n\n/** Outcome of {@link handshakeChainsToCa}: `code` is the Node TLS error code, which the caller discriminates on. */\nexport type HandshakeResult = { ok: true } | { ok: false; code: string }\n\n/**\n * Does the certificate served on `port` chain to the CA in `ca.pem`? A **validating** TLS handshake \u2014 the\n * complement of {@link defaultIsProxyServing}, which deliberately does not validate.\n *\n * `servername` is **mandatory and load-bearing**, never optional: Node sends no SNI to an IP literal\n * (RFC 6066), which drops portless onto its default certificate, whose SANs (`localhost`, `*.localhost`,\n * `*.local`) contain **no IP entry** \u2014 so a validating probe of `127.0.0.1` with no `servername` fails with\n * `ERR_TLS_CERT_ALTNAME_INVALID` against a perfectly healthy daemon. Any such code coming back from here is\n * therefore a bug in the CALLER's probe, never a finding about the user's trust store. Passing an\n * unregistered name is safe: portless's SNI callback mints a cert on demand for any servername.\n *\n * Time-bounded; never throws.\n */\nexport const handshakeChainsToCa = (port: number, servername: string): Promise<HandshakeResult> => {\n return new Promise((resolve) => {\n let ca: Buffer<ArrayBufferLike>\n\n try {\n ca = readFileSync(readCaPath())\n } catch {\n resolve({ ok: false, code: 'ENOENT' })\n\n return\n }\n\n const socket = tls.connect({ host: LOOPBACK, port, servername, ca: [ca], rejectUnauthorized: true }, () => {\n // With `rejectUnauthorized: true` a chain failure normally surfaces as an 'error' event and this\n // callback never runs; the check is here so a future Node that connects-then-reports can't slip a\n // rejected chain through as a pass.\n const authError = socket.authorizationError as NodeJS.ErrnoException | undefined\n const authorized = socket.authorized\n\n socket.destroy()\n resolve(authorized ? { ok: true } : { ok: false, code: authError?.code ?? authError?.message ?? 'UNKNOWN' })\n })\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('timeout', () => {\n socket.destroy()\n resolve({ ok: false, code: 'ETIMEDOUT' })\n })\n socket.once('error', (err: NodeJS.ErrnoException) => {\n socket.destroy()\n resolve({ ok: false, code: err.code ?? 'UNKNOWN' })\n })\n })\n}\n\n/**\n * Routes portless currently has registered, read from `routes.json` in {@link portlessStateDir}. `[]` on any\n * failure (absent file, malformed JSON, unexpected shape) \u2014 an unreadable route list is reported as \"no\n * routes\", never as an error, because every caller uses this for diagnostics only.\n */\nexport const listRoutes = (): PortlessRoute[] => {\n try {\n const raw: unknown = JSON.parse(readFileSync(join(portlessStateDir(), 'routes.json'), 'utf-8'))\n\n if (!Array.isArray(raw)) return []\n\n return raw.flatMap((entry): PortlessRoute[] => {\n const { hostname, port } = (entry ?? {}) as { hostname?: unknown; port?: unknown }\n\n if (typeof hostname !== 'string' || hostname === '' || typeof port !== 'number') return []\n\n return [{ name: hostname, port }]\n })\n } catch {\n return []\n }\n}\n\nexport interface PortlessDriver {\n /**\n * Absolute path to the `dist/cli.js` this driver executes, or `null` when portless is not installed.\n *\n * Exposed so a caller rendering a remediation ({@link formatPortlessCommand}) names the binary THIS driver\n * would run, rather than re-resolving one behind its back \u2014 which, under an injected driver, would print a\n * fix derived from the real machine instead of the one under test.\n */\n binPath: () => string | null\n /** Resolve (and memoize) whether the `portless` binary is usable. Absent \u2192 every other call no-ops. */\n isAvailable: () => Promise<boolean>\n /**\n * Is a portless daemon serving `port` over `tls`? **Probe only \u2014 this never starts anything.** Binding\n * the privileged `:443` needs root, and portless's sudo re-exec cannot prompt from a detached child, so\n * the daemon is installed once, out-of-band (a root `service install`). A `false` here is turned into a\n * fatal, actionable start error by the caller.\n */\n isProxyServing: (port: number, tls: boolean) => Promise<boolean>\n /**\n * Same probe as {@link PortlessDriver.isProxyServing}, but reporting WHICH way it failed instead of\n * collapsing every non-serving case into `false`. `ensureProxy` uses this to print a distinct, actionable\n * message for \"nothing there\", \"something else is there\", and (combined with {@link isServiceInstalled})\n * \"installed but not running\" vs \"never installed\". Never starts anything \u2014 probe only, same as above.\n */\n probeProxy: (port: number, tls: boolean) => Promise<ProxyProbeOutcome>\n /**\n * Is portless's OS-level service (what `service install` registers) present on disk? Cheap, synchronous,\n * never throws. `'unknown'` on a platform this cannot check \u2014 a caller must not read that as `'no'`.\n */\n isServiceInstalled: () => ServiceInstalled\n /**\n * Register `<name> \u2192 127.0.0.1:<port>` (`name` = `<release>.<package>`). Returns `true` on success so\n * the caller shows the hero URL only for an alias that actually resolves (best-effort otherwise).\n */\n registerAlias: (name: string, port: number) => Promise<boolean>\n /** Deregister `<name>`. Best-effort. */\n removeAlias: (name: string) => Promise<void>\n}\n\nexport interface PortlessDriverDeps {\n /** Override the resolved `dist/cli.js` path (default: the real node_modules walk). Injected in tests. */\n bin?: string | null\n run?: PortlessRun\n /** TCP liveness pre-filter (default: real `net` connect). Injected in tests. */\n isListening?: IsListening\n /** Wire-probe identity check (default: real `HEAD /` + `X-Portless`). Injected in tests. */\n isProxyServing?: IsProxyServing\n /** OS-service-on-disk check (default: real `existsSync` on the plist/unit path). Injected in tests. */\n isServiceInstalled?: () => ServiceInstalled\n timeoutMs?: number\n}\n\n/**\n * Build a {@link PortlessDriver}. Inject `run` in tests to assert argv without shelling out.\n * `isAvailable` memoizes so the binary is probed at most once per runner.\n */\nexport const createPortlessDriver = (deps: PortlessDriverDeps = {}): PortlessDriver => {\n const bin = deps.bin === undefined ? portlessBin() : deps.bin\n const run = deps.run ?? defaultRun\n const isListening = deps.isListening ?? defaultIsListening\n const isProxyServing = deps.isProxyServing ?? defaultIsProxyServing\n const isServiceInstalled = deps.isServiceInstalled ?? defaultIsServiceInstalled\n const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS\n let availability: boolean | null = null\n\n /** Run a portless subcommand, swallowing any failure into `false` (best-effort contract). */\n const tryRun = async (args: string[]): Promise<boolean> => {\n try {\n await run(args, { timeoutMs })\n\n return true\n } catch {\n return false\n }\n }\n\n const isAvailable = async (): Promise<boolean> => {\n availability ??= await tryRun(['--version'])\n\n return availability\n }\n\n const serving = async (port: number, tls: boolean): Promise<boolean> => {\n if (!(await isAvailable())) return false\n // Nothing is even accepting TCP \u2192 skip the (more expensive) wire probe entirely.\n if (!(await isListening(port))) return false\n\n return isProxyServing(port, tls)\n }\n\n /**\n * The classifying counterpart of {@link serving}. Deliberately does NOT gate on `isAvailable()` first (unlike\n * `serving`): a broken/missing CLI binary says nothing about whether a daemon a PRIOR install started is\n * still up on the wire, so the two are independent facts and the caller (which already checked availability\n * before ever calling this) must not have that distinction collapsed here.\n */\n const probeProxy = async (port: number, tls: boolean): Promise<ProxyProbeOutcome> => {\n if (!(await isListening(port))) return 'daemon-down'\n\n return (await isProxyServing(port, tls)) ? 'serving' : 'not-portless'\n }\n\n const registerAlias = async (name: string, port: number): Promise<boolean> => {\n if (!(await isAvailable())) return false\n\n return tryRun(['alias', name, String(port)])\n }\n\n const removeAlias = async (name: string): Promise<void> => {\n if (!(await isAvailable())) return\n await tryRun(['alias', '--remove', name])\n }\n\n return {\n binPath: () => {\n return bin\n },\n isAvailable,\n isProxyServing: serving,\n probeProxy,\n isServiceInstalled,\n registerAlias,\n removeAlias,\n }\n}\n", "/**\n * Render an argv array as a line a POSIX shell runs back verbatim.\n *\n * Every surface that PRINTS a command for a human to paste has the same obligation, and `join(' ')` does\n * not meet it. The load-bearing case is `lib/dependency-install`'s refusals: a recipe we decline to run\n * is printed precisely so the human can run it, and joining\n * `['/bin/bash', '-c', 'curl -fsSL \u2026 | bash']` on spaces yields\n * `/bin/bash -c curl -fsSL \u2026 | bash` \u2014 which loses the argument boundary and runs `curl` with `-fsSL`\n * as `$0`, no URL, and the rest piped into a second shell. It fails, and it fails in a way that reads\n * like the tool's fault rather than the transcription's.\n *\n * The implementation began inside `dev/proxy/portless-driver`, which needed it first and is still a\n * caller; a second copy beside the recipes would drift from it.\n */\n\n/**\n * Characters that survive a POSIX shell unquoted. Anything outside this set \u2014 a space, a pipe, a paren,\n * all of which appear in real recipes and real install paths \u2014 gets single-quoted.\n */\nconst SHELL_SAFE = /^[\\w@%+=:,./-]+$/\n\n/** A literal `'` inside single quotes: close, emit an escaped quote, reopen \u2014 the only way a shell allows it. */\nconst SINGLE_QUOTE_ESCAPE = \"'\\\\''\"\n\n/** Single-quote `value` for a POSIX shell unless it is already inert. */\nexport const shellQuote = (value: string): string => {\n return SHELL_SAFE.test(value) ? value : `'${value.replaceAll(\"'\", SINGLE_QUOTE_ESCAPE)}'`\n}\n\n/** One pasteable shell line from an argv array, each word quoted only when it needs to be. */\nexport const shellLine = (argv: readonly string[]): string => {\n return argv.map(shellQuote).join(' ')\n}\n", "/**\n * @fileoverview\n *\n * `~/.infra-kit/node` \u2014 a stable, regular-file name for the Node binary the global infra-kit runs, kept\n * current by every process boot beside `~/.infra-kit/portless` (see that module's header for the link).\n *\n * Why a HARDLINK: `portless service install` bakes `process.execPath` into the root plist, and Node\n * realpaths `execPath` (measured: a hardlink of node prints its own path from `-p process.execPath`;\n * a symlink prints the target), so no symlink in front of the binary survives into the plist. Under\n * pnpm 12 the binary lives in `global/v11/{pid}-{ts}/\u2026/node@runtime/\u2026`, a directory every `pnpm add -g`\n * re-mints \u2014 with no Node bump. A hardlink is a regular file, costs 0.3 ms and 0 bytes, and its inode\n * outlives the manager's directory, so the name cannot dangle across a re-mint + reboot the way a\n * symlink would. `copyFile(COPYFILE_FICLONE)` is a full 134 MB copy on APFS here, so it is the FALLBACK\n * only: root-owned `/usr/bin/node` under `protected_hardlinks`, a cross-volume home (macOS answers\n * `EPERM`, not `EXDEV`), exFAT/SMB/NFS (`ENOTSUP`), dataless iCloud (`EDEADLK`) \u2014 the failure set of\n * `link(2)` is not enumerable, so ANY throw takes the copy. The daemon never consults `execPath` again\n * after boot (`proxy start --foreground` spawns nothing), so that one plist word is the whole contract.\n *\n * T-1 \u2014 the hardlink SHARES an inode with the package manager's node, and macOS enforces no `ETXTBSY`:\n * a write through this name lands in the developer's real node and, on Apple Silicon, kills every\n * process mapping it by signature invalidation. Rename-only discipline is the ONLY guard: every byte\n * goes to a `node.tmp-<pid>` sibling and is published by `rename(2)`; the node path is never opened\n * for writing, never chmod'ed (that too mutates the shared inode) and never unlinked. `chmod` runs on\n * the copy branch's tmp alone \u2014 the source is executable already, this process executed it.\n *\n * Staleness is one inode compare against `process.execPath`, never a version or byte compare: after a\n * re-mint the source is a new inode with identical bytes and relinking is free. The sidecar keeps two\n * clocks \u2014 `refreshedAt` (the file) and `versionChangedAt` (the Node behind it, carried over on a\n * same-version relink) \u2014 because doctor's \"daemon predates Node \u2026\" advisory must not nag after every\n * global install. Neither is an fs timestamp: a hardlink's mtime is the source's install time.\n *\n * Same gate and contract as the link: `isGlobalInstall` is the only thing between a checkout and the\n * root daemon; nothing here spawns, writes stdout, or throws.\n */\nimport fs from 'node:fs'\nimport { basename, dirname, join } from 'node:path'\nimport process from 'node:process'\n\nimport { USER_CONFIG_DIR_NAME } from 'src/lib/constants'\n\n/** `<home>/.infra-kit/node` \u2014 the file the plist's first argv word names. */\nexport const portlessNodePath = (home: string): string => {\n return join(home, USER_CONFIG_DIR_NAME, 'node')\n}\n\n/** `<node>.source.json` \u2014 what the file is (method, Node triple, source) and the two clocks. */\nexport const portlessNodeSidecar = (home: string): string => {\n return `${portlessNodePath(home)}.source.json`\n}\n\n// Hand-checked, not zod: this module is reached from the `ik-mcp` bundle, which must stay free of every\n// node_modules input (`dist-shebang.test.ts`). A sidecar is eight scalars \u2014 a validator is cheaper than\n// the dependency.\nexport interface PortlessNodeSidecar {\n method: 'hardlink' | 'copy'\n version: string\n arch: string\n platform: string\n source: string\n sourceSize?: number\n refreshedAt: string\n versionChangedAt: string\n}\n\nconst isSidecar = (value: unknown): value is PortlessNodeSidecar => {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Record<string, unknown>\n const strings = ['version', 'arch', 'platform', 'source', 'refreshedAt', 'versionChangedAt']\n\n return (\n (record.method === 'hardlink' || record.method === 'copy') &&\n strings.every((key) => {\n return typeof record[key] === 'string'\n }) &&\n (record.sourceSize === undefined || typeof record.sourceSize === 'number')\n )\n}\n\n/** The subset of `fs.Stats` the inode compare and the copy-path size witness need. */\nexport interface PortlessNodeStat {\n ino: number\n dev: number\n size: number\n isFile: () => boolean\n}\n\n/**\n * Every fs call the file needs, as an OBJECT seam: `vi.spyOn` cannot intercept named `node:fs` imports,\n * so tests hand in an in-memory fake and the call log \u2014 not the final state \u2014 carries the rename-only\n * contract (T-1). `copyFileSync` takes the mode so the FICLONE flag is visible in that log.\n */\nexport interface PortlessNodeFs {\n mkdirSync: (dir: string, options: { recursive: true }) => unknown\n lstatSync: (target: string, options: { throwIfNoEntry: false }) => PortlessNodeStat | undefined\n statSync: (target: string, options: { throwIfNoEntry: false }) => PortlessNodeStat | undefined\n readFileSync: (target: string, encoding: 'utf8') => string\n writeFileSync: (target: string, data: string) => void\n readdirSync: (dir: string) => string[]\n linkSync: (existing: string, newPath: string) => void\n copyFileSync: (src: string, dest: string, mode: number) => void\n chmodSync: (target: string, mode: number) => void\n renameSync: (from: string, to: string) => void\n unlinkSync: (target: string) => void\n}\n\nexport type PortlessNodeOutcome =\n 'created' | 'refreshed' | 'unchanged' | 'skipped-local' | 'skipped-platform' | 'failed'\n\nexport interface PortlessNodeResult {\n kind: 'node'\n outcome: PortlessNodeOutcome\n node: string\n /** The `execPath` the file was (or would have been) made from. */\n source: string\n version: string\n /** How the file relates to `source`; `null` when nothing was published and nothing converged was found. */\n method: 'hardlink' | 'copy' | null\n}\n\nexport interface EnsurePortlessNodeDeps {\n /** The SAME memoised closure the link uses \u2014 the ONLY gate between a checkout and the root daemon. */\n isGlobal: () => boolean\n home: string\n execPath: string\n version: string\n arch: string\n platform: NodeJS.Platform\n fs?: PortlessNodeFs\n now?: () => Date\n}\n\n// EXCL is load-bearing, not hygiene: a stale `node.tmp-<pid>` from a boot that died before its `rename`\n// can be a HARDLINK of the live node, and a reused pid would hand the copy branch that name \u2014 an\n// `O_TRUNC` open of it is the T-1 write-through. With EXCL the copy refuses (`EEXIST` \u2192 `'failed'`) and\n// the next boot's sweep clears the name.\nconst COPY_FLAGS = fs.constants.COPYFILE_FICLONE | fs.constants.COPYFILE_EXCL\nconst COPY_MODE = 0o755\n\n/** `null` when the sidecar is absent, unreadable or does not parse \u2014 every one of those forces a refresh. */\nexport const readPortlessNodeSidecar = (home: string, nodeFs: PortlessNodeFs = fs): PortlessNodeSidecar | null => {\n try {\n const parsed: unknown = JSON.parse(nodeFs.readFileSync(portlessNodeSidecar(home), 'utf8'))\n\n return isSidecar(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n\nconst sameInode = (a: PortlessNodeStat, b: PortlessNodeStat): boolean => {\n return a.ino === b.ino && a.dev === b.dev\n}\n\n/**\n * `<home>/.infra-kit/node` when it is a regular file on the SAME inode as `execPath`, else `null`.\n * Inode equality is proof of runnability \u2014 the asking process IS that inode \u2014 so this needs no sidecar\n * and no spawn, which is what lets `dev` render the short `service install` line on its hot path. A\n * copy-path file is never a candidate: nothing short of running it proves it runs (doctor's job).\n */\nexport const stableNodeCandidate = (input: { home: string; execPath: string; fs?: PortlessNodeFs }): string | null => {\n const { home, execPath, fs: nodeFs = fs } = input\n const node = portlessNodePath(home)\n\n try {\n const current = nodeFs.lstatSync(node, { throwIfNoEntry: false })\n const exec = nodeFs.statSync(execPath, { throwIfNoEntry: false })\n\n if (current === undefined || exec === undefined || !current.isFile()) return null\n\n return sameInode(current, exec) ? node : null\n } catch {\n return null\n }\n}\n\ntype NodeTriple = Pick<EnsurePortlessNodeDeps, 'version' | 'arch' | 'platform'>\n\nconst describesProcess = (sidecar: PortlessNodeSidecar, deps: NodeTriple): boolean => {\n return sidecar.version === deps.version && sidecar.arch === deps.arch && sidecar.platform === deps.platform\n}\n\n/**\n * The fast path. Inode equality is the strongest signal for the FILE; the version clause is for the\n * SIDECAR: a crash between the two renames after a Node bump leaves the new inode described as the old\n * version with a pre-bump `versionChangedAt`, and without this clause that would be `'unchanged'` forever\n * (doctor printing the wrong version, the restart advisory keyed on a clock that is too old). On the copy\n * path the inode can never match, so the size is the second witness beside the version triple.\n */\nconst isConverged = (\n current: PortlessNodeStat,\n exec: PortlessNodeStat,\n sidecar: PortlessNodeSidecar,\n deps: NodeTriple,\n): boolean => {\n if (!describesProcess(sidecar, deps)) return false\n if (sameInode(current, exec)) return true\n\n return sidecar.method === 'copy' && sidecar.sourceSize === exec.size\n}\n\nconst discard = (tmp: string, nodeFs: PortlessNodeFs): void => {\n try {\n nodeFs.unlinkSync(tmp)\n } catch {\n // Best effort: the failure that got us here is the one worth surfacing, not a leftover sibling.\n }\n}\n\n/**\n * A SIGKILL mid-copy leaves a 134 MB `node.tmp-<pid>` under a pid that may never recur; the sidecar\n * orphan is ~250 B, but one pass covers both. Only these two prefixes are ours to remove. A concurrent\n * boot's live tmp may go too \u2014 its `rename` then fails into `'failed'` and the next boot converges;\n * the published name always holds a complete file.\n */\nconst sweepOrphans = (dir: string, prefixes: string[], nodeFs: PortlessNodeFs): void => {\n let names: string[]\n\n try {\n names = nodeFs.readdirSync(dir)\n } catch {\n return\n }\n\n for (const name of names) {\n const orphan = prefixes.some((prefix) => {\n return name.startsWith(prefix)\n })\n\n if (orphan) discard(join(dir, name), nodeFs)\n }\n}\n\n/** Hardlink first; on ANY throw, the copy (see the header for why the error set is not filtered). */\nconst stageNode = (execPath: string, tmp: string, nodeFs: PortlessNodeFs): 'hardlink' | 'copy' => {\n try {\n nodeFs.linkSync(execPath, tmp)\n\n return 'hardlink'\n } catch {\n nodeFs.copyFileSync(execPath, tmp, COPY_FLAGS)\n // The copy branch ONLY: on a hardlink this would chmod the manager's inode. 0755 is what the source\n // carries and what root needs to exec a file under a 0700 home \u2014 no secret lives in a node binary.\n // eslint-disable-next-line sonarjs/file-permissions -- an executable's mode, not a data file's\n nodeFs.chmodSync(tmp, COPY_MODE)\n\n return 'copy'\n }\n}\n\n/**\n * Stage under the pid-suffixed sibling, publish by ONE `rename` (T-1). The old inode stays mapped by a\n * running daemon; `rename` touches no byte of it. On any throw the sibling is removed and the old file\n * is exactly as it was.\n */\nconst publishNode = (execPath: string, node: string, nodeFs: PortlessNodeFs): 'hardlink' | 'copy' => {\n const tmp = `${node}.tmp-${process.pid}`\n\n try {\n const method = stageNode(execPath, tmp, nodeFs)\n\n nodeFs.renameSync(tmp, node)\n\n return method\n } catch (error) {\n discard(tmp, nodeFs)\n throw error\n }\n}\n\nconst publishSidecar = (sidecarPath: string, sidecar: PortlessNodeSidecar, nodeFs: PortlessNodeFs): void => {\n const tmp = `${sidecarPath}.tmp-${process.pid}`\n\n try {\n nodeFs.writeFileSync(tmp, `${JSON.stringify(sidecar, null, 2)}\\n`)\n nodeFs.renameSync(tmp, sidecarPath)\n } catch (error) {\n discard(tmp, nodeFs)\n throw error\n }\n}\n\n/**\n * `versionChangedAt` is carried over only when the Node behind the file is the same one the previous\n * sidecar described: the triple, plus the size whenever the previous sidecar recorded one (a copy of a\n * same-version different build IS a different Node). A same-version relink after a re-mint must not\n * look like a Node bump to doctor's restart advisory. No parsable previous sidecar \u2192 `now`, which errs\n * towards one advisory too many, never too few.\n */\nconst nextSidecar = (\n previous: PortlessNodeSidecar | null,\n method: 'hardlink' | 'copy',\n exec: PortlessNodeStat,\n deps: EnsurePortlessNodeDeps,\n now: string,\n): PortlessNodeSidecar => {\n const sameNode =\n previous !== null &&\n describesProcess(previous, deps) &&\n (previous.sourceSize === undefined || previous.sourceSize === exec.size)\n\n return {\n method,\n version: deps.version,\n arch: deps.arch,\n platform: deps.platform,\n source: deps.execPath,\n ...(method === 'copy' ? { sourceSize: exec.size } : {}),\n refreshedAt: now,\n versionChangedAt: sameNode ? previous.versionChangedAt : now,\n }\n}\n\n/**\n * Converge `~/.infra-kit/node` on the Node running THIS install. Never throws; every outcome is a value.\n *\n * A symlink or directory at the path is `'failed'` and left exactly as found \u2014 this code owns a regular\n * file, and removing whatever someone else put there is the one destructive act a boot hook must never\n * take. A converged machine pays one `lstat`, one `stat` and a ~250-byte read: no write, no subprocess.\n *\n * @example\n * ensurePortlessNode({ isGlobal: () => true, home: '/Users/x', execPath: process.execPath, version: process.version, arch: process.arch, platform: process.platform })\n * // => { kind: 'node', outcome: 'created', node: '/Users/x/.infra-kit/node', source: process.execPath, version: process.version, method: 'hardlink' }\n */\nexport const ensurePortlessNode = (deps: EnsurePortlessNodeDeps): PortlessNodeResult => {\n const {\n home,\n execPath,\n version,\n fs: nodeFs = fs,\n now = () => {\n return new Date()\n },\n } = deps\n const node = portlessNodePath(home)\n const sidecarPath = portlessNodeSidecar(home)\n const result = (outcome: PortlessNodeOutcome, method: PortlessNodeResult['method']): PortlessNodeResult => {\n return { kind: 'node', outcome, node, source: execPath, version, method }\n }\n\n if (deps.platform !== 'darwin' && deps.platform !== 'linux') return result('skipped-platform', null)\n if (!deps.isGlobal()) return result('skipped-local', null)\n\n try {\n nodeFs.mkdirSync(dirname(node), { recursive: true })\n\n const current = nodeFs.lstatSync(node, { throwIfNoEntry: false })\n\n if (current !== undefined && !current.isFile()) return result('failed', null)\n\n const exec = nodeFs.statSync(execPath, { throwIfNoEntry: false })\n\n if (exec === undefined) return result('failed', null)\n\n const previous = readPortlessNodeSidecar(home, nodeFs)\n\n if (current !== undefined && previous !== null && isConverged(current, exec, previous, deps)) {\n return result('unchanged', previous.method)\n }\n\n sweepOrphans(dirname(node), [`${basename(node)}.tmp-`, `${basename(sidecarPath)}.tmp-`], nodeFs)\n\n const method = publishNode(execPath, node, nodeFs)\n\n publishSidecar(sidecarPath, nextSidecar(previous, method, exec, deps, now().toISOString()), nodeFs)\n\n return result(current === undefined ? 'created' : 'refreshed', method)\n } catch {\n return result('failed', null)\n }\n}\n"],
5
- "mappings": "8FAgCA,OAAOA,MAAQ,UACf,OAAS,WAAAC,OAAe,UACxB,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAOC,MAAa,eACpB,OAAS,iBAAAC,OAAqB,WCP9B,OAAS,YAAAC,OAAgB,qBACzB,OAAS,cAAAC,OAAkB,cAC3B,OAAS,cA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AAO,CACL,KAAM,CAAE,WAAYI,EAAoB,SAAAT,EAAU,KAAA5B,CAAK,EACvD,KAAM,CACJ,SAAA4B,EACA,KAAA5B,EACA,SAAUW,EAAQ,SAClB,QAASA,EAAQ,QACjB,KAAMA,EAAQ,KACd,SAAUA,EAAQ,QACpB,CACF,CACF,EAEM2B,EAAU,CAACC,EAAsBC,EAAiBC,IAA6D,CACnH,GAAI,CACFF,EAAIE,EAAI,EAAGD,CAAO,CACpB,MAAQ,CAER,CACF,EAQaE,GAAmB,CAACH,EAAsBb,IAAoC,CACzF,IAAMiB,EAASjB,GAAQK,GAAuB,EAE9CO,EAAQC,EAAK,gBAAiB,IACrBd,GAAmBkB,EAAO,IAAI,CACtC,EACDL,EAAQC,EAAK,gBAAiB,IACrBK,EAAmBD,EAAO,IAAI,CACtC,CACH",
6
- "names": ["fs", "homedir", "dirname", "join", "process", "fileURLToPath", "execFile", "createHash", "existsSync", "readFileSync", "http", "https", "net", "homedir", "dirname", "join", "process", "tls", "fileURLToPath", "promisify", "SHELL_SAFE", "SINGLE_QUOTE_ESCAPE", "shellQuote", "value", "shellLine", "argv", "execFileAsync", "promisify", "execFile", "readBinRel", "pkgJsonPath", "pkg", "readFileSync", "rel", "resolvePortlessBin", "dir", "dirname", "fileURLToPath", "join", "existsSync", "parent", "cachedBin", "portlessBin", "formatPortlessCommand", "args", "options", "words", "process", "shellLine", "DEFAULT_TIMEOUT_MS", "PROBE_TIMEOUT_MS", "PORTLESS_HEADER", "LOOPBACK", "PROBE_SERVERNAME", "DARWIN_SERVICE_LABEL", "DARWIN_SERVICE_PLIST_PATH", "LINUX_SERVICE_UNIT_PATH", "LINUX_SERVICE_UNIT_NAME", "defaultIsServiceInstalled", "exists", "defaultIsListening", "port", "resolve", "socket", "net", "finish", "result", "defaultIsProxyServing", "tls", "req", "https", "http", "res", "defaultRun", "timeoutMs", "bin", "withoutPackageManagerEnv", "portlessStateDir", "homedir", "CA_CERT_FILE", "CA_TRUST_MARKER_FILE", "readCaPath", "caFingerprintMatches", "recorded", "createHash", "handshakeChainsToCa", "servername", "ca", "authError", "authorized", "err", "listRoutes", "raw", "entry", "hostname", "createPortlessDriver", "deps", "run", "isListening", "isProxyServing", "isServiceInstalled", "availability", "tryRun", "isAvailable", "name", "fs", "basename", "dirname", "join", "process", "portlessNodePath", "home", "join", "USER_CONFIG_DIR_NAME", "portlessNodeSidecar", "isSidecar", "value", "record", "strings", "key", "COPY_FLAGS", "fs", "COPY_MODE", "readPortlessNodeSidecar", "nodeFs", "parsed", "sameInode", "a", "b", "stableNodeCandidate", "input", "execPath", "node", "current", "exec", "describesProcess", "sidecar", "deps", "isConverged", "discard", "tmp", "sweepOrphans", "dir", "prefixes", "names", "name", "prefix", "stageNode", "publishNode", "process", "method", "error", "publishSidecar", "sidecarPath", "nextSidecar", "previous", "now", "sameNode", "ensurePortlessNode", "version", "result", "outcome", "dirname", "basename", "portlessLinkPath", "home", "join", "USER_CONFIG_DIR_NAME", "portlessLinkCliPath", "exists", "fs", "cliPath", "serviceInstallCommand", "bin", "seams", "execPath", "process", "stableNode", "stableNodeCandidate", "formatPortlessCommand", "ABSENT", "NOT_A_SYMLINK", "readCurrentLink", "link", "linkFs", "stat", "writeLink", "target", "tmp", "error", "ensurePortlessLink", "deps", "resolveBin", "isGlobal", "dirname", "current", "realPortlessStableDeps", "homedir", "global", "isGlobalInstall", "fileURLToPath", "safeRealpath", "resolvePortlessBin", "logStep", "log", "message", "run", "bootPortlessLink", "stable", "ensurePortlessNode"]
7
- }
@@ -1,7 +0,0 @@
1
- import{P as p,S as w,ba as C,d,f as u,fa as g}from"./chunk-FRBNA6VH.js";import{o as b}from"./chunk-QSTGO43H.js";import{a as A,b as D}from"./chunk-QWVLAZ6N.js";var H=()=>{let e="",r=[],t=!1;return{start(n){e=n,r=[],t=!1},setInteractive(){t=!0},addOption(n,o){r.push({flag:n,value:o})},formatOptions(){return r.map(n=>typeof n.value=="boolean"?n.value?n.flag:"":Array.isArray(n.value)?`${n.flag} "${n.value.join(", ")}"`:`${n.flag} "${n.value}"`).filter(Boolean).join(" ")},snapshot(){return r.length===0?null:{formattedOptions:this.formatOptions()}},print(){!t||r.length===0||!e||p.info(`\u{1F4DF} Equivalent command:
2
- pnpm exec infra-kit ${e} ${this.formatOptions()}
3
- `)},reset(){e="",r=[],t=!1}}},x=H();import{isAbsolute as $,resolve as I}from"node:path";import M from"node:process";var E=null,y=null,K=e=>{E=[...e],y=M.cwd()},q=new Set(["--yes","-y"]),B=(e,r)=>{let t=[...e];for(let[n,o]of t.entries())o==="-C"&&t[n+1]!==void 0&&!$(t[n+1])?t[n+1]=I(r,t[n+1]):o.startsWith("-C")&&o.length>2&&!o.startsWith("--")&&!$(o.slice(2))&&(t[n]=`-C${I(r,o.slice(2))}`);return t},S=()=>{if(E===null||y===null)return["--yes"];let e=B(E.slice(2),y);return e.some(t=>q.has(t))?e:[...e,"--yes"]};import _ from"node:process";var J=27,L=e=>e===null?"an interactive prompt was reached under --json, which never prompts":`an interactive prompt was reached in agent mode (${e==="flag"?"--agent":"INFRA_KIT_AGENT / CLAUDECODE"}), where there is no human to answer it`,W=e=>`${e===void 0?"pass the value explicitly instead of relying on the prompt":`pass --${e}`} on the re-run`,z=e=>{if(typeof e=="object"&&"value"in e)return e.value;let r=typeof e=="object"?e.refuse:void 0,{source:t}=d;throw new g(r===void 0?{status:"refused",agentMode:t}:{status:"argument_required",argument:r,agentMode:t},2,{operation:"interactive prompt",remediation:W(r),stderrExcerpt:L(t)})},j=async(e,r)=>{let t=new AbortController,{whenHeadless:n="refuse",...o}=r??{},s={...o,signal:t.signal};if(u())return z(n);if(!_.stdin.isTTY)return e(s);let m=_.stdin,P=f=>{f.length===1&&f[0]===J&&t.abort()};A();try{let f=e(s);return m.isPaused()&&m.resume(),m.on("data",P),await f}finally{m.removeListener("data",P),D()}};import U from"@inquirer/confirm";import Y from"node:process";var a=class extends Error{constructor(r="Operation cancelled by the operator"){super(r),this.name="CommandDeclinedError"}},de=e=>e instanceof a;var N=(e,r,t=S())=>{let{source:n}=d;throw new g({status:"confirmation_required",message:e,plan:r,rerun:t,agentMode:n},2,{operation:"confirm before running",remediation:n===null?"pass `--yes` to confirm, or drop `--json` to be prompted":`show the plan to the human, then re-run \`infra-kit ${t.join(" ")}\` to confirm`,stderrExcerpt:"confirmation required and nobody to ask"})},G=async(e,r,t={})=>{!e&&u()&&N(r,t.plan,t.rerun);let n=e?!0:await j(o=>U({message:r},o),{whenHeadless:"refuse"});if(e||x.setInteractive(),!n){if(t.throwOnDecline)throw new a;p.info("Operation cancelled. Exiting..."),Y.exit(0)}};import h from"node:fs/promises";import l from"node:path";import{z as i}from"zod";var c=class extends Error{env;constructor(r,t=null){super(r),this.name="EnvAuthError",this.env=t}};var V="tokens.json",v=1,R=384,F=448,Q=i.object({version:i.literal(v).default(v),envs:i.record(i.string().min(1),i.string().min(1))}).strict(),T=async()=>{let e=await C();return l.join(l.dirname(e.userProject),V)},k=async()=>{let e=await T(),r;try{r=await h.readFile(e,"utf-8")}catch{return null}let t;try{t=JSON.parse(r)}catch(o){throw new c(`Invalid JSON in the token store at ${w(e)}: ${o.message}
4
- Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`)}let n=Q.safeParse(t);if(!n.success)throw new c(`Invalid token store at ${w(e)}: ${i.prettifyError(n.error)}
5
- Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return n.data},O=async e=>{let r=await T(),t=l.dirname(r),n=l.dirname(t),o=l.dirname(n);for(let s of[o,n,t])await h.mkdir(s,{recursive:!0,mode:F}),await h.chmod(s,F);b(r,`${JSON.stringify(e,null,2)}
6
- `,R),await h.chmod(r,R)},X=async(e,r)=>{let t=await k();await O({version:v,envs:{...t?.envs,[e]:r}})},Z=async e=>{let r=await k();if(!r||!(e in r.envs))return;let t={...r.envs};delete t[e],await O({version:v,envs:t})};export{x as a,de as b,K as c,S as d,j as e,N as f,G as g,c as h,T as i,k as j,X as k,Z as l};
7
- //# sourceMappingURL=chunk-DW2SQ2XU.js.map
@@ -1,4 +0,0 @@
1
- import R from"node:fs";import u from"node:os";import I from"node:path";import F from"node:process";var h="env-load.sh",O="env-clear.sh",A="INFRA_KIT_SESSION",S=".infra-kit",f="INFRA_KIT_ENV",x="INFRA_KIT_ENV_CONFIG",v="INFRA_KIT_ENV_PROJECT",d="INFRA_KIT_ENV_PROJECT_ROOT",K="INFRA_KIT_ENV_LOADED_AT",m=/^([A-Z_]\w*)=/i,C=/^unset ([A-Z_]\w*)$/i,c=(t,e)=>{let s=e;for(let n=0;n<t.length;n++){if(!s&&t[n]==="\\"){n++;continue}t[n]==="'"&&(s=!s)}return s},D=t=>{let e=t.startsWith("'")?t.slice(1):t;return(e.endsWith("'")?e.slice(0,-1):e).split("'\\''").join("'")},p=t=>{try{return R.readFileSync(t,"utf-8")}catch{return""}},g=(t,e,s)=>{let n=t.split(`
2
- `).map(o=>o.endsWith("\r")?o.slice(0,-1):o),r=0,i=!1;for(;r<n.length;){let o=n[r];if(i){i=c(o,i),r+=1;continue}let a=m.exec(o);if(!a){let _=C.exec(o);_&&s?.(_[1]),i=c(o,!1),r+=1;continue}let l=a[1],E=o.slice(a[0].length);if(!E.startsWith("'")){e({name:l,value:E}),i=c(o,!1),r+=1;continue}let T=[E],N=c(E,!1);for(;N&&r+1<n.length;){r+=1;let _=n[r];T.push(_),N=c(_,!0)}e({name:l,value:D(T.join(`
3
- `))}),i=N,r+=1}},L=t=>{let e=[];return g(p(t),({name:s})=>{e.push(s)}),e},y=t=>{let e={};return g(p(t),({name:s,value:n})=>{e[s]=n}),e},W=t=>{let e=[];return g(p(t),()=>{},s=>{e.push(s)}),e},V=()=>{let t=F.env.XDG_CACHE_HOME,e=t&&t.length>0?t:I.join(u.homedir(),".cache");return I.join(e,"infra-kit")},P=()=>{let t=F.env[A];if(!t)throw new Error(`${A} is not set. Run \`infra-kit setup --skip-tools\` then \`source ~/.zshrc\`.`);return I.join(V(),t)},U=(t,e,s)=>{let n=`${t}.tmp.${F.pid}`;R.writeFileSync(n,e,{mode:s});try{R.renameSync(n,t)}catch(r){throw R.rmSync(n,{force:!0}),r}},w="-worktrees",b={release:"release",feature:"feature",mergeDev:"merge-dev"};export{h as a,O as b,A as c,S as d,f as e,x as f,v as g,d as h,K as i,L as j,y as k,W as l,V as m,P as n,U as o,w as p,b as q};
4
- //# sourceMappingURL=chunk-QSTGO43H.js.map
@@ -1,7 +0,0 @@
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\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 * 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', mergeDev: 'merge-dev' } as const\n"],
5
- "mappings": "AAAA,OAAOA,MAAQ,UACf,OAAOC,MAAQ,UACf,OAAOC,MAAU,YACjB,OAAOC,MAAa,eAEb,IAAMC,EAAgB,cAChBC,EAAiB,eAEjBC,EAAwB,oBAYxBC,EAAuB,aAQvBC,EAAoB,gBACpBC,EAA2B,uBAC3BC,EAA4B,wBAK5BC,EAAiC,6BACjCC,EAA8B,0BAO9BC,EAAuB,iBAM9BC,EAAqB,uBAQrBC,EAA0B,CAACC,EAAcC,IAAmC,CAChF,IAAIC,EAAUD,EAEd,QAASE,EAAI,EAAGA,EAAIH,EAAK,OAAQG,IAAK,CACpC,GAAI,CAACD,GAAWF,EAAKG,CAAC,IAAM,KAAM,CAChCA,IACA,QACF,CAEIH,EAAKG,CAAC,IAAM,MACdD,EAAU,CAACA,EAEf,CAEA,OAAOA,CACT,EAaME,EAAsBC,GAAwB,CAClD,IAAMC,EAAcD,EAAI,WAAW,GAAG,EAAIA,EAAI,MAAM,CAAC,EAAIA,EAGzD,OAFaC,EAAY,SAAS,GAAG,EAAIA,EAAY,MAAM,EAAG,EAAE,EAAIA,GAExD,MAAM,OAAO,EAAE,KAAK,GAAG,CACrC,EAGMC,EAAsBC,GAA6B,CACvD,GAAI,CACF,OAAOxB,EAAG,aAAawB,EAAU,OAAO,CAC1C,MAAQ,CACN,MAAO,EACT,CACF,EASMC,EAAoB,CACxBC,EACAC,EACAC,IACS,CAGT,IAAMC,EAAQH,EAAQ,MAAM;AAAA,CAAI,EAAE,IAAKV,GAC9BA,EAAK,SAAS,IAAI,EAAIA,EAAK,MAAM,EAAG,EAAE,EAAIA,CAClD,EACGc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ECT_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", "WORKTREE_SUBDIRS"]
7
- }
@@ -1,10 +0,0 @@
1
- import{a as x,e as re,h as S,i as te,j as p}from"./chunk-DW2SQ2XU.js";import{P as a,S as ee,ca as b,d,e as D,f as Q,fa as m,h as _,i as X,w as P}from"./chunk-FRBNA6VH.js";import{a as J,c as T,e as W,f as Z,g as U,h as G,i as H,n as B,o as Y}from"./chunk-QSTGO43H.js";import We from"@inquirer/select";import{Buffer as Ze}from"node:buffer";import Ue from"node:fs";import Ge from"node:path";import z from"node:process";import{z as k}from"zod";import{$ as I}from"zx";var Te="Could not find requested project",Pe="Could not find requested config",oe="Invalid Auth token",ne="does not have access to requested config",A=e=>e.includes(oe)||e.includes(ne)?"auth":e.includes(Te)?"project":e.includes(Pe)?"config":"unknown",R=e=>e.includes(ne)?"mis-scoped":e.includes(oe)?"revoked":null;var se=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??se(r),r),this.name="DopplerAuthError",this.authKind=t}};var $=({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 Ae=5e3,Re="DOPPLER_CONFIG",g=async()=>{let{envManagement:e}=await b();return e.config.name},De=async({childEnv:e,project:r,config:t})=>{let o=N.quiet;N.quiet=!0;try{let s=(await N({env:e})`doppler secrets get ${Re} --plain --project ${r} --config ${t}`.timeout(Ae)).stdout.trim();return s!==t?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(n){return{outcome:_e(n)}}finally{N.quiet=o}},_e=e=>{let r=_(e)??(e instanceof Error?e.message:String(e));return A(r)!=="auth"?"unreachable":R(r)??"unreachable"};import be from"node:process";var l="INFRA_KIT_ENV_TOKEN",K=async e=>{let r=be.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(xe(e,await te()),e)},xe=(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 ${ee(r)} (mode 0600, never in the repo).`,`CI / agents: set ${l} instead \u2014 it takes precedence and needs no home config.`].join(`
4
- `);import ge from"node:process";import{z as me}from"zod";import Le from"node:process";import{z as u}from"zod";var ie=["prod"],v={allowed:!1,reason:"disallow"},h=e=>ie.includes(e),Se=["dev","stage"],Ne=e=>Se.includes(e)||h(e),Oe=(e,r=v)=>r.allowed?e:e.filter(t=>!h(t)),je=(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 X(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 Fe=async()=>{let e;try{e=(await b()).protectedEnvs??"disallow"}catch{return v}return e==="disallow"?v:e==="cli-only"&&D()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var Ie=e=>{let{env:r,branch:t}=e;h(r)&&a.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 ae from"node:fs/promises";import L from"node:path";import $e from"yaml";var ce=".github/workflows",Ke=async e=>{let r=await P();return le(L.resolve(r,ce,e))},C=async()=>{let e=await P(),r=L.resolve(e,ce),t;try{t=await ae.readdir(r)}catch{return[]}let o=t.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),n=await Promise.all(o.map(s=>le(L.resolve(r,s))));return[...new Set(n.flat())]},le=async e=>{let r;try{r=$e.parse(await ae.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 C(),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]},M=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])})),pe=["Environment","Source","Token"],Ce=e=>{let r=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),t=pe.map((s,i)=>Math.max(s.length,...r.map(c=>(c[i]??"").length))),o=s=>s.map((i,c)=>i.padEnd(t[c]??0)).join(" | ").trimEnd(),n=t.map(s=>"\u2500".repeat(s)).join("\u2500\u253C\u2500");return["Environments:","",o(pe),n,...r.map(o)]},de=async()=>{let e=await g(),r=await w(),t=await p(),o=Le.env[l],n=F(r,t?.envs??{},o);if(a.info(`Doppler project: ${e}
6
- `),n.length===0)return a.info("No environments found."),a.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),a.info(" or add a token for one manually."),ue({project:e,envs:n});for(let s of Ce(n))a.info(s);return ue({project:e,envs:n})},ue=({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}},Me=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:de});var fe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ve=async e=>{try{return await e}catch{return[]}},ze=async e=>{let r=await p().catch(()=>null);return F(e,r?.envs??{},ge.env[l]).filter(t=>!t.hasToken).map(t=>t.env)},V=()=>({get message(){return`Choose the environment to load into terminal session ${ge.env[T]??`UNKNOWN \u2014 ${T} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>fe(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await Ve(w());if(e.length===0)return a.info({msg:"Tool execution form options empty: env-load"}),null;let r=e.map(o=>o.env),t=await ze(e);return me.object({config:me.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:{...fe(r)?r:{},config:t}}});import{z as qe}from"zod";var Je=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(r){return a.debug({err:r,operation:e.operation},"argument form builder threw; refusing without choices"),null}},ve=async e=>{if(!Q()||!e.provider.isFormable(e.params))return;let r=await Je(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:qe.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 He="DOPPLER_CONFIG",he=new Set(["DOPPLER_TOKEN",l]),Ee=!1,Be=e=>{e.length===0||Ee||(Ee=!0,a.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},Ye=({pairs:e,config:r,project:t,projectRoot:o,loadedAt:n})=>{let s=e.filter(([i])=>!he.has(i));return Be(e.filter(([i])=>he.has(i)).map(([i])=>i)),["set -a",...s.map(([i,c])=>`${i}=${y(c)}`),`${W}=${y(r)}`,`${Z}=${y(r)}`,`${U}=${y(t)}`,`${G}=${y(o)}`,`${H}=${y(n)}`,"set +a"]},Qe=async()=>{try{return await P()}catch{return""}},Xe=async({config:e})=>{let r=await g(),t=await Qe(),o=await ye(r,e),n=new Date().toISOString(),i=`${Ye({pairs:o,config:e,project:r,projectRoot:t,loadedAt:n}).join(`
7
- `)}
8
- `,c=B(),q=Ge.resolve(c,J);return Ue.mkdirSync(c,{recursive:!0,mode:448}),Y(q,i,384),{filePath:q,variableCount:o.length,project:r,config:e}},ke=V(),er=async e=>{let{config:r}=e;await ve({provider:ke,params:e,operation:"env-load",argument:"config"});let t="";if(r)t=r;else{if(D())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 M();x.setInteractive(),t=await re(i=>We({message:"Select environment config",choices:s.map(c=>({name:c,value:c}))},i),{output:z.stderr,whenHeadless:"refuse"})}x.addOption("--config",t);let o=await Xe({config:t});x.print();let n={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config,sessionId:z.env[T]??null};return{content:O(JSON.stringify(n,null,2)),structuredContent:n}},we=1024*1024,rr=3e4,tr=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],or=(e,r=z.env)=>{let t={...r};for(let o of tr)delete t[o];return t.DOPPLER_TOKEN=e,t},Gt=async e=>new Map(await ye(await g(),e)),ye=async(e,r)=>{let{token:t}=await K(r),o=or(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(rr)}catch(c){throw sr(c,e,r)}ir(s.stdout);let i=cr(s.stdout);return nr(i,r),i}finally{I.quiet=n}},nr=(e,r)=>{let t=e.find(([o])=>o===He)?.[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.
9
- Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},sr=(e,r,t)=>{let o=_(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($({kind:n,project:r,config:t,available:null}))},ir=e=>{let r=Ze.byteLength(e,"utf-8");if(r>we)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${we}) \u2014 refusing to write to disk`)},y=e=>`'${e.replaceAll("'","'\\''")}'`,ar=/^[A-Z_]\w*$/i,cr=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(!ar.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},Ht=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:ke,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:er});export{O as a,j as b,A as c,R as d,g as e,De as f,l as g,K as h,h as i,Ne as j,Oe as k,je as l,Fe as m,Ie as n,Ke as o,M as p,de as q,Me as r,ve as s,Ye as t,Xe as u,er as v,we as w,or as x,Gt as y,nr as z,sr as A,ir as B,y as C,cr as D,Ht as E};
10
- //# sourceMappingURL=chunk-UD6VVXUY.js.map
@@ -1,7 +0,0 @@
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 { 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 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 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 * 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 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": "2QAAA,OAAOA,OAAY,mBACnB,OAAS,UAAAC,OAAc,cACvB,OAAOC,OAAQ,UACf,OAAOC,OAAU,YACjB,OAAOC,MAAa,eACpB,OAAS,KAAAC,MAAS,MAClB,OAAS,KAAAC,MAAS,KCyBlB,IAAMC,GAA2B,mCAC3BC,GAA0B,kCAS1BC,GAAuB,qBACvBC,GAAqB,2CAcdC,EAA0BC,GACjCA,EAAO,SAASH,EAAoB,GAAKG,EAAO,SAASF,EAAkB,EAAU,OAErFE,EAAO,SAASL,EAAwB,EAAU,UAElDK,EAAO,SAASJ,EAAuB,EAAU,SAE9C,UAsBIK,EAA8BD,GACrCA,EAAO,SAASF,EAAkB,EAAU,aAE5CE,EAAO,SAASH,EAAoB,EAAU,UAE3C,KA4CF,IAAMK,GAAkCC,GACtC,CACL,+CAA+CA,CAAG,oE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,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,QAASnD,EACX,CAAC",
6
- "names": ["select", "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", "writeEnvLoadFile", "getDopplerProject", "downloadDopplerSecrets", "fileContents", "cacheDir", "getSessionCacheDir", "envFilePath", "path", "ENV_LOAD_FILE", "fs", "atomicWriteFileSync", "envLoadForm", "createEnvLoadFormProvider", "envLoad", "args", "refuseMissingArguments", "selectedConfig", "isAgentMode", "StructuredRefusalError", "agentMode", "envs", "listProjectEnvNames", "commandEcho", "withEscape", "context", "select", "env", "process", "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
- }