infra-kit 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-MFHYIQ7B.js → chunk-3UE375II.js} +2 -2
- package/dist/{chunk-MFHYIQ7B.js.map → chunk-3UE375II.js.map} +1 -1
- package/dist/chunk-4RZM53X7.js +7 -0
- package/dist/{chunk-DW2SQ2XU.js.map → chunk-4RZM53X7.js.map} +3 -3
- package/dist/{chunk-VDBJ73LS.js → chunk-DVXTZPQ5.js} +1 -1
- package/dist/chunk-DVXTZPQ5.js.map +7 -0
- package/dist/{chunk-FRBNA6VH.js → chunk-EZ4DIT5A.js} +3 -3
- package/dist/{chunk-FRBNA6VH.js.map → chunk-EZ4DIT5A.js.map} +1 -1
- package/dist/chunk-I23MDR4X.js +5 -0
- package/dist/chunk-I23MDR4X.js.map +7 -0
- package/dist/{chunk-CMF7HEVU.js → chunk-IT6XJWTW.js} +2 -2
- package/dist/chunk-IT6XJWTW.js.map +7 -0
- package/dist/{chunk-BQPSXIH2.js → chunk-MH37P7W4.js} +2 -2
- package/dist/chunk-PP3ZZKB3.js +12 -0
- package/dist/chunk-PP3ZZKB3.js.map +7 -0
- package/dist/{chunk-EAUGQ3ZU.js → chunk-ZTAUGYJF.js} +2 -2
- package/dist/cli.js +117 -109
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +21 -21
- package/dist/dev-server.js.map +3 -3
- package/dist/{dev-wizard-run-3DNKOVPD.js → dev-wizard-run-6PLC5YEW.js} +2 -2
- package/dist/env-load-NURS7WNH.js +2 -0
- package/dist/mcp-proxy.js +7 -7
- package/dist/mcp-proxy.js.map +3 -3
- package/dist/{persistent-ink-dev-ui-P65EJCC6.js → persistent-ink-dev-ui-ZSOS3CF4.js} +2 -2
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- package/readme.md +5 -2
- package/dist/chunk-CMF7HEVU.js.map +0 -7
- package/dist/chunk-DW2SQ2XU.js +0 -7
- package/dist/chunk-QSTGO43H.js +0 -4
- package/dist/chunk-QSTGO43H.js.map +0 -7
- package/dist/chunk-UD6VVXUY.js +0 -10
- package/dist/chunk-UD6VVXUY.js.map +0 -7
- package/dist/chunk-VDBJ73LS.js.map +0 -7
- package/dist/env-load-MF26WMDL.js +0 -2
- /package/dist/{chunk-BQPSXIH2.js.map → chunk-MH37P7W4.js.map} +0 -0
- /package/dist/{chunk-EAUGQ3ZU.js.map → chunk-ZTAUGYJF.js.map} +0 -0
- /package/dist/{dev-wizard-run-3DNKOVPD.js.map → dev-wizard-run-6PLC5YEW.js.map} +0 -0
- /package/dist/{env-load-MF26WMDL.js.map → env-load-NURS7WNH.js.map} +0 -0
- /package/dist/{persistent-ink-dev-ui-P65EJCC6.js.map → persistent-ink-dev-ui-ZSOS3CF4.js.map} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/commands/env-load/env-load.ts", "../src/integrations/doppler/doppler-errors.ts", "../src/integrations/doppler/doppler-project.ts", "../src/integrations/doppler/token-resolver.ts", "../src/lib/env-load-form/env-load-form.ts", "../src/commands/env-list/env-list.ts", "../src/lib/workflow-envs/protected-envs.ts", "../src/lib/workflow-envs/protected-env-access.ts", "../src/lib/workflow-envs/protected-env-warning.ts", "../src/lib/workflow-envs/workflow-envs.ts", "../src/lib/project-envs/project-envs.ts", "../src/types.ts", "../src/lib/prompts/refuse-missing-arguments.ts"],
|
|
4
|
+
"sourcesContent": ["import select from '@inquirer/select'\nimport { readRepoIdentity } from '@slip-stream-kit/config/internal'\nimport { Buffer } from 'node:buffer'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { z } from 'zod'\nimport { $ } from 'zx'\n\nimport {\n DopplerAuthError,\n INFRA_KIT_ENV_TOKEN_VAR,\n buildDopplerNotFoundMessage,\n classifyDopplerAuthFailure,\n classifyDopplerFailure,\n getDopplerProject,\n resolveEnvToken,\n} from 'src/integrations/doppler'\nimport { agentMode, isAgentMode } from 'src/lib/agent-mode'\nimport { commandEcho } from 'src/lib/command-echo'\nimport {\n ENV_LOAD_FILE,\n ENV_LOAD_ROOT_FILE,\n INFRA_KIT_ENV_CONFIG_VAR,\n INFRA_KIT_ENV_LOADED_AT_VAR,\n INFRA_KIT_ENV_PROJECT_ROOT_VAR,\n INFRA_KIT_ENV_PROJECT_VAR,\n INFRA_KIT_ENV_VAR,\n INFRA_KIT_SESSION_VAR,\n WORKTREES_DIR_SUFFIX,\n atomicWriteFileSync,\n getSessionCacheDir,\n} from 'src/lib/constants'\nimport { createEnvLoadFormProvider } from 'src/lib/env-load-form'\nimport { extractStderr } from 'src/lib/errors/operation-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { getProjectRoot } from 'src/lib/git-utils'\nimport { logger } from 'src/lib/logger'\nimport { listProjectEnvNames } from 'src/lib/project-envs'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\nimport { refuseMissingArguments } from 'src/lib/prompts/refuse-missing-arguments'\nimport { defineMcpTool, textContent } from 'src/types'\n\ninterface EnvLoadArgs {\n config?: string\n}\n\ninterface WriteEnvLoadFileArgs {\n /** Resolved Doppler config / environment name (no interactive picker here). */\n config: string\n}\n\nexport interface EnvLoadFileResult {\n filePath: string\n variableCount: number\n project: string\n config: string\n}\n\ninterface EnvLoadFileLinesArgs {\n pairs: Array<[string, string]>\n config: string\n project: string\n projectRoot: string\n loadedAt: string\n}\n\n/** The payload key that carries the token's scope \u2014 the one {@link assertTokenScope} compares. */\nconst DOPPLER_CONFIG_KEY = 'DOPPLER_CONFIG'\n\n/**\n * Secret names that must NEVER be written into the sourced file. A Doppler project can hold a secret\n * called `DOPPLER_TOKEN` (or `INFRA_KIT_ENV_TOKEN`), and `env-load.sh` is sourced into EVERY shell \u2014\n * exporting one would hand a live credential to every child process forever, and (per SPIKE-0 Q5) an\n * exported `DOPPLER_TOKEN` would then hijack the next download's auth.\n *\n * `DOPPLER_CONFIG` / `DOPPLER_PROJECT` are deliberately NOT filtered: they are not credentials, they\n * are the scope evidence {@link assertTokenScope} and `doctor` read back.\n */\nconst CREDENTIAL_SECRET_KEYS = new Set<string>(['DOPPLER_TOKEN', INFRA_KIT_ENV_TOKEN_VAR])\n\n/** Warn at most once per process: a project carrying a token secret would otherwise warn on every load. */\nlet credentialFilterWarned = false\n\n/**\n * Tell the user we dropped a credential-bearing secret from their shell env \u2014 silently swallowing a\n * key they can see in the Doppler dashboard would read as a bug. Names the KEY only, never the value.\n */\nconst warnFilteredCredentialKeys = (keys: string[]): void => {\n if (keys.length === 0 || credentialFilterWarned) return\n\n credentialFilterWarned = true\n\n logger.warn(\n `infra-kit: not exporting ${keys.join(', ')} from Doppler into your shell \u2014 ` +\n 'a service token must not be sourced into every process.',\n )\n}\n\n/**\n * Build the dotenv-format shell lines for env-load.sh. Pure apart from the one-shot credential\n * warning, so callers can assert the exact file contents. `set -a`/`set +a` auto-export every\n * assignment when the file is sourced.\n */\nexport const buildEnvLoadFileLines = ({\n pairs,\n config,\n project,\n projectRoot,\n loadedAt,\n}: EnvLoadFileLinesArgs): string[] => {\n const emitted = pairs.filter(([key]) => {\n return !CREDENTIAL_SECRET_KEYS.has(key)\n })\n\n warnFilteredCredentialKeys(\n pairs\n .filter(([key]) => {\n return CREDENTIAL_SECRET_KEYS.has(key)\n })\n .map(([key]) => {\n return key\n }),\n )\n\n return [\n 'set -a',\n ...emitted.map(([key, value]) => {\n return `${key}=${shellSingleQuote(value)}`\n }),\n // Purpose-named env-name handle for non-shell tooling (e.g. infra-kit/vite's\n // `<env>` proxy interpolation). Single-quoted like every sourced value.\n `${INFRA_KIT_ENV_VAR}=${shellSingleQuote(config)}`,\n `${INFRA_KIT_ENV_CONFIG_VAR}=${shellSingleQuote(config)}`,\n `${INFRA_KIT_ENV_PROJECT_VAR}=${shellSingleQuote(project)}`,\n `${INFRA_KIT_ENV_PROJECT_ROOT_VAR}=${shellSingleQuote(projectRoot)}`,\n `${INFRA_KIT_ENV_LOADED_AT_VAR}=${shellSingleQuote(loadedAt)}`,\n 'set +a',\n ]\n}\n\n/**\n * Project root (git top-level) the loaded env belongs to. Returns '' when this isn't\n * a git checkout so a non-git infra-kit project still loads instead of the whole\n * load breaking on `git rev-parse` throwing.\n */\nconst resolveProjectRootSafe = async (): Promise<string> => {\n try {\n return await getProjectRoot()\n } catch {\n return ''\n }\n}\n\n/**\n * The directories the loaded env applies in ({@link ENV_LOAD_ROOT_FILE}): the repo's own directory (the\n * same `readRepoIdentity` that names the dev alias's `<repo>`) and its `-worktrees` container, so every\n * worktree of the repo shares one load, plus the loading worktree itself in case it lives elsewhere.\n * Outside git, just `cwd`.\n */\nexport const resolveEnvLoadRoots = (projectRoot: string, cwd = process.cwd()): string[] => {\n if (projectRoot === '') return [path.resolve(cwd)]\n\n const repoRoot = readRepoIdentity(projectRoot).root ?? projectRoot\n\n return [...new Set([repoRoot, `${repoRoot}${WORKTREES_DIR_SUFFIX}`, projectRoot])]\n}\n\n/**\n * Download Doppler secrets for a resolved config and atomically write env-load.sh\n * to the session cache dir. Does NOT print to stdout \u2014 the path line belongs to the\n * CLI action in `lib/program`.\n */\nexport const writeEnvLoadFile = async ({ config }: WriteEnvLoadFileArgs): Promise<EnvLoadFileResult> => {\n const project = await getDopplerProject()\n const projectRoot = await resolveProjectRootSafe()\n\n const pairs = await downloadDopplerSecrets(project, config)\n\n const loadedAt = new Date().toISOString()\n const envFileLines = buildEnvLoadFileLines({ pairs, config, project, projectRoot, loadedAt })\n const fileContents = `${envFileLines.join('\\n')}\\n`\n\n const cacheDir = getSessionCacheDir()\n const envFilePath = path.resolve(cacheDir, ENV_LOAD_FILE)\n\n fs.mkdirSync(cacheDir, { recursive: true, mode: 0o700 })\n // The scope lands first: a shell reading between the two writes then never sees the new env unscoped.\n const roots = resolveEnvLoadRoots(projectRoot)\n\n atomicWriteFileSync(path.resolve(cacheDir, ENV_LOAD_ROOT_FILE), `${roots.join('\\n')}\\n`, 0o600)\n atomicWriteFileSync(envFilePath, fileContents, 0o600)\n\n return {\n filePath: envFilePath,\n variableCount: pairs.length,\n project,\n config,\n }\n}\n\n/**\n * Load environment variables from Doppler for the given config\n */\n// ONE provider instance for the tool definition (`envLoadMcpTool.formProvider`) and the agent-mode\n// refusal below, so the rows an agent is handed as `choices` are the form the schema describes.\nconst envLoadForm = createEnvLoadFormProvider()\n\nexport const envLoad = async (args: EnvLoadArgs) => {\n const { config } = args\n\n // Before the picker: an agent / `--json` run without `config` gets the form's env list as `choices`.\n await refuseMissingArguments({ provider: envLoadForm, params: args, operation: 'env-load', argument: 'config' })\n\n let selectedConfig = ''\n\n if (config) {\n selectedConfig = config\n } else {\n // No auth pre-probe before the picker: under token-only auth there is no account\n // to validate, and the per-env token is only knowable AFTER a config is chosen.\n // A missing/rejected token surfaces from the download with an actionable message.\n //\n // The choices are every env this project has \u2014 workflow-declared and token-only alike (see\n // `lib/project-envs`). Deliberately NOT filtered to the envs we hold a token for: an env you cannot\n // yet load is exactly the one you need to SEE, so that picking it tells you to run\n // `infra-kit env-token-set <env>` rather than leaving you to wonder where it went.\n //\n // An agent that omits `config` is refused with `choices` by `refuseMissingArguments` above; landing\n // here headless means the provider judged the arguments unformable, and the refusal has to name the\n // source.\n if (isAgentMode()) {\n throw new StructuredRefusalError(\n { status: 'argument_required', argument: 'config', agentMode: agentMode.source },\n 2,\n {\n operation: 'env-load',\n remediation: 'call env-list, ask the human which environment, and re-call env-load with \"config\"',\n },\n )\n }\n\n const envs = await listProjectEnvNames()\n\n commandEcho.setInteractive()\n selectedConfig = await withEscape(\n (context) => {\n return select(\n {\n message: 'Select environment config',\n choices: envs.map((env) => {\n return { name: env, value: env }\n }),\n },\n context,\n )\n },\n // Render to stderr so the prompt is visible when stdout is captured via $() in the shell function.\n // Only env-load and env-clear use the $() stdout-capture shell pattern.\n { output: process.stderr, whenHeadless: 'refuse' },\n )\n }\n\n commandEcho.addOption('--config', selectedConfig)\n\n const result = await writeEnvLoadFile({ config: selectedConfig })\n\n // The path the zsh wrapper captures is printed by the CLI action in `lib/program`, not here: the\n // handler's stdout stays empty so a `--json` caller gets exactly one document; `emitSourcePath` in\n // `lib/program` owns the path line and its ordering. Logs go to stderr for the same reason.\n commandEcho.print()\n\n const structuredContent = {\n filePath: result.filePath,\n variableCount: result.variableCount,\n project: result.project,\n config: result.config,\n // The terminal session the file was written FOR. A Bash-driven agent inherits the session id but\n // never sees the shell that sources the file; naming it here is how it can tell which terminal\n // just got the variables (and notice when there was none).\n sessionId: process.env[INFRA_KIT_SESSION_VAR] ?? null,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n/**\n * Cap the Doppler stdout we're willing to accept. A well-formed env bundle is\n * O(10 KB); megabytes would indicate a service regression or the wrong stream\n * being captured, and we don't want to write that to disk or source it.\n */\nexport const DOPPLER_MAX_OUTPUT_BYTES = 1024 * 1024\n\n/**\n * Hard upper bound for the Doppler subprocess. Well under zx's default so a\n * hung call surfaces quickly instead of blocking an interactive shell.\n */\nconst DOPPLER_DOWNLOAD_TIMEOUT_MS = 30_000\n\n/**\n * Doppler env vars we refuse to inherit into the download child. SPIKE-0 Q5: an inherited\n * `DOPPLER_TOKEN` OVERRIDES everything else the CLI would use \u2014 and `env-load` itself exports a whole\n * Doppler project into the shell, so a project that happens to hold a secret named `DOPPLER_TOKEN`\n * would silently hijack the NEXT download. `DOPPLER_PROJECT` / `DOPPLER_CONFIG` are scrubbed for the\n * same reason: they are the payload's own scope evidence, and an inherited copy could shadow the\n * `--project` / `--config` we pass in argv.\n */\nconst INHERITED_DOPPLER_VARS = ['DOPPLER_TOKEN', 'DOPPLER_PROJECT', 'DOPPLER_CONFIG'] as const\n\n/**\n * The child environment for `doppler secrets download`: the caller's env with the inherited Doppler\n * vars scrubbed and OUR resolved token set explicitly.\n *\n * The token travels by ENV, never by argv: `ps` shows argv to every user on the box, and\n * `commandEcho` prints option values back to the terminal. Pure (takes the base env) so the scrub is\n * unit-testable without touching `process.env`.\n *\n * @example\n * buildDopplerChildEnv('dp.st.x', { PATH: '/bin', DOPPLER_CONFIG: 'prod' })\n * // => { PATH: '/bin', DOPPLER_TOKEN: 'dp.st.x' } (DOPPLER_CONFIG dropped)\n */\nexport const buildDopplerChildEnv = (token: string, baseEnv: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv => {\n const childEnv: NodeJS.ProcessEnv = { ...baseEnv }\n\n for (const name of INHERITED_DOPPLER_VARS) {\n delete childEnv[name]\n }\n\n childEnv.DOPPLER_TOKEN = token\n\n return childEnv\n}\n\n/**\n * One Doppler config's secrets, downloaded with the token stored for it \u2014 `env-load`'s own fetch, for a\n * caller that needs a few values of an env without loading the whole env into a shell.\n */\nexport const downloadEnvSecrets = async (config: string): Promise<Map<string, string>> => {\n return new Map(await downloadDopplerSecrets(await getDopplerProject(), config))\n}\n\nconst downloadDopplerSecrets = async (project: string, config: string): Promise<Array<[string, string]>> => {\n const { token } = await resolveEnvToken(config)\n\n const childEnv = buildDopplerChildEnv(token)\n\n const prevQuiet = $.quiet\n\n $.quiet = true\n try {\n let result\n\n try {\n result = await $({\n env: childEnv,\n })`doppler secrets download --no-file --format json --project ${project} --config ${config}`.timeout(\n DOPPLER_DOWNLOAD_TIMEOUT_MS,\n )\n } catch (error: unknown) {\n throw translateDopplerDownloadError(error, project, config)\n }\n\n assertDopplerOutputSize(result.stdout)\n\n const pairs = parseDopplerSecretsJson(result.stdout)\n\n assertTokenScope(pairs, config)\n\n return pairs\n } finally {\n $.quiet = prevQuiet\n }\n}\n\n/**\n * Defense in depth against a MIS-SCOPED token: the payload always carries `DOPPLER_CONFIG` as an\n * ordinary secret, and it echoes the `--config` we asked for (SPIKE-0 Q2 \u2014 it is the CONFIG, not\n * `DOPPLER_ENVIRONMENT`, which can differ: config `dev_personal` lives in environment `dev`).\n *\n * ABSENT \u21D2 PROCEED, deliberately. The Doppler CLI already refuses a real mismatch on the wire\n * (SPIKE-0 Q1: exit 1, \"does not have access to requested config\"), so it \u2014 not this \u2014 is the\n * load-bearing guard. An absent `DOPPLER_CONFIG` therefore means Doppler changed what it injects,\n * and failing closed here would blank every developer's shell at once.\n *\n * @example\n * assertTokenScope([['DOPPLER_CONFIG', 'dev']], 'dev') // ok\n * assertTokenScope([['FOO', 'bar']], 'dev') // ok (absent \u21D2 proceed)\n * assertTokenScope([['DOPPLER_CONFIG', 'prod']], 'dev') // throws: token is scoped to \"prod\"\n */\nexport const assertTokenScope = (pairs: Array<[string, string]>, config: string): void => {\n const actual = pairs.find(([key]) => {\n return key === DOPPLER_CONFIG_KEY\n })?.[1]\n\n if (actual === undefined || actual === config) return\n\n // A DopplerAuthError, not a plain Error: this IS an auth failure, and callers classify by TYPE\n // (`isEnvAuthFailure`), so a plain Error would read as transient. The message stays richer than the\n // generic one: we know the token's real config.\n throw new DopplerAuthError(\n config,\n null,\n `Doppler returned secrets for config \"${actual}\" but \"${config}\" was requested \u2014 the service token for ` +\n `env \"${config}\" is scoped to the wrong config. Refusing to load another environment's secrets.\\n` +\n `Fix: run \\`infra-kit env-token-set ${config}\\` with a token scoped to \"${config}\".`,\n )\n}\n\n/**\n * Turn a raw `doppler secrets download` failure into an actionable error. An AUTH-class failure (the\n * token is invalid, revoked, or mis-scoped) becomes a {@link DopplerAuthError} carrying the\n * env-token-set message; a recognized project/config not-found points at the exact infra-kit.json\n * field. Anything else \u2014 network, timeout \u2014 is rethrown untouched so it degrades to the existing\n * behavior, never worse.\n *\n * This is THE boundary where Doppler's raw stderr is read: the markers exist only here, and the\n * classification leaves as a TYPE (`DopplerAuthError`), never as prose for a downstream module to\n * re-parse. Exported so a seam test can drive the REAL error a caller sees.\n *\n * @example\n * translateDopplerDownloadError({ stderr: 'Doppler Error: Invalid Auth token' }, 'p', 'dev')\n * // => DopplerAuthError { authKind: 'revoked', message: '\u2026 `infra-kit env-token-set <env>` \u2026' }\n * translateDopplerDownloadError(new Error('connect ETIMEDOUT'), 'p', 'dev')\n * // => the same Error, untouched\n */\n// Why a type and not prose: a caller that text-matched the raw Doppler markers on the error this\n// function had already rewritten found them long gone, and a revoked token went silent.\n//\n// The not-found message no longer lists the AVAILABLE names: `listDopplerProjects` /\n// `listDopplerConfigs` require an ACCOUNT login, which token-only auth deleted, so that probe\n// could only ever return `null` now. `buildDopplerNotFoundMessage` already treats `null` as\n// \"couldn't tell\" and omits the suggestion line rather than misreporting \"none exist\".\nexport const translateDopplerDownloadError = (error: unknown, project: string, config: string): Error => {\n const stderr = extractStderr(error) ?? (error instanceof Error ? error.message : String(error))\n const kind = classifyDopplerFailure(stderr)\n\n if (kind === 'auth') return new DopplerAuthError(config, classifyDopplerAuthFailure(stderr))\n\n if (kind === 'unknown') return error instanceof Error ? error : new Error(String(error))\n\n return new Error(buildDopplerNotFoundMessage({ kind, project, config, available: null }))\n}\n\nexport const assertDopplerOutputSize = (stdout: string): void => {\n const bytes = Buffer.byteLength(stdout, 'utf-8')\n\n if (bytes > DOPPLER_MAX_OUTPUT_BYTES) {\n throw new Error(\n `doppler returned unexpectedly large output (${bytes} bytes > ${DOPPLER_MAX_OUTPUT_BYTES}) \u2014 refusing to write to disk`,\n )\n }\n}\n\nexport const shellSingleQuote = (value: string): string => {\n const escaped = value.replaceAll(\"'\", \"'\\\\''\")\n\n return `'${escaped}'`\n}\n\n/** A valid POSIX env-var name: a letter or underscore, then word characters. */\nconst ENV_VAR_NAME_PATTERN = /^[A-Z_]\\w*$/i\n\n/**\n * Parse the `doppler secrets download --format json` output (a flat\n * `{\"KEY\":\"value\"}` map) into ordered `[key, value]` pairs, validating the shape\n * and every name/value. Values are returned RAW \u2014 callers must single-quote them\n * before emitting shell (an unquoted `a$(cmd)b` would execute on `source`).\n *\n * @example\n * parseDopplerSecretsJson('{\"FOO\":\"bar\",\"BAZ\":\"a$(x)\"}')\n * // => [['FOO', 'bar'], ['BAZ', 'a$(x)']]\n */\nexport const parseDopplerSecretsJson = (stdout: string): Array<[string, string]> => {\n let parsed: unknown\n\n try {\n parsed = JSON.parse(stdout)\n } catch {\n throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(stdout.slice(0, 80))})`)\n }\n\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)')\n }\n\n const pairs: Array<[string, string]> = []\n\n for (const [key, value] of Object.entries(parsed)) {\n if (!ENV_VAR_NAME_PATTERN.test(key)) {\n throw new Error(\n `doppler returned an invalid env var name for env-load (got: ${JSON.stringify(key.slice(0, 80))})`,\n )\n }\n\n if (typeof value !== 'string') {\n throw new TypeError(`doppler returned a non-string value for \"${key}\" (got ${typeof value})`)\n }\n\n pairs.push([key, value])\n }\n\n if (pairs.length === 0) {\n throw new Error('doppler returned empty output for env-load')\n }\n\n return pairs\n}\n\n// MCP Tool Registration\nexport const envLoadMcpTool = defineMcpTool({\n name: 'env-load',\n description:\n 'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced (\"source <filePath>\") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. This server picks the file up on its next tool call, so a tool that needs the variables can be called right after. Omit \"config\" and this server offers the human a form listing every environment env-list knows, token-less ones marked; a client that cannot render one gets a refusal naming the missing field \u2014 call env-list and ask the human, never guess.',\n inputSchema: {\n config: z\n .string()\n .optional()\n .describe(\n 'Doppler config / environment name to load (e.g. \"dev\", \"arthur\"). Omit it to have the human choose from a form.',\n ),\n },\n formProvider: envLoadForm,\n outputSchema: {\n filePath: z.string().describe('Path to the file that must be sourced to apply variables'),\n variableCount: z.number().describe('Number of variables loaded'),\n project: z.string().describe('Doppler project name'),\n config: z.string().describe('Doppler config name'),\n sessionId: z\n .string()\n .nullable()\n .describe('The INFRA_KIT_SESSION the file was written for; null when the process had no session'),\n },\n handler: envLoad,\n})\n", "/**\n * @fileoverview\n *\n * Translate Doppler `secrets download` not-found failures into actionable,\n * point-at-the-fix guidance. Pure (no I/O) so the classification + message policy\n * is unit-testable without spawning the Doppler CLI \u2014 mirroring the pure-helper\n * pattern in `commands/env-load/env-load.ts`.\n *\n * Observed Doppler output on a not-found download (verified 2026-06-27, doppler\n * v3.76.0), exit 1, written to STDERR (stdout empty):\n * Unable to download secrets\n * Doppler Error: Could not find requested project 'name'\n * Doppler Error: Could not find requested config 'name'\n * Only the \"Doppler Error:\" prefix is ANSI-colored; the \"Could not find requested\n * ...\" text is plain, so substring matching is color-safe. zx's\n * `ProcessOutput.message` also concatenates stdout+stderr, so the same markers are\n * matchable off `.message` when `.stderr` is unavailable.\n */\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\n\n/** Which kind of Doppler not-found a download failure represents (`unknown` = not a not-found error). */\nexport type DopplerNotFoundKind = 'project' | 'config' | 'unknown'\n\n/**\n * Every class of `secrets download` failure we act on. `'auth'` is the token-only addition: the\n * service token is absent, revoked, garbage, or scoped to a DIFFERENT config. It is deliberately\n * distinct from the not-found kinds (the name is wrong) and from `'unknown'` (network, timeout,\n * Doppler down) \u2014 only `'auth'` is a durable, user-fixable state.\n */\nexport type DopplerFailureKind = 'auth' | DopplerNotFoundKind\n\nconst PROJECT_NOT_FOUND_MARKER = 'Could not find requested project'\nconst CONFIG_NOT_FOUND_MARKER = 'Could not find requested config'\n\n/**\n * The REAL auth-class stderr markers, captured from a live Doppler CLI v3.76.0 (SPIKE-0 Q1/Q4):\n * - `Invalid Auth token` \u2014 revoked / garbage token\n * - `This token does not have access to requested config 'x'` \u2014 mis-scoped token\n * Both are plain (uncolored) text, so substring matching is ANSI-safe. The second one is the CLI\n * ENFORCING the token's scope for us \u2014 it is the primary mis-scope guard, not our payload assert.\n */\nconst INVALID_TOKEN_MARKER = 'Invalid Auth token'\nconst TOKEN_SCOPE_MARKER = 'does not have access to requested config'\n\n/**\n * Classify a Doppler `secrets download` failure from its stderr/message text. The full lattice:\n * auth-class first (a mis-scoped token's message names a config but is NOT a not-found), then the\n * two not-found kinds, then `'unknown'` for everything else so the caller can rethrow the original\n * untouched (degrades to status quo, never worse).\n *\n * @example\n * classifyDopplerFailure('Doppler Error: Invalid Auth token') // => 'auth'\n * classifyDopplerFailure(\"This token does not have access to requested config 'dev'\") // => 'auth'\n * classifyDopplerFailure(\"Doppler Error: Could not find requested project 'x'\") // => 'project'\n * classifyDopplerFailure('connect ETIMEDOUT') // => 'unknown'\n */\nexport const classifyDopplerFailure = (stderr: string): DopplerFailureKind => {\n if (stderr.includes(INVALID_TOKEN_MARKER) || stderr.includes(TOKEN_SCOPE_MARKER)) return 'auth'\n\n if (stderr.includes(PROJECT_NOT_FOUND_MARKER)) return 'project'\n\n if (stderr.includes(CONFIG_NOT_FOUND_MARKER)) return 'config'\n\n return 'unknown'\n}\n\n/**\n * The two auth-class failures, told apart. Both are `'auth'` to\n * {@link classifyDopplerFailure} \u2014 they share one fix (a new token) \u2014 but they are DIFFERENT\n * diagnoses, and `doctor` must not conflate them: \"your token was revoked\" sends a user to the\n * Doppler dashboard, \"your token is scoped to the wrong config\" sends them to re-issue it against\n * the right one.\n */\nexport type DopplerAuthKind = 'revoked' | 'mis-scoped'\n\n/**\n * Split an auth-class failure into its two diagnoses, or `null` when the text is not auth-class at\n * all (network, timeout, not-found) \u2014 the caller must not read `null` as \"the token is fine\", only\n * as \"this failure says nothing about the token\".\n *\n * @example\n * classifyDopplerAuthFailure(\"This token does not have access to requested config 'dev'\") // => 'mis-scoped'\n * classifyDopplerAuthFailure('Doppler Error: Invalid Auth token') // => 'revoked'\n * classifyDopplerAuthFailure('connect ETIMEDOUT') // => null\n */\nexport const classifyDopplerAuthFailure = (stderr: string): DopplerAuthKind | null => {\n if (stderr.includes(TOKEN_SCOPE_MARKER)) return 'mis-scoped'\n\n if (stderr.includes(INVALID_TOKEN_MARKER)) return 'revoked'\n\n return null\n}\n\n/**\n * Is this failure text an auth-class Doppler failure (bad / absent / mis-scoped service token)\n * rather than a transient one (network, timeout, Doppler down)? The single source of truth\n * callers classify on.\n *\n * @example\n * isDopplerAuthFailure('Doppler Error: Invalid Auth token') // => true\n * isDopplerAuthFailure('network unreachable') // => false\n */\nexport const isDopplerAuthFailure = (stderr: string): boolean => {\n return classifyDopplerFailure(stderr) === 'auth'\n}\n\n/**\n * Classify a Doppler download failure into the NOT-FOUND lattice only. Auth-class failures collapse\n * to `'unknown'` here on purpose: this predicate's whole contract is \"is this a wrong-NAME error\",\n * and its callers enrich with project/config listings that an auth failure must never trigger. Use\n * {@link classifyDopplerFailure} when you need the full lattice.\n *\n * @example\n * classifyDopplerDownloadError(\"Doppler Error: Could not find requested project 'x'\") // => 'project'\n * classifyDopplerDownloadError(\"Doppler Error: Could not find requested config 'dev'\") // => 'config'\n * classifyDopplerDownloadError('Doppler Error: Invalid Auth token') // => 'unknown'\n */\nexport const classifyDopplerDownloadError = (stderr: string): DopplerNotFoundKind => {\n const kind = classifyDopplerFailure(stderr)\n\n return kind === 'auth' ? 'unknown' : kind\n}\n\n/**\n * The actionable body for an auth-class download failure: Doppler REFUSED the token we sent, so the\n * fix is always a new token for this env \u2014 never `doppler login` (account auth no longer exists).\n *\n * Deliberately does not interpolate the raw stderr: this message is user-facing, and the one rule a\n * credential path cannot bend is that nothing token-adjacent gets rendered by accident.\n *\n * @example\n * buildDopplerAuthFailureMessage('dev')\n * // => 'Doppler rejected the service token for env \"dev\" \u2026 run `infra-kit env-token-set <env>` \u2026'\n */\nexport const buildDopplerAuthFailureMessage = (env: string): string => {\n return [\n `Doppler rejected the service token for env \"${env}\" \u2014 it is invalid, revoked, or scoped to a different config.`,\n `Fix: run \\`infra-kit env-token-set ${env}\\` with a token scoped to that config.`,\n 'CI / agents: set INFRA_KIT_ENV_TOKEN to a token scoped to that config.',\n ].join('\\n')\n}\n\n/**\n * An auth-class `secrets download` failure, as a TYPE rather than a string. This is the error\n * `env-load`'s `translateDopplerDownloadError` throws for the auth class, and it is what every\n * DOWNSTREAM consumer classifies on.\n *\n * It is the DOPPLER-REFUSED-US subset of {@link EnvAuthError}, the durable/user-fixable env-auth\n * class. Downstream policy therefore classifies on `isEnvAuthFailure`; `isDopplerAuthError`\n * remains for the callers who genuinely mean \"the token was SENT and Doppler\n * rejected it\". The message is unchanged \u2014 {@link buildDopplerAuthFailureMessage} still renders\n * it \u2014 so a human who only ever sees `error.message` sees precisely what they saw before.\n *\n * @example\n * throw new DopplerAuthError('dev', 'revoked')\n * // message: 'Doppler rejected the service token for env \"dev\" \u2026 `infra-kit env-token-set <env>` \u2026'\n */\n// WHY a class and not \"match the message\": the moment the raw Doppler stderr is translated into a\n// human-facing message the markers it was classified by are GONE. A consumer that re-derives the\n// class by re-parsing that message is coupled to prose owned by another module \u2014 and the coupling\n// is SILENT: reword the message and the auth channel simply stops firing, with every unit test on\n// both sides still green (exactly the defect this type exists to make impossible). The\n// classification now travels WITH the error.\n//\n// Why the subset framing: a missing token never reaches Doppler, and a corrupt token store never\n// reaches the resolver, yet all three are equally durable and equally the user's to fix.\n//\n// The @example names the command as `infra-kit env-token-set <env>` rather than with a literal arg\n// for `program.test.ts`'s benefit: to that scan an `<env>` placeholder ENDS the command, but a\n// literal `dev` is indistinguishable from a subcommand and would be reported as a dead one.\nexport class DopplerAuthError extends EnvAuthError {\n /**\n * The env (= Doppler config) whose service token Doppler refused. Names the fix, carries no token.\n *\n * `declare` NARROWS the base's `string | null` (a Doppler refusal always names one env) without\n * re-declaring the field: under `useDefineForClassFields` a real re-declaration would `defineProperty`\n * it back to `undefined` AFTER `super()` had set it.\n */\n declare readonly env: string\n /**\n * Which of the two auth diagnoses the raw stderr indicated, or `null` when it was not stated\n * (e.g. the payload-scope assert, which never sees Doppler's stderr). Diagnostic only \u2014 every\n * auth kind shares one fix.\n */\n readonly authKind: DopplerAuthKind | null\n\n /**\n * `message` overrides the rendered text for a caller that knows MORE than the generic diagnosis \u2014\n * the payload-scope assert can name the config the token actually belongs to, which Doppler's own\n * refusal cannot. It never changes the CLASS: every auth failure must remain type-detectable, or it\n * degrades to the transient 30s marker and the user is never told (the defect this type exists to\n * make impossible).\n */\n constructor(env: string, authKind: DopplerAuthKind | null = null, message?: string) {\n super(message ?? buildDopplerAuthFailureMessage(env), env)\n this.name = 'DopplerAuthError'\n this.authKind = authKind\n }\n}\n\n/**\n * The NARROW type guard: \"we sent Doppler a token and Doppler refused it\". Not text-matching \u2014 that\n * is how a caller asks \"was this the token?\" without re-parsing a rendered message.\n *\n * Use {@link isEnvAuthFailure} instead when the question is the POLICY one \u2014 \"is this durable and the\n * user's to fix?\" \u2014 because a missing token and a corrupt token store are both of those and neither is\n * a Doppler refusal; narrowing policy to this guard silently drops both cases.\n *\n * @example\n * isDopplerAuthError(new DopplerAuthError('dev')) // => true\n * isDopplerAuthError(new Error('Doppler Error: Invalid Auth token')) // => false (untranslated: not ours to claim)\n */\nexport const isDopplerAuthError = (error: unknown): error is DopplerAuthError => {\n return error instanceof DopplerAuthError\n}\n\ninterface DopplerNotFoundMessageArgs {\n /** Whether the missing entity is the project or the config within it. */\n kind: 'project' | 'config'\n project: string\n config: string\n /**\n * Names to suggest. `null` = lookup failed/unavailable, `[]` = none exist; both\n * omit the suggestion line so a failed enrichment probe is never misreported as\n * a definitive \"none available\".\n */\n available?: string[] | null\n}\n\n/**\n * Build the actionable, multi-line error body for a Doppler not-found failure:\n * states what's missing, points at the exact infra-kit.json field, lists available\n * names when known, and gives a concrete fix.\n *\n * @example\n * buildDopplerNotFoundMessage({ kind: 'project', project: 'infra-kit', config: 'dev', available: ['nomadream'] })\n * // => 'Doppler project \"infra-kit\" not found (set in infra-kit.json \u2192 envManagement.config.name).\\nAvailable projects: nomadream.\\nFix: ...'\n */\nexport const buildDopplerNotFoundMessage = ({\n kind,\n project,\n config,\n available,\n}: DopplerNotFoundMessageArgs): string => {\n const lines: string[] =\n kind === 'project'\n ? [`Doppler project \"${project}\" not found (set in infra-kit.json \u2192 envManagement.config.name).`]\n : [`Doppler config \"${config}\" not found in project \"${project}\".`]\n\n if (available && available.length > 0) {\n const label = kind === 'project' ? 'Available projects' : `Available configs in \"${project}\"`\n\n lines.push(`${label}: ${available.join(', ')}.`)\n }\n\n // The config half no longer points at a config file: there IS no declared env list any more. The name\n // came from a workflow, a token, or the `--config` flag, and the only place to fix a genuinely missing\n // one is Doppler itself.\n lines.push(\n kind === 'project'\n ? 'Fix: update envManagement.config.name to an existing project, or create it in Doppler.'\n : 'Fix: pass an existing config, or create it in Doppler.',\n )\n\n return lines.join('\\n')\n}\n", "import { $ } from 'zx'\n\nimport { classifyDopplerAuthFailure, classifyDopplerFailure } from 'src/integrations/doppler/doppler-errors'\nimport { extractStderr } from 'src/lib/errors/operation-error'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\n\n/**\n * Hard upper bound for the Doppler probe. It runs only on the diagnostic path (`doctor`), but a hung\n * VPN/connection must not stall it.\n */\nconst DOPPLER_PROBE_TIMEOUT_MS = 5_000\n\n/**\n * The one secret every Doppler payload carries, whose value is the config the token is scoped to\n * (SPIKE-0 Q2 \u2014 the CONFIG, not `DOPPLER_ENVIRONMENT`, which can differ: config `dev_personal` lives\n * in environment `dev`). Reading it back is what turns a liveness probe into a SCOPE probe.\n */\nconst SCOPE_KEY = 'DOPPLER_CONFIG'\n\n/**\n * Resolve Doppler project name from infra-kit.json at the project root\n */\nexport const getDopplerProject = async (): Promise<string> => {\n const { envManagement } = await getInfraKitConfig()\n\n return envManagement.config.name\n}\n\n/**\n * What a service token turned out to be, once Doppler was asked.\n *\n * `'unreachable'` is the load-bearing one and it means \"COULDN'T TELL\", never \"bad\": network,\n * timeout, VPN, Doppler down, a CLI that isn't installed. A caller that renders it as a definitive\n * verdict would tell a developer on a plane that their token was revoked. (Same `null`-vs-`[]`\n * contract the deleted `listDopplerProjects` carried, in enum form.)\n */\nexport type EnvTokenProbeOutcome = 'valid' | 'revoked' | 'mis-scoped' | 'unreachable'\n\nexport interface EnvTokenProbe {\n outcome: EnvTokenProbeOutcome\n /** The config the token actually resolved to, when Doppler told us. Never a token value. */\n scopedTo?: string\n}\n\ninterface EnvTokenProbeArgs {\n /**\n * The child environment carrying the token \u2014 built by `buildDopplerChildEnv`, which scrubs the\n * inherited `DOPPLER_*` vars and sets ours. Passed in rather than built here so the token travels\n * by ENV and never by argv (`ps` shows argv to every user on the box), and so this module stays\n * free of a cycle back through `commands/env-load`.\n */\n childEnv: NodeJS.ProcessEnv\n project: string\n config: string\n}\n\n/**\n * The cheapest combined VALIDITY + SCOPE probe of a Doppler service token (SPIKE-0): read one secret\n * back \u2014 the payload's own `DOPPLER_CONFIG` \u2014 and compare it to the config we asked for.\n *\n * `doppler me` is NOT enough: it works under a service token but returns no project/config, so it can\n * only prove the token is alive, never that it points where we think. One `secrets get` answers both\n * questions in one round trip, and the CLI enforces the scope for us on the wire.\n *\n * Never throws. Every failure becomes an outcome, and an unrecognized one becomes `'unreachable'`\n * (\"couldn't tell\") rather than a guess \u2014 the caller is `doctor`, whose whole value is that its\n * verdicts are true.\n *\n * @example\n * await probeEnvToken({ childEnv, project: 'api', config: 'dev' })\n * // => { outcome: 'valid', scopedTo: 'dev' }\n * // revoked token => { outcome: 'revoked' }\n * // token for prod => { outcome: 'mis-scoped' }\n * // offline => { outcome: 'unreachable' }\n */\nexport const probeEnvToken = async ({ childEnv, project, config }: EnvTokenProbeArgs): Promise<EnvTokenProbe> => {\n const prevQuiet = $.quiet\n\n $.quiet = true\n try {\n const result = await $({\n env: childEnv,\n })`doppler secrets get ${SCOPE_KEY} --plain --project ${project} --config ${config}`.timeout(\n DOPPLER_PROBE_TIMEOUT_MS,\n )\n const scopedTo = result.stdout.trim()\n\n // Exit 0 with a DIFFERENT config would mean the CLI's own scope enforcement let a mis-scoped token\n // through \u2014 belt and braces, but this is the check that would catch it.\n if (scopedTo !== config) return { outcome: 'mis-scoped', scopedTo }\n\n return { outcome: 'valid', scopedTo }\n } catch (error: unknown) {\n return { outcome: classifyProbeFailure(error) }\n } finally {\n $.quiet = prevQuiet\n }\n}\n\n/**\n * Turn a failed probe into an outcome. Only the two auth-class markers are definitive; a\n * project/config not-found is a config bug rather than a token verdict, so it collapses to\n * `'unreachable'` too \u2014 the token check must not claim a token is bad because the PROJECT name is.\n */\nconst classifyProbeFailure = (error: unknown): EnvTokenProbeOutcome => {\n const stderr = extractStderr(error) ?? (error instanceof Error ? error.message : String(error))\n\n if (classifyDopplerFailure(stderr) !== 'auth') return 'unreachable'\n\n return classifyDopplerAuthFailure(stderr) ?? 'unreachable'\n}\n", "import process from 'node:process'\n\nimport { getTokenStorePath, readTokenStore } from 'src/lib/env-tokens'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * The ONE environment variable that carries a Doppler service token into infra-kit (the CI / agent\n * path: no home directory, no token store, no interactive `env-token-set`).\n *\n * Deliberately NOT named `DOPPLER_TOKEN`. That name is contaminated on both ends: a Doppler project\n * may itself hold a secret called `DOPPLER_TOKEN`, and `env-load` exports the WHOLE project into the\n * shell \u2014 so a `DOPPLER_TOKEN` in the environment cannot be trusted to be the token WE were handed\n * (SPIKE-0 Q5: an inherited `DOPPLER_TOKEN` silently overrides everything else the CLI would use).\n * A private name keeps the input channel ours.\n */\nexport const INFRA_KIT_ENV_TOKEN_VAR = 'INFRA_KIT_ENV_TOKEN'\n\n/** Where a resolved token came from. Surfaced by `env-token-list`; never carries the token itself. */\nexport type EnvTokenSource = 'env' | 'store'\n\nexport interface ResolvedEnvToken {\n /** The Doppler service token. NEVER log, echo, or write this into a sourced file. */\n token: string\n source: EnvTokenSource\n}\n\n/**\n * Resolve the Doppler service token for one environment (= one Doppler config).\n *\n * Precedence, highest first:\n * 1. `INFRA_KIT_ENV_TOKEN` \u2014 the CI / agent channel. Checked BEFORE the store so a machine with no\n * home config (or a deliberately corrupted one) still loads, and so nothing on that path can\n * throw on a store it never needed.\n * 2. `envs[env]` from `~/.infra-kit/projects/<repo>/tokens.json` \u2014 the developer channel.\n * 3. Nothing \u21D2 THROW an {@link EnvAuthError}. Token-only auth has no fallback: there is no\n * `doppler login` account to degrade to, so a missing token is a hard, actionable stop rather than\n * a mysterious empty env. The CLASS matters as much as the message \u2014 see the throw below.\n *\n * An EMPTY `INFRA_KIT_ENV_TOKEN` is a MISS, not an empty token: `export INFRA_KIT_ENV_TOKEN=` (or an\n * unset var expanded by a CI template) must fall through to the store, not authenticate as \"\".\n *\n * @example\n * await resolveEnvToken('dev') // => { token: 'dp.st.dev.xxxx', source: 'store' }\n * // with INFRA_KIT_ENV_TOKEN set => { token: <that value>, source: 'env' }\n * // with neither => throws 'No Doppler service token for env \"dev\". \u2026'\n */\nexport const resolveEnvToken = async (env: string): Promise<ResolvedEnvToken> => {\n const fromEnv = process.env[INFRA_KIT_ENV_TOKEN_VAR]\n\n if (fromEnv) return { token: fromEnv, source: 'env' }\n\n const store = await readTokenStore()\n const fromStore = store?.envs[env]\n\n if (fromStore) return { token: fromStore, source: 'store' }\n\n // An EnvAuthError, not a plain Error: \"no token\" is the DURABLE, user-fixable auth failure \u2014 see\n // EnvAuthError's own doc for why the class, not the message, is what downstream callers classify on.\n throw new EnvAuthError(buildMissingTokenMessage(env, await getTokenStorePath()), env)\n}\n\n/**\n * The no-token refusal. It is the first thing an un-migrated user sees at update time, so it must be\n * fixable without reading any docs: it names the env, where to mint a token, the exact command, where\n * the token lands (and that it is NOT the repo), and the CI escape hatch.\n *\n * The fix command is a BACKTICK code span \u2014 the repo convention for naming a command to a human, and\n * the anchor `program.test.ts` scans to prove every command we print is a command we accept.\n *\n * (The @example names the command as `infra-kit env-token-set <env>` rather than with a literal arg\n * for that scan's benefit: a `<env>` placeholder ENDS the command, but a literal `dev` is\n * indistinguishable from a subcommand and would be reported as a dead one.)\n *\n * @example\n * buildMissingTokenMessage('dev', '/Users/x/.infra-kit/projects/api/tokens.json')\n * // => 'No Doppler service token for env \"dev\". Mint one at https://dashboard.doppler.com \u2026 run `infra-kit env-token-set <env>` \u2026'\n */\nconst buildMissingTokenMessage = (env: string, storePath: string): string => {\n return [\n `No Doppler service token for env \"${env}\".`,\n `Mint one at https://dashboard.doppler.com \u2014 this project \u2192 config \"${env}\" \u2192 Access tab \u2192 \"Generate Service Token\".`,\n `Fix: run \\`infra-kit env-token-set ${env}\\` and paste it.`,\n `It is stored in ${tildify(storePath)} (mode 0600, never in the repo).`,\n `CI / agents: set ${INFRA_KIT_ENV_TOKEN_VAR} instead \u2014 it takes precedence and needs no home config.`,\n ].join('\\n')\n}\n", "import process from 'node:process'\nimport { z } from 'zod'\n\nimport { buildEnvTokenStatus } from 'src/commands/env-list'\nimport { INFRA_KIT_ENV_TOKEN_VAR } from 'src/integrations/doppler/token-resolver'\nimport { INFRA_KIT_SESSION_VAR } from 'src/lib/constants'\nimport { readTokenStore } from 'src/lib/env-tokens'\nimport { logger } from 'src/lib/logger'\nimport type { ProjectEnv } from 'src/lib/project-envs'\nimport { listProjectEnvs } from 'src/lib/project-envs'\nimport type { ArgumentFormProvider } from 'src/types'\n\n/**\n * @fileoverview\n *\n * The argument form `env-load` offers when `config` is omitted: pick the environment to load into\n * the calling terminal session, from the same list `env-list` reports.\n *\n * Same seam as `lib/deploy-form`, same silent failure modes \u2014 the tests assert `!== null` on the\n * wire shape for that reason.\n */\n\n/** A plain object \u2014 not an array, not `null`, not a primitive. */\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Collapse a failed enumeration into an empty one \u2014 the provider's own contract is never-throws. */\nconst orEmpty = async (work: Promise<ProjectEnv[]>): Promise<ProjectEnv[]> => {\n try {\n return await work\n } catch {\n return []\n }\n}\n\n/**\n * The envs no token resolves for. An unreadable store reports every env as token-less: the load\n * would fail on the same read, so the form says so up front rather than pretending otherwise.\n */\nconst tokenlessEnvs = async (envs: ProjectEnv[]): Promise<string[]> => {\n const store = await readTokenStore().catch(() => {\n return null\n })\n\n return buildEnvTokenStatus(envs, store?.envs ?? {}, process.env[INFRA_KIT_ENV_TOKEN_VAR])\n .filter((status) => {\n return !status.hasToken\n })\n .map((status) => {\n return status.env\n })\n}\n\n/**\n * Build the `formProvider` for the `env-load` tool.\n *\n * @example\n * envLoadMcpTool.formProvider = createEnvLoadFormProvider()\n */\nexport const createEnvLoadFormProvider = (): ArgumentFormProvider => {\n return {\n // A getter, not a string: `envLoadMcpTool` is a module-scope constant, so a plain string would\n // freeze the session id at import time. Production never changes it after boot; tests set it\n // after the import. Satisfies `message: string` structurally.\n get message(): string {\n const session =\n process.env[INFRA_KIT_SESSION_VAR] ?? `UNKNOWN \u2014 ${INFRA_KIT_SESSION_VAR} is not set, the load will fail`\n\n return `Choose the environment to load into terminal session ${session}. Picking one LOADS it; there is no further prompt.`\n },\n\n isFormable: (params: unknown): boolean => {\n return isRecord(params) && (params.config === undefined || params.config === '')\n },\n\n buildRequestedSchema: async (): Promise<z.ZodObject<z.ZodRawShape> | null> => {\n const envs = await orEmpty(listProjectEnvs())\n\n // `null` with a log line, never `z.enum([])`: the latter throws inside `elicit()` and degrades\n // to a gate that looks exactly like a client which cannot render forms.\n if (envs.length === 0) {\n logger.info({ msg: 'Tool execution form options empty: env-load' })\n\n return null\n }\n\n const names = envs.map((env) => {\n return env.env\n })\n const tokenless = await tokenlessEnvs(envs)\n\n // The token annotation rides in the field prose: the elicitation wire shape carries no\n // per-option labels, so the description is the only place the human can be told before they pick.\n return z.object({\n config: z\n .enum(names)\n .describe(\n `The environment to load. ${\n tokenless.length === 0\n ? 'A service token is stored for every one of them.'\n : `NO stored token for: ${tokenless.join(', ')} \u2014 choosing one of those fails until you run \\`infra-kit env-token-set <env>\\`.`\n } The list is what env-list knows: workflow-declared environments first, then token-only ones.`,\n ),\n })\n },\n\n toArgs: (content: Record<string, unknown>, params: unknown): Record<string, unknown> | null => {\n const { config } = content\n\n if (typeof config !== 'string' || config.length === 0) return null\n\n return { ...(isRecord(params) ? params : {}), config }\n },\n }\n}\n", "import process from 'node:process'\nimport { z } from 'zod'\n\nimport { getDopplerProject } from 'src/integrations/doppler/doppler-project'\nimport { INFRA_KIT_ENV_TOKEN_VAR } from 'src/integrations/doppler/token-resolver'\nimport { readTokenStore } from 'src/lib/env-tokens'\nimport { logger } from 'src/lib/logger'\nimport type { ProjectEnv, ProjectEnvSource } from 'src/lib/project-envs'\nimport { listProjectEnvs } from 'src/lib/project-envs'\nimport { defineMcpTool, textContent } from 'src/types'\n\n/** One row of the token column: an env, where we learned it exists, and whether a token resolves. */\nexport interface EnvTokenStatus {\n env: string\n /** `gh-workflow` \u2014 declared in a workflow's dispatch options. `token-only` \u2014 we hold a token, no workflow names it. */\n source: ProjectEnvSource\n hasToken: boolean\n}\n\n/**\n * Build the token column: one row per known environment, reporting only WHETHER a token resolves \u2014\n * never the token itself. Mirrors `resolveEnvToken`'s precedence (`INFRA_KIT_ENV_TOKEN` shadows the\n * store for every env) without importing it, so this stays a pure, no-I/O function the same way\n * `buildEnvTokenRows` in `env-token-list` is.\n *\n * @example\n * buildEnvTokenStatus([{ env: 'dev', source: 'gh-workflow' }], { dev: 'dp.st.dev.xxxx' }, undefined)\n * // => [{ env: 'dev', source: 'gh-workflow', hasToken: true }]\n */\nexport const buildEnvTokenStatus = (\n envs: ProjectEnv[],\n storeTokens: Record<string, string>,\n envToken: string | undefined,\n): EnvTokenStatus[] => {\n return envs.map(({ env, source }) => {\n return { env, source, hasToken: Boolean(envToken || storeTokens[env]) }\n })\n}\n\n/** Column headers for the environments table, in render order. */\nconst ENV_TABLE_HEADERS = ['Environment', 'Source', 'Token'] as const\n\n/**\n * Render the environments as an aligned, vertical-bar-separated table \u2014 the same columnar shape as\n * `gh-release-list`, with explicit `|` column rules. Display only: the `--json` payload is built\n * separately in {@link buildResult} from the same rows, so the machine contract never depends on this\n * formatting. Deliberately prints no fix command \u2014 setting a token is a manual `env-token-set` step,\n * not something this read-only listing spells out.\n *\n * @example\n * formatEnvTable([{ env: 'dev', source: 'gh-workflow', hasToken: true }])\n * // => ['Environments:', '', 'Environment | Source | Token', '\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2026', 'dev | gh-workflow | set']\n */\nconst formatEnvTable = (rows: EnvTokenStatus[]): string[] => {\n const cells = rows.map((row) => {\n return [row.env, row.source, row.hasToken ? 'set' : 'not set']\n })\n\n const widths = ENV_TABLE_HEADERS.map((header, col) => {\n return Math.max(\n header.length,\n ...cells.map((cell) => {\n return (cell[col] ?? '').length\n }),\n )\n })\n\n const renderRow = (values: readonly string[]): string => {\n return values\n .map((value, col) => {\n return value.padEnd(widths[col] ?? 0)\n })\n .join(' | ')\n .trimEnd()\n }\n\n const separator = widths\n .map((width) => {\n return '\u2500'.repeat(width)\n })\n .join('\u2500\u253C\u2500')\n\n return ['Environments:', '', renderRow(ENV_TABLE_HEADERS), separator, ...cells.map(renderRow)]\n}\n\n/**\n * List the environments this project has, alongside whether a service token resolves for each one.\n *\n * Purely local: reads the repo's workflows and the local token store, and does not call Doppler \u2014 so\n * it works before any service token exists, which is exactly when a user needs to see the env names\n * they have to run `infra-kit env-token-set <env>` for. (A Doppler SERVICE token could not answer this\n * anyway: it is config-scoped and enumerates only its own config.) The token PRESENCE check is a local\n * file read, not a network probe \u2014 validating that a stored token is still accepted stays\n * `env-token-list --check`'s job.\n *\n * @example\n * await envList()\n * // logs an aligned table: 'dev | gh-workflow | set', 'stage | gh-workflow | not set'\n */\nexport const envList = async () => {\n const project = await getDopplerProject()\n const envs = await listProjectEnvs()\n const store = await readTokenStore()\n const envToken = process.env[INFRA_KIT_ENV_TOKEN_VAR]\n\n const tokens = buildEnvTokenStatus(envs, store?.envs ?? {}, envToken)\n\n logger.info(`Doppler project: ${project}\\n`)\n\n if (tokens.length === 0) {\n // Not an error \u2014 a repo can legitimately declare no dispatchable environment. But an empty list with\n // no explanation is the one thing this command must never print: it is read precisely by the person\n // who does not yet know what the env names ARE.\n logger.info('No environments found.')\n logger.info(` Declare them in a workflow's \\`workflow_dispatch\\` \\`environment.options\\`,`)\n logger.info(' or add a token for one manually.')\n\n return buildResult({ project, envs: tokens })\n }\n\n for (const line of formatEnvTable(tokens)) {\n logger.info(line)\n }\n\n return buildResult({ project, envs: tokens })\n}\n\n/** Shared tail for both exits above \u2014 the empty state is a first-class result, not an error. */\nconst buildResult = ({ project, envs }: { project: string; envs: EnvTokenStatus[] }) => {\n const structuredContent = {\n project,\n configs: envs.map((row) => {\n return row.env\n }),\n tokens: envs,\n }\n\n return {\n content: textContent(JSON.stringify(structuredContent, null, 2)),\n structuredContent,\n }\n}\n\n// MCP Tool Registration\nexport const envListMcpTool = defineMcpTool({\n name: 'env-list',\n description:\n \"List the environments this project has. The list is the union of two local sources: every environment declared in a GitHub workflow's `workflow_dispatch` `environment.options` (source `gh-workflow`), and every environment the local token store holds a token for (source `token-only`). Not a live fetch from Doppler \u2014 a Doppler service token is config-scoped and cannot enumerate sibling configs. Also returns the Doppler project name, and reports per environment whether a service token resolves locally (from the token store or INFRA_KIT_ENV_TOKEN) \u2014 presence only, never the token value, and never a live Doppler probe. Read-only.\",\n inputSchema: {},\n outputSchema: {\n project: z.string().describe('Detected Doppler project name'),\n configs: z.array(z.string()).describe('Every environment name known to this project'),\n tokens: z\n .array(\n z.object({\n env: z.string().describe('Environment / Doppler config name'),\n source: z\n .enum(['gh-workflow', 'token-only'])\n .describe('Where we learned this environment exists \u2014 a workflow declaration, or a token we hold'),\n hasToken: z.boolean().describe('Whether a service token resolves locally for this environment'),\n }),\n )\n .describe('Per-environment token presence \u2014 never the token value'),\n },\n handler: envList,\n})\n", "import { agentMode } from 'src/lib/agent-mode'\nimport { OperationError } from 'src/lib/errors/operation-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\n\n/**\n * Environments that are NOT ordinary ad-hoc deploy targets by default.\n *\n * This is the DEFAULT, not an immovable policy: a project opts out with `protectedEnvs` in its\n * `infra-kit.json` (`'disallow' | 'allow' | 'cli-only'`, absent meaning `'disallow'`), resolved by\n * `protected-env-access.ts`. The LIST stays in code because it answers \"what is delivery-shaped in\n * this org\", which no single repo owns; the config answers \"may this repo reach it\", which each\n * repo does.\n */\n// `prod` is not a deploy target \u2014 it is a DELIVERY target. `gh-release-deliver` is the sanctioned\n// path to it, and it is a whole flow, not a dispatch: squash-merge the release branch to `main`,\n// open and merge the RC PR, dispatch `deploy-all.yml --ref main -f environment=prod` (see\n// `gh-release-deliver.ts`), then release the matching Jira fix version. A `gh-release-deploy-all\n// --env prod` straight from a release branch skips every one of those steps and ships production\n// from an unmerged ref.\n//\n// `stage` is deliberately NOT here. The old per-repo allowlists excluded it, but nothing delivers\n// to it either \u2014 so it was simply unreachable, which was an oversight rather than a policy. It is\n// an ad-hoc deploy target like any other.\n//\n// What is deliberately NOT rebuilt here is the deleted `environments` key \u2014 a hand-maintained\n// per-repo copy of each workflow's own `environment.options` that drifted from them and turned\n// that drift into a REFUSAL to deploy.\nexport const DEFAULT_PROTECTED_ENVS = ['prod']\n\n/**\n * A project's resolved access to {@link DEFAULT_PROTECTED_ENVS}, and WHY.\n *\n * The reason is not decoration: a refusal because the project disallows protected envs and a refusal\n * because the caller is an agent under `'cli-only'` need opposite remediation. Collapsed to a bare\n * boolean, the second case emits \"prod is delivered, not deployed\" and sends an agent off to run the\n * delivery flow, or to report that prod is unconfigured for the project.\n *\n * Declared here, in the pure leaf, so `protected-env-access.ts` depends on this module and never the\n * reverse.\n */\nexport interface ProtectedEnvAccess {\n allowed: boolean\n reason: 'disallow' | 'agent-blocked' | 'allowed'\n}\n\n/**\n * No access \u2014 the DEFAULT for every function below.\n *\n * That default is the safety property of this module: a call site that forgets to thread the resolved\n * access refuses rather than permits, so a seventh caller is fail-closed until someone deliberately\n * opts it in.\n */\nexport const PROTECTED_ENV_DENIED: ProtectedEnvAccess = { allowed: false, reason: 'disallow' }\n\n/** Whether an environment is delivery-shaped by default, before any project opt-out. */\nexport const isProtectedEnv = (env: string): boolean => {\n return DEFAULT_PROTECTED_ENVS.includes(env)\n}\n\n/**\n * Environments the whole team shares. Everything else in a deploy picker is somebody's personal\n * account (`arthur`, `renana`, \u2026), where a dirty tree is the normal case rather than a hazard.\n */\nconst SHARED_ENVS = ['dev', 'stage']\n\n/**\n * Whether this environment belongs to other people \u2014 the input to `local-deploy`'s confirmation\n * prompt and, via `runPreflight`, its dirty-tree refusal, and to the argument form's `env` prose.\n *\n * A delivery-shaped env is shared by definition, more so than `dev`, yet it is deliberately NOT in\n * {@link SHARED_ENVS}: until a project could reach `prod` at all the question never arose, because\n * `assertDeployable` refused first. Now that a project can allow it, resolving from the list alone\n * would hand production the WEAKER treatment of a personal environment \u2014 a y/N prompt and no\n * clean-tree check, i.e. shipping an uncommitted working tree to prod.\n *\n * @example\n * isSharedEnv('dev') // => true\n * isSharedEnv('prod') // => true \u2014 protected, therefore shared\n * isSharedEnv('arthur') // => false\n */\n// Lives in this leaf rather than in `local-deploy.ts`, where it was written, because the deploy\n// argument form partitions its env dropdown's `.describe()` with it. The form provider is wired into\n// `local-deploy`'s own tool definitions, so importing it from there would close a cycle \u2014 and a\n// second hand-written list of shared envs in the provider is exactly the drift the plan requires the\n// prose be derived to avoid. Extracted rather than inlined so the resolution stays testable:\n// asserting `assertCleanTreeForSharedEnv({ isShared: true, \u2026 })` hand-passes the value under test and\n// passes whether or not the bug exists.\nexport const isSharedEnv = (env: string): boolean => {\n return SHARED_ENVS.includes(env) || isProtectedEnv(env)\n}\n\n/**\n * The ad-hoc deploy picker: a workflow's declared options, minus what this project may not reach.\n *\n * @example\n * deployableEnvs(['dev', 'prod']) // => ['dev']\n * deployableEnvs(['dev', 'prod'], { allowed: true, reason: 'allowed' }) // => ['dev', 'prod']\n */\nexport const deployableEnvs = (options: string[], access: ProtectedEnvAccess = PROTECTED_ENV_DENIED): string[] => {\n if (access.allowed) return options\n\n return options.filter((env) => {\n return !isProtectedEnv(env)\n })\n}\n\n/**\n * Refuse a protected environment this project may not reach, naming the fix for THIS refusal.\n *\n * GitHub cannot enforce either rule for us \u2014 from its side `-f environment=prod` is a perfectly valid\n * choice \u2014 so both are ours. Note what is NOT vetoed: an env absent from the local YAML still\n * dispatches, because that read is of the working tree while the run targets `--ref <branch>`, and\n * GitHub validates the choice itself.\n *\n * @example\n * assertDeployable('dev', 'launch deploy-all workflow') // ok\n * assertDeployable('prod', 'launch deploy-all workflow') // throws \u2014 use `infra-kit release deliver`\n */\nexport const assertDeployable = (\n env: string,\n operation: string,\n access: ProtectedEnvAccess = PROTECTED_ENV_DENIED,\n): void => {\n if (access.allowed) return\n if (!isProtectedEnv(env)) return\n\n // Structured (exit 2, nothing ran): the agent that reads it needs the env named and the fact that no\n // flag of its own opens this door \u2014 it is an agent-side withholding, not a transport one.\n if (access.reason === 'agent-blocked') {\n throw new StructuredRefusalError({ status: 'refused', env, agentMode: agentMode.source }, 2, {\n operation,\n remediation: `a human runs it from their own terminal \u2014 this project sets \\`protectedEnvs: \"cli-only\"\\``,\n stderrExcerpt: `\"${env}\" is withheld from agents in this project (protectedEnvs: \"cli-only\")`,\n })\n }\n\n throw new OperationError(undefined, {\n operation,\n remediation:\n `use \\`infra-kit release deliver\\` \u2014 it merges the release to main, opens the RC PR, ` +\n `deploys from main, and releases the Jira version. To allow ad-hoc deploys to \"${env}\" in this ` +\n `project, set \\`protectedEnvs\\` to \"allow\" or \"cli-only\" in infra-kit.json`,\n stderrExcerpt: `\"${env}\" is delivered, not deployed ad-hoc`,\n })\n}\n", "import { isAgentMode } from 'src/lib/agent-mode'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\n\nimport { PROTECTED_ENV_DENIED } from './protected-envs'\nimport type { ProtectedEnvAccess } from './protected-envs'\n\n/**\n * Resolve whether THIS project may reach the delivery-shaped environments, and why not when it may\n * not. The single place the three-value `protectedEnvs` setting is interpreted \u2014 every call site\n * downstream sees the resolved {@link ProtectedEnvAccess} and nothing else.\n *\n * NEVER THROWS. A repo with no `infra-kit.json`, an unreadable one, or one the merge chain rejects\n * all resolve to denied.\n *\n * @example\n * await resolveProtectedEnvAccess() // no `protectedEnvs` key => { allowed: false, reason: 'disallow' }\n */\n// The only impure member of the protected-env pair: it reads the merged config and the agent-mode\n// flag, so `protected-envs.ts` stays a dependency-free policy leaf with a mock-free unit test.\n//\n// Refusing a protected env on a config we cannot read is correct; turning every deploy into a\n// config-parse error is not \u2014 and `getInfraKitConfig` genuinely throws for a missing file.\n//\n// `isAgentMode()` is called INSIDE this function on purpose. `agentMode` is a mutable object read at\n// call time, and the source is assigned in the CLI's `preAction` hook, which runs after this module\n// is imported. Hoisting the read to module\n// scope \u2014 `const inAgent = agentMode.source !== null` at the top \u2014 would freeze `false` and silently\n// degrade `'cli-only'` into `'allow'` for every agent.\nexport const resolveProtectedEnvAccess = async (): Promise<ProtectedEnvAccess> => {\n let setting\n\n try {\n setting = (await getInfraKitConfig()).protectedEnvs ?? 'disallow'\n } catch {\n return PROTECTED_ENV_DENIED\n }\n\n if (setting === 'disallow') return PROTECTED_ENV_DENIED\n\n if (setting === 'cli-only' && isAgentMode()) {\n return { allowed: false, reason: 'agent-blocked' }\n }\n\n return { allowed: true, reason: 'allowed' }\n}\n", "import { logger } from 'src/lib/logger'\n\nimport { isProtectedEnv } from './protected-envs'\n\n/**\n * Warn, at selection time, about what an ad-hoc dispatch to a delivery-shaped environment SKIPS.\n *\n * This is the knowledge the refusal in `assertDeployable` used to carry. A project that sets\n * `protectedEnvs` to `\"allow\"` removes the block, and the block was the only place in the codebase\n * recording WHY `prod` was special \u2014 so the sentence has to outlive it, or the next person learns the\n * hard way that `release deploy-all --env prod` is `release deliver` minus its bookkeeping.\n *\n * Deliberately a warning and not a second confirmation: the project already decided, and a prompt the\n * user cannot act on differently is just friction. The dispatch commands run their own `confirmDeploy`\n * immediately after this.\n *\n * Shared by both dispatch commands rather than copied: `gh-release-deploy-selected` already carries a\n * cognitive-complexity suppression, and this must not add to it.\n *\n * @example\n * warnProtectedEnvDispatch({ env: 'prod', branch: 'release/1.9.0' }) // logs the skipped steps\n * warnProtectedEnvDispatch({ env: 'dev', branch: 'release/1.9.0' }) // no-op\n */\nexport const warnProtectedEnvDispatch = (args: { env: string; branch: string }): void => {\n const { env, branch } = args\n\n if (!isProtectedEnv(env)) return\n\n logger.warn(\n [\n `\u26A0\uFE0F \"${env}\" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,\n `Dispatching from \"${branch}\" ships ${env} from a ref that is not merged to main, and skips:`,\n ' \u2022 the squash-merge of the release branch into main',\n ' \u2022 the RC pull request',\n ' \u2022 the Jira fix-version release',\n 'Run `infra-kit release deliver` instead if you want those.',\n ].join('\\n'),\n )\n}\n", "import fs from 'node:fs/promises'\nimport path from 'node:path'\nimport yaml from 'yaml'\n\nimport { getProjectRoot } from 'src/lib/git-utils'\n\n/** Where GitHub keeps dispatchable workflows. The only place we look for environment declarations. */\nconst WORKFLOWS_DIR = '.github/workflows'\n\n/**\n * The environment list a workflow will accept, read from its own `workflow_dispatch` `choice`\n * input.\n *\n * ADVISORY ONLY: it sources the interactive picker, and callers must NOT veto against it. The value\n * comes from the WORKING TREE while the dispatch targets `--ref <branch>`, so the two can\n * legitimately differ and an explicit `--env` must always win.\n *\n * Never throws. A repo with no such workflow (bridge has none), a `type: string` input, an absent\n * `options:` key, or malformed YAML all yield `[]` \u2014 an empty picker, never a dead command.\n *\n * @example\n * await readWorkflowEnvOptions('deploy-all.yml') // => ['dev', 'arthur', 'stage', 'prod']\n * await readWorkflowEnvOptions('absent.yml') // => []\n */\n// This replaces `infra-kit.json \u2192 environments`, which was a THIRD copy of a fact GitHub already\n// owns and already enforces: a `choice` input is validated server-side on dispatch, so an\n// out-of-range value is rejected by GitHub whether or not we check it here. The copy had drifted \u2014\n// hulyo declared 6 envs while every hulyo workflow declared 8, and the CLI's client-side check\n// turned that drift into a REFUSAL to deploy to `stage` and `prod`. Vetoing on a local read of a\n// remote fact is what created the bug this function exists to remove.\nexport const readWorkflowEnvOptions = async (workflowFile: string): Promise<string[]> => {\n const projectRoot = await getProjectRoot()\n\n return parseEnvOptions(path.resolve(projectRoot, WORKFLOWS_DIR, workflowFile))\n}\n\n/**\n * Every environment this repo declares anywhere \u2014 the union across ALL workflows.\n *\n * Deliberately a UNION, and deliberately not `deploy-all.yml` alone. Two repos prove why: travelist's\n * `deploy-all` omits `eliran` and `roman` (who both hold live tokens and ARE deployable via\n * `deploy-selected-services`), and bridge has no `deploy-all.yml` at all, so a single-file read would\n * report that it has zero environments.\n *\n * Note the asymmetry with {@link readWorkflowEnvOptions}, and keep it: this answers the REPO-scoped\n * question (\"what environments exist here?\") and so unions; the deploy pickers answer the\n * WORKFLOW-scoped question (\"where can THIS workflow deploy?\") and so must not.\n *\n * Never throws \u2014 an unreadable workflows directory yields `[]`.\n *\n * @example\n * await listWorkflowEnvs() // => ['dev', 'arthur', 'eliran', 'renana', 'roman', 'oriana', 'stage', 'prod']\n */\nexport const listWorkflowEnvs = async (): Promise<string[]> => {\n const projectRoot = await getProjectRoot()\n const workflowsDir = path.resolve(projectRoot, WORKFLOWS_DIR)\n\n let entries: string[]\n\n try {\n entries = await fs.readdir(workflowsDir)\n } catch {\n return []\n }\n\n const workflows = entries\n .filter((entry) => {\n return entry.endsWith('.yml') || entry.endsWith('.yaml')\n })\n .sort()\n\n const perWorkflow = await Promise.all(\n workflows.map((file) => {\n return parseEnvOptions(path.resolve(workflowsDir, file))\n }),\n )\n\n // First-seen order, de-duped: the picker reads best when `dev` leads, as it does in every workflow.\n return [...new Set(perWorkflow.flat())]\n}\n\n/**\n * Pull `on.workflow_dispatch.inputs.environment.options` out of one workflow, or `[]`.\n *\n * `yaml.parse` is untyped, and every hop here is a place a real workflow legitimately differs (a\n * `push`-only workflow has no `workflow_dispatch`; a reusable `_jobs.yml` takes `environment` as a\n * `type: string`). Hence the guards rather than a schema: absence is normal, not an error.\n *\n * @example\n * await parseEnvOptions('/repo/.github/workflows/deploy-all.yml') // => ['dev', 'prod']\n * await parseEnvOptions('/repo/.github/workflows/code-quality.yml') // => []\n */\nconst parseEnvOptions = async (workflowPath: string): Promise<string[]> => {\n let parsed: unknown\n\n try {\n parsed = yaml.parse(await fs.readFile(workflowPath, 'utf-8'))\n } catch {\n return []\n }\n\n // `on` is the YAML 1.1 boolean `true` under some parsers; `yaml@2` keeps it a string, but read\n // defensively \u2014 a wrong key here would silently empty every picker.\n const on = pick(parsed, 'on') ?? pick(parsed, 'true')\n const options = pick(pick(pick(pick(on, 'workflow_dispatch'), 'inputs'), 'environment'), 'options')\n\n if (!Array.isArray(options)) return []\n\n return options.filter((option): option is string => {\n return typeof option === 'string' && option.length > 0\n })\n}\n\n/** One safe hop into an unknown object graph. Returns `undefined` for anything that is not a record. */\nconst pick = (value: unknown, key: string): unknown => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n\n return (value as Record<string, unknown>)[key]\n}\n", "import { readTokenStore } from 'src/lib/env-tokens'\nimport { listWorkflowEnvs } from 'src/lib/workflow-envs'\n\n/** Where the knowledge that an environment EXISTS came from. Never says anything about credentials. */\nexport type ProjectEnvSource = 'gh-workflow' | 'token-only'\n\nexport interface ProjectEnv {\n env: string\n source: ProjectEnvSource\n}\n\n/**\n * Every environment this project has, as the union of the two authorities that actually own the\n * answer: `gh-workflow` (declared in a `workflow_dispatch` `environment.options` list) and\n * `token-only` (we hold a token for it, but no workflow mentions it \u2014 real and reachable, just not\n * deployable from here).\n *\n * @example\n * await listProjectEnvs()\n * // => [{ env: 'dev', source: 'gh-workflow' }, \u2026, { env: 'prod_observability', source: 'token-only' }]\n */\n// `gh-workflow` is what a repo says about itself, in git, reviewed, and enforced by GitHub on\n// dispatch. It is the ONLY source that works on a fresh clone with zero credentials, which is\n// exactly when a new developer needs to be told the env names they have to run\n// `infra-kit env-token-set <env>` for. hulyo's `prod_observability` is exactly a token-only env.\n//\n// The union is the point. Neither source alone is the truth: the token store is a per-DEVELOPER\n// cache (a teammate's holds one entry; a fresh clone's holds none), and the workflows cannot know\n// about an env that exists only to be read from. Reading them together is what replaced\n// `infra-kit.json \u2192 environments`, which was a hand-maintained third copy of both and had drifted\n// from both.\nexport const listProjectEnvs = async (): Promise<ProjectEnv[]> => {\n const workflowEnvs = await listWorkflowEnvs()\n const store = await readTokenStore()\n\n const declared: ProjectEnv[] = workflowEnvs.map((env) => {\n return { env, source: 'gh-workflow' }\n })\n\n const known = new Set(workflowEnvs)\n\n const tokenOnly: ProjectEnv[] = Object.keys(store?.envs ?? {})\n .filter((env) => {\n return !known.has(env)\n })\n .sort()\n .map((env) => {\n return { env, source: 'token-only' }\n })\n\n // Workflow envs first, in the order the workflows declare them (`dev` leads everywhere), then the\n // strays. A picker reads best when the common choice is at the top.\n return [...declared, ...tokenOnly]\n}\n\n/** The env names alone, for the callers that only need choices. Same order as {@link listProjectEnvs}. */\nexport const listProjectEnvNames = async (): Promise<string[]> => {\n const envs = await listProjectEnvs()\n\n return envs.map((entry) => {\n return entry.env\n })\n}\n", "import type { z } from 'zod'\n\nexport interface ToolsExecutionResult<TStructured = Record<string, unknown>> {\n [x: string]: unknown\n content: {\n type: 'text'\n text: string\n }[]\n structuredContent?: TStructured\n}\n\nexport interface RequiredConfirmedOptionArg {\n confirmedCommand: boolean\n}\n\n/**\n * The per-tool seam that lets the domain-blind `refuseMissingArguments` describe a tool's arguments\n * as a form \u2014 the `choices` an agent's refusal carries \u2014 without learning anything about the tool's\n * domain. It asks only \"is there a provider?\" and \"is this input formable?\"; every domain-specific\n * answer lives behind these three members.\n */\nexport interface ArgumentFormProvider {\n /** Human-facing prompt rendered above the form. */\n message: string\n /**\n * Whether a form is WORTH opening for THESE arguments. Pure, synchronous, never\n * throws; `false` sends the call straight to the gate with its arguments intact.\n * Defaults to `false` on anything it does not recognise.\n *\n * NOT load-bearing for TRUNCATION: the chokepoint's non-narrowing check\n * catches top-level key removal and any array length change \u2014 shortening OR\n * growth \u2014 which no provider can weaken. The check is load-bearing for NOTHING\n * ELSE: it does not look at nested keys or at values, so it does NOT cover a\n * form that drops `releases[0].type`. Do not read this as \"the chokepoint has\n * it covered\": for anything below the top level, `toArgs`'s merge is the only\n * control.\n */\n isFormable: (params: unknown) => boolean\n /**\n * Candidate values for THIS tool's arguments, as a zod object (a Standard\n * Schema \u2014 `inputRequired.elicit` accepts one). Returned rather than inlined so\n * the SAME schema validates the response on re-entry.\n *\n * Contract: never throws, never blocks past the caller's deadline, and returns\n * `null` when it cannot offer real values \u2014 which the handler reads as \"no\n * form\" and falls to the gate.\n *\n * Also: **validates SYNCHRONOUSLY \u2014 no `.refine(async \u2026)` anywhere in the\n * object.** `acceptedContent`'s schema-aware overload throws a `TypeError` on an\n * asynchronously-validating schema, and the declared return type\n * `z.ZodObject<z.ZodRawShape>` cannot express that constraint \u2014 so it is stated\n * here and backstopped by a wrap at the call site.\n */\n buildRequestedSchema: (params: unknown) => Promise<z.ZodObject<z.ZodRawShape> | null>\n /**\n * MERGES validated form content over the round-1 `params` \u2014 never constructs a\n * fresh argument object. The form overwrites field-by-field and only where the\n * human supplied a value; untouched fields keep their round-1 value.\n *\n * Contract: TOTAL over anything `buildRequestedSchema`'s own schema accepts,\n * and NEVER THROWS \u2014 it is the one member called on client-supplied input, and\n * a throw here escapes the chokepoint's catch as a tool error where a gate was\n * owed. It returns `null` if it cannot map, which the handler treats exactly as\n * a validation failure: gate, with the round-1 arguments.\n */\n toArgs: (content: Record<string, unknown>, params: unknown) => Record<string, unknown> | null\n}\n\nexport interface McpTool<TIn extends z.ZodRawShape = z.ZodRawShape, TOut extends z.ZodRawShape = z.ZodRawShape> {\n name: string\n description: string\n inputSchema: TIn\n outputSchema: TOut\n /**\n * The catalog's own \"this mutation is gated by `confirmOrExit`\" declaration \u2014 the only machine-readable\n * link between the catalog's `mutating` flag and `confirmOrExit`: a run without `--yes` previews its\n * plan and exits, and only a re-run carrying `--yes` executes. Set only on genuinely destructive\n * tools; the default-deny catalog test enforces coverage.\n */\n requiresHumanConfirm?: boolean\n /**\n * Optional per-tool {@link ArgumentFormProvider}. Present means \"this command can describe a form for\n * its arguments\", which `refuseMissingArguments` renders as the `choices` of an agent's refusal. It is\n * ORTHOGONAL to `requiresHumanConfirm`: a form answer is an ARGUMENT, not consent \u2014 the re-run still\n * meets `confirmOrExit`, and the form path can execute nothing a direct call with the same arguments\n * could not.\n */\n formProvider?: ArgumentFormProvider\n handler: (\n params: z.infer<z.ZodObject<TIn>> & RequiredConfirmedOptionArg,\n ) => Promise<ToolsExecutionResult<z.infer<z.ZodObject<TOut>>>>\n}\n\n/**\n * Build the `content` half of a handler result. Narrows the literal `type: 'text'`\n * so handlers can use inferred return types without TS widening `type` to\n * `string` \u2014 the shape is the retired server's, kept because every handler and\n * every handler test is written against it and `--json` reads only\n * `structuredContent`.\n *\n * @example\n * return {\n * content: textContent(JSON.stringify(structuredContent, null, 2)),\n * structuredContent,\n * }\n */\nexport const textContent = (text: string): ToolsExecutionResult['content'] => {\n return [{ type: 'text', text }]\n}\n\n/**\n * Factory that ties the handler's return type to the declared `outputSchema`\n * so `structuredContent` is checked against the schema at compile time. If a\n * handler accidentally drops or renames a field, TS errors at the declaration\n * site rather than in whatever parses the `--json` document.\n *\n * @example\n * export const envLoadMcpTool = defineMcpTool({\n * name: 'env-load',\n * description: '...',\n * inputSchema: { config: z.string() },\n * outputSchema: { filePath: z.string(), variableCount: z.number() },\n * handler: envLoad,\n * })\n */\nexport const defineMcpTool = <TIn extends z.ZodRawShape, TOut extends z.ZodRawShape>(\n tool: McpTool<TIn, TOut>,\n): McpTool<TIn, TOut> => {\n return tool\n}\n", "import { z } from 'zod'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { logger } from 'src/lib/logger'\nimport type { ArgumentFormProvider } from 'src/types'\n\n/**\n * @fileoverview\n * The form-backed twin of `resolveHeadless`: where a human would be shown the command's picker, an\n * agent (or a `--json` run) is refused with `argument_required` AND `choices` \u2014 the form's requested\n * schema rendered as JSON Schema, i.e. exactly the rows the `src/lib/*-form/` builders already\n * produce. No command invents a row shape of its own; the skill turns `choices` into a question and\n * re-runs with the pick.\n *\n * Runs at the TOP of the six form-backed handlers, before their pickers, because a picker only knows\n * its own field while the provider knows every field round 1 omitted (`deploy-selected` can be\n * missing `version`, `env` and `services` at once \u2014 one refusal lists all three).\n */\n\nexport interface RefuseMissingArgumentsInput {\n provider: ArgumentFormProvider\n /** The handler's arguments as received \u2014 what `isFormable` and `buildRequestedSchema` inspect. */\n params: unknown\n operation: string\n /**\n * The CLI flag to name \u2014 a string when one flag answers the whole form (`release-create`'s four\n * fields all fold into `--release <spec>`), or a function of the form's fields that `params` left\n * EMPTY, for the tools whose flags mirror their fields (`deploy-selected` names `env` when\n * `version` was given, although the form re-offers `version` too). The function sees `[]` when\n * the builder had nothing to offer.\n */\n argument: string | ((missing: string[]) => string)\n}\n\n/** The provider contract says never-throw; a programming error inside it must not become a crash here. */\nconst requestedSchema = async (input: RefuseMissingArgumentsInput): Promise<z.ZodObject<z.ZodRawShape> | null> => {\n try {\n return await input.provider.buildRequestedSchema(input.params)\n } catch (error) {\n logger.debug({ err: error, operation: input.operation }, 'argument form builder threw; refusing without choices')\n\n return null\n }\n}\n\n/**\n * Refuse, naming the first argument the form would have asked for and carrying the whole form as\n * `choices`, when an agent / `--json` run omitted a picker argument. A no-op for a human at a TTY\n * and when the provider says the arguments are already complete.\n *\n * @example\n * await refuseMissingArguments({ provider, params: args, operation: 'env-load', argument: 'config' })\n * // agent, `config` omitted \u2192 throws { status: 'argument_required', argument: 'config', choices: {...} }\n */\nexport const refuseMissingArguments = async (input: RefuseMissingArgumentsInput): Promise<void> => {\n if (!isHeadless() || !input.provider.isFormable(input.params)) return\n\n const schema = await requestedSchema(input)\n const params =\n typeof input.params === 'object' && input.params !== null ? (input.params as Record<string, unknown>) : {}\n // A form may re-offer a field round 1 already carried (the deploy form keeps `version` editable);\n // the flag named is the first one the caller actually left out.\n const missing = (schema === null ? [] : Object.keys(schema.shape)).filter((field) => {\n return params[field] === undefined || params[field] === ''\n })\n const argument = typeof input.argument === 'string' ? input.argument : input.argument(missing)\n const choices = schema === null ? undefined : z.toJSONSchema(schema)\n\n throw new StructuredRefusalError(\n {\n status: 'argument_required',\n argument,\n ...(choices === undefined ? {} : { choices }),\n agentMode: agentMode.source,\n },\n 2,\n {\n operation: input.operation,\n remediation:\n choices === undefined\n ? `pass --${argument} on the re-run \u2014 nothing could be listed to choose from`\n : `ask the human to pick from \"choices\", then pass --${argument} on the re-run`,\n stderrExcerpt: `--${argument} was not given and there is no human to ask`,\n },\n )\n}\n"],
|
|
5
|
+
"mappings": "4RAAA,OAAOA,OAAY,mBACnB,OAAS,oBAAAC,OAAwB,mCACjC,OAAS,UAAAC,OAAc,cACvB,OAAOC,OAAQ,UACf,OAAOC,MAAU,YACjB,OAAOC,MAAa,eACpB,OAAS,KAAAC,MAAS,MAClB,OAAS,KAAAC,MAAS,KCwBlB,IAAMC,GAA2B,mCAC3BC,GAA0B,kCAS1BC,GAAuB,qBACvBC,GAAqB,2CAcdC,EAA0BC,GACjCA,EAAO,SAASH,EAAoB,GAAKG,EAAO,SAASF,EAAkB,EAAU,OAErFE,EAAO,SAASL,EAAwB,EAAU,UAElDK,EAAO,SAASJ,EAAuB,EAAU,SAE9C,UAsBIK,EAA8BD,GACrCA,EAAO,SAASF,EAAkB,EAAU,aAE5CE,EAAO,SAASH,EAAoB,EAAU,UAE3C,KA4CF,IAAMK,GAAkCC,GACtC,CACL,+CAA+CA,CAAG,oEAClD,sCAAsCA,CAAG,yCACzC,wEACF,EAAE,KAAK;AAAA,CAAI,EA+BAC,EAAN,cAA+BC,CAAa,CAcxC,SAST,YAAYF,EAAaG,EAAmC,KAAMC,EAAkB,CAClF,MAAMA,GAAWL,GAA+BC,CAAG,EAAGA,CAAG,EACzD,KAAK,KAAO,mBACZ,KAAK,SAAWG,CAClB,CACF,EAwCO,IAAME,EAA8B,CAAC,CAC1C,KAAAC,EACA,QAAAC,EACA,OAAAC,EACA,UAAAC,CACF,IAA0C,CACxC,IAAMC,EACJJ,IAAS,UACL,CAAC,oBAAoBC,CAAO,uEAAkE,EAC9F,CAAC,mBA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aAAcpD,GACd,aAAc,CACZ,SAAUoD,EAAE,OAAO,EAAE,SAAS,0DAA0D,EACxF,cAAeA,EAAE,OAAO,EAAE,SAAS,4BAA4B,EAC/D,QAASA,EAAE,OAAO,EAAE,SAAS,sBAAsB,EACnD,OAAQA,EAAE,OAAO,EAAE,SAAS,qBAAqB,EACjD,UAAWA,EACR,OAAO,EACP,SAAS,EACT,SAAS,sFAAsF,CACpG,EACA,QAASlD,EACX,CAAC",
|
|
6
|
+
"names": ["select", "readRepoIdentity", "Buffer", "fs", "path", "process", "z", "$", "PROJECT_NOT_FOUND_MARKER", "CONFIG_NOT_FOUND_MARKER", "INVALID_TOKEN_MARKER", "TOKEN_SCOPE_MARKER", "classifyDopplerFailure", "stderr", "classifyDopplerAuthFailure", "buildDopplerAuthFailureMessage", "env", "DopplerAuthError", "EnvAuthError", "authKind", "message", "buildDopplerNotFoundMessage", "kind", "project", "config", "available", "lines", "label", "$", "DOPPLER_PROBE_TIMEOUT_MS", "SCOPE_KEY", "getDopplerProject", "envManagement", "getInfraKitConfig", "probeEnvToken", "childEnv", "project", "config", "prevQuiet", "$", "scopedTo", "error", "classifyProbeFailure", "stderr", "extractStderr", "classifyDopplerFailure", "classifyDopplerAuthFailure", "process", "INFRA_KIT_ENV_TOKEN_VAR", "resolveEnvToken", "env", "fromEnv", "process", "fromStore", "readTokenStore", "EnvAuthError", "buildMissingTokenMessage", "getTokenStorePath", "storePath", "tildify", "process", "z", "process", "z", "DEFAULT_PROTECTED_ENVS", "PROTECTED_ENV_DENIED", "isProtectedEnv", "env", "SHARED_ENVS", "isSharedEnv", "deployableEnvs", "options", "access", "assertDeployable", "operation", "StructuredRefusalError", "agentMode", "OperationError", "resolveProtectedEnvAccess", "setting", "getInfraKitConfig", "PROTECTED_ENV_DENIED", "isAgentMode", "warnProtectedEnvDispatch", "args", "env", "branch", "isProtectedEnv", "logger", "fs", "path", "yaml", "WORKFLOWS_DIR", "readWorkflowEnvOptions", "workflowFile", "projectRoot", "getProjectRoot", "parseEnvOptions", "path", "listWorkflowEnvs", "workflowsDir", "entries", "fs", "workflows", "entry", "perWorkflow", "file", "workflowPath", "parsed", "yaml", "on", "pick", "options", "option", "value", "key", "listProjectEnvs", "workflowEnvs", "listWorkflowEnvs", "store", "readTokenStore", "declared", "env", "known", "tokenOnly", "listProjectEnvNames", "entry", "textContent", "text", "defineMcpTool", "tool", "buildEnvTokenStatus", "envs", "storeTokens", "envToken", "env", "source", "ENV_TABLE_HEADERS", "formatEnvTable", "rows", "cells", "row", "widths", "header", "col", "cell", "renderRow", "values", "value", "separator", "width", "envList", "project", "getDopplerProject", "listProjectEnvs", "store", "readTokenStore", "process", "INFRA_KIT_ENV_TOKEN_VAR", "tokens", "logger", "buildResult", "line", "structuredContent", "textContent", "envListMcpTool", "defineMcpTool", "z", "isRecord", "value", "orEmpty", "work", "tokenlessEnvs", "envs", "store", "readTokenStore", "buildEnvTokenStatus", "process", "INFRA_KIT_ENV_TOKEN_VAR", "status", "createEnvLoadFormProvider", "INFRA_KIT_SESSION_VAR", "params", "listProjectEnvs", "logger", "names", "env", "tokenless", "z", "content", "config", "z", "requestedSchema", "input", "error", "logger", "refuseMissingArguments", "isHeadless", "schema", "params", "missing", "field", "argument", "choices", "z", "StructuredRefusalError", "agentMode", "DOPPLER_CONFIG_KEY", "CREDENTIAL_SECRET_KEYS", "INFRA_KIT_ENV_TOKEN_VAR", "credentialFilterWarned", "warnFilteredCredentialKeys", "keys", "logger", "buildEnvLoadFileLines", "pairs", "config", "project", "projectRoot", "loadedAt", "emitted", "key", "value", "shellSingleQuote", "INFRA_KIT_ENV_VAR", "INFRA_KIT_ENV_CONFIG_VAR", "INFRA_KIT_ENV_PROJECT_VAR", "INFRA_KIT_ENV_PROJECT_ROOT_VAR", "INFRA_KIT_ENV_LOADED_AT_VAR", "resolveProjectRootSafe", "getProjectRoot", "resolveEnvLoadRoots", "cwd", "process", "path", "repoRoot", "readRepoIdentity", "WORKTREES_DIR_SUFFIX", "writeEnvLoadFile", "getDopplerProject", "downloadDopplerSecrets", "fileContents", "cacheDir", "getSessionCacheDir", "envFilePath", "ENV_LOAD_FILE", "fs", "roots", "atomicWriteFileSync", "ENV_LOAD_ROOT_FILE", "envLoadForm", "createEnvLoadFormProvider", "envLoad", "args", "refuseMissingArguments", "selectedConfig", "isAgentMode", "StructuredRefusalError", "agentMode", "envs", "listProjectEnvNames", "commandEcho", "withEscape", "context", "select", "env", "result", "structuredContent", "INFRA_KIT_SESSION_VAR", "textContent", "DOPPLER_MAX_OUTPUT_BYTES", "DOPPLER_DOWNLOAD_TIMEOUT_MS", "INHERITED_DOPPLER_VARS", "buildDopplerChildEnv", "token", "baseEnv", "childEnv", "name", "downloadEnvSecrets", "resolveEnvToken", "prevQuiet", "$", "error", "translateDopplerDownloadError", "assertDopplerOutputSize", "parseDopplerSecretsJson", "assertTokenScope", "actual", "DopplerAuthError", "stderr", "extractStderr", "kind", "classifyDopplerFailure", "classifyDopplerAuthFailure", "buildDopplerNotFoundMessage", "stdout", "bytes", "Buffer", "ENV_VAR_NAME_PATTERN", "parsed", "envLoadMcpTool", "defineMcpTool", "z"]
|
|
7
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{l as F}from"./chunk-Y3RW74TE.js";import{P as f,l as G,r as $}from"./chunk-
|
|
1
|
+
import{l as F}from"./chunk-Y3RW74TE.js";import{P as f,l as G,r as $}from"./chunk-EZ4DIT5A.js";import{execFile as oe,execFileSync as ne}from"node:child_process";import b from"node:process";var ae=5e3,se=100,W=2e3,J="/bin/ps",ie=1e3,B=["-eo","pid=,ppid=,pgid=,lstart="],V=8<<20,j=e=>e.split(`
|
|
2
2
|
`).flatMap(r=>{let[t,o,n,...a]=r.trim().split(/\s+/);if(t==null||o==null||n==null)return[];let c=Number(t),s=Number(o),l=Number(n);return!Number.isInteger(c)||!Number.isInteger(s)||!Number.isInteger(l)?[]:[{pid:c,ppid:s,pgid:l,lstart:a.join(" ")}]}),H=e=>{let r=new Map;for(let t of e)t.pid===t.pgid&&r.set(t.pgid,t.lstart);return r},ce=(e,r,t)=>{let o=H(r);return q(e,r,t).flatMap(n=>{let a=o.get(n);return a==null||a===""?[]:[{pgid:n,leaderStart:a}]})},K=(e,r)=>{let t=H(r);return e.flatMap(({pgid:o,leaderStart:n})=>t.get(o)===n?[o]:[])},U=(e,r)=>K(e,r).flatMap(t=>{try{b.kill(-t,"SIGKILL")}catch{return[]}return[t]}),q=(e,r,t)=>{let o=new Map;for(let s of r){let l=o.get(s.ppid);l?l.push(s):o.set(s.ppid,[s])}let n=new Set([e]),a=new Set([e]),c=[e];for(let s=0;s<c.length;s+=1)for(let l of o.get(c[s]??-1)??[])a.has(l.pid)||(a.add(l.pid),n.add(l.pgid),c.push(l.pid));return[...n].filter(s=>s>1&&s!==t)},L=()=>{try{return j(ne(J,[...B],{encoding:"utf8",maxBuffer:V}))}catch{return[]}},le=async()=>new Promise(e=>{oe(J,[...B],{encoding:"utf8",maxBuffer:V},(r,t)=>{e(r?[]:j(t))})}),ue=(e,r,t)=>t.some(o=>o.pid===e&&o.ppid===r),A=(e,r)=>{let t=r.find(o=>o.pid===b.pid)?.pgid;return q(e,r,t)},z=e=>{try{return b.kill(-e,0),!0}catch{return!1}},C=(e,r)=>{for(let t of e)try{b.kill(-t,r)}catch{}},P=new Set,pe=(e,r,t)=>{let o=A(e,r),n=t.flatMap(a=>K(a,r));return[...new Set([...o,...n])]},X=()=>{let e=L(),r=[...P].map(t=>t());C(pe(b.pid,e,r),"SIGKILL")},de=async e=>new Promise(r=>{setTimeout(r,e)}),_=async(e,r)=>{let t=Date.now()+r,o=e;for(;o.length>0&&Date.now()<t&&(o=o.filter(z),o.length!==0);)await de(se);return o};function cr(e,r=ae,t,o=L){e.unref();let n=!1,a=!1,c=[],s=null,l=()=>c;P.add(l);let m=()=>{s&&clearInterval(s),s=null},w=async()=>{await _(c.map(i=>i.pgid),W),P.delete(l)},y=i=>{let u=e.pid;if(u==null||a||n||i.length===0)return;let T=i.find(v=>v.pid===b.pid)?.pgid,S=ce(u,i,T);S.length>0&&(c=S)},h=async()=>{e.pid==null||a||n||y(await le())};y(L()),s=setInterval(()=>{h()},ie),s.unref();let R=i=>{n||t?.(i)};return e.on("exit",(i,u)=>{a=!0,m(),n||(U(c,o()),w()),R(`exited unexpectedly (code=${i??"null"}, signal=${u??"null"})`)}),e.on("error",i=>{R(`failed to spawn: ${i.message}`)}),{kill:async()=>{n=!0,m();let i=e.pid;if(i==null){P.delete(l);return}if(e.exitCode!==null||e.signalCode!==null){U(c,o()),await w();return}let u=o();if(u.length>0&&!ue(i,b.pid,u))return;let T=A(i,u);C(T,"SIGTERM");let S=await _(T,r);if(S.length===0){P.delete(l);return}let v=A(i,o()),D=[...new Set([...S,...v])].filter(z);C(D,"SIGKILL"),await _(D,W),P.delete(l)}}}import{constants as me}from"node:os";import k from"node:process";var fe=["SIGINT","SIGTERM","SIGHUP"],ge=me.signals,Oe=2,N=e=>128+(ge[e]??Oe),be=2e4,we=e=>{k.exit(e)},ye=(e,r)=>{k.on(e,r)},he=(e,r)=>{k.off(e,r)},Pe=(e,r)=>{let t=setTimeout(e,r);return t.unref(),()=>{clearTimeout(t)}},I=e=>{try{k.stderr.write(e)}catch{}},xe=(e,r)=>{let t=r instanceof Error?`${r.message}
|
|
3
3
|
${r.stack??"(no stack)"}`:String(r);I(`
|
|
4
4
|
\u2717 Teardown failed while handling ${e}: ${t}
|
|
@@ -7,4 +7,4 @@ ${r.stack??"(no stack)"}`:String(r);I(`
|
|
|
7
7
|
`),w?.(),n(),h(),r(N(i));return}m=i,w=c(()=>{let u=`
|
|
8
8
|
\u26A0 Teardown deadline exceeded at stage=${s()} after ${a}ms \u2014 force-quitting.
|
|
9
9
|
`;I(u),l(u),n(),h(),r(N(i))},a),(async()=>{try{await e(i)}catch(u){xe(i,u)}finally{w?.(),h(),r(N(i))}})()};for(let i of fe){let u=()=>R(i);y.set(i,u),t(i,u)}return h};var Se=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),Y=e=>e instanceof Error&&Se.has(e.name),gr=e=>{if(Y(e))return!0;let r=e?.cause;return Y(r)};import{loadDev as Re}from"@slip-stream-kit/config/internal";import Te from"node:path";var ke=(e,r)=>{let t=new Set;for(let o of Object.values(e))for(let n of Object.keys(F(o,r).proxy))t.add(n);return[...t]},Ee=async(e,r)=>{let t={},o=[];return await Promise.all(r.map(async n=>{try{let c=(await Re(Te.join(e,"apps",n,"ui")))?.proxy?.routes;if(!c)return;t[n]=Object.fromEntries(Object.entries(c).map(([s,l])=>[s,l.packageName]))}catch(a){o.push({app:n,message:a instanceof Error?a.message:String(a)})}})),{routePkg:(n,a)=>t[n]?.[a],loadErrors:o}},hr=async(e,r,t,o)=>{let{routePkg:n,loadErrors:a}=await Ee(e,ke(r,t));return{ctx:{discovered:t,apiPkgByApp:Object.fromEntries(o.map(c=>[c.name,c.packageName])),routePkg:n},loadErrors:a}};import{$ as ve}from"zx";var d=class extends Error{code;data;constructor(r){super(r.message),this.name="OrcaError",this.code=r.code,this.data=r.data}},x=class extends Error{exitCode;stderrTail;constructor(r,t){super(`orca: stdout is not a JSON envelope (exit ${r??"signal"})`),this.name="OrcaMalformedError",this.exitCode=r,this.stderrTail=t}},g=class extends Error{constructor(){super("orca: command not found \u2014 the CLI is registered from Orca \u2192 Settings \u2192 Experimental \u2192 CLI"),this.name="OrcaAbsentError"}},_e=400,Le=127,Ae=e=>typeof e=="object"&&e!==null&&e.code==="ENOENT",Ce=async e=>{try{return await ve({nothrow:!0,quiet:!0})`orca ${e} --json`}catch(r){throw Ae(r)?new g:r}},Ne=e=>{try{let r=JSON.parse(e);return typeof r=="object"&&r!==null&&typeof r.ok=="boolean"?r:null}catch{return null}},p=async e=>{let r=await Ce(e),t=Ne(r.stdout);if(f.debug({argv:e,ok:t?.ok,code:t?.error?.code,exitCode:r.exitCode},"orca"),!t)throw r.exitCode===Le?new g:new x(r.exitCode,r.stderr.slice(-_e));if(!t.ok)throw new d(t.error??{code:"unknown",message:"orca: ok:false without an error payload"});return t.result};var Ie=async()=>{try{let e=await p(["status"]);return f.debug({appVersion:e.runtime?.appVersion},"orca: status"),e.app?.running===!0&&e.runtime?.reachable===!0?"ready":"unreachable"}catch(e){return e instanceof g?"absent":(f.debug({error:e},"orca: status probe failed"),"unreachable")}};import{realpath as Me}from"node:fs/promises";var O=async e=>{try{return await Me(e)}catch{return e}};var De=async e=>{let[{repos:r=[]},t]=await Promise.all([p(["repo","list"]),O(e)]);for(let o of r)if(await O(o.path)===t)return{registered:!0,visibility:o.externalWorktreeVisibility};return{registered:!1}},Ge=async e=>{let{repo:r}=await p(["repo","add","--path",e]);return{visibility:r?.externalWorktreeVisibility}};var $e="500",Fe=async(e,r)=>{let[{worktrees:t=[]},o]=await Promise.all([p(["worktree","list","--repo",`path:${e}`,"--limit",$e]),O(r)]);for(let n of t)if(await O(n.path)===o)return!0;return!1};import We from"node:process";var Q="::",Ue=e=>{let r=e.ORCA_WORKTREE_ID;if(!r)return null;let t=r.indexOf(Q);if(t<0)return null;let o=r.slice(t+Q.length);return o.length>0?o:null},Je=async(e,r=We.env)=>{let t=Ue(r);if(t===null)return null;let o=await O(t);for(let n of e)if(await O(n)===o)return n;return null};var Z="200",M=async e=>{try{let r=await p(["terminal","list","--worktree",`path:${e}`,"--limit",Z]),t=r.truncated===!0;return t&&f.debug({cwd:e,limit:Z},"orca: terminal list truncated"),{terminals:r.terminals??[],truncated:t}}catch(r){if(r instanceof d&&r.code==="selector_not_found")return{terminals:[],truncated:!1};throw r}};var Be=async e=>{try{return await p(["terminal","close","--worktree",`path:${e}`,"--all"]),"retired"}catch(r){if(r instanceof d&&r.code==="selector_not_found")return"not_found";if(r instanceof d&&r.code==="terminal_close_incomplete")return f.debug({cwd:e,error:r},"orca: surfaces not retired"),"retired";throw r}},Ve=async e=>{let{terminals:r}=await M(e);for(let o of r)await p(["terminal","close","--terminal",o.handle]);let t=await Be(e);return r.length===0&&t==="not_found"?{closed:!1,skipped:"not_found"}:{closed:!0,count:r.length}},je=(e,r)=>r instanceof g?{closed:!1,skipped:"absent"}:r instanceof d?{closed:!1,error:r}:r instanceof x?{closed:!1,error:new d({code:"orca_malformed_output",message:r.message,data:{exitCode:r.exitCode,stderrTail:r.stderrTail}})}:(f.debug({cwd:e,error:r},"orca: close failed outside the Orca contract"),{closed:!1,error:new d({code:"orca_close_failed",message:r instanceof Error?r.message:String(r)})}),He=async(e,r)=>{if(r!=="ready")return{closed:!1,skipped:r};try{return await Ve(e)}catch(t){return je(e,t)}};import{setTimeout as Ke}from"node:timers/promises";var qe=3,ze=300,re=(e={})=>({attempts:e.attempts??qe,delayMs:e.delayMs??ze,exhausted:!1}),Xe=async e=>{try{return{created:await p(e)}}catch(r){if(r instanceof d&&r.code==="selector_not_found")return{notSelectable:r};throw r}},Ye=async(e,r,t)=>{let o=t.exhausted?1:t.attempts,n=Array.from({length:o},(c,s)=>s+1),a;for(let c of n){let s=await Xe(e);if("created"in s)return s.created.terminal.handle;a=s.notSelectable,c<o&&await Ke(t.delayMs)}throw t.exhausted=!0,new d({code:"orca_worktree_not_selectable",message:`orca: worktree ${r} is not selectable after ${o} attempt(s): ${a?.message??""}`,data:{cwd:r,attempts:o,cause:a?.data}})},ee=async(e,r)=>(await p(["terminal","split","--terminal",e,"--direction",r])).split.handle,Qe=async e=>{let{cwd:r,title:t,focus:o,layout:n,panes:a,poll:c=re()}=e,s=["terminal","create","--worktree",`path:${r}`,"--title",t,...o?["--focus"]:[]],l=await Ye(s,r,c),m=[l];return n==="full"&&(m.push(await ee(l,"horizontal")),a==="three-pane"&&m.push(await ee(l,"vertical"))),{handles:m,layout:n}};var Ze=e=>{let{branch:r}=e,t=G(r);return t?$(t):r};var it=e=>typeof e=="object",E=async e=>(await e.body?.cancel(),{kind:"foreign",status:e.status,contentType:e.headers.get("content-type")}),ct=(e,r)=>{let t=r.contentType?.split(";")[0]?.trim(),o=t==null||t===""?`${r.status}`:`${r.status} ${t}`;return`port ${e} answered ${o}, not vite's ping \u2014 liveness cannot be verified`};var te={accept:"text/x-vite-ping"},er=e=>e.kind==="api"?`http://127.0.0.1:${e.port}/__health`:`http://127.0.0.1:${e.port}/`,rr=(e,r)=>{try{return new URL(e,r)}catch{return null}},tr=async(e,r)=>{let t=await fetch(e,{signal:r});return t.ok?(await t.body?.cancel(),"ok"):E(t)},or=async(e,r)=>{let t=await fetch(e,{headers:te,redirect:"manual",signal:r});if(t.status===204)return"ok";if(t.status<300||t.status>=400)return E(t);let o=t.headers.get("location"),n=o==null?null:rr(o,e);if(n==null||n.origin!==new URL(e).origin)return E(t);await t.body?.cancel();let a=await fetch(n,{headers:te,redirect:"manual",signal:r});return a.status!==204?E(a):(await a.body?.cancel(),"ok")},lt=async e=>{let r=er(e),t=AbortSignal.timeout(1500);try{return e.kind==="api"?await tr(r,t):await or(r,t)}catch{return"refused"}};import{readRelease as nr}from"@slip-stream-kit/config/internal";var ar=e=>nr(e);export{hr as a,X as b,cr as c,N as d,mr as e,d as f,p as g,Ie as h,Je as i,M as j,He as k,De as l,Ge as m,Fe as n,re as o,Qe as p,Ze as q,it as r,ct as s,lt as t,ar as u,gr as v};
|
|
10
|
-
//# sourceMappingURL=chunk-
|
|
10
|
+
//# sourceMappingURL=chunk-ZTAUGYJF.js.map
|