infra-kit 0.11.16 → 0.13.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.
- package/dist/{boot-XLDVLQEG.js → boot-LC2ESPY6.js} +2 -2
- package/dist/chunk-D76UWTR5.js +13 -0
- package/dist/chunk-D76UWTR5.js.map +7 -0
- package/dist/chunk-EU7LD5IV.js +7 -0
- package/dist/chunk-EU7LD5IV.js.map +7 -0
- package/dist/chunk-FKA65HOC.js +2 -0
- package/dist/chunk-FKA65HOC.js.map +7 -0
- package/dist/chunk-LR57E6IP.js +10 -0
- package/dist/chunk-LR57E6IP.js.map +7 -0
- package/dist/chunk-Y3RW74TE.js +2 -0
- package/dist/chunk-Y3RW74TE.js.map +7 -0
- package/dist/{chunk-TT7OQ4PI.js → chunk-Z4ZY2G4O.js} +5 -5
- package/dist/{chunk-TT7OQ4PI.js.map → chunk-Z4ZY2G4O.js.map} +3 -3
- package/dist/cli.js +125 -122
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +24 -24
- package/dist/dev-server.js.map +4 -4
- package/dist/dev-wizard-run-SHX5YW6J.js +2 -0
- package/dist/dev-wizard-run-SHX5YW6J.js.map +7 -0
- package/dist/env-load-EYVU4TIM.js +2 -0
- package/dist/env-load-EYVU4TIM.js.map +7 -0
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- package/readme.md +6 -4
- package/dist/chunk-6SLDCUNI.js +0 -2
- package/dist/chunk-6SLDCUNI.js.map +0 -7
- package/dist/chunk-J7KIXQRB.js +0 -12
- package/dist/chunk-J7KIXQRB.js.map +0 -7
- package/dist/chunk-UZTYMT6R.js +0 -7
- package/dist/chunk-UZTYMT6R.js.map +0 -7
- package/dist/dev-wizard-run-QIOXS26F.js +0 -2
- package/dist/dev-wizard-run-QIOXS26F.js.map +0 -7
- /package/dist/{boot-XLDVLQEG.js.map → boot-LC2ESPY6.js.map} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/command-echo/command-echo.ts", "../src/lib/parsed-argv/parsed-argv.ts", "../src/lib/prompts/escapable-context.ts", "../src/lib/command-echo/confirm-or-exit.ts", "../src/lib/errors/command-declined-error.ts", "../src/lib/env-tokens/env-tokens.ts", "../src/lib/errors/env-auth-error.ts"],
|
|
4
|
+
"sourcesContent": ["import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n *\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the handler was called off the CLI (a test, an in-process caller), where a\n * `pnpm exec` line would be nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be\n * worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import { isAbsolute, resolve } from 'node:path'\nimport process from 'node:process'\n\n/**\n * The argv Commander actually parsed for this run \u2014 captured by `entry/cli.ts` at the one place it\n * hands an argv to `parseAsync`, the interactive-menu re-entry included. Commands that need to name\n * their own invocation (a `confirmation_required` refusal's `rerun`) read it here instead of\n * `process.argv`, which the menu path never rewrites.\n */\n\nlet parsedArgv: readonly string[] | null = null\nlet launchCwd: string | null = null\n\n/**\n * Record the full node-style argv (`[node, script, ...args]`) handed to `parseAsync`, and the cwd it\n * was typed in \u2014 read NOW because the `-C` chdir in `preAction` runs later, and a relative `-C` only\n * means anything against this directory.\n */\nexport const setParsedArgv = (argv: readonly string[]): void => {\n parsedArgv = [...argv]\n launchCwd = process.cwd()\n}\n\nconst YES_FLAGS = new Set(['--yes', '-y'])\n\n/**\n * Make every `-C <dir>` in `args` absolute against `cwd`, in place. Commander accepts both\n * `-C dir` and `-Cdir`; both are handled so the re-run is cwd-independent whichever way it was typed.\n */\nconst absolutizeChangeDir = (args: string[], cwd: string): string[] => {\n const out = [...args]\n\n for (const [index, token] of out.entries()) {\n if (token === '-C' && out[index + 1] !== undefined && !isAbsolute(out[index + 1] as string)) {\n out[index + 1] = resolve(cwd, out[index + 1] as string)\n } else if (token.startsWith('-C') && token.length > 2 && !token.startsWith('--') && !isAbsolute(token.slice(2))) {\n out[index] = `-C${resolve(cwd, token.slice(2))}`\n }\n }\n\n return out\n}\n\n/**\n * The argv an agent re-runs to confirm what this run refused: the captured user args with `--yes`\n * appended and any relative `-C` made absolute, so the next Bash call may run from any cwd.\n *\n * Appending is safe: no leaf uses `passThroughOptions` or `--`, and the only variadic option\n * (`--project <names...>`) stops at `--yes`. An argv that already carries `--yes`/`-y` is returned\n * as-is \u2014 a second copy would be noise, and a confirm that fired despite it is not this function's\n * problem to hide.\n *\n * @example\n * // captured: ['node', 'infra-kit', '-C', 'app', 'release', 'remove', '1.2.3', '--json'], cwd /w\n * rerunArgv() // ['-C', '/w/app', 'release', 'remove', '1.2.3', '--json', '--yes']\n */\nexport const rerunArgv = (): string[] => {\n if (parsedArgv === null || launchCwd === null) return ['--yes']\n\n const args = absolutizeChangeDir(parsedArgv.slice(2), launchCwd)\n\n const alreadyConfirmed = args.some((token) => {\n return YES_FLAGS.has(token)\n })\n\n return alreadyConfirmed ? args : [...args, '--yes']\n}\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport type { AgentModeSource } from 'src/lib/agent-mode'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\n/**\n * What this call site does when there is no human: refuse, refuse NAMING the argument that would have\n * answered the prompt, or answer with a fixed value.\n *\n * - `'refuse'` \u2014 throw `{ status: 'refused' }`: the site has no single argument to name.\n * - `{ refuse: 'version' }` \u2014 throw `{ status: 'argument_required', argument: 'version' }`: the\n * agent is told exactly what to pass on the re-run. The name is the CLI flag / tool field without\n * its dashes; G8 (`headless-policy-guards`) checks it exists on every owning tool's schema.\n * - `{ value: T }` \u2014 answer with `value`, no throw.\n *\n * There is no `'unreachable'` any more: that was a claim about the retired server's schema making a\n * field required, and no schema stands between a Bash-driven agent and this prompt.\n */\nexport type HeadlessPolicy<T> = 'refuse' | { refuse: string } | { value: T }\n\n/** {@link withEscape}'s options: the prompt context, plus this site's headless policy. */\nexport type EscapeOptions<T> = PromptContext & { whenHeadless?: HeadlessPolicy<T> }\n\nconst ESC_BYTE = 0x1b\n\n// Widening the existing options object rather than adding a third parameter: six call sites already\n// pass a `PromptContext` (`entry/cli.ts`, `env-load`, `env-token-set`, and the wizard's shared\n// context used by three prompts), all of them `{ output: process.stderr }` for documented reasons \u2014\n// `env-token-set.ts:64-68` notes that some env commands run inside `$(\u2026)`, where a prompt on stdout\n// would leave the user typing a credential into a captured stream. A third parameter would have\n// forced every one of them to grow a positional `undefined`.\n//\n// Optional, and the default is `'refuse'`. That default is safe for the same reason the guard exists\n// at all: under `isAgentMode()` nobody is at the keyboard, so no prompt at any site can return a\n// usable answer, and refusing removes no\n// capability that exists. It is what CLI-only sites (the palette, the dev wizard, `env-token-set`)\n// keep, because they face a real human.\n//\n// It is NOT what an agent-reachable site may keep. There, omitting `whenHeadless` is indistinguishable\n// from never having considered the question, so G7 (`every-inquirer-site-is-escapable`) requires the\n// answer to be written out \u2014 `'refuse'` included.\n//\n// What the default is NOT is *correct* everywhere \u2014 that distinction is the whole point of the\n// parameter. `worktrees-add` documents a `false` fallback for agents in its own schema, so a refusal\n// there is right-outcome-by-accident at best and a regression at worst. The type cannot tell those\n// apart; G6 (description-to-policy) and G8 (argument-to-schema) are what check the answers,\n// because a wrong answer here compiles and can never fail a test on its own.\nconst headlessExcerpt = (source: AgentModeSource): string => {\n if (source === null) return 'an interactive prompt was reached under --json, which never prompts'\n\n return `an interactive prompt was reached in agent mode (${source === 'flag' ? '--agent' : 'INFRA_KIT_AGENT / CLAUDECODE'}), where there is no human to answer it`\n}\n\nconst headlessRemediation = (argument: string | undefined): string => {\n const passIt =\n argument === undefined ? 'pass the value explicitly instead of relying on the prompt' : `pass --${argument}`\n\n return `${passIt} on the re-run`\n}\n\nconst resolveHeadless = <T>(policy: HeadlessPolicy<T>): T => {\n if (typeof policy === 'object' && 'value' in policy) return policy.value\n\n const argument = typeof policy === 'object' ? policy.refuse : undefined\n const { source } = agentMode\n\n throw new StructuredRefusalError(\n argument === undefined\n ? { status: 'refused', agentMode: source }\n : { status: 'argument_required', argument, agentMode: source },\n 2,\n {\n operation: 'interactive prompt',\n remediation: headlessRemediation(argument),\n stderrExcerpt: headlessExcerpt(source),\n },\n )\n}\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation. On Esc the prompt rejects with an\n * `AbortPromptError`, which `entry/cli.ts` already catches at the top level -> \"Operation\n * cancelled.\" -> exit 0.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a sufficient\n * guard \u2014 see lib/agent-mode for why `stdio: 'inherit'` defeats it.\n */\n// The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal goes into the\n// prompt context, `@inquirer/core` rejects with an `AbortPromptError` when it fires, and that name\n// is already in `CANCELLATION_ERROR_NAMES` (lib/errors/is-prompt-cancellation). All this adds is\n// the thing that calls `abort()`.\n//\n// DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b` byte.\n// Deliberately NOT readline `keypress`: that delivers a lone Esc only after its escape-sequence\n// timeout (~523ms measured), and the `escapeCodeTimeout` dial that would shorten it is\n// process-global and first-armer-wins \u2014 a second `emitKeypressEvents` call on `process.stdin` is\n// SILENTLY IGNORED, so the dial degrades to a no-op with no error and no failing test. The raw\n// listener costs ~24ms and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n// (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is involved. Node\n// `data` listeners broadcast, so this one does not steal bytes from readline: arrows and Enter keep\n// working while it is attached.\n//\n// FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk. Focus events\n// (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports (`\\x1b[M\u2026`) are all\n// multi-byte, and inquirer enables none of them.\n//\n// FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE chunk, i.e.\n// Esc immediately followed by another key) is silently dropped and the prompt stays open. The fix\n// would be Ink's 20ms deferred abort \u2014 hold the lone Esc, cancel it if a follow-up chunk lands.\n// That is a logged NON-GOAL; do not pre-build it.\nexport const withEscape = async <T>(\n run: (context: PromptContext) => Promise<T>,\n base?: EscapeOptions<T>,\n): Promise<T> => {\n const controller = new AbortController()\n // `whenHeadless` is ours, not inquirer's \u2014 split it off so it never reaches a prompt's context.\n const { whenHeadless = 'refuse', ...promptBase } = base ?? {}\n const context: PromptContext = { ...promptBase, signal: controller.signal }\n\n // Keyed on `isHeadless()`. `!isTTY` deliberately does NOT ride along: a piped-but-human\n // run (`infra-kit worktrees add > log.txt`) has no TTY and still deserves its prompt, and the two\n // conditions were only ever collapsed here because both merely skipped the Esc listener. Now that\n // this branch decides an ANSWER rather than just a listener, conflating them would refuse prompts\n // no agent is waiting on. `release-picker.ts` keeps its own `!isTTY` clause for its own reason.\n //\n // `--json` joins because a prompt is stdout traffic on a stream a machine is parsing, and because\n // `release-picker`/`source-picker` already treat `--json` as never-prompt \u2014 this makes the 20 sites\n // agree with those two.\n if (isHeadless()) return resolveHeadless(whenHeadless)\n\n if (!process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // STDIN OWNERSHIP \u2014 this is the seam that keeps stdin alive for inquirer, which refs\n // nothing itself. It must sit BELOW the early return above: a non-TTY run never reads\n // stdin, so acquiring there would ref a handle nobody reads and hang the process. See\n // lib/prompts/stdin-ref for why an unref'd stdin kills a prompt with exit 13.\n acquireStdin()\n\n try {\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n //\n // INSIDE the `try`, both of them: `run` is caller-supplied and `@inquirer/core` runs\n // synchronously up to readline construction, so a SYNCHRONOUS throw here would skip a\n // `finally` placed any lower \u2014 leaking the ref and hanging the CLI, which is the exact\n // failure this module exists to prevent.\n const pending = run(context)\n\n // Explicit, because `on('data')` alone is NOT enough to start the flow: `Readable` resumes on a\n // new `data` listener only when `flowing !== false`, and the palette's teardown now pauses stdin\n // (tui/boot.tsx) so a prompt opened after an Ink screen inherits `flowing === false`. Esc would be\n // silently dead. It happens to work anyway today \u2014 `run()` above builds inquirer's readline, whose\n // constructor resumes the stream \u2014 but that is an undocumented side effect of a TRANSITIVE\n // dependency, and the ordering it relies on is the very thing the comment below reserves the right\n // to change. One idempotent call is cheaper than that coupling.\n if (input.isPaused()) input.resume()\n\n input.on('data', onData)\n\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n // Same `finally` as the listener teardown, and for the same reason: every exit path\n // (answer, Esc abort, throw) must give the ref back, or node never exits.\n releaseStdin()\n }\n}\n", "/**\n * @fileoverview\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (`--yes`, the argv a `confirmation_required`\n * refusal hands back) the prompt is skipped and execution proceeds. Otherwise, with no human to ask \u2014 agent mode, or `--json`, whose\n * stdout a machine is parsing \u2014 it throws a `confirmation_required` refusal\n * carrying the argv that confirms (preview-then-execute, no new flag). Otherwise\n * it prompts the user, marks the echo as interactive, and exits cleanly if the\n * user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path: headless\n * callers refuse above it, so a `--json` document is never cut short by it.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nimport confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport { CommandDeclinedError } from 'src/lib/errors/command-declined-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { logger } from 'src/lib/logger'\nimport { rerunArgv } from 'src/lib/parsed-argv'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\nexport interface ConfirmOrExitOptions {\n /**\n * The structured form of what `message` renders, handed back verbatim in the\n * `confirmation_required` payload so an agent can show the human WHAT it is\n * about to confirm without parsing prose. JSON-safe and secret-free \u2014 it is\n * emitted to stdout. Sites with no structured plan pass nothing.\n */\n plan?: unknown\n /**\n * Throw {@link CommandDeclinedError} on a decline instead of `process.exit(0)`.\n *\n * **Defaults to false, and must stay that way.** Seven commands call this\n * helper; flipping the default would change the exit semantics of all of them\n * at once, inside a change whose tests cover none of them.\n *\n * Opt in when the command has already acquired something that needs releasing\n * by the time it prompts \u2014 `process.exit` skips every `finally`, so for those\n * commands the decline path is precisely where a resource leaks. The caller\n * owns catching it and exiting 0: a decline is a successful outcome.\n */\n throwOnDecline?: boolean\n /**\n * The argv that confirms, when it must carry more than this run's own argv plus `--yes` \u2014 e.g.\n * the content hash the human is approving. Defaults to `rerunArgv()`.\n */\n rerun?: string[]\n}\n\n/**\n * Throw the `confirmation_required` refusal an agent (or a `--json` run) gets in place of a confirm\n * prompt: the message, the site's plan, the argv that confirms, and the source. Exit 2 \u2014 nothing ran.\n *\n * Exported for the one confirm site that is not `confirmOrExit` (`lib/release-deploy/confirm-deploy`),\n * so both speak the same shape.\n */\n// Thrown from HERE, not from `withEscape`'s headless branch, because it needs what only a confirm\n// site has: the message, the plan, and the knowledge that `--yes` is the answer. Callers key it on\n// `isHeadless()`, never on `confirmedCommand`, so their `--yes` short-circuit stays as it was for\n// agent and human alike.\nexport const refuseUnconfirmed = (message: string, plan?: unknown, rerun: string[] = rerunArgv()): never => {\n const { source } = agentMode\n\n throw new StructuredRefusalError({ status: 'confirmation_required', message, plan, rerun, agentMode: source }, 2, {\n operation: 'confirm before running',\n remediation:\n source === null\n ? 'pass `--yes` to confirm, or drop `--json` to be prompted'\n : `show the plan to the human, then re-run \\`infra-kit ${rerun.join(' ')}\\` to confirm`,\n stderrExcerpt: 'confirmation required and nobody to ask',\n })\n}\n\nexport const confirmOrExit = async (\n confirmedCommand: boolean | undefined,\n message: string,\n options: ConfirmOrExitOptions = {},\n): Promise<void> => {\n if (!confirmedCommand && isHeadless()) refuseUnconfirmed(message, options.plan, options.rerun)\n\n const answer = confirmedCommand\n ? true\n : await withEscape(\n (context) => {\n return confirm({ message }, context)\n },\n // Unreachable headless: the guard above already refused every agent / `--json` run that got\n // here without `confirmedCommand`. Written out anyway \u2014 G7 requires every reachable site to\n // answer, and `'refuse'` is the answer that costs nothing if the guard above ever moves.\n { whenHeadless: 'refuse' },\n )\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n if (options.throwOnDecline) {\n throw new CommandDeclinedError()\n }\n\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n", "/**\n * The operator answered \"no\" at a confirmation prompt.\n *\n * Deliberately NOT an {@link OperationError}: nothing failed. It is also not a prompt\n * cancellation \u2014 Esc means \"I never answered\" and has its own handling, while this means\n * \"I answered, and the answer was no.\" Callers that opt in via `throwOnDecline` are\n * responsible for catching it and exiting 0.\n */\n// It exists so a command that acquired a resource before prompting \u2014 a scratch worktree, a temp\n// directory, a lock \u2014 can unwind through its own `finally` blocks and release it, instead of\n// `confirmOrExit` calling `process.exit(0)` and skipping every one of them.\n//\n// That distinction is load-bearing rather than stylistic. In a plan -> confirm -> apply design,\n// declining is a first-class expected outcome, not an edge case, so the most ordinary non-happy\n// path is exactly the one that would leak.\nexport class CommandDeclinedError extends Error {\n constructor(message = 'Operation cancelled by the operator') {\n super(message)\n this.name = 'CommandDeclinedError'\n }\n}\n\n/** Narrow an unknown catch binding to a decline. */\nexport const isCommandDeclined = (error: unknown): error is CommandDeclinedError => {\n return error instanceof CommandDeclinedError\n}\n", "// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n */\n// HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were\n// dropped for it \u2014 do not re-add either without re-deciding that:\n//\n// - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version\n// key, and a store the CLI refuses to read is a store the human cannot write.\n// - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout.\n// That guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so\n// `~/work/api` and `~/oss/api` share ONE token directory and repo B could load (and then\n// overwrite) repo A's credentials. It was removed anyway, knowingly: it also made the CLI refuse\n// every hand-written store, which carries no such field. Hand-authorability wins; the\n// basename-collision risk is ACCEPTED. A weakened version of the guard (warn-and-continue, or\n// \"only check when present\") is NOT the compromise here \u2014 it would re-introduce the same refusal\n// for anyone who did write the field. If you want the guard back, key the store directory on\n// something collision-free instead.\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 only a human can fix it \u2014 and downstream callers classify on that\n // CLASS (see EnvAuthError's doc). `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, [env]: token },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * Throw this (or a subclass) \u2014 never a plain `Error` \u2014 for anything a user must fix before\n * env-load can work: no token minted, a corrupt token store, a foreign token store.\n * `DopplerAuthError extends EnvAuthError` for the subset that is specifically \"Doppler refused the\n * token we sent\".\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\n// WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): every consumer of the auth\n// channel needs to classify a failure by its CLASS, not by re-deriving the answer from a message\n// some other module owns \u2014 and it has to be throwable from EVERY module that can produce the\n// class. `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a Doppler-owned\n// base type could not be thrown there without a layering inversion and an import cycle. Hence a\n// neutral base here in `lib/errors`.\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * Deliberately WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only\n * one of the durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store\n * never reaches the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n"],
|
|
5
|
+
"mappings": "+JAOA,IAAMA,EAAoB,IAAM,CAC9B,IAAIC,EAAU,GACVC,EAA2B,CAAC,EAC5BC,EAAgB,GAEpB,MAAO,CAWL,MAAMC,EAAoB,CACxBH,EAAUG,EACVF,EAAU,CAAC,EACXC,EAAgB,EAClB,EAMA,gBAAuB,CACrBA,EAAgB,EAClB,EAQA,UAAUE,EAAcC,EAA0C,CAChEJ,EAAQ,KAAK,CAAE,KAAAG,EAAM,MAAAC,CAAM,CAAC,CAC9B,EAKA,eAAwB,CACtB,OAAOJ,EACJ,IAAKK,GACA,OAAOA,EAAI,OAAU,UAChBA,EAAI,MAAQA,EAAI,KAAO,GAG5B,MAAM,QAAQA,EAAI,KAAK,EAClB,GAAGA,EAAI,IAAI,KAAKA,EAAI,MAAM,KAAK,IAAI,CAAC,IAGtC,GAAGA,EAAI,IAAI,KAAKA,EAAI,KAAK,GACjC,EACA,OAAO,OAAO,EACd,KAAK,GAAG,CACb,EAOA,UAAgD,CAC9C,OAAIL,EAAQ,SAAW,EACd,KAGF,CAAE,iBAAkB,KAAK,cAAc,CAAE,CAClD,EAUA,OAAc,CACR,CAACC,GAAiBD,EAAQ,SAAW,GAAK,CAACD,GAI/CO,EAAO,KAAK;AAAA,sBAAgDP,CAAO,IAAI,KAAK,cAAc,CAAC;AAAA,CAAI,CACjG,EAKA,OAAc,CACZA,EAAU,GACVC,EAAU,CAAC,EACXC,EAAgB,EAClB,CACF,CACF,EAGaM,EAAcT,EAAkB,EC5G7C,OAAS,cAAAU,EAAY,WAAAC,MAAe,YACpC,OAAOC,MAAa,eASpB,IAAIC,EAAuC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,MAAO,OAE1C,IAAME,EAAO,CAAE,GAAGF,EAAS,IAAK,EAEhC,OAAOE,EAAKJ,CAAG,EAEf,MAAMR,EAAgB,CACpB,QAASlB,EACT,KAAA8B,CACF,CAAC,CACH",
|
|
6
|
+
"names": ["createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "isAbsolute", "resolve", "process", "parsedArgv", "launchCwd", "setParsedArgv", "argv", "YES_FLAGS", "absolutizeChangeDir", "args", "cwd", "out", "index", "token", "rerunArgv", "process", "ESC_BYTE", "headlessExcerpt", "source", "headlessRemediation", "argument", "resolveHeadless", "policy", "agentMode", "StructuredRefusalError", "withEscape", "run", "base", "controller", "whenHeadless", "promptBase", "context", "isHeadless", "process", "input", "onData", "chunk", "acquireStdin", "pending", "releaseStdin", "confirm", "process", "CommandDeclinedError", "message", "isCommandDeclined", "error", "refuseUnconfirmed", "message", "plan", "rerun", "rerunArgv", "source", "agentMode", "StructuredRefusalError", "confirmOrExit", "confirmedCommand", "options", "isHeadless", "answer", "withEscape", "context", "confirm", "commandEcho", "CommandDeclinedError", "logger", "process", "fs", "path", "z", "EnvAuthError", "message", "env", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "setToken", "env", "token", "existing", "removeToken", "envs"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var i={name:"infra-kit",type:"module",version:"0.13.0",repository:{type:"git",url:"git+https://github.com/ArthurSaenz/infra-kit.git",directory:"apps/infra-kit/cli"},files:["dist"],description:"infra-kit",bin:{"infra-kit":"dist/cli.js",ik:"dist/cli.js","ik-mcp":"dist/mcp-proxy.js"},engines:{node:">=24.x"},scripts:{build:"pnpm run clean-artifacts && node ./scripts/build.js",prepack:"pnpm run build","infra-kit-check":"pnpm exec infra-kit audit","clean-artifacts":"rm -rf dist","clean-cache":"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc","prettier-fix":"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","eslint-check":"pnpm exec eslint --cache --report-unused-disable-directives ./src","eslint-fix":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix","ts-check":"tsc --noEmit",test:"pnpm exec vitest run --reporter=minimal","test-watch":"pnpm exec vitest --watch --silent passed-only","test-ui":"pnpm exec vitest --ui --silent passed-only","test-report":"pnpm exec vitest run --coverage --silent passed-only","qa:pty":"INFRA_KIT_REQUIRE_PTY=1 pnpm exec vitest run --reporter=minimal src/tui/__tests__/stdin-pause-pty.test.ts src/entry/__tests__/quit-keys-pty.test.ts src/entry/__tests__/post-run-pause-pty.test.ts",qa:"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success",fix:"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa"},dependencies:{"@aws-lambda-powertools/logger":"^2.35.0","@inquirer/checkbox":"^5.2.5","@inquirer/confirm":"^6.3.2","@inquirer/input":"^5.1.6","@inquirer/password":"^5.2.2","@inquirer/select":"^5.2.5","@slip-stream-kit/config":"workspace:^",chalk:"^6.0.0",chokidar:"^5.0.0",commander:"^15.0.0",fastify:"^5.12.5",ink:"^7.1.1",pino:"^10.3.1","pino-pretty":"^13.1.3",portless:"^0.15.6",react:"19.3.0",yaml:"^2.9.1",zod:"^4.6.5",zx:"^8.8.5"},devDependencies:{"@slip-stream-kit/eslint-plugin":"workspace:*","@types/aws-lambda":"catalog:","@types/react":"catalog:","@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.2","ink-testing-library":"^4.0.0",typescript:"^6.0.3"}};export{i as a};
|
|
2
|
+
//# sourceMappingURL=chunk-FKA65HOC.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../package.json"],
|
|
4
|
+
"sourcesContent": ["{\n \"name\": \"infra-kit\",\n \"type\": \"module\",\n \"version\": \"0.13.0\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/ArthurSaenz/infra-kit.git\",\n \"directory\": \"apps/infra-kit/cli\"\n },\n \"files\": [\n \"dist\"\n ],\n \"description\": \"infra-kit\",\n \"bin\": {\n \"infra-kit\": \"dist/cli.js\",\n \"ik\": \"dist/cli.js\",\n \"ik-mcp\": \"dist/mcp-proxy.js\"\n },\n \"engines\": {\n \"node\": \">=24.x\"\n },\n \"scripts\": {\n \"build\": \"pnpm run clean-artifacts && node ./scripts/build.js\",\n \"prepack\": \"pnpm run build\",\n \"infra-kit-check\": \"pnpm exec infra-kit audit\",\n \"clean-artifacts\": \"rm -rf dist\",\n \"clean-cache\": \"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc\",\n \"prettier-fix\": \"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"prettier-check\": \"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"eslint-check\": \"pnpm exec eslint --cache --report-unused-disable-directives ./src\",\n \"eslint-fix\": \"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix\",\n \"ts-check\": \"tsc --noEmit\",\n \"test\": \"pnpm exec vitest run --reporter=minimal\",\n \"test-watch\": \"pnpm exec vitest --watch --silent passed-only\",\n \"test-ui\": \"pnpm exec vitest --ui --silent passed-only\",\n \"test-report\": \"pnpm exec vitest run --coverage --silent passed-only\",\n \"qa:pty\": \"INFRA_KIT_REQUIRE_PTY=1 pnpm exec vitest run --reporter=minimal src/tui/__tests__/stdin-pause-pty.test.ts src/entry/__tests__/quit-keys-pty.test.ts src/entry/__tests__/post-run-pause-pty.test.ts\",\n \"qa\": \"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success\",\n \"fix\": \"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa\"\n },\n \"dependencies\": {\n \"@aws-lambda-powertools/logger\": \"^2.35.0\",\n \"@inquirer/checkbox\": \"^5.2.5\",\n \"@inquirer/confirm\": \"^6.3.2\",\n \"@inquirer/input\": \"^5.1.6\",\n \"@inquirer/password\": \"^5.2.2\",\n \"@inquirer/select\": \"^5.2.5\",\n \"@slip-stream-kit/config\": \"workspace:^\",\n \"chalk\": \"^6.0.0\",\n \"chokidar\": \"^5.0.0\",\n \"commander\": \"^15.0.0\",\n \"fastify\": \"^5.12.5\",\n \"ink\": \"^7.1.1\",\n \"pino\": \"^10.3.1\",\n \"pino-pretty\": \"^13.1.3\",\n \"portless\": \"^0.15.6\",\n \"react\": \"19.3.0\",\n \"yaml\": \"^2.9.1\",\n \"zod\": \"^4.6.5\",\n \"zx\": \"^8.8.5\"\n },\n \"devDependencies\": {\n \"@slip-stream-kit/eslint-plugin\": \"workspace:*\",\n \"@types/aws-lambda\": \"catalog:\",\n \"@types/react\": \"catalog:\",\n \"@wl/eslint-config\": \"workspace:*\",\n \"@wl/vitest-config\": \"workspace:*\",\n \"esbuild\": \"^0.28.2\",\n \"ink-testing-library\": \"^4.0.0\",\n \"typescript\": \"^6.0.3\"\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,IAAAA,EAAA,CACE,KAAQ,YACR,KAAQ,SACR,QAAW,SACX,WAAc,CACZ,KAAQ,MACR,IAAO,mDACP,UAAa,oBACf,EACA,MAAS,CACP,MACF,EACA,YAAe,YACf,IAAO,CACL,YAAa,cACb,GAAM,cACN,SAAU,mBACZ,EACA,QAAW,CACT,KAAQ,QACV,EACA,QAAW,CACT,MAAS,sDACT,QAAW,iBACX,kBAAmB,4BACnB,kBAAmB,cACnB,cAAe,2EACf,eAAgB,4HAChB,iBAAkB,4HAClB,eAAgB,oEAChB,aAAc,kFACd,WAAY,eACZ,KAAQ,0CACR,aAAc,gDACd,UAAW,6CACX,cAAe,uDACf,SAAU,qMACV,GAAM,gHACN,IAAO,6DACT,EACA,aAAgB,CACd,gCAAiC,UACjC,qBAAsB,SACtB,oBAAqB,SACrB,kBAAmB,SACnB,qBAAsB,SACtB,mBAAoB,SACpB,0BAA2B,cAC3B,MAAS,SACT,SAAY,SACZ,UAAa,UACb,QAAW,UACX,IAAO,SACP,KAAQ,UACR,cAAe,UACf,SAAY,UACZ,MAAS,SACT,KAAQ,SACR,IAAO,SACP,GAAM,QACR,EACA,gBAAmB,CACjB,iCAAkC,cAClC,oBAAqB,WACrB,eAAgB,WAChB,oBAAqB,cACrB,oBAAqB,cACrB,QAAW,UACX,sBAAuB,SACvB,WAAc,QAChB,CACF",
|
|
6
|
+
"names": ["package_default"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{a as x,e as re,h as S,i as te,j as p}from"./chunk-EU7LD5IV.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-D76UWTR5.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-LR57E6IP.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/commands/env-load/env-load.ts", "../src/integrations/doppler/doppler-errors.ts", "../src/integrations/doppler/doppler-project.ts", "../src/integrations/doppler/token-resolver.ts", "../src/lib/env-load-form/env-load-form.ts", "../src/commands/env-list/env-list.ts", "../src/lib/workflow-envs/protected-envs.ts", "../src/lib/workflow-envs/protected-env-access.ts", "../src/lib/workflow-envs/protected-env-warning.ts", "../src/lib/workflow-envs/workflow-envs.ts", "../src/lib/project-envs/project-envs.ts", "../src/types.ts", "../src/lib/prompts/refuse-missing-arguments.ts"],
|
|
4
|
+
"sourcesContent": ["import select from '@inquirer/select'\nimport { 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,IA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,MAAM,IAAI,UAAU,4CAA4CD,CAAG,UAAU,OAAOC,CAAK,GAAG,EAG9FP,EAAM,KAAK,CAACM,EAAKC,CAAK,CAAC,CACzB,CAEA,GAAIP,EAAM,SAAW,EACnB,MAAM,IAAI,MAAM,4CAA4C,EAG9D,OAAOA,CACT,EAGa8E,GAAiBC,EAAc,CAC1C,KAAM,WACN,YACE,+sBACF,YAAa,CACX,OAAQC,EACL,OAAO,EACP,SAAS,EACT,SACC,iHACF,CACJ,EACA,aAAcrD,GACd,aAAc,CACZ,SAAUqD,EAAE,OAAO,EAAE,SAAS,0DAA0D,EACxF,cAAeA,EAAE,OAAO,EAAE,SAAS,4BAA4B,EAC/D,QAASA,EAAE,OAAO,EAAE,SAAS,sBAAsB,EACnD,OAAQA,EAAE,OAAO,EAAE,SAAS,qBAAqB,EACjD,UAAWA,EACR,OAAO,EACP,SAAS,EACT,SAAS,sFAAsF,CACpG,EACA,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
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import*as a from"node:fs";import*as o from"node:path";function k(t){let e=t;for(let r=0;r<10;r++){let n=o.join(e,"pnpm-workspace.yaml");if(a.existsSync(n))return e;e=o.dirname(e)}throw new Error("Could not find monorepo root (pnpm-workspace.yaml)")}function m(t,e){let r=o.join(t,"package.json");if(!a.existsSync(r))return e;try{let n=JSON.parse(a.readFileSync(r,"utf-8"));return typeof n.name=="string"?n.name:e}catch{return e}}function F(t){let e=o.join(t,"apps"),r=[];if(!a.existsSync(e))throw new Error(`Apps directory not found: ${e}`);let n=a.readdirSync(e,{withFileTypes:!0}).filter(s=>s.isDirectory()).map(s=>s.name);for(let s of n){let i=o.join(e,s,"api"),p=o.join(i,"serverless.yml");a.existsSync(p)&&r.push({name:s,packageName:m(i,s),path:i})}return r}var P=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs"],D=["@slip-stream-kit/vite","@slip-stream-kit/config/vite","infra-kit/vite"];function S(t){for(let e of P){let r=o.join(t,e);if(a.existsSync(r))try{let n=a.readFileSync(r,"utf-8");return D.some(s=>n.includes(s))}catch{return!1}}return!1}function O(t){for(let e of P){let r=o.join(t,e);if(a.existsSync(r))try{return a.readFileSync(r,"utf-8").includes("infraKit(")}catch{return!1}}return!1}function b(t){let e=o.join(t,"package.json");if(!a.existsSync(e))return!1;try{let r=JSON.parse(a.readFileSync(e,"utf-8"));return typeof r.scripts?.dev=="string"&&r.scripts.dev.length>0}catch{return!1}}function V(t){let e=o.join(t,"apps"),r=[];if(!a.existsSync(e))return r;let n=a.readdirSync(e,{withFileTypes:!0}).filter(s=>s.isDirectory()).map(s=>s.name);for(let s of n){let i=o.join(e,s,"ui");a.existsSync(i)&&b(i)&&r.push({name:s,packageName:m(i,s),path:i,managedPort:S(i)})}return r}function G(t){let e=t?.filter(Boolean)??[];return e.length>0?e:null}function L(t){let e=k(t),r=o.relative(o.join(e,"apps"),t),n=r.split(o.sep)[0];if(r===""||r.startsWith("..")||o.isAbsolute(r)||!n)throw new Error(`--self: not inside an apps/<app> directory (cwd: ${t}). Run from an app folder or use --app=<name>.`);return n}var A=new Set(["api","ui"]),y=t=>{let e=o.join(t,"dist");return a.existsSync(e)&&a.statSync(e).isDirectory()?e:void 0},h=t=>a.existsSync(t)?a.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name):[];function _(t){let e=[];for(let n of h(o.join(t,"packages"))){let s=y(o.join(t,"packages",n));s!==void 0&&e.push(s)}let r=o.join(t,"apps");for(let n of h(r))for(let s of h(o.join(r,n))){if(A.has(s))continue;let i=o.join(r,n,s);if(!a.existsSync(o.join(i,"package.json")))continue;let p=y(i);p!==void 0&&e.push(p)}return e}function z(t){return t.map(e=>o.join(e.path,"dist")).filter(e=>a.existsSync(e))}function U(t,e,r){let n=o.normalize(t),s=c=>{let u=o.normalize(c);return n===u||n.startsWith(u+o.sep)},i=r.find(s);return i?{kind:"package",packageDir:i}:{kind:"app",app:e.find(s)}}var w={"*/api":{},"*/ui":{}},v=t=>{let e=t.split("/"),[r,n]=e;return e.length!==2||!r?`devServersPresets: invalid target "${t}" (expected "<app>/api" or "<app>/ui")`:n!=="api"&&n!=="ui"?`devServersPresets: invalid target part "${n}" in "${t}" (expected "api" or "ui")`:null},j=t=>{let e=v(t);if(e)throw new Error(e);let[r,n]=t.split("/");return{appGlob:r,part:n}},B=t=>{let e=[];for(let[r,n]of Object.entries(t))for(let s of Object.keys(n.apps??{})){let i=v(s);i&&e.push({preset:r,key:s,message:`preset "${r}": ${i}`})}return e},R=(t,e)=>e==="api"?t.api:t.ui,I=t=>[...new Set([...t.api,...t.ui])].sort(),x=(t,e)=>`${t}/${e}`,T=t=>t?0:1,$=(t,e)=>e.watchDeps===void 0?t??{watchDeps:!0,rank:e.rank,explicitValue:!1}:!t||!t.explicitValue?{watchDeps:e.watchDeps,rank:e.rank,explicitValue:!0}:e.rank>t.rank?{watchDeps:e.watchDeps,rank:e.rank,explicitValue:!0}:t,C=(t,e,r)=>{let{app:n,part:s,watchDeps:i,isGlob:p}=r;if(!R(e,s).includes(n)){p||t.unmatched.push(x(n,s));return}let c=x(n,s),u=$(t.targets.get(c),{watchDeps:i,rank:T(p)});t.targets.set(c,{app:n,part:s,...u})},E=(t,e)=>{let r=Object.entries(t.apps??w),n={targets:new Map,proxy:{},unmatched:[]};for(let[p,c]of r){let{appGlob:u,part:l}=j(p),g=u==="*",f=g?I(e):[u];for(let d of f)C(n,e,{app:d,part:l,watchDeps:c.watchDeps,isGlob:g}),c.proxy&&(n.proxy[d]={...n.proxy[d]??{},...c.proxy})}let s=[...n.targets.values()].map(({app:p,part:c,watchDeps:u})=>({app:p,part:c,watchDeps:u})),i=[...new Set(s.filter(p=>p.part==="api").map(p=>p.app))];return{targets:s,orca:t.orca??!1,proxy:n.proxy,localApps:i,unmatched:n.unmatched}},M=t=>{if(t.preset!=null)return t.preset;if(t.running.length===0)return"nothing";let e=new Set(t.running);return t.discovered.every(n=>e.has(n))?"*":[...e].sort().join(" + ")},K=(t,e)=>Object.keys(t).find(r=>t[r]===e),N=({preset:t,app:e,route:r,launchedPkgs:n,ctx:s})=>{let i=s.routePkg(e,r);if(i===void 0)return{preset:t,app:e,route:r,kind:"unknown-route",message:`preset "${t}": proxy override "${r}" on "${e}" names a route not declared in ${e}'s infra-kit.config.ts dev.proxy.routes`};if(n.has(i))return null;let p=K(s.apiPkgByApp,i),c=p?`add "${p}/api" to the preset`:`launch the api whose package is "${i}"`;return{preset:t,app:e,route:r,pkg:i,kind:"backend-not-launched",message:`preset "${t}": proxy override "${r}" \u2192 "local" requires backend "${i}" to run locally, but the preset does not launch it \u2014 ${c}, or set "${r}" to "cloud"`}},J=(t,e)=>{let r=[];for(let[n,s]of Object.entries(t)){let i=E(s,e.discovered),p=new Set(i.localApps.map(c=>e.apiPkgByApp[c]).filter(c=>c!==void 0));for(let[c,u]of Object.entries(i.proxy))for(let[l,g]of Object.entries(u)){if(g!=="local")continue;let f=N({preset:n,app:c,route:l,launchedPkgs:p,ctx:e});f&&r.push(f)}}return r};export{k as a,F as b,O as c,V as d,G as e,L as f,_ as g,z as h,U as i,v as j,B as k,E as l,M as m,J as n};
|
|
2
|
+
//# sourceMappingURL=chunk-Y3RW74TE.js.map
|