infra-kit 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/{boot-BL4EQMZV.js → boot-XLDVLQEG.js} +2 -2
  2. package/dist/boot-XLDVLQEG.js.map +7 -0
  3. package/dist/chunk-7AMRJ4IW.js +9 -0
  4. package/dist/chunk-7AMRJ4IW.js.map +7 -0
  5. package/dist/{chunk-HHWP3YXW.js → chunk-AWFGP6GY.js} +1 -1
  6. package/dist/{chunk-HHWP3YXW.js.map → chunk-AWFGP6GY.js.map} +1 -1
  7. package/dist/chunk-JUNJK2YC.js +3 -0
  8. package/dist/chunk-JUNJK2YC.js.map +7 -0
  9. package/dist/chunk-MOVRKV3I.js +4 -0
  10. package/dist/{chunk-75URROMU.js.map → chunk-MOVRKV3I.js.map} +3 -3
  11. package/dist/{chunk-X2HFNQRU.js → chunk-OPL7C5H6.js} +2 -2
  12. package/dist/chunk-WUTG6VMP.js +7 -0
  13. package/dist/chunk-WUTG6VMP.js.map +7 -0
  14. package/dist/{chunk-GRWUCPQL.js → chunk-YYC3QGGC.js} +2 -2
  15. package/dist/cli.js +457 -13
  16. package/dist/cli.js.map +4 -4
  17. package/dist/dev-server.js +2 -2
  18. package/dist/dev-server.js.map +2 -2
  19. package/dist/dev-wizard-run-ITRFKMTL.js +2 -0
  20. package/dist/dev-wizard-run-ITRFKMTL.js.map +7 -0
  21. package/dist/mcp-proxy.js +1 -1
  22. package/dist/update-check.js +1 -1
  23. package/dist/update-check.js.map +1 -1
  24. package/package.json +3 -7
  25. package/dist/boot-BL4EQMZV.js.map +0 -7
  26. package/dist/chunk-75BE6MSY.js +0 -7
  27. package/dist/chunk-75BE6MSY.js.map +0 -7
  28. package/dist/chunk-75URROMU.js +0 -4
  29. package/dist/chunk-FWINBDB5.js +0 -444
  30. package/dist/chunk-FWINBDB5.js.map +0 -7
  31. package/dist/chunk-H5AAXCRJ.js +0 -9
  32. package/dist/chunk-H5AAXCRJ.js.map +0 -7
  33. package/dist/chunk-IXWQ7EQT.js +0 -3
  34. package/dist/chunk-IXWQ7EQT.js.map +0 -7
  35. package/dist/dev-wizard-run-643QKSR3.js +0 -2
  36. package/dist/dev-wizard-run-643QKSR3.js.map +0 -7
  37. package/dist/mcp.js +0 -3
  38. package/dist/mcp.js.map +0 -7
  39. /package/dist/{chunk-X2HFNQRU.js.map → chunk-OPL7C5H6.js.map} +0 -0
  40. /package/dist/{chunk-GRWUCPQL.js.map → chunk-YYC3QGGC.js.map} +0 -0
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../package.json", "../src/lib/update-check/run-update-check.ts", "../src/lib/update-check/lock.ts", "../src/lib/update-check/registry.ts", "../src/lib/update-check/semver.ts", "../src/lib/update-check/update-cache.ts", "../src/lib/update-check/update-plugin.ts", "../src/lib/plugin-pointer/claude-cli.ts", "../src/lib/plugin-pointer/names.ts", "../src/lib/plugin-pointer/install-state.ts"],
4
- "sourcesContent": ["{\n \"name\": \"infra-kit\",\n \"type\": \"module\",\n \"version\": \"0.9.0\",\n \"files\": [\n \"dist\"\n ],\n \"description\": \"infra-kit\",\n \"bin\": {\n \"infra-kit\": \"dist/cli.js\",\n \"ik\": \"dist/cli.js\",\n \"ik-mcp\": \"dist/mcp-proxy.js\"\n },\n \"engines\": {\n \"node\": \">=24.x\"\n },\n \"scripts\": {\n \"inspector\": \"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug\",\n \"build\": \"pnpm run clean-artifacts && node ./scripts/build.js\",\n \"prepack\": \"pnpm run build\",\n \"infra-kit-check\": \"pnpm exec infra-kit audit\",\n \"clean-artifacts\": \"rm -rf dist\",\n \"clean-cache\": \"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc\",\n \"prettier-fix\": \"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"prettier-check\": \"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"eslint-check\": \"pnpm exec eslint --cache --report-unused-disable-directives ./src\",\n \"eslint-fix\": \"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix\",\n \"ts-check\": \"tsc --noEmit\",\n \"test\": \"pnpm exec vitest run --reporter=minimal\",\n \"test-watch\": \"pnpm exec vitest --watch --silent passed-only\",\n \"test-ui\": \"pnpm exec vitest --ui --silent passed-only\",\n \"test-report\": \"pnpm exec vitest run --coverage --silent passed-only\",\n \"qa:pty\": \"INFRA_KIT_REQUIRE_PTY=1 pnpm exec vitest run --reporter=minimal src/tui/__tests__/stdin-pause-pty.test.ts src/entry/__tests__/quit-keys-pty.test.ts src/entry/__tests__/post-run-pause-pty.test.ts\",\n \"qa\": \"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success\",\n \"fix\": \"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa\"\n },\n \"dependencies\": {\n \"@aws-lambda-powertools/logger\": \"^2.35.0\",\n \"@inquirer/checkbox\": \"^5.2.5\",\n \"@inquirer/confirm\": \"^6.3.2\",\n \"@inquirer/input\": \"^5.1.6\",\n \"@inquirer/password\": \"^5.2.2\",\n \"@inquirer/select\": \"^5.2.5\",\n \"@modelcontextprotocol/server\": \"^2.0.0\",\n \"@slip-stream-kit/config\": \"^0.9.0\",\n \"chalk\": \"^6.0.0\",\n \"chokidar\": \"^5.0.0\",\n \"commander\": \"^15.0.0\",\n \"fastify\": \"^5.12.4\",\n \"ink\": \"^7.1.1\",\n \"pino\": \"^10.3.1\",\n \"pino-pretty\": \"^13.1.3\",\n \"portless\": \"^0.15.6\",\n \"react\": \"19.3.0\",\n \"yaml\": \"^2.9.1\",\n \"zod\": \"^4.6.2\",\n \"zx\": \"^8.8.5\"\n },\n \"devDependencies\": {\n \"@modelcontextprotocol/client\": \"^2.0.0\",\n \"@modelcontextprotocol/sdk\": \"^1.30.0\",\n \"@slip-stream-kit/eslint-plugin\": \"workspace:*\",\n \"@types/aws-lambda\": \"catalog:\",\n \"@types/react\": \"catalog:\",\n \"@wl/eslint-config\": \"workspace:*\",\n \"@wl/vitest-config\": \"workspace:*\",\n \"esbuild\": \"^0.28.2\",\n \"ink-testing-library\": \"^4.0.0\",\n \"typescript\": \"^6.0.3\"\n }\n}\n", "/**\n * The CHILD half of the auto-update, spawned detached by `maybeAutoUpdate`. It outlives the CLI\n * invocation that started it, so it may take its time and it may replace the binary.\n *\n * WHY IT WAITS FOR THE PARENT TO EXIT \u2014 the load-bearing invariant of this whole feature:\n * `scripts/build.js` sets esbuild `splitting: true`, so `dist/cli.js` lazily imports sibling\n * `chunk-*.js` files at runtime (that is how the Ink TUI stays off the fast path). A package manager\n * installing over `dist/` mid-command deletes chunks the parent has not imported yet, and the parent\n * dies on a dynamic import of a file that no longer exists. Waiting for the parent to exit is what\n * makes a silent background install safe rather than a random crash under `infra-kit dev`.\n */\nimport { spawnSync } from 'node:child_process'\nimport { homedir } from 'node:os'\nimport process from 'node:process'\n\nimport { PACKAGE_NAME, defaultLazyNpmRoot, detectInstallManager, safeRealpath } from 'src/lib/install-manager'\nimport { packageManagerInstallEnv } from 'src/lib/pm-env'\n\nimport { acquireUpdateLock } from './lock'\nimport { fetchLatestVersion } from './registry'\nimport { isNewerVersion } from './semver'\nimport { writeUpdateCache } from './update-cache'\nimport type { UpdateCache } from './update-cache'\n// Static, like every import in this file \u2014 see the module doc: on the `installed` path the plugin step\n// runs after `dist/` has been replaced, and a lazy `import()` of a chunk from a replaced dist is unsafe.\nimport { updatePlugin } from './update-plugin'\nimport type { UpdatePluginDeps } from './update-plugin'\n\n/** How often to re-check whether the parent is gone. */\nexport const PARENT_POLL_INTERVAL_MS = 200\n\n/**\n * Give up waiting after this long. A long-lived parent (`infra-kit dev` runs for hours) must not leave\n * an immortal child pinned to a stale version: we simply skip this cycle. `lastCheckMs` is already\n * persisted by then, so the next short-lived command re-checks after the normal throttle window.\n */\nexport const PARENT_WAIT_TIMEOUT_MS = 5 * 60 * 1000\n\nexport interface RunUpdateCheckDeps extends UpdatePluginDeps {\n env?: NodeJS.ProcessEnv\n nowMs?: number\n fetchLatest?: (env: NodeJS.ProcessEnv) => Promise<string | null>\n writeCache?: typeof writeUpdateCache\n isProcessAlive?: (pid: number) => boolean\n sleep?: (ms: number) => Promise<void>\n /** Monotonic-ish source for the parent-wait deadline. Injected so the timeout is testable without real time. */\n clock?: () => number\n /** `npm root -g` probe. Defaults to the real subprocess; this child is detached, so it can afford one. */\n lazyNpmRoot?: () => string | undefined\n /** Single-flight guard. Returns a release fn, or null when another worker already holds the lock. */\n acquireLock?: () => (() => void) | null\n spawnSync?: typeof spawnSync\n /**\n * The version the user now gets from the `infra-kit` on their PATH. Consulted once, after the install\n * command returns 0, because that exit code is not proof of anything \u2014 see {@link readInstalledVersion}.\n */\n installedVersion?: (env: NodeJS.ProcessEnv) => string | null\n /** Realpath of the installed `dist/cli.js`, used to identify the owning package manager. */\n selfRealPath: string\n parentPid?: number\n}\n\n/** Bounds the post-install probe; a hung shim must not pin this worker for the parent's 5-minute budget. */\nconst VERSION_PROBE_TIMEOUT_MS = 15_000\n\n/**\n * Ask the freshly installed CLI what it is, the way the user will: the `infra-kit` bin on PATH.\n *\n * Not `<selfRealPath>/../package.json`. pnpm keeps each version in its own directory\n * (`.pnpm/infra-kit@0.5.1/\u2026`, `global/v11/<hash>/\u2026`) and repoints the shim, so the path THIS worker was\n * launched from keeps reporting the old version forever, while the path the user gets has moved.\n *\n * `--json` doubles as the guard that stops the probe spawning a second updater from inside the first:\n * `autoUpdateSkipReason` returns `json` before anything else runs, and piped stdio fails the tty arm too.\n * Anything short of a parseable version is `null` \u2014 a shim that no longer resolves, a bin that crashes on\n * boot, output that is not JSON \u2014 and the caller treats every one of those as \"not verified\".\n */\nconst readInstalledVersion = (env: NodeJS.ProcessEnv): string | null => {\n const result = spawnSync(PACKAGE_NAME, ['version', '--json'], {\n stdio: ['ignore', 'pipe', 'ignore'],\n shell: process.platform === 'win32',\n cwd: homedir(),\n env,\n timeout: VERSION_PROBE_TIMEOUT_MS,\n windowsHide: true,\n encoding: 'utf8',\n })\n\n if (result.error || result.signal || result.status !== 0) return null\n\n try {\n const parsed: unknown = JSON.parse(result.stdout)\n const version = (parsed as { version?: unknown } | null)?.version\n\n return typeof version === 'string' && version !== '' ? version : null\n } catch {\n return null\n }\n}\n\n/** Signal 0 performs the permission/existence check without delivering anything. */\nconst defaultIsProcessAlive = (pid: number): boolean => {\n try {\n process.kill(pid, 0)\n\n return true\n } catch {\n return false\n }\n}\n\nconst defaultSleep = (ms: number): Promise<void> => {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n\n/**\n * Block until `parentPid` exits or {@link PARENT_WAIT_TIMEOUT_MS} elapses. Returns whether the parent\n * is actually gone \u2014 the caller must not install on a timeout.\n */\nconst waitForParentExit = async (\n parentPid: number,\n deps: Required<Pick<RunUpdateCheckDeps, 'isProcessAlive' | 'sleep' | 'clock'>>,\n): Promise<boolean> => {\n const deadline = deps.clock() + PARENT_WAIT_TIMEOUT_MS\n\n while (deps.clock() < deadline) {\n if (!deps.isProcessAlive(parentPid)) return true\n\n await deps.sleep(PARENT_POLL_INTERVAL_MS)\n }\n\n return !deps.isProcessAlive(parentPid)\n}\n\nexport type UpdateCheckOutcome =\n | 'installed'\n | 'install-failed'\n /** The install command returned 0, yet the `infra-kit` on PATH still does not report `latestVersion`. */\n | 'install-stale'\n | 'up-to-date'\n | 'fetch-failed'\n | 'cannot-self-spawn'\n | 'parent-still-running'\n | 'parent-unknown'\n | 'already-running'\n\n/**\n * Fetch, decide, and (when safe) install \u2014 returning WHY it did what it did so tests can distinguish\n * \"no update\" from \"could not install\". Never throws.\n *\n * `lastCheckMs` is written from the ATTEMPT, before any early return. If it were written only on\n * success, an offline user would re-spawn a doomed child on every single command.\n *\n * @example\n * await runUpdateCheck('0.1.130', { selfRealPath: '/usr/local/lib/node_modules/infra-kit/dist/cli.js' })\n * // => 'installed'\n */\nexport const runUpdateCheck = async (currentVersion: string, deps: RunUpdateCheckDeps): Promise<UpdateCheckOutcome> => {\n const acquireLock = deps.acquireLock ?? acquireUpdateLock\n const writeCache = deps.writeCache ?? writeUpdateCache\n\n // Single-flight. N shells launched at once all read the same stale cache and each spawns a worker;\n // the cache throttle cannot stop them because it is only written after the fetch returns. Without\n // this, a pending update means N concurrent `npm install -g` over one global directory.\n const release = acquireLock()\n\n if (!release) return 'already-running'\n\n // Remember the locked function's final cache write so the plugin step can stamp its own outcome\n // onto it instead of reading the file back (a holder, not a `let`: TypeScript cannot see a closure\n // assignment and would narrow a `let` to its initial `null`).\n const written: { last: UpdateCache | null } = { last: null }\n const recordingWriteCache: typeof writeUpdateCache = (cache) => {\n written.last = cache\n writeCache(cache)\n }\n\n try {\n const outcome = await runUpdateCheckLocked(currentVersion, { ...deps, writeCache: recordingWriteCache })\n\n // The plugin step runs AFTER the locked function has returned, on EVERY outcome \u2014 `up-to-date`\n // included, which is what makes a plugin-only bump deliverable \u2014 and never inside its early-return\n // chain or ahead of the fetch. Placement is about the throttle: `lastCheckMs` is stamped only by\n // `finish()` after the fetch, and the lock is reaped as stale at `LOCK_STALE_MS` (30 min). A\n // `claude` probe (up to 120 s) plus an update ahead of the fetch would delay that stamp on every\n // run and eat into the stale window on a slow link. Here the stamp is written, the lock is still\n // held (single-flight), and the step has a bounded budget of its own. \"Every outcome\" has one\n // exception, decided by the cache the locked function wrote rather than by name: see\n // `pluginStepWithheld`.\n recordPluginUpdate(deps, written.last, currentVersion, writeCache)\n\n return outcome\n } finally {\n release()\n }\n}\n\n/**\n * Must the plugin step stand down because the CLI is behind? Reads the `latestVersion` the locked\n * function wrote, not its outcome name: \"a newer CLI exists and this run did not install it\" is\n * exactly what a non-null value newer than `currentVersion` encodes.\n *\n * That covers `cannot-self-spawn` (`:300`), `parent-unknown` (`:305`), `parent-still-running` (`:326`),\n * `install-failed` (`:353`) and `install-stale` (`:364`) \u2014 each leaves the newer version in the cache \u2014\n * and any outcome added later that does the same, without this list needing to know. `installed` clears\n * `latestVersion` (`:367`) and `up-to-date` writes a non-newer one (`:282`), so both still advance the\n * plugin and a plugin-only bump keeps delivering; `fetch-failed` writes null (`:280`) and cannot be\n * gated \u2014 the plugin advances, as before; `already-running` never reaches the wrapper.\n *\n * @example\n * pluginStepWithheld('0.8.0', '0.7.2') // => true\n * pluginStepWithheld(null, '0.7.2') // => false\n */\n// Without this a Homebrew or unknown-location machine advances the plugin on every run while its CLI\n// waits for a hand-typed update, and once a repo serves infra-kit through the plugin, plugin N+1 spawns\n// CLI N \u2014 skills citing tool names that server does not serve, a `doctor` that fails on a key that is\n// meant to be absent, and a `setup` that re-adds it to a tracked `.mcp.json`.\nexport const pluginStepWithheld = (latestVersion: string | null, currentVersion: string): boolean => {\n return latestVersion !== null && isNewerVersion(latestVersion, currentVersion)\n}\n\n/**\n * Run the plugin step and write its outcome beside the CLI outcome. Never throws: `updatePlugin` is\n * total, and a cache write that fails here has nowhere left to record itself \u2014 the CLI outcome the\n * worker already produced is worth more than a plugin diagnostic.\n */\nconst recordPluginUpdate = (\n deps: UpdatePluginDeps,\n base: UpdateCache | null,\n currentVersion: string,\n writeCache: typeof writeUpdateCache,\n): void => {\n const outcome = pluginStepWithheld(base?.latestVersion ?? null, currentVersion)\n ? 'skipped-cli-stale'\n : updatePlugin(deps)\n const checkedMs = (deps.clock ?? Date.now)()\n\n // `finish()` writes on every path the locked function returns through, so `base` is only null if that\n // invariant breaks \u2014 and then there is no throttle stamp to attach the outcome to either.\n if (base === null) return\n\n try {\n writeCache({ ...base, plugin: { outcome, checkedMs } })\n } catch {\n // Recorded nowhere, deliberately: see the function doc.\n }\n}\n\nconst runUpdateCheckLocked = async (currentVersion: string, deps: RunUpdateCheckDeps): Promise<UpdateCheckOutcome> => {\n const env = deps.env ?? process.env\n const nowMs = deps.nowMs ?? Date.now()\n const fetchLatest = deps.fetchLatest ?? fetchLatestVersion\n const writeCache = deps.writeCache ?? writeUpdateCache\n const isProcessAlive = deps.isProcessAlive ?? defaultIsProcessAlive\n const sleep = deps.sleep ?? defaultSleep\n const clock = deps.clock ?? Date.now\n const lazyNpmRoot = deps.lazyNpmRoot ?? defaultLazyNpmRoot\n const spawn = deps.spawnSync ?? spawnSync\n const installedVersion = deps.installedVersion ?? readInstalledVersion\n\n const latestVersion = await fetchLatest(env)\n\n // Every path below writes the cache EXACTLY once, and always with `lastCheckMs: nowMs` \u2014 the throttle\n // burns on the ATTEMPT, never on success. If it burned only on success, an offline user would respawn\n // a doomed child on every command.\n const finish = (\n outcome: UpdateCheckOutcome,\n cache: Omit<UpdateCache, 'lastCheckMs' | 'outcome'>,\n ): UpdateCheckOutcome => {\n // `outcome` is recorded on EVERY write: it is what lets a reader (human or `isStale`) tell a settled\n // `installed`/`up-to-date` from a transient `fetch-failed`, all of which otherwise write an identical\n // `{latestVersion:null}`. See `UpdateCache.outcome`.\n writeCache({ lastCheckMs: nowMs, ...cache, outcome })\n\n return outcome\n }\n\n if (latestVersion === null) return finish('fetch-failed', { latestVersion: null, updateCommand: null })\n if (!isNewerVersion(latestVersion, currentVersion))\n return finish('up-to-date', { latestVersion, updateCommand: null })\n\n // `lazyNpmRoot` is what makes the COMMON case work: a plain `npm i -g infra-kit` leaves no\n // `npm_config_prefix` in the user's shell, so every cheap matcher misses and detection would report\n // `unknown` / `canSelfSpawn: false`. Without this probe the auto-update would silently degrade to a\n // notice for the majority of installs. The subprocess is affordable here and nowhere else.\n // `version` pins the spec to what we just fetched: a `@latest` command is resolved by the package\n // manager from ITS cache, which pnpm does not revalidate \u2014 see `pinSpec` in install-manager.\n const { canSelfSpawn, updateCommand } = detectInstallManager({\n selfRealPath: deps.selfRealPath,\n env,\n realpath: safeRealpath,\n lazyNpmRoot,\n version: latestVersion,\n })\n\n // Homebrew relinks its prefix and may prompt; an unknown location means the command is a guess.\n // Both stay the user's call, so record the command for `maybeAutoUpdate` to print next invocation.\n if (!canSelfSpawn) return finish('cannot-self-spawn', { latestVersion, updateCommand })\n\n // Fail SAFE. Without a parent to outlive we cannot know whether a live CLI is still lazily importing\n // `chunk-*.js` out of the `dist/` we are about to replace, so we skip the cycle rather than install\n // blind. The real spawn always passes `--parent-pid`; only a hand-run worker lands here.\n if (deps.parentPid == null) return finish('parent-unknown', { latestVersion, updateCommand: null })\n\n // Burn the throttle NOW, before the two unbounded-ish operations below (a 5-minute parent wait, then an\n // install of no fixed duration). Everything after this point can take many minutes, and until the cache\n // is written it still reads as STALE \u2014 so every new shell in that window spawns its own worker, and the\n // single-flight lock becomes the only thing standing between them and concurrent `npm install -g` runs\n // over one global directory. The lock is reaped by mtime (LOCK_STALE_MS), so a slow enough install has\n // its live lock stolen and we get exactly the pile-up the lock exists to prevent.\n //\n // Writing the stamp here makes the throttle \u2014 not the lock \u2014 the primary guard, which is what the cache\n // was always for. `finish()` overwrites this with the real outcome; this is the only path that writes\n // the cache twice, and deliberately so.\n //\n // `outcome: 'installing'` marks a mid-install checkpoint: if the worker is killed here (machine sleeps,\n // SIGKILL) and never reaches `finish()`, this stamp is what the next run reads, and the cache says so\n // rather than looking like a settled result. It does not shorten the next window \u2014 see CHECK_INTERVAL_MS.\n writeCache({ lastCheckMs: nowMs, latestVersion, updateCommand: null, outcome: 'installing' })\n\n const parentGone = await waitForParentExit(deps.parentPid, { isProcessAlive, sleep, clock })\n\n // A long-lived parent (`infra-kit dev`) outlasted the wait. Stay silent and retry next window.\n if (!parentGone) return finish('parent-still-running', { latestVersion, updateCommand: null })\n\n // `shell` on win32 so the `.cmd` shims npm/pnpm/yarn ship as global bins resolve.\n //\n // `packageManagerInstallEnv` strips the inherited npx/dlx markers \u2014 which otherwise make\n // pnpm/portless-style tools believe they were invoked via `npx`/`dlx` and refuse to run \u2014 while KEEPING\n // `npm_config_prefix` and `npm_config_registry`. Using the blunt `withoutPackageManagerEnv` here was a\n // bug: it also erased the prefix that `detectInstallManager` had just matched on, so we would detect a\n // global install at prefix P and then install into the default prefix instead \u2014 silently, forever. See\n // the module doc on `packageManagerInstallEnv`.\n //\n // `cwd` is pinned to the home directory, and this is a SECURITY control, not tidiness: npm resolves\n // `registry=` from an `.npmrc` on disk relative to the cwd. Inheriting the caller's cwd would let any\n // repo containing a hostile `.npmrc` silently redirect this unattended `install -g` to an attacker's\n // registry, executing its lifecycle scripts. Stripping `npm_config_registry` from the env does NOT\n // close that hole, because the redirect lives in a file, not the environment.\n const result = spawn(updateCommand[0] as string, updateCommand.slice(1), {\n stdio: 'ignore',\n shell: process.platform === 'win32',\n cwd: homedir(),\n env: packageManagerInstallEnv(env),\n windowsHide: true,\n })\n\n // Record the manual command so a persistently failing silent install (EACCES on a root-owned global\n // dir, say) still surfaces ONE actionable line, instead of failing invisibly forever.\n if (result.error || result.signal || result.status !== 0) {\n return finish('install-failed', { latestVersion, updateCommand })\n }\n\n // Exit 0 is the package manager saying it is content, not that anything changed. `pnpm add -g\n // infra-kit@latest` resolved the tag from its own stale metadata cache, reinstalled the version already\n // present, and returned 0 \u2014 and this function recorded `installed`, cleared `latestVersion`, and\n // repeated the same no-op every cycle. The spec is pinned now, but the check that would have SHOWN\n // that bug is this one: ask the binary the user actually runs. A mismatch keeps `latestVersion` and the\n // command in the cache, so the parent prints the manual line instead of staying silent.\n const nowInstalled = installedVersion(env)\n\n if (nowInstalled !== latestVersion) return finish('install-stale', { latestVersion, updateCommand })\n\n // Verified: clear `latestVersion` so the next run does not re-notify.\n return finish('installed', { latestVersion: null, updateCommand: null })\n}\n", "/**\n * Single-flight lock for the background update worker.\n *\n * Without it, N shells starting at once all read the same stale cache and each spawns a worker \u2014 and\n * once a newer version exists, each of those runs `npm install -g` concurrently, over the same global\n * directory. (Measured: five concurrent `ik` invocations spawn five workers.) The throttle in the cache\n * cannot prevent this: it is only written AFTER the fetch returns, long after the other workers launched.\n *\n * `openSync(path, 'wx')` is the primitive \u2014 an atomic create-if-absent, so exactly one worker wins even\n * if all of them call it in the same millisecond.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { getCacheRoot } from 'src/lib/constants'\n\nexport const LOCK_FILE_NAME = 'update-check.lock'\n\n/**\n * A lock older than this is assumed to belong to a worker that was killed before it could clean up.\n *\n * Must exceed the worker's ENTIRE critical section, and the install is part of it: the lock is held across\n * `fetch` (\u22642.5s) + the parent wait (\u22645min) + `npm install -g`, which has no bound at all \u2014 a cold cache on\n * a slow link can run for many minutes. The previous 10 minutes was budgeted from the wait and the fetch\n * alone, silently omitting the very operation the lock exists to serialise. A slow enough install therefore\n * had its own LIVE lock reaped as stale by the next worker, which then ran a second concurrent\n * `npm install -g` over the same global directory \u2014 precisely the pile-up described above.\n *\n * The throttle, not this timeout, is now the primary guard: `runUpdateCheck` stamps `lastCheckMs` BEFORE\n * the wait and the install, so concurrent shells stop spawning workers at all. This value only has to\n * outlive a plausible install, and is deliberately generous \u2014 the cost of being too large is that a worker\n * killed mid-install delays the next attempt, which the throttle would delay anyway.\n */\nexport const LOCK_STALE_MS = 30 * 60 * 1000\n\nexport const lockFilePath = (): string => {\n return path.join(getCacheRoot(), LOCK_FILE_NAME)\n}\n\nexport interface LockDeps {\n nowMs?: number\n lockPath?: string\n}\n\n/** Delete a lock whose mtime predates the staleness window. Best-effort: losing the race is harmless. */\nconst reapIfStale = (lockPath: string, nowMs: number): void => {\n try {\n if (nowMs - fs.statSync(lockPath).mtimeMs > LOCK_STALE_MS) fs.rmSync(lockPath, { force: true })\n } catch {\n // Vanished under us \u2014 another worker reaped it. Nothing to do.\n }\n}\n\n/**\n * Take the lock, or return null when another worker already holds it.\n *\n * Returns a release function rather than a boolean so the caller cannot forget which path releases:\n * there is exactly one handle, and it is the only thing that can unlink the file.\n *\n * @example\n * const release = acquireUpdateLock()\n * if (!release) return 'already-running'\n * try { ... } finally { release() }\n */\nexport const acquireUpdateLock = (deps: LockDeps = {}): (() => void) | null => {\n const nowMs = deps.nowMs ?? Date.now()\n const lockPath = deps.lockPath ?? lockFilePath()\n\n try {\n fs.mkdirSync(path.dirname(lockPath), { recursive: true })\n } catch {\n return null\n }\n\n const open = (): number | null => {\n try {\n // 'wx' fails with EEXIST if the file is already there: an atomic test-and-set.\n return fs.openSync(lockPath, 'wx', 0o600)\n } catch {\n return null\n }\n }\n\n let fd = open()\n\n if (fd === null) {\n reapIfStale(lockPath, nowMs)\n // One retry only. If a live worker holds the lock, we are the loser and must simply stand down.\n fd = open()\n }\n\n if (fd === null) return null\n\n try {\n fs.writeFileSync(fd, String(process.pid))\n } catch {\n // The pid is a debugging aid, not part of the protocol; the lock is held either way.\n }\n\n return () => {\n try {\n fs.closeSync(fd)\n } catch {\n // Already closed.\n }\n\n try {\n fs.rmSync(lockPath, { force: true })\n } catch {\n // Already gone; a later worker will reap it via LOCK_STALE_MS regardless.\n }\n }\n}\n", "/**\n * Ask the npm registry for the `latest` dist-tag. Node >= 24 (see `engines`), so global `fetch` is\n * available and this needs no dependency.\n */\nimport { PACKAGE_NAME } from 'src/lib/install-manager'\n\nexport const DEFAULT_REGISTRY = 'https://registry.npmjs.org'\n\n/**\n * Bounded so a hanging registry can never keep a detached child alive indefinitely. 5s, not a tighter\n * bound: the abbreviated `/pkg/latest` endpoint is usually ~20-900ms, but a cold TLS/DNS handshake in a\n * freshly-spawned worker can spike past a 2.5s cap \u2014 and a single trip used to cost a `fetch-failed` that\n * pushed the next check a full window out. A detached child that lingers a few extra seconds harms nothing.\n */\nexport const FETCH_TIMEOUT_MS = 5_000\n\n/**\n * The registry this install actually talks to. A user behind a corporate mirror has `npm_config_registry`\n * set; hitting registry.npmjs.org directly would either fail closed (firewall) or, worse, report a public\n * version they cannot install.\n *\n * @example\n * registryUrl({ npm_config_registry: 'https://nexus.corp/repo/npm/' }) // => 'https://nexus.corp/repo/npm'\n */\n/**\n * `npm_config_registry` in WHICHEVER case the environment spells it.\n *\n * A bare `env.npm_config_registry` reads only the lowercase form, but npm itself matches `/^npm_config_/i`,\n * and POSIX `process.env` is case-SENSITIVE \u2014 so a `NPM_CONFIG_REGISTRY` (the form Dockerfiles and CI\n * images export) was invisible here while npm honoured it. The check then queried the public registry that\n * the install would never touch: the two halves of this feature were exactly inverted.\n */\nconst configuredRegistry = (env: NodeJS.ProcessEnv): string | undefined => {\n const hit = Object.entries(env).find(([key, value]) => {\n return /^npm_config_registry$/i.test(key) && value != null && value !== ''\n })\n\n return hit?.[1]\n}\n\nexport const registryUrl = (env: NodeJS.ProcessEnv): string => {\n const configured = configuredRegistry(env)\n\n let base = configured != null && configured !== '' ? configured : DEFAULT_REGISTRY\n\n // A `/\\/+$/` regex would do this in one line, but its backtracking is super-linear on a hostile input.\n while (base.endsWith('/')) {\n base = base.slice(0, -1)\n }\n\n return base\n}\n\n/**\n * The published `latest` version, or null on ANY failure (offline, timeout, non-200, malformed body).\n * Never throws: a failed check must be indistinguishable from \"no update available\" to every caller.\n *\n * @example\n * await fetchLatestVersion(process.env) // => '0.1.131' | null\n */\nexport const fetchLatestVersion = async (\n env: NodeJS.ProcessEnv,\n fetchFn: typeof fetch = fetch,\n): Promise<string | null> => {\n const controller = new AbortController()\n const timer = setTimeout(() => {\n controller.abort()\n }, FETCH_TIMEOUT_MS)\n\n try {\n const response = await fetchFn(`${registryUrl(env)}/${PACKAGE_NAME}/latest`, {\n signal: controller.signal,\n headers: { accept: 'application/json' },\n })\n\n if (!response.ok) return null\n\n const body: unknown = await response.json()\n const version = (body as { version?: unknown } | null)?.version\n\n return typeof version === 'string' && version !== '' ? version : null\n } catch {\n return null\n } finally {\n clearTimeout(timer)\n }\n}\n", "/**\n * Registry-safe version comparison for the auto-update check.\n *\n * Deliberately NOT `src/lib/version-utils`: `parseVersion` there does `versionStr.slice(1)` because it\n * only ever sees `v`-prefixed release tags, so it turns a bare registry version (`0.1.130`) into\n * `[NaN, 1, 130]`. Feeding npm's `dist-tags.latest` through it silently compares NaNs and never fires.\n * These inputs are bare semver from `registry.npmjs.org` and from our own `package.json`.\n */\n\n/** `1.2.3-beta.4+build` \u2192 the `[1, 2, 3]` release triple and the `beta.4` prerelease, or null if unparsable. */\ninterface ParsedVersion {\n release: [number, number, number]\n /** Dot-separated prerelease identifiers, empty when this is a final release. */\n prerelease: string[]\n}\n\nconst RELEASE_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)$/\n\n/**\n * Parse bare semver. Returns null (never throws, never NaNs) for anything that is not\n * `major.minor.patch` with optional `-prerelease` and `+build` \u2014 a garbled registry body must read as\n * \"no update\", not as \"update to NaN\".\n *\n * @example\n * parseSemver('0.1.130') // => { release: [0, 1, 130], prerelease: [] }\n * parseSemver('1.0.0-rc.1+abc') // => { release: [1, 0, 0], prerelease: ['rc', '1'] }\n * parseSemver('v1.0.0') // => null\n */\nexport const parseSemver = (version: string): ParsedVersion | null => {\n // Build metadata is ignored entirely by semver precedence rules.\n const [withoutBuild = ''] = version.trim().split('+')\n const [core = '', ...prereleaseParts] = withoutBuild.split('-')\n const match = RELEASE_PATTERN.exec(core)\n\n if (!match) return null\n\n const [major, minor, patch] = [match[1], match[2], match[3]].map(Number) as [number, number, number]\n\n return {\n release: [major, minor, patch],\n // Re-join on '-' so `1.0.0-rc-1` keeps its hyphen inside a single identifier.\n prerelease: prereleaseParts.length > 0 ? prereleaseParts.join('-').split('.') : [],\n }\n}\n\nconst NUMERIC_IDENTIFIER = /^\\d+$/\n\n/** Compare two unequal prerelease identifiers per semver \u00A711. Numeric ones rank below alphanumeric ones. */\nconst compareIdentifier = (left: string, right: string): number => {\n const leftNumeric = NUMERIC_IDENTIFIER.test(left)\n const rightNumeric = NUMERIC_IDENTIFIER.test(right)\n\n if (leftNumeric && rightNumeric) return Number(left) - Number(right)\n if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1\n\n return left < right ? -1 : 1\n}\n\n/** Compare prerelease identifier lists. A shorter list has lower precedence: `1.0.0-rc` < `1.0.0-rc.1`. */\nconst comparePrerelease = (a: string[], b: string[]): number => {\n for (let index = 0; index < Math.max(a.length, b.length); index += 1) {\n const left = a[index]\n const right = b[index]\n\n if (left === undefined) return -1\n if (right === undefined) return 1\n if (left !== right) return compareIdentifier(left, right)\n }\n\n return 0\n}\n\n/**\n * Is `latest` strictly newer than `current`? False when either is unparsable, so a bad registry\n * response can never trigger an install.\n *\n * The load-bearing case is NUMERIC, not lexical, comparison: `0.1.9` must be older than `0.1.130`.\n * A string compare would order them the other way and pin every user to the older build forever.\n *\n * A final release outranks its own prereleases (`1.0.0` > `1.0.0-rc.1`), so a user on `rc` is offered\n * the release, and a user on the release is never \"downgraded\" to an rc.\n *\n * @example\n * isNewerVersion('0.1.130', '0.1.9') // => true (numeric, not lexical)\n * isNewerVersion('1.0.0', '1.0.0-rc.1') // => true\n * isNewerVersion('0.1.130', '0.1.130') // => false\n * isNewerVersion('garbage', '0.1.0') // => false\n */\nexport const isNewerVersion = (latest: string, current: string): boolean => {\n const parsedLatest = parseSemver(latest)\n const parsedCurrent = parseSemver(current)\n\n if (!parsedLatest || !parsedCurrent) return false\n\n for (let index = 0; index < 3; index += 1) {\n const left = parsedLatest.release[index] as number\n const right = parsedCurrent.release[index] as number\n\n if (left !== right) return left > right\n }\n\n const latestIsFinal = parsedLatest.prerelease.length === 0\n const currentIsFinal = parsedCurrent.prerelease.length === 0\n\n if (latestIsFinal !== currentIsFinal) return latestIsFinal\n\n return comparePrerelease(parsedLatest.prerelease, parsedCurrent.prerelease) > 0\n}\n", "/**\n * The throttle + notice state for the auto-update check, at `$cacheRoot/update-check.json`.\n *\n * `getCacheRoot()` \u2014 NOT `getSessionCacheDir()`, which throws unless `INFRA_KIT_SESSION` is set. A user\n * who installed this CLI globally and never ran `infra-kit setup` has no session, and the update check\n * must still work for exactly that person.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport { atomicWriteFileSync, getCacheRoot } from 'src/lib/constants'\n\nexport const CACHE_FILE_NAME = 'update-check.json'\n\n/**\n * The ONE re-check window, whatever the last outcome was. A background check is cheap \u2014 one\n * detached child and a single registry fetch bounded by `FETCH_TIMEOUT_MS` \u2014 but not once per\n * shell command, which is the storm this throttle exists to stop.\n *\n * MUST stay above a full worker cycle: `runUpdateCheck` stamps `lastCheckMs` BEFORE waiting up to\n * `PARENT_WAIT_TIMEOUT_MS` (5min) for the parent to exit and THEN installing.\n */\n// There is deliberately no shorter \"retry after a transient failure\" window. One used to exist\n// because this interval was 24h, and burning a whole day on a single network blip locked out\n// exactly the publisher pushing a release mid-window. At 20 minutes that gap is gone: a blip costs\n// one window, so a second window buys nothing and cannot pay for what it costs.\n//\n// What it would cost: go below a full worker cycle and the cache reads stale while the first worker\n// is still legitimately working, so the next shell spawns a worker that dies on the live\n// single-flight lock and returns WITHOUT writing \u2014 leaving the cache stale for every command until\n// `LOCK_STALE_MS` (30min) reaps the lock. That is the per-command spawn storm this throttle exists\n// to prevent, and it is why a 5-minute retry window is not an option.\nexport const CHECK_INTERVAL_MS = 20 * 60 * 1000\n\n/**\n * What the worker's Claude Code plugin step did. `skipped` = no project-scope install record on this\n * machine; `updated` = every recorded project whose path still exists took `claude plugin update`\n * with exit 0, \"already at the latest version\" included.\n *\n * `skipped-cli-stale` = the step was withheld because a newer CLI exists that this run did not install\n * (`pluginStepWithheld` in `run-update-check.ts`) \u2014 advancing the plugin past the CLI would hand its\n * skills a server that does not serve the tool names they cite.\n */\nexport type PluginUpdateOutcome = 'updated' | 'failed' | 'claude-missing' | 'skipped' | 'skipped-cli-stale'\n\nexport interface PluginUpdateRecord {\n outcome: PluginUpdateOutcome\n /** When the plugin step ran \u2014 stamped separately from `lastCheckMs`, which it never moves. */\n checkedMs: number\n}\n\nexport interface UpdateCache {\n /**\n * When the last check was ATTEMPTED \u2014 never \"when it last succeeded\". An offline user whose fetch\n * throws must still burn their window, or every single command spawns another doomed child.\n */\n lastCheckMs: number\n /** Latest version seen on the registry, or null when the last attempt failed. */\n latestVersion: string | null\n /**\n * The command the USER must run, set only when the worker was not allowed to install for them\n * (Homebrew, or an install location it could not identify). Null means \"handled, say nothing\".\n *\n * The worker decides this, not the reader: identifying the owning package manager can cost an\n * `npm root -g` subprocess, and the CLI startup path must never pay for one. The background child\n * already pays it, so it writes the verdict down.\n */\n updateCommand: string[] | null\n /**\n * The last check's terminal outcome (`installed`, `fetch-failed`, `up-to-date`, \u2026), or absent on a\n * cache written before this field existed.\n *\n * Diagnostic ONLY \u2014 nothing branches on it, {@link isStale} included. It earns its keep by being the\n * one thing that makes this file legible: a successful `installed` and a failed `fetch-failed` both\n * write a byte-identical `{latestVersion:null, updateCommand:null}`, so without this the cache cannot\n * say which happened, and a silent auto-update leaves no other trace of what it did.\n */\n outcome?: string | null\n /**\n * The plugin step's outcome, written beside the CLI outcome by the same worker; absent on a cache\n * written before the step existed. Diagnostic like `outcome`: the plugin is delivered through the\n * marketplace, and this is the only trace on disk of whether the worker asked for it.\n */\n plugin?: PluginUpdateRecord\n}\n\nexport const cacheFilePath = (): string => {\n return path.join(getCacheRoot(), CACHE_FILE_NAME)\n}\n\nconst isStringArray = (value: unknown): value is string[] => {\n return (\n Array.isArray(value) &&\n value.every((entry) => {\n return typeof entry === 'string'\n })\n )\n}\n\nconst isPluginUpdateRecord = (value: unknown): value is PluginUpdateRecord => {\n if (typeof value !== 'object' || value === null) return false\n\n const { outcome, checkedMs } = value as Partial<PluginUpdateRecord>\n\n return typeof outcome === 'string' && typeof checkedMs === 'number' && Number.isFinite(checkedMs)\n}\n\nconst isUpdateCache = (value: unknown): value is UpdateCache => {\n if (typeof value !== 'object' || value === null) return false\n\n const { lastCheckMs, latestVersion, updateCommand, outcome, plugin } = value as Partial<UpdateCache>\n\n return (\n typeof lastCheckMs === 'number' &&\n Number.isFinite(lastCheckMs) &&\n (latestVersion === null || typeof latestVersion === 'string') &&\n (updateCommand === null || isStringArray(updateCommand)) &&\n (outcome === undefined || outcome === null || typeof outcome === 'string') &&\n (plugin === undefined || isPluginUpdateRecord(plugin))\n )\n}\n\n/**\n * Read the cache, or null when it is missing/unreadable/corrupt. A null read means \"stale\" to every\n * caller, so a first run and a hand-mangled file behave identically: check again.\n *\n * @example\n * readUpdateCache() // => { lastCheckMs: 1770000000000, latestVersion: '0.1.131' } | null\n */\nexport const readUpdateCache = (\n readFile: (p: string) => string = (p) => {\n return fs.readFileSync(p, 'utf8')\n },\n): UpdateCache | null => {\n try {\n const parsed: unknown = JSON.parse(readFile(cacheFilePath()))\n\n return isUpdateCache(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n\n/**\n * Persist the check result. Creates `$cacheRoot` first: `atomicWriteFileSync` writes a temp file\n * beside the target and renames, so it throws ENOENT on a machine that has never had a `~/.cache/infra-kit`.\n * Without this mkdir the write fails, `lastCheckMs` never lands, and the throttle degrades into a\n * detached-child spawn on every invocation.\n *\n * @example\n * writeUpdateCache({ lastCheckMs: Date.now(), latestVersion: '0.1.131' })\n */\nexport const writeUpdateCache = (cache: UpdateCache): void => {\n const root = getCacheRoot()\n\n fs.mkdirSync(root, { recursive: true })\n atomicWriteFileSync(path.join(root, CACHE_FILE_NAME), JSON.stringify(cache), 0o600)\n}\n\n/**\n * Has the throttle window elapsed? A missing cache is stale by definition (first run).\n *\n * A `lastCheckMs` in the future (clock skew, or a restored backup) also reads as stale rather than\n * locking the user out of updates until their clock catches up.\n *\n * The window does NOT depend on `outcome`: every last outcome, transient or settled, is re-checked\n * after {@link CHECK_INTERVAL_MS}. See that constant for why a shorter transient-failure window is not\n * worth its cost here.\n *\n * @example\n * isStale(null, 1_000) // => true\n * isStale({ lastCheckMs: 0, latestVersion: null, updateCommand: null }, CHECK_INTERVAL_MS + 1) // => true\n */\nexport const isStale = (cache: UpdateCache | null, nowMs: number): boolean => {\n if (!cache) return true\n\n const elapsed = nowMs - cache.lastCheckMs\n\n if (elapsed < 0) return true\n\n return elapsed >= CHECK_INTERVAL_MS\n}\n", "/**\n * The Claude Code plugin half of the update worker: `claude plugin update infra-kit@infra-kit` for\n * every project this machine has the plugin installed in.\n *\n * WHY THE WORKER AND NOT CLAUDE CODE: Claude Code never advances an installed plugin on its own and\n * prints nothing for installed-but-old, so a plugin bump on `main` reached nobody until they typed\n * `claude plugin update` by hand \u2014 the CLI kept itself fresh while the skills it ships with rotted.\n * This step rides the same throttled child, so a plugin-only bump is delivered on the next check.\n *\n * Everything here is imported statically (see `run-update-check.ts`): on the `installed` path this runs\n * AFTER `npm install -g` has replaced `dist/`, where a lazy `import()` of a chunk is unsafe.\n */\nimport { spawnSync } from 'node:child_process'\nimport fs from 'node:fs'\nimport process from 'node:process'\n\nimport {\n CLAUDE_BIN,\n CLAUDE_VERSION_ARGV,\n PLUGIN_UPDATE_ARGV,\n defaultClaudeRunner,\n} from 'src/lib/plugin-pointer/claude-cli'\nimport type { ClaudeRunner } from 'src/lib/plugin-pointer/claude-cli'\nimport { listProjectPluginInstallations } from 'src/lib/plugin-pointer/install-state'\nimport type { PluginInstallation } from 'src/lib/plugin-pointer/install-state'\nimport { withoutPackageManagerEnv } from 'src/lib/pm-env'\n\nimport type { PluginUpdateOutcome } from './update-cache'\n\n/**\n * Probe plus every per-project run, end to end. Well inside `LOCK_STALE_MS` (30 min) even after a slow\n * CLI install has already spent minutes of the same lock \u2014 a plugin step that outlived the lock would\n * hand the next shell's worker a reaped lock and the concurrent-install pile-up the lock exists to stop.\n */\nexport const PLUGIN_UPDATE_BUDGET_MS = 5 * 60 * 1000\n\n/** One `claude plugin update` measured at \u22480.7 s; a minute is a wedged network, not a slow one. */\nexport const PLUGIN_UPDATE_RUN_TIMEOUT_MS = 60_000\n\nexport interface UpdatePluginDeps {\n env?: NodeJS.ProcessEnv\n /** Deadline source, injected so the budget is testable without real time. */\n clock?: () => number\n /** The `claude --version` probe. Output is captured and discarded; only `ok` is read. */\n runClaude?: ClaudeRunner\n /** The per-project update spawn \u2014 its own seam, so the CLI-install spawn's call count stays honest. */\n spawnPluginUpdate?: typeof spawnSync\n /** The project-scope install records; defaults to reading `~/.claude/plugins/installed_plugins.json`. */\n listPluginInstallations?: () => readonly PluginInstallation[]\n pathExists?: (target: string) => boolean\n}\n\ntype RecordResult = 'ok' | 'skipped' | 'failed'\n\ninterface UpdateContext {\n spawn: typeof spawnSync\n env: NodeJS.ProcessEnv\n clock: () => number\n deadlineMs: number\n pathExists: (target: string) => boolean\n}\n\n/**\n * The child env: npx/dlx markers stripped like every other child this CLI spawns, plus `CLAUDECODE`\n * \u2014 the marker a nested Claude Code refuses to start under. Whether `plugin update` shares that\n * refusal was not measured; the spike that proved this command ran without it, so it stays out.\n */\nconst pluginUpdateEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n const child = withoutPackageManagerEnv(env)\n\n delete child.CLAUDECODE\n\n return child\n}\n\nconst isEnoent = (error: Error): boolean => {\n return (error as NodeJS.ErrnoException).code === 'ENOENT'\n}\n\n/**\n * One recorded project. `cwd` is the whole mechanism: `claude` resolves WHICH project-scope record an\n * update touches from the cwd, and from a non-project directory it silently picks some other record.\n *\n * A path that no longer exists is skipped, never a failure \u2014 `installed_plugins.json` is append-only,\n * so records for deleted checkouts outlive the checkouts. `ENOENT` from the spawn is the same case\n * caught a moment later (the directory vanished between the check and the spawn).\n */\nconst updateRecordedProject = (record: PluginInstallation, ctx: UpdateContext): RecordResult => {\n const projectPath = record.projectPath\n\n if (projectPath === null || !ctx.pathExists(projectPath)) return 'skipped'\n\n const remainingMs = ctx.deadlineMs - ctx.clock()\n\n if (remainingMs <= 0) return 'failed'\n\n const result = ctx.spawn(CLAUDE_BIN, [...PLUGIN_UPDATE_ARGV], {\n cwd: projectPath,\n // Silent, like the CLI install: this is a detached worker with nowhere to write.\n stdio: 'ignore',\n shell: process.platform === 'win32',\n env: ctx.env,\n timeout: Math.min(PLUGIN_UPDATE_RUN_TIMEOUT_MS, remainingMs),\n windowsHide: true,\n })\n\n if (result.error) return isEnoent(result.error) ? 'skipped' : 'failed'\n\n return result.signal === null && result.status === 0 ? 'ok' : 'failed'\n}\n\nconst updatePluginUnguarded = (deps: UpdatePluginDeps): PluginUpdateOutcome => {\n const clock = deps.clock ?? Date.now\n // The probe's own timeout (`CLAUDE_TIMEOUT_MS`) is inside this budget, not in addition to it.\n const deadlineMs = clock() + PLUGIN_UPDATE_BUDGET_MS\n const runClaude = deps.runClaude ?? defaultClaudeRunner\n\n // The only gate besides the lock. `canSelfSpawn` is a question about where npm put the CLI and says\n // nothing about `claude`; a Homebrew-owned CLI still gets its plugin updated.\n if (!runClaude({ args: CLAUDE_VERSION_ARGV }).ok) return 'claude-missing'\n\n const records = (deps.listPluginInstallations ?? listProjectPluginInstallations)()\n\n if (records.length === 0) return 'skipped'\n\n const ctx: UpdateContext = {\n spawn: deps.spawnPluginUpdate ?? spawnSync,\n env: pluginUpdateEnv(deps.env ?? process.env),\n clock,\n deadlineMs,\n pathExists: deps.pathExists ?? fs.existsSync,\n }\n\n // Every record gets its turn even after one fails: the records are independent projects, and a\n // failure in one is no reason to leave another stale. The verdict is still `failed` \u2014 the manual\n // command is what fixes the one that did not take.\n const results = records.map((record) => {\n return updateRecordedProject(record, ctx)\n })\n\n if (results.includes('failed')) return 'failed'\n\n return results.includes('ok') ? 'updated' : 'skipped'\n}\n\n/**\n * Update the installed plugin in every recorded project. NEVER throws: a plugin failure is a recorded\n * outcome, not a reason to lose the CLI outcome the worker has already produced.\n *\n * @example\n * updatePlugin({ listPluginInstallations: () => [] }) // => 'skipped'\n */\nexport const updatePlugin = (deps: UpdatePluginDeps = {}): PluginUpdateOutcome => {\n try {\n return updatePluginUnguarded(deps)\n } catch {\n return 'failed'\n }\n}\n", "import { spawnSync } from 'node:child_process'\n\nimport { PLUGIN_KEY } from './names'\n\n/**\n * @fileoverview\n *\n * The `claude` binary as a dependency: the argv this CLI hands it and the one seam through which it is\n * spawned. Kept apart from `install-plugin.ts` (and its logger import) because the detached update\n * worker runs `claude plugin update` too, and that worker must stay a bundle of `node:child_process`\n * plus the cache writer \u2014 nothing that constructs a logger at import time.\n */\n\n/** Trust the `claude` binary resolved from `PATH`; there is no configured path and none is wanted. */\nexport const CLAUDE_BIN = 'claude'\n\n/**\n * Ceiling for any one `claude` invocation. `plugin install` clones a marketplace repo, so it is not\n * instant \u2014 but an `initCore` that hangs forever on a wedged network is worse than one that reports a\n * failed install step, and the user's remaining setup steps are behind this call.\n */\nexport const CLAUDE_TIMEOUT_MS = 120_000\n\n/** The PATH probe. Cheapest command that fails loudly when the binary is absent. */\nexport const CLAUDE_VERSION_ARGV: readonly string[] = ['--version']\n\n/**\n * `claude plugin update infra-kit@infra-kit --scope project -y`, as argv.\n *\n * Every flag is load-bearing (measured on Claude Code 2.1.270). Without `--scope project` the command\n * resolves USER scope from every cwd and fails \"not installed at scope user\" \u2014 while still refreshing\n * the marketplace clone as a side effect, so the failure looks like progress. `-y` is required when\n * stdio is not a TTY, which is every spawn from this CLI. WHICH project record the update advances is\n * decided by the command's cwd, not by any flag: callers pass `cwd: <recorded projectPath>`.\n */\nexport const PLUGIN_UPDATE_ARGV: readonly string[] = ['plugin', 'update', PLUGIN_KEY, '--scope', 'project', '-y']\n\n/** One `claude` invocation. `cwd` matters: `--scope project` records the directory it ran in. */\nexport interface ClaudeCommand {\n args: readonly string[]\n cwd?: string\n}\n\nexport interface ClaudeCommandResult {\n ok: boolean\n /** Diagnostic text from the command. Only read when `ok` is false. */\n output?: string\n}\n\n/** The injectable seam. Tests pass a fake so a suite never installs a plugin on the developer's machine. */\nexport type ClaudeRunner = (command: ClaudeCommand) => ClaudeCommandResult\n\n/**\n * Run one `claude` command, capturing its output instead of inheriting the terminal.\n *\n * Captured, not inherited, because `initCore` renders its own progress: a raw `plugin install` transcript\n * dumped between two `INFO:` lines reads as a crash. The captured text is not discarded \u2014 its first\n * line is what the failure warning quotes.\n *\n * @example\n * defaultClaudeRunner({ args: ['--version'] }) // => { ok: true, output: '2.0.0 (Claude Code)' }\n */\nexport const defaultClaudeRunner: ClaudeRunner = (command) => {\n // PATH lookup is the point: `claude` is installed by its own installer to a location this CLI does\n // not know and must not guess, and \"is it on PATH\" is exactly the question step (b) asks.\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n const result = spawnSync(CLAUDE_BIN, [...command.args], {\n cwd: command.cwd,\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'pipe'],\n timeout: CLAUDE_TIMEOUT_MS,\n })\n\n if (result.error !== undefined) return { ok: false, output: result.error.message }\n\n const output = `${result.stderr ?? ''}\\n${result.stdout ?? ''}`.trim()\n\n return { ok: result.status === 0, output }\n}\n", "/**\n * The three names every plugin-pointer module agrees on, in a file that imports NOTHING.\n *\n * Split out of `plugin-pointer.ts` because that module constructs the pino logger at import time,\n * and the detached update worker (`dist/update-check.js`) needs `PLUGIN_KEY` to spawn\n * `claude plugin update` \u2014 a worker that logs to an ignored stderr has no business paying for pino.\n */\n\n/** The marketplace name, as it appears in `extraKnownMarketplaces` and in `<plugin>@<marketplace>`. */\nexport const MARKETPLACE_NAME = 'infra-kit'\n\n/** The `enabledPlugins` key: `<plugin>@<marketplace>`, both `infra-kit`. */\nexport const PLUGIN_KEY = 'infra-kit@infra-kit'\n\n/** The GitHub repo the marketplace is served from. */\nexport const MARKETPLACE_REPO = 'ArthurSaenz/infra-kit'\n", "import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\n\nimport { MARKETPLACE_NAME, PLUGIN_KEY } from './names'\n\n/**\n * @fileoverview\n *\n * HOST-STATE readers: what Claude Code itself records on this machine about the `infra-kit`\n * marketplace and plugin. The consumer repo's own `.mcp.json` is read by `mcp-registration.ts`.\n *\n * All of it is read-only and total \u2014 every reader answers \"not registered / not installed\" for an\n * absent, unreadable or malformed file rather than throwing. `initCore` prints an install hint from\n * these answers and `doctor` reports them as rows, and neither may crash because a user hand-edited\n * a JSON file under `~/.claude/`.\n *\n * These files are Claude Code's, not ours. Nothing here writes to them: installing a plugin is the\n * `claude plugin install` command's job, and a CLI that edited another tool's state directory would\n * be repairing something it does not own.\n */\n\n/** Where Claude Code keeps its plugin bookkeeping, relative to `$HOME`. */\nconst PLUGINS_DIR = ['.claude', 'plugins']\n\n/** One entry of `installed_plugins.json`'s per-plugin array. Extra fields are ignored, not rejected. */\nexport interface PluginInstallation {\n scope: string | null\n projectPath: string | null\n installPath: string | null\n version: string | null\n}\n\nconst readJsonFile = (filePath: string): unknown => {\n try {\n return JSON.parse(fs.readFileSync(filePath, 'utf-8'))\n } catch {\n return undefined\n }\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nconst readString = (source: Record<string, unknown>, key: string): string | null => {\n const value = source[key]\n\n return typeof value === 'string' ? value : null\n}\n\n/** `~/.claude/plugins/<file>`, with `$HOME` injectable so tests never read the developer's own state. */\nconst pluginsPath = (file: string, home: string = os.homedir()): string => {\n return path.join(home, ...PLUGINS_DIR, file)\n}\n\n/**\n * Is the `infra-kit` marketplace registered on this machine?\n *\n * Registration is a machine fact (`~/.claude/plugins/known_marketplaces.json`), distinct from the\n * per-project `extraKnownMarketplaces` pointer `initCore` writes: the pointer says where to look, this\n * says the lookup has actually happened.\n *\n * @example\n * isMarketplaceRegistered() // => true once `claude plugin marketplace add ArthurSaenz/infra-kit` has run\n */\nexport const isMarketplaceRegistered = (home?: string): boolean => {\n const parsed = readJsonFile(pluginsPath('known_marketplaces.json', home))\n\n return isPlainObject(parsed) && MARKETPLACE_NAME in parsed\n}\n\nconst toInstallation = (entry: unknown): PluginInstallation | null => {\n if (!isPlainObject(entry)) return null\n\n return {\n scope: readString(entry, 'scope'),\n projectPath: readString(entry, 'projectPath'),\n installPath: readString(entry, 'installPath'),\n version: readString(entry, 'version'),\n }\n}\n\nconst readInstallations = (home?: string): PluginInstallation[] => {\n const parsed = readJsonFile(pluginsPath('installed_plugins.json', home))\n\n if (!isPlainObject(parsed) || !isPlainObject(parsed.plugins)) return []\n\n const entries = parsed.plugins[PLUGIN_KEY]\n\n if (!Array.isArray(entries)) return []\n\n return entries.flatMap((entry): PluginInstallation[] => {\n const installation = toInstallation(entry)\n\n return installation === null ? [] : [installation]\n })\n}\n\nexport interface PluginInstallationQuery {\n /** Override `$HOME` (tests, and nothing else). */\n home?: string\n /** The project root being asked about. Omitted, only a user-scope entry can count as installed. */\n projectPath?: string\n}\n\n/**\n * Whether the plugin is installed FOR THIS PROJECT \u2014 not merely present somewhere on the machine.\n *\n * `elsewhere` is the distinction that matters: it carries the records that exist, so the caller can\n * say which other project they belong to instead of reporting a bare \"not installed\".\n */\nexport type PluginInstallState =\n | { kind: 'installed'; installation: PluginInstallation }\n | { kind: 'elsewhere'; installations: readonly PluginInstallation[] }\n | { kind: 'absent' }\n\n/**\n * A path in the form the two sides can be compared in. `realpath` on both sides or neither: on macOS\n * `/tmp` resolves to `/private/tmp`, so a resolved path compared against an unresolved one never\n * matches. Falls back to `path.resolve` for a path that no longer exists, which `realpath` rejects.\n */\nconst canonicalPath = (target: string): string => {\n try {\n return fs.realpathSync(target)\n } catch {\n return path.resolve(target)\n }\n}\n\n/**\n * Does one record make the plugin active in `root`?\n *\n * A `user`-scope install is machine-wide and covers every project. Otherwise the record has to NAME\n * this project: `claude plugin install --scope project` stores the directory the session was started\n * in, so an install done for another repo covers that repo and nothing else.\n *\n * A record whose `projectPath` is this root counts whatever scope string it carries \u2014 the path is the\n * stronger signal, and an older Claude Code wrote records with no `scope` field at all.\n */\nconst coversProject = (entry: PluginInstallation, root: string | null): boolean => {\n if (entry.scope === 'user') return true\n if (root === null || entry.projectPath === null) return false\n\n return canonicalPath(entry.projectPath) === root\n}\n\n/**\n * Resolve what `~/.claude/plugins/installed_plugins.json` says about THIS project.\n *\n * @example\n * resolvePluginInstall({ projectPath: '/repo' })\n * // => { kind: 'elsewhere', installations: [{ projectPath: '/other', \u2026 }] } // installed, but not here\n */\nexport const resolvePluginInstall = (query: PluginInstallationQuery = {}): PluginInstallState => {\n const installations = readInstallations(query.home)\n\n if (installations.length === 0) return { kind: 'absent' }\n\n const root = query.projectPath === undefined ? null : canonicalPath(query.projectPath)\n\n const covering = installations.find((entry) => {\n return coversProject(entry, root)\n })\n\n return covering === undefined ? { kind: 'elsewhere', installations } : { kind: 'installed', installation: covering }\n}\n\n/**\n * Every PROJECT-scope record, one per distinct project path \u2014 the set `claude plugin update` has to be\n * run against, because Claude Code resolves which record an update touches from the command's cwd\n * (measured: from a non-project cwd it silently picks some other record, so one run from `$HOME`\n * advances one project, not all).\n *\n * A record with no `scope` but a `projectPath` counts as project scope, the way `coversProject`\n * treats it. User-scope records are excluded: this CLI never installs at user scope, and an update\n * there needs no cwd at all. Duplicates collapse on the canonical path \u2014 the file is append-only, so\n * a reinstalled project may carry two records naming one directory.\n *\n * @example\n * listProjectPluginInstallations()\n * // => [{ scope: 'project', projectPath: '/Users/me/hulyo', installPath: '\u2026/0.7.0', version: '0.7.0' }]\n */\nexport const listProjectPluginInstallations = (home?: string): PluginInstallation[] => {\n const seen = new Set<string>()\n\n return readInstallations(home).filter((entry) => {\n if (entry.scope === 'user' || entry.projectPath === null) return false\n\n const key = canonicalPath(entry.projectPath)\n\n if (seen.has(key)) return false\n\n seen.add(key)\n\n return true\n })\n}\n\n/**\n * The installed plugin's version: the record's own `version`, falling back to the manifest at\n * `<installPath>/.claude-plugin/plugin.json`.\n *\n * The fallback is not redundant. `installed_plugins.json` records a git-commit sha as `version` for\n * marketplaces served from a repo, so the manifest is the only place a human-readable `0.4.0` lives\n * \u2014 and an entry written by an older Claude Code may carry no `version` at all.\n *\n * @example\n * readInstalledPluginVersion({ scope: 'project', projectPath: null, installPath: '/cache/infra-kit', version: null })\n * // => '0.4.0' (read from /cache/infra-kit/.claude-plugin/plugin.json)\n */\nexport const readInstalledPluginVersion = (installation: PluginInstallation): string | null => {\n if (installation.installPath === null) return installation.version\n\n const manifest = readJsonFile(path.join(installation.installPath, '.claude-plugin', 'plugin.json'))\n const declared = isPlainObject(manifest) ? readString(manifest, 'version') : null\n\n return declared ?? installation.version\n}\n\n/**\n * The plugin's directory inside the marketplace clone: `plugins/<plugin name>`, the left half of\n * `<plugin>@<marketplace>`. Derived, not spelled out again, so the two can never disagree.\n */\nconst [PLUGIN_NAME = MARKETPLACE_NAME] = PLUGIN_KEY.split('@')\n\n/**\n * The plugin version the marketplace CLONE carries \u2014 `~/.claude/plugins/marketplaces/<marketplace>/\n * plugins/<plugin>/.claude-plugin/plugin.json` \u2014 which is NOT what a session serves.\n *\n * Measured (plan \u00A76.1 S0-7(b)): sessions load the plugin from the install record's cache\n * `installPath`, and only a successful `claude plugin update --scope project` advances that record,\n * while any `claude plugin update` \u2014 a failing user-scope one included \u2014 refreshes the clone as a\n * side effect. So the clone can sit AHEAD of the served copy, and comparing the two is the one\n * freshness signal readable offline: \"fetched but not applied\". Reads as `null` for a clone that is\n * absent, unreadable or carries no version, so the caller drops the comparison instead of failing.\n *\n * @example\n * readMarketplacePluginVersion() // => '0.8.0' after a `claude plugin update` refreshed the clone\n * readMarketplacePluginVersion({ home: '/tmp/no-such-home' }) // => null\n */\nexport const readMarketplacePluginVersion = ({ home }: Pick<PluginInstallationQuery, 'home'> = {}): string | null => {\n const manifestPath = pluginsPath(\n path.join('marketplaces', MARKETPLACE_NAME, 'plugins', PLUGIN_NAME, '.claude-plugin', 'plugin.json'),\n home,\n )\n const manifest = readJsonFile(manifestPath)\n\n return isPlainObject(manifest) ? readString(manifest, 'version') : null\n}\n"],
5
- "mappings": "0HAAA,IAAAA,GAAA,CACE,KAAQ,YACR,KAAQ,SACR,QAAW,QACX,MAAS,CACP,MACF,EACA,YAAe,YACf,IAAO,CACL,YAAa,cACb,GAAM,cACN,SAAU,mBACZ,EACA,QAAW,CACT,KAAQ,QACV,EACA,QAAW,CACT,UAAa,iEACb,MAAS,sDACT,QAAW,iBACX,kBAAmB,4BACnB,kBAAmB,cACnB,cAAe,2EACf,eAAgB,4HAChB,iBAAkB,4HAClB,eAAgB,oEAChB,aAAc,kFACd,WAAY,eACZ,KAAQ,0CACR,aAAc,gDACd,UAAW,6CACX,cAAe,uDACf,SAAU,qMACV,GAAM,gHACN,IAAO,6DACT,EACA,aAAgB,CACd,gCAAiC,UACjC,qBAAsB,SACtB,oBAAqB,SACrB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IAAK,CAAC,CACzE",
6
- "names": ["package_default", "spawnSync", "homedir", "process", "fs", "path", "process", "LOCK_FILE_NAME", "LOCK_STALE_MS", "lockFilePath", "path", "getCacheRoot", "reapIfStale", "lockPath", "nowMs", "fs", "acquireUpdateLock", "deps", "open", "fd", "process", "DEFAULT_REGISTRY", "FETCH_TIMEOUT_MS", "configuredRegistry", "env", "key", "value", "registryUrl", "configured", "base", "fetchLatestVersion", "fetchFn", "controller", "timer", "response", "PACKAGE_NAME", "version", "RELEASE_PATTERN", "parseSemver", "version", "withoutBuild", "core", "prereleaseParts", "match", "major", "minor", "patch", "NUMERIC_IDENTIFIER", "compareIdentifier", "left", "right", "leftNumeric", "rightNumeric", "comparePrerelease", "a", "b", "index", "isNewerVersion", "latest", "current", "parsedLatest", "parsedCurrent", "latestIsFinal", "currentIsFinal", "fs", "path", "CACHE_FILE_NAME", "CHECK_INTERVAL_MS", "cacheFilePath", "path", "getCacheRoot", "isStringArray", "value", "entry", "isPluginUpdateRecord", "outcome", "checkedMs", "isUpdateCache", "lastCheckMs", "latestVersion", "updateCommand", "plugin", "readUpdateCache", "readFile", "p", "fs", "parsed", "writeUpdateCache", "cache", "root", "atomicWriteFileSync", "isStale", "nowMs", "elapsed", "spawnSync", "fs", "process", "spawnSync", "MARKETPLACE_NAME", "PLUGIN_KEY", "MARKETPLACE_REPO", "CLAUDE_BIN", "CLAUDE_TIMEOUT_MS", "CLAUDE_VERSION_ARGV", "PLUGIN_UPDATE_ARGV", "PLUGIN_KEY", "defaultClaudeRunner", "command", "result", "spawnSync", "output", "fs", "os", "path", "PLUGINS_DIR", "readJsonFile", "filePath", "fs", "isPlainObject", "value", "readString", "source", "key", "pluginsPath", "file", "home", "os", "path", "isMarketplaceRegistered", "parsed", "MARKETPLACE_NAME", "toInstallation", "entry", "readInstallations", "entries", "PLUGIN_KEY", "installation", "canonicalPath", "target", "coversProject", "root", "resolvePluginInstall", "query", "installations", "covering", "listProjectPluginInstallations", "seen", "readInstalledPluginVersion", "manifest", "PLUGIN_NAME", "readMarketplacePluginVersion", "manifestPath", "PLUGIN_UPDATE_BUDGET_MS", "PLUGIN_UPDATE_RUN_TIMEOUT_MS", "pluginUpdateEnv", "env", "child", "withoutPackageManagerEnv", "isEnoent", "error", "updateRecordedProject", "record", "ctx", "projectPath", "remainingMs", "result", "CLAUDE_BIN", "PLUGIN_UPDATE_ARGV", "process", "updatePluginUnguarded", "deps", "clock", "deadlineMs", "defaultClaudeRunner", "CLAUDE_VERSION_ARGV", "records", "listProjectPluginInstallations", "spawnSync", "fs", "results", "updatePlugin", "PARENT_POLL_INTERVAL_MS", "PARENT_WAIT_TIMEOUT_MS", "VERSION_PROBE_TIMEOUT_MS", "readInstalledVersion", "env", "result", "spawnSync", "PACKAGE_NAME", "process", "homedir", "version", "defaultIsProcessAlive", "pid", "defaultSleep", "ms", "resolve", "waitForParentExit", "parentPid", "deps", "deadline", "runUpdateCheck", "currentVersion", "acquireLock", "acquireUpdateLock", "writeCache", "writeUpdateCache", "release", "written", "recordingWriteCache", "cache", "outcome", "runUpdateCheckLocked", "recordPluginUpdate", "pluginStepWithheld", "latestVersion", "isNewerVersion", "base", "updatePlugin", "checkedMs", "nowMs", "fetchLatest", "fetchLatestVersion", "isProcessAlive", "sleep", "clock", "lazyNpmRoot", "defaultLazyNpmRoot", "spawn", "installedVersion", "finish", "canSelfSpawn", "updateCommand", "detectInstallManager", "safeRealpath", "packageManagerInstallEnv"]
7
- }
@@ -1,2 +0,0 @@
1
- import{d as x,g as f,k as g}from"./chunk-75BE6MSY.js";import{$ as y,P as u,ca as k,da as v,fa as w,pa as C}from"./chunk-H5AAXCRJ.js";import"./chunk-MFAFQVTW.js";import{f as b}from"./chunk-75URROMU.js";import"./chunk-QWVLAZ6N.js";import B from"@inquirer/checkbox";import _ from"@inquirer/confirm";import j,{Separator as I}from"@inquirer/select";import{loadDev as K}from"@slip-stream-kit/config/internal";import q from"node:path";import m from"node:process";var W=e=>e.split("/")[0],A=e=>new Map(e.apps.map(r=>[r.name,r])),D=e=>e.localCapable&&e.cloudCapable,N=(e,r,a)=>D(r)?a[`${e} ${r.path}`]??(r.cloudCapable?"cloud":"local"):r.localCapable?"local":"cloud",$=(e,r,a)=>{let t=new Set,o=new Map;for(let n of e){let s=r.get(W(n));for(let c of s?.backends??[]){o.set(c.packageName,c.ownerApp);for(let l of c.routes)N(n,l,a)==="local"&&t.add(c.packageName)}}return{localPkgs:t,ownerByPkg:o}},O=(e,r)=>{let a={},t=!1;for(let o of e?.backends??[]){let n=r.has(o.packageName);for(let s of o.routes){let c=s.localCapable&&n?"local":"cloud";a[s.path]=c,c==="cloud"&&(t=!0)}}return{overrides:a,anyCloud:t}},z=(e,r)=>{let a=A(r),t=e.targets.filter(p=>p.endsWith("/ui")),o=e.targets.filter(p=>p.endsWith("/api")),{localPkgs:n,ownerByPkg:s}=$(t,a,e.sources),c={},l=!1;for(let p of t){let{overrides:d,anyCloud:i}=O(a.get(W(p)),n);i&&(l=!0),c[p]=Object.keys(d).length>0?{proxy:d}:{}}for(let p of o)c[p]??={};for(let p of n){let d=s.get(p);d!=null&&(c[`${d}/api`]??={})}return{presetDef:{apps:c,orca:e.orca},anyCloudRoute:l,targetKeys:Object.keys(c).sort()}},R=(e,r)=>{let a=[`--target=${e.targetKeys.join(",")}`];return r.watch&&a.push("--watch"),r.orca&&a.push("--orca"),{flags:a.join(" ")}};var h={output:m.stderr,clearPromptOnDone:!0},E={select:e=>g(r=>j({message:e.message,choices:e.choices,default:e.default},r),h),checkbox:e=>g(r=>B({message:e.message,choices:e.choices},r),h),confirm:e=>g(r=>_({message:e.message,default:e.default},r),h)},T=(e,r)=>{let a=new Map;for(let[t,o]of Object.entries(e)){let n={path:t,localCapable:o.from.includes("local"),cloudCapable:o.from.includes("cloud"),default:o.default},s=a.get(o.packageName);s?(s.routes.push(n),s.localCapable=s.localCapable||n.localCapable,s.cloudCapable=s.cloudCapable||n.cloudCapable):a.set(o.packageName,{packageName:o.packageName,routes:[n],localCapable:n.localCapable,cloudCapable:n.cloudCapable,ownerApp:r.get(o.packageName)})}return[...a.values()]},U=async(e,r,a)=>{try{let t=(await K(e))?.proxy?.routes;return t?T(t,a):[]}catch(t){return u.warn(`\u26A0\uFE0F Skipping ${r}: its dev config failed to load \u2014 ${t instanceof Error?t.message:String(t)}`),[]}},V=async e=>{let r=v(e),a=w(e),t=await y(),o=new Map(r.map(i=>[i.packageName,i.name])),n=new Map(r.map(i=>[i.name,i.packageName])),s=new Set(a.map(i=>i.name)),c=new Set(r.map(i=>i.name)),l=[...new Set([...c,...s])].sort(),p=await Promise.all(l.map(async i=>{let P=s.has(i);return{name:i,hasApi:c.has(i),hasUi:P,apiPackage:n.get(i),backends:P?await U(q.join(e,"apps",i,"ui"),i,o):[]}})),d=await x();return{apps:p,presets:Object.keys(t.devServersPresets??{}),environments:Object.keys(d?.envs??{}).sort()}},F=e=>{let r=[];for(let a of e.apps){if(a.hasUi){let t=a.backends.flatMap(n=>n.routes.map(s=>s.path)),o=t.length>0?`frontend \u2014 proxies ${[...t].sort().join(", ")}`:"frontend";r.push({name:`${a.name}/ui`,value:`${a.name}/ui`,description:o})}a.hasApi&&!a.hasUi&&r.push({name:`${a.name}/api`,value:`${a.name}/api`,description:"backend"})}return r},L=e=>{let r={api:e.apps.filter(o=>o.hasApi).map(o=>o.name),ui:e.apps.filter(o=>o.hasUi).map(o=>o.name)},a={},t=new Map;for(let o of e.apps){o.apiPackage!=null&&(a[o.name]=o.apiPackage);for(let n of o.backends)for(let s of n.routes)t.set(`${o.name} ${s.path}`,n.packageName)}return{discovered:r,apiPkgByApp:a,routePkg:(o,n)=>t.get(`${o} ${n}`)}},Z=(e,r)=>C({__wizard__:e},L(r)).map(a=>a.message),H="INFRA_KIT_DEV_WIZARD_ORCA",G=()=>m.env[H]==="1",J=async(e,r,a)=>{let t=new Map(r.apps.map(n=>[n.name,n])),o={};for(let n of a){let s=t.get(n.split("/")[0]);for(let c of s?.backends??[])for(let l of c.routes){if(!l.localCapable||!l.cloudCapable)continue;let p=await e.select({message:`\u{1F500} ${n} ${l.path} \u2192 local or cloud?`,choices:[{name:"local (this machine)",value:"local"},{name:"cloud",value:"cloud"}],default:l.default??"local"});o[`${n} ${l.path}`]=p}}return o},Q=(e,r,a)=>e.apps.find(t=>t.name===r)?.backends.flatMap(t=>t.routes).find(t=>t.path===a),X=(e,r)=>{let a=[];for(let[t,o]of Object.entries(e.presetDef.apps??{})){if(!t.endsWith("/ui")||!o.proxy)continue;let n=t.split("/")[0];for(let[s,c]of Object.entries(o.proxy)){let l=Q(r,n,s),p=l&&l.localCapable&&l.cloudCapable?"":" (only option)";a.push(` ${t} ${s} \u2192 ${c}${p}`)}}if(a.length!==0){u.info("Resolved routes:");for(let t of[...a].sort())u.info(t)}},M=async(e,r)=>{if(r.apps.length===0)return u.warn("No apps discovered to run."),null;let a=await e.checkbox({message:"\u{1F4E6} Which packages?",choices:F(r)});if(a.length===0)return u.warn("No packages selected."),null;let t=a.filter(i=>i.endsWith("/ui")),o=await J(e,r,t),n=await e.confirm({message:"\u{1F440} Rebuild & restart on save (watch)?",default:!1}),s=G()?await e.confirm({message:"\u{1F9E9} Run each app in its own Orca pane?",default:!1}):!1,c={targets:a,sources:o,watch:n,orca:s},l=z(c,r);if(l.anyCloudRoute){if(r.environments.length===0)return u.warn("\u2601\uFE0F This selection routes to a cloud environment, but no environment token is loaded."),u.warn(" Run `infra-kit env-load` to add one, then re-run the wizard."),null;c.env=await e.select({message:"\u2601\uFE0F Point cloud routes at which environment?",choices:r.environments.map(i=>({name:i,value:i}))}),m.env[b]=c.env}let p=Z(l.presetDef,r);if(p.length>0){u.warn("\u26A0\uFE0F Proxy audit found issues with this selection:");for(let i of p)u.warn(` \u2022 ${i}`);return null}X(l,r),Y(l,c);let d=l.targetKeys.filter(i=>i.endsWith("/api")).map(i=>i.split("/")[0]);return s&&d.length>0?{include:d,presetDef:l.presetDef,watch:n,orca:!0}:(s&&u.info("\u2139\uFE0F Orca needs at least one local backend (panes are backend-only) \u2014 running in-process instead."),{presetDef:l.presetDef,watch:n,orca:!1})},Y=(e,r)=>{f.setInteractive();let a=R(e,r);f.addOption(a.flags,!0),f.print(),u.info("\u2139\uFE0F Prefer a short name? Save this selection as a devPreset and run `infra-kit dev <name>`.")},ee=async(e,r)=>{let a=await e.confirm({message:"\u{1F440} Rebuild & restart on save (watch)?",default:!1});return f.setInteractive(),f.addOption(r,!0),a&&f.addOption("--watch",!0),f.print(),{preset:r,watch:a,orca:!1}},S=" manual",re=async(e,r)=>{if(r.presets.length===0)return M(e,r);let a=await e.select({message:"\u{1F680} Start from a preset, or configure manually?",choices:[...r.presets.map(t=>({name:t,value:t})),new I(" "),{name:"Manual (custom)\u2026",value:S}]});return a===S?M(e,r):ee(e,a)},be=async(e=E,r=k(m.cwd()))=>re(e,await V(r));export{S as MANUAL_CHOICE,H as WIZARD_ORCA_VAR,Z as auditManualPlan,E as defaultPrompts,V as gatherWizardModel,U as loadBackends,be as runDevWizard,re as runWizardFlow};
2
- //# sourceMappingURL=dev-wizard-run-643QKSR3.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/dev/dev-wizard-run.ts", "../src/dev/dev-wizard.ts"],
4
- "sourcesContent": ["/**\n * Impure driver for the interactive `infra-kit dev` wizard: filesystem/config discovery, the inquirer\n * prompt flow (step-0 preset-or-manual, then the manual matrix), the pre-flight proxy audit, and the\n * `commandEcho` teaching line. The pure answer\u2192plan mapping lives in {@link file://./dev-wizard.ts}.\n *\n * Prompts are behind the injectable {@link WizardPrompts} seam so the flow is testable without a TTY.\n * This module is reached ONLY from the bare-invocation TTY branch of the entry point; every flagged /\n * non-TTY / `--json` / MCP invocation bypasses it entirely.\n */\nimport inquirerCheckbox from '@inquirer/checkbox'\nimport inquirerConfirm from '@inquirer/confirm'\nimport inquirerSelect, { Separator } from '@inquirer/select'\nimport { loadDev } from '@slip-stream-kit/config/internal'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { discoverApiApps, discoverUiApps, findMonorepoRoot } from 'src/dev/discovery'\nimport { commandEcho } from 'src/lib/command-echo'\nimport { INFRA_KIT_ENV_VAR } from 'src/lib/constants'\nimport { readTokenStore } from 'src/lib/env-tokens'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\nimport type { DevPreset, ProxySource } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { deriveManualPlan, equivalentCommand } from './dev-wizard.js'\nimport type { DerivedPlan, ManualSelection, ProxyBackend, RouteCap, WizardApp, WizardModel } from './dev-wizard.js'\nimport { validatePresetProxy } from './presets.js'\nimport type { DiscoveredParts, PresetProxyContext } from './presets.js'\n\n/** A wizard prompt choice \u2014 all values are strings, so the seam needs no generics. */\nexport interface WizardChoice {\n name: string\n value: string\n description?: string\n checked?: boolean\n disabled?: boolean | string\n}\n\n/**\n * Injectable prompt seam (a string-valued subset of `@inquirer/*`). The default implementation\n * ({@link defaultPrompts}) delegates to the real prompts, rendering to stderr so the dev-server's\n * stdout stays clean. Tests pass a scripted object.\n */\nexport interface WizardPrompts {\n select: (cfg: { message: string; choices: (WizardChoice | Separator)[]; default?: string }) => Promise<string>\n checkbox: (cfg: { message: string; choices: WizardChoice[] }) => Promise<string[]>\n confirm: (cfg: { message: string; default?: boolean }) => Promise<boolean>\n}\n\n/**\n * Shared `@inquirer/*` context. Rendered to stderr (mirrors the bare-`infra-kit` command palette).\n *\n * `clearPromptOnDone` erases each answered prompt instead of leaving a `\u2714 <question> <answer>` line\n * behind, so the wizard collapses to nothing once it finishes and the dev-server's ready header lands\n * at the top of a clean screen. The choices are not lost: {@link echoManual} / {@link runPresetBranch}\n * print the equivalent flag command, which is the durable record of what was picked.\n */\nconst promptContext = { output: process.stderr, clearPromptOnDone: true }\n\n/**\n * Real `@inquirer/*` prompts, rendered to stderr and erased once answered.\n *\n * Every one goes through {@link withEscape}, which binds Esc to cancellation. The wrap is here rather\n * than around the {@link WizardPrompts} seam so the scripted prompts the tests inject stay untouched:\n * the seam is the test boundary, `defaultPrompts` is the only implementation that talks to a terminal.\n *\n * Esc rejects with an `AbortPromptError`, which `entry/cli.ts` catches as a cancellation \u2192 exit 0. The\n * wizard therefore needs no cancel branch of its own: a cancelled prompt never returns here at all, so\n * no server is started.\n */\nexport const defaultPrompts: WizardPrompts = {\n select: (cfg) => {\n return withEscape((context) => {\n return inquirerSelect({ message: cfg.message, choices: cfg.choices, default: cfg.default }, context)\n }, promptContext)\n },\n checkbox: (cfg) => {\n return withEscape((context) => {\n return inquirerCheckbox({ message: cfg.message, choices: cfg.choices }, context)\n }, promptContext)\n },\n confirm: (cfg) => {\n return withEscape((context) => {\n return inquirerConfirm({ message: cfg.message, default: cfg.default }, context)\n }, promptContext)\n },\n}\n\n/** What the wizard hands back to the entry point (merged into `DevServerOptions`), or null on cancel. */\nexport interface WizardResult {\n /** Named preset (preset branch) \u2014 passed through as `options.preset`. */\n preset?: string\n /** In-memory preset (manual branch, non-Orca) \u2014 passed through as `options.presetDef`. */\n presetDef?: DevPreset\n /**\n * App-name include list for the Orca path only: which discovered API apps get a pane. Paired with\n * `presetDef`, which tells each pane the exact parts to run. An app selected UI-only gets no pane\n * (Orca panes are opened per API app). Unset for the non-Orca manual path.\n */\n include?: string[]\n watch: boolean\n orca: boolean\n}\n\n/** Group one frontend's `dev.proxy.routes` into {@link ProxyBackend}s keyed by backend package. */\nconst groupBackends = (\n routes: Record<string, { packageName: string; from: readonly string[]; default?: 'local' | 'cloud' }>,\n ownerByPkg: Map<string, string>,\n): ProxyBackend[] => {\n const byPkg = new Map<string, ProxyBackend>()\n\n for (const [route, def] of Object.entries(routes)) {\n const cap: RouteCap = {\n path: route,\n localCapable: def.from.includes('local'),\n cloudCapable: def.from.includes('cloud'),\n default: def.default,\n }\n const existing = byPkg.get(def.packageName)\n\n if (existing) {\n existing.routes.push(cap)\n existing.localCapable = existing.localCapable || cap.localCapable\n existing.cloudCapable = existing.cloudCapable || cap.cloudCapable\n } else {\n byPkg.set(def.packageName, {\n packageName: def.packageName,\n routes: [cap],\n localCapable: cap.localCapable,\n cloudCapable: cap.cloudCapable,\n ownerApp: ownerByPkg.get(def.packageName),\n })\n }\n }\n\n return [...byPkg.values()]\n}\n\n/**\n * Load one frontend's proxy routes and group them into backends. A config that throws \u2014 schema-invalid\n * or an import-time error \u2014 degrades THAT app to zero backends with a named warning instead of rejecting.\n * Without this, a single broken `apps/<x>/ui/infra-kit.config.ts` fails the whole `Promise.all` in\n * {@link gatherWizardModel} and takes the entire wizard down, so `infra-kit dev` becomes unusable for every\n * other app in the monorepo. Mirrors the audit path's per-app guard ({@link file://../commands/audit/preset-proxy-check.ts}).\n */\nexport const loadBackends = async (\n uiDir: string,\n name: string,\n ownerByPkg: Map<string, string>,\n): Promise<ProxyBackend[]> => {\n try {\n const routes = (await loadDev(uiDir))?.proxy?.routes\n\n return routes ? groupBackends(routes, ownerByPkg) : []\n } catch (error) {\n logger.warn(\n `\u26A0\uFE0F Skipping ${name}: its dev config failed to load \u2014 ${error instanceof Error ? error.message : String(error)}`,\n )\n\n return []\n }\n}\n\n/** Discover apps + configs and assemble the {@link WizardModel} (backends resolved per frontend). */\nexport const gatherWizardModel = async (root: string): Promise<WizardModel> => {\n const apiApps = discoverApiApps(root)\n const uiApps = discoverUiApps(root)\n const config = await getInfraKitConfig()\n\n const ownerByPkg = new Map(\n apiApps.map((a) => {\n return [a.packageName, a.name] as const\n }),\n )\n const apiPkgByName = new Map(\n apiApps.map((a) => {\n return [a.name, a.packageName] as const\n }),\n )\n const uiNames = new Set(\n uiApps.map((a) => {\n return a.name\n }),\n )\n const apiNames = new Set(\n apiApps.map((a) => {\n return a.name\n }),\n )\n const allNames = [...new Set([...apiNames, ...uiNames])].sort()\n\n const apps: WizardApp[] = await Promise.all(\n allNames.map(async (name): Promise<WizardApp> => {\n const hasUi = uiNames.has(name)\n\n return {\n name,\n hasApi: apiNames.has(name),\n hasUi,\n apiPackage: apiPkgByName.get(name),\n backends: hasUi ? await loadBackends(path.join(root, 'apps', name, 'ui'), name, ownerByPkg) : [],\n }\n }),\n )\n\n // The cloud-env choices are the envs we hold a token for \u2014 the same authority as `env-load`, because\n // it is the same question. This picker writes INFRA_KIT_ENV, which `@slip-stream-kit/config/vite`\n // reads to build the cloud backend's URL, and whose only other writer is `env-load` (which cannot run\n // without a Doppler token). Sourcing it from the workflow options instead would put `prod` in the list\n // for everyone \u2014 including a developer holding no prod credential \u2014 and point a local UI at\n // production. No token, no entry.\n const store = await readTokenStore()\n\n return {\n apps,\n presets: Object.keys(config.devServersPresets ?? {}),\n environments: Object.keys(store?.envs ?? {}).sort(),\n }\n}\n\n/**\n * Build the checkbox choices: one `<app>/ui` per frontend, plus `<app>/api` ONLY for api-only apps\n * (an api with no ui). A full-stack `<app>/api` is deliberately NOT offered \u2014 a full-stack backend is\n * launched by choosing `local` for one of its frontend's routes (asked per-route afterwards), so the\n * checkbox stays a pick of frontends + standalone backends.\n *\n * Nothing starts checked: the manual branch is opt-in, so a run only ever launches what was explicitly\n * ticked. Pre-checking every part would make the fast path (accept the defaults) boot the whole monorepo\n * \u2014 the exact opposite of why someone reached for \"Manual\" over a preset.\n */\nconst buildPartChoices = (model: WizardModel): WizardChoice[] => {\n const choices: WizardChoice[] = []\n\n for (const app of model.apps) {\n if (app.hasUi) {\n const paths = app.backends.flatMap((b) => {\n return b.routes.map((r) => {\n return r.path\n })\n })\n const description = paths.length > 0 ? `frontend \u2014 proxies ${[...paths].sort().join(', ')}` : 'frontend'\n\n choices.push({ name: `${app.name}/ui`, value: `${app.name}/ui`, description })\n }\n if (app.hasApi && !app.hasUi) {\n choices.push({ name: `${app.name}/api`, value: `${app.name}/api`, description: 'backend' })\n }\n }\n\n return choices\n}\n\n/** Build the audit context from the gathered model (no re-reading of configs). */\nconst buildAuditContext = (model: WizardModel): PresetProxyContext => {\n const discovered: DiscoveredParts = {\n api: model.apps\n .filter((a) => {\n return a.hasApi\n })\n .map((a) => {\n return a.name\n }),\n ui: model.apps\n .filter((a) => {\n return a.hasUi\n })\n .map((a) => {\n return a.name\n }),\n }\n const apiPkgByApp: Record<string, string> = {}\n const routeToPkg = new Map<string, string>()\n\n for (const app of model.apps) {\n // Map EVERY discovered api app to its own api package \u2014 including api-only apps a frontend proxies\n // to cross-app \u2014 so `launchedPkgs` in validatePresetProxy is faithful (mirrors preset-proxy-check.ts).\n // Deriving this from proxy backends alone would miss api-only owners and false-positive the audit.\n if (app.apiPackage != null) apiPkgByApp[app.name] = app.apiPackage\n for (const b of app.backends) {\n for (const route of b.routes) {\n routeToPkg.set(`${app.name} ${route.path}`, b.packageName)\n }\n }\n }\n\n return {\n discovered,\n apiPkgByApp,\n routePkg: (app, route) => {\n return routeToPkg.get(`${app} ${route}`)\n },\n }\n}\n\n/**\n * Run the assembled plan through the SAME proxy-locality rule the root audit uses. Returns issue\n * messages (empty when clean). Catches a `local` override whose backend won't launch \u2014 the wizard's\n * derivation launches owners, so a hit means the backend has no discoverable owning app.\n */\nexport const auditManualPlan = (presetDef: DevPreset, model: WizardModel): string[] => {\n return validatePresetProxy({ __wizard__: presetDef }, buildAuditContext(model)).map((i) => {\n return i.message\n })\n}\n\n/**\n * Opt back into the Orca question: set to exactly `'1'`. The prompt is temporarily off \u2014 the manual\n * branch always runs in-process \u2014 but the derivation below is kept whole for when it returns. `--orca`\n * on the command line is a separate path and stays live either way.\n */\nexport const WIZARD_ORCA_VAR = 'INFRA_KIT_DEV_WIZARD_ORCA'\n\nconst asksOrca = (): boolean => {\n return process.env[WIZARD_ORCA_VAR] === '1'\n}\n\n/**\n * Ask, per selected frontend, an EXPLICIT local/cloud choice for every TWO-OPTION route (its `from`\n * lists both). Single-option routes are auto-picked in the pure mapping, so they are never prompted.\n * The answers are keyed `${app}/ui ${routePath}` to match {@link ManualSelection.sources}; the select's\n * default seeds from the route's declared `default` when it has one.\n */\nconst promptRouteSources = async (\n prompts: WizardPrompts,\n model: WizardModel,\n uiKeys: string[],\n): Promise<Record<string, ProxySource>> => {\n const apps = new Map(\n model.apps.map((a) => {\n return [a.name, a] as const\n }),\n )\n const sources: Record<string, ProxySource> = {}\n\n for (const key of uiKeys) {\n const app = apps.get(key.split('/')[0]!)\n\n for (const backend of app?.backends ?? []) {\n for (const route of backend.routes) {\n if (!route.localCapable || !route.cloudCapable) continue\n\n const answer = await prompts.select({\n message: `\uD83D\uDD00 ${key} ${route.path} \u2192 local or cloud?`,\n choices: [\n { name: 'local (this machine)', value: 'local' },\n { name: 'cloud', value: 'cloud' },\n ],\n default: route.default ?? 'local',\n })\n\n sources[`${key} ${route.path}`] = answer as ProxySource\n }\n }\n }\n\n return sources\n}\n\n/** Look up a frontend route's capability in the model (for the recap's \"only option\" annotation). */\nconst findRouteCap = (model: WizardModel, app: string, routePath: string): RouteCap | undefined => {\n return model.apps\n .find((a) => {\n return a.name === app\n })\n ?.backends.flatMap((b) => {\n return b.routes\n })\n .find((r) => {\n return r.path === routePath\n })\n}\n\n/**\n * Print a one-line-per-route recap of what each frontend route resolved to, so the chosen sources are\n * visible before launch. A single-option route is annotated `(only option)` \u2014 it was auto-picked, not\n * asked. This is in addition to {@link echoManual}'s pasteable `--target` command.\n */\nconst recapSources = (plan: DerivedPlan, model: WizardModel): void => {\n const lines: string[] = []\n\n for (const [key, cfg] of Object.entries(plan.presetDef.apps ?? {})) {\n if (!key.endsWith('/ui') || !cfg.proxy) continue\n\n const app = key.split('/')[0]!\n\n for (const [routePath, source] of Object.entries(cfg.proxy)) {\n const cap = findRouteCap(model, app, routePath)\n const suffix = cap && cap.localCapable && cap.cloudCapable ? '' : ' (only option)'\n\n lines.push(` ${key} ${routePath} \u2192 ${source}${suffix}`)\n }\n }\n\n if (lines.length === 0) return\n logger.info('Resolved routes:')\n for (const line of [...lines].sort()) {\n logger.info(line)\n }\n}\n\n/** The manual-branch flow: frontends + per-route source + env + watch + orca \u2192 audited plan \u2192 recap \u2192 echo. */\nconst runManualBranch = async (prompts: WizardPrompts, model: WizardModel): Promise<WizardResult | null> => {\n if (model.apps.length === 0) {\n logger.warn('No apps discovered to run.')\n\n return null\n }\n\n const selectedTargets = await prompts.checkbox({ message: '\uD83D\uDCE6 Which packages?', choices: buildPartChoices(model) })\n\n if (selectedTargets.length === 0) {\n logger.warn('No packages selected.')\n\n return null\n }\n\n const uiKeys = selectedTargets.filter((t) => {\n return t.endsWith('/ui')\n })\n const sources = await promptRouteSources(prompts, model, uiKeys)\n\n const watch = await prompts.confirm({ message: '\uD83D\uDC40 Rebuild & restart on save (watch)?', default: false })\n const orca = asksOrca()\n ? await prompts.confirm({ message: '\uD83E\uDDE9 Run each app in its own Orca pane?', default: false })\n : false\n\n const selection: ManualSelection = { targets: selectedTargets, sources, watch, orca }\n const plan = deriveManualPlan(selection, model)\n\n if (plan.anyCloudRoute) {\n // A cloud route needs an environment to point at, and the only environments we can offer are those we\n // hold a token for. With none loaded, the `select` below would be handed zero choices and `@inquirer/select`\n // throws `No selectable choices` \u2014 a raw stack on a realistic first-run path (fresh clone, no `env-load`).\n // Back out cleanly with guidance instead, and BEFORE mutating `process.env`, so a refused run leaks nothing.\n if (model.environments.length === 0) {\n logger.warn('\u2601\uFE0F This selection routes to a cloud environment, but no environment token is loaded.')\n logger.warn(' Run `infra-kit env-load` to add one, then re-run the wizard.')\n\n return null\n }\n\n selection.env = await prompts.select({\n message: '\u2601\uFE0F Point cloud routes at which environment?',\n choices: model.environments.map((e) => {\n return { name: e, value: e }\n }),\n })\n process.env[INFRA_KIT_ENV_VAR] = selection.env\n }\n\n const issues = auditManualPlan(plan.presetDef, model)\n\n if (issues.length > 0) {\n logger.warn('\u26A0\uFE0F Proxy audit found issues with this selection:')\n for (const issue of issues) {\n logger.warn(` \u2022 ${issue}`)\n }\n\n return null\n }\n\n recapSources(plan, model)\n echoManual(plan, selection)\n\n // Orca opens one pane per selected API app. `include` picks WHICH apps get a pane; `presetDef` tells\n // each pane exactly which of its parts to run. Without the latter a pane runs `--app=<name>`, which\n // expands to every part the app has \u2014 silently starting a UI the user just unticked.\n const apiApps = plan.targetKeys\n .filter((k) => {\n return k.endsWith('/api')\n })\n .map((k) => {\n return k.split('/')[0]!\n })\n\n // An empty include would collapse to `null` in `normalizeAppInclude` and make Orca run EVERY api app,\n // so an Orca run with no selected backends (e.g. an all-frontend selection) falls back to in-process.\n if (orca && apiApps.length > 0) {\n return { include: apiApps, presetDef: plan.presetDef, watch, orca: true }\n }\n\n if (orca) {\n logger.info('\u2139\uFE0F Orca needs at least one local backend (panes are backend-only) \u2014 running in-process instead.')\n }\n\n return { presetDef: plan.presetDef, watch, orca: false }\n}\n\n/** Print the equivalent (`--target=\u2026`) flag command, plus a save-as-preset ergonomics hint. */\nconst echoManual = (plan: DerivedPlan, selection: ManualSelection): void => {\n commandEcho.setInteractive()\n\n const eq = equivalentCommand(plan, selection)\n\n commandEcho.addOption(eq.flags, true)\n commandEcho.print()\n\n // The `--target=\u2026` line reproduces the selection exactly; the preset is pure convenience \u2014 a short,\n // memorable name instead of retyping the target keys.\n logger.info('\u2139\uFE0F Prefer a short name? Save this selection as a devPreset and run `infra-kit dev <name>`.')\n}\n\n/** The preset-branch flow: run a named preset, asking only whether to watch (presets can't encode it). */\nconst runPresetBranch = async (prompts: WizardPrompts, preset: string): Promise<WizardResult> => {\n const watch = await prompts.confirm({ message: '\uD83D\uDC40 Rebuild & restart on save (watch)?', default: false })\n\n commandEcho.setInteractive()\n commandEcho.addOption(preset, true)\n if (watch) commandEcho.addOption('--watch', true)\n commandEcho.print()\n\n return { preset, watch, orca: false }\n}\n\n/** Sentinel value for the \"Manual (custom)\" step-0 choice (a preset name can never be empty). */\nexport const MANUAL_CHOICE = ' manual'\n\n/**\n * Drive the wizard's branch flow over an ALREADY-gathered model (no disk/config access). Split from\n * {@link runDevWizard} so the flow is unit-testable with scripted prompts + a fixture model.\n */\nexport const runWizardFlow = async (prompts: WizardPrompts, model: WizardModel): Promise<WizardResult | null> => {\n if (model.presets.length === 0) {\n return runManualBranch(prompts, model)\n }\n\n const choice = await prompts.select({\n message: '\uD83D\uDE80 Start from a preset, or configure manually?',\n choices: [\n ...model.presets.map((p) => {\n return { name: p, value: p }\n }),\n new Separator(' '),\n { name: 'Manual (custom)\u2026', value: MANUAL_CHOICE },\n ],\n })\n\n return choice === MANUAL_CHOICE ? runManualBranch(prompts, model) : runPresetBranch(prompts, choice)\n}\n\n/**\n * Gather the model from disk/config, then drive the wizard flow, returning the resolved run options (or\n * null on cancel / empty selection). The entry point calls this on a bare TTY `infra-kit dev`.\n */\nexport const runDevWizard = async (\n prompts: WizardPrompts = defaultPrompts,\n root: string = findMonorepoRoot(process.cwd()),\n): Promise<WizardResult | null> => {\n return runWizardFlow(prompts, await gatherWizardModel(root))\n}\n", "/**\n * Pure core of the interactive `infra-kit dev` wizard (the no-args, TTY path).\n *\n * The wizard is FRONTEND-CENTRIC: you pick which frontends to run, and for each frontend you choose,\n * every proxy route that has TWO real options (its `from` lists both `local` and `cloud`) is decided\n * EXPLICITLY \u2014 local (its backend is launched \u2192 the route resolves local) or cloud (the route proxies\n * to the `<env>` cloud target). Single-option routes are auto-picked. Because a backend runs local OR\n * cloud as a whole, routes that share one backend package RECONCILE: if any of them resolved local, the\n * backend runs local and all its local-capable routes follow. This module turns those answers into an\n * in-memory {@link DevPreset} the runner consumes verbatim (part-level targets the app-name-only `--app`\n * include cannot express) \u2014 and is side-effect-free so the mapping is fully unit-testable. The impure\n * I/O (discovery, inquirer prompts, audit, launch) lives in {@link file://./dev-wizard-run.ts}.\n */\nimport type { DevPreset, ProxySource } from 'src/lib/infra-kit-config'\n\n/**\n * One proxy route's per-route capability, carried through grouping so the wizard can decide whether it\n * even needs to ask about the route (only a `local`+`cloud` route is a real choice).\n */\nexport interface RouteCap {\n /** Route path (e.g. `/api`). */\n path: string\n /** `from` includes `local` \u2014 the route can resolve to a locally-launched backend. */\n localCapable: boolean\n /** `from` includes `cloud` \u2014 the route can resolve to the cloud target. */\n cloudCapable: boolean\n /** The route's declared `default` source when it has one (present iff `from` lists >1 source) \u2014 seeds the prompt's default. */\n default?: ProxySource\n}\n\n/**\n * One backend a frontend's proxy routes can be pointed at, grouped by the backend package. A frontend\n * that maps `/api` and `/media` to the same package yields ONE {@link ProxyBackend} with both routes \u2014\n * launching the package flips every one of its `local`-capable routes together (the reconcile in\n * {@link deriveManualPlan}).\n */\nexport interface ProxyBackend {\n /** Backend package name (a route's `packageName`). */\n packageName: string\n /** The routes that resolve to this package, each with its own local/cloud capability. */\n routes: RouteCap[]\n /** True when at least one of `routes` lists `local` in its `from` capabilities \u2014 i.e. it is launchable-local. */\n localCapable: boolean\n /** True when at least one of `routes` lists `cloud` \u2014 i.e. it can stay on the cloud target. */\n cloudCapable: boolean\n /** App folder whose `api` package is {@link packageName}, or undefined when no discovered app owns it (a `local` choice then has nothing to launch \u2014 the audit flags it). */\n ownerApp?: string\n}\n\n/** A discovered app as the wizard sees it: which parts exist + which backends its frontend proxies to. */\nexport interface WizardApp {\n /** App folder name (e.g. `client`). */\n name: string\n /** Has `apps/<app>/api` (a launchable backend). */\n hasApi: boolean\n /** Has `apps/<app>/ui` (a launchable frontend). */\n hasUi: boolean\n /**\n * This app's OWN `api` package name (from `apps/<app>/api`), or undefined when it has no api. Carried\n * so the audit can build a faithful `app \u2192 apiPackage` map for EVERY discovered api app \u2014 including\n * api-only apps a frontend proxies to cross-app \u2014 mirroring the root audit (`preset-proxy-check.ts`).\n */\n apiPackage?: string\n /** Backends this app's frontend proxies to (empty for api-only apps or a frontend with no `dev.proxy`). */\n backends: ProxyBackend[]\n}\n\n/** Everything the wizard needs, gathered impurely by {@link file://./dev-wizard-run.ts}. */\nexport interface WizardModel {\n /** All discovered apps (api and/or ui), sorted by name. */\n apps: WizardApp[]\n /** `devServersPresets` names (drives the preset-or-manual step-0). */\n presets: string[]\n /** Configured `environments` (the cloud-env `select` options). */\n environments: string[]\n}\n\n/** The manual-branch answers collected from the prompts, fed to {@link deriveManualPlan}. */\nexport interface ManualSelection {\n /**\n * The target keys the user ticked directly: every selected `<app>/ui` frontend, plus any api-only\n * `<app>/api` backend (apps with an api but no ui). A full-stack backend is NOT ticked here \u2014 it is\n * launched by choosing `local` for one of its frontend's routes (recorded in {@link sources}).\n */\n targets: string[]\n /**\n * Explicit per-route choice for every TWO-OPTION route, keyed `${app}/ui ${routePath}` (e.g.\n * `client/ui /api`). Single-option routes are absent (auto-picked). Missing two-option answers fall\n * back to the route's cloud/local capability in {@link deriveManualPlan}.\n */\n sources: Record<string, ProxySource>\n /** Chosen cloud env for cloud routes (undefined when nothing resolves cloud). */\n env?: string\n /** Rebuild + restart on save. */\n watch: boolean\n /** One Orca pane per app. */\n orca: boolean\n}\n\n/** The resolved run plan derived from a {@link ManualSelection}. */\nexport interface DerivedPlan {\n /** In-memory preset handed to the runner (`options.presetDef`). */\n presetDef: DevPreset\n /** At least one route resolves to cloud \u2192 an env must be chosen (pre-flight gate). */\n anyCloudRoute: boolean\n /** Resolved `<app>/<part>` target keys, sorted \u2014 for the echo + audit display. */\n targetKeys: string[]\n}\n\n/** App folder name from an `<app>/<part>` target key. */\nconst appOf = (key: string): string => {\n return key.split('/')[0]!\n}\n\n/** Index a model's apps by folder name for O(1) lookup. */\nconst byName = (model: WizardModel): Map<string, WizardApp> => {\n return new Map(\n model.apps.map((a) => {\n return [a.name, a]\n }),\n )\n}\n\n/** Is this route a real choice (both local and cloud reachable)? */\nconst isTwoOption = (route: RouteCap): boolean => {\n return route.localCapable && route.cloudCapable\n}\n\n/**\n * The source a single route resolves to BEFORE per-backend reconciliation:\n * - two-option: the user's recorded answer, else 'cloud' when cloud-capable else 'local';\n * - single local-only: always 'local';\n * - single cloud-only: always 'cloud'.\n */\nconst rawSource = (uiKey: string, route: RouteCap, sources: Record<string, ProxySource>): ProxySource => {\n if (isTwoOption(route)) {\n return sources[`${uiKey} ${route.path}`] ?? (route.cloudCapable ? 'cloud' : 'local')\n }\n\n return route.localCapable ? 'local' : 'cloud'\n}\n\n/**\n * Pass 1: which backend packages resolve local (any of their routes did), plus each package's owner app.\n * A package's local verdict is shared across every frontend that proxies to it \u2014 that is the reconcile.\n */\nconst collectLocalPackages = (\n uiKeys: string[],\n apps: Map<string, WizardApp>,\n sources: Record<string, ProxySource>,\n): { localPkgs: Set<string>; ownerByPkg: Map<string, string | undefined> } => {\n const localPkgs = new Set<string>()\n const ownerByPkg = new Map<string, string | undefined>()\n\n for (const key of uiKeys) {\n const app = apps.get(appOf(key))\n\n for (const backend of app?.backends ?? []) {\n ownerByPkg.set(backend.packageName, backend.ownerApp)\n for (const route of backend.routes) {\n if (rawSource(key, route, sources) === 'local') localPkgs.add(backend.packageName)\n }\n }\n }\n\n return { localPkgs, ownerByPkg }\n}\n\n/**\n * Pass 2 for ONE frontend: its per-route overrides after the per-package verdict, and whether any route\n * went cloud. A local-capable route on a local package is `local` (reconciled up); everything else `cloud`.\n */\nconst frontendOverrides = (\n app: WizardApp | undefined,\n localPkgs: ReadonlySet<string>,\n): { overrides: Record<string, ProxySource>; anyCloud: boolean } => {\n const overrides: Record<string, ProxySource> = {}\n let anyCloud = false\n\n for (const backend of app?.backends ?? []) {\n const backendLocal = localPkgs.has(backend.packageName)\n\n for (const route of backend.routes) {\n const source: ProxySource = route.localCapable && backendLocal ? 'local' : 'cloud'\n\n overrides[route.path] = source\n if (source === 'cloud') anyCloud = true\n }\n }\n\n return { overrides, anyCloud }\n}\n\n/**\n * Turn the manual {@link ManualSelection} into an in-memory {@link DevPreset}. The frontend checkbox picks\n * which UIs (and standalone api-only backends) to run; the per-route answers in {@link ManualSelection.sources}\n * decide each two-option route. Resolution is two passes so same-backend routes stay coherent:\n *\n * 1. Resolve every route of every selected frontend to its raw source; a package is LOCAL iff any of its\n * routes resolved local.\n * 2. Re-resolve each route against that per-package verdict: a local-capable route on a local package is\n * `local` (reconciled up even if it was individually answered cloud); a cloud-only route stays `cloud`.\n *\n * Launched backends are the ticked api-only parts \u222A every package that resolved local (added as\n * `${ownerApp}/api` when the owner is discoverable \u2014 a local override on an owner-less package is still\n * emitted, and the audit flags it).\n *\n * @example\n * // client frontend, its /api answered local \u2192 launches client/api + client/ui, /api resolves local:\n * deriveManualPlan(\n * { targets: ['client/ui'], sources: { 'client/ui /api': 'local' }, watch: false, orca: false },\n * { apps: [{ name: 'client', hasApi: true, hasUi: true, backends: [{ packageName: 'client-api',\n * cloudCapable: true, localCapable: true, ownerApp: 'client',\n * routes: [{ path: '/api', localCapable: true, cloudCapable: true }] }] }],\n * presets: [], environments: ['dev'] },\n * ).targetKeys // => ['client/api', 'client/ui']\n */\nexport const deriveManualPlan = (selection: ManualSelection, model: WizardModel): DerivedPlan => {\n const apps = byName(model)\n const uiKeys = selection.targets.filter((t) => {\n return t.endsWith('/ui')\n })\n const apiOnlyKeys = selection.targets.filter((t) => {\n return t.endsWith('/api')\n })\n\n // Pass 1: a package is local iff any of its routes (across every selected frontend) resolved local.\n const { localPkgs, ownerByPkg } = collectLocalPackages(uiKeys, apps, selection.sources)\n\n // Pass 2: re-resolve each route against the per-package verdict + build per-frontend overrides.\n const presetApps: Record<string, { proxy?: Record<string, ProxySource> }> = {}\n let anyCloud = false\n\n for (const key of uiKeys) {\n const { overrides, anyCloud: cloud } = frontendOverrides(apps.get(appOf(key)), localPkgs)\n\n if (cloud) anyCloud = true\n presetApps[key] = Object.keys(overrides).length > 0 ? { proxy: overrides } : {}\n }\n\n // Launch: the ticked api-only backends, plus every package that resolved local (via its owner app).\n for (const key of apiOnlyKeys) {\n presetApps[key] ??= {}\n }\n for (const pkg of localPkgs) {\n const owner = ownerByPkg.get(pkg)\n\n if (owner != null) presetApps[`${owner}/api`] ??= {}\n }\n\n return {\n presetDef: { apps: presetApps, orca: selection.orca },\n anyCloudRoute: anyCloud,\n targetKeys: Object.keys(presetApps).sort(),\n }\n}\n\n/** The equivalent non-interactive command for a derived plan. */\nexport interface EquivalentCommand {\n /** The `--target=<app>/<part>,\u2026`-form flag string (no leading `infra-kit dev`). */\n flags: string\n}\n\n/**\n * Build the equivalent `infra-kit dev --target=\u2026 [--watch] [--orca]` flag string for a derived plan.\n * Always exact: `--target` names packages at `<app>/<part>` granularity \u2014 the same grammar the plan's\n * `targetKeys` already use \u2014 so every wizard selection, whole-app or part-level, round-trips into a\n * pasteable command. (`--app` is deliberately NOT used here: its app-name granularity over-launches a\n * part-level pick \u2014 `--app=client` starts `client/api` even when only `client/ui` was ticked.)\n */\nexport const equivalentCommand = (plan: DerivedPlan, selection: ManualSelection): EquivalentCommand => {\n const parts = [`--target=${plan.targetKeys.join(',')}`]\n\n if (selection.watch) parts.push('--watch')\n if (selection.orca) parts.push('--orca')\n\n return { flags: parts.join(' ') }\n}\n"],
5
- "mappings": "qOASA,OAAOA,MAAsB,qBAC7B,OAAOC,MAAqB,oBAC5B,OAAOC,GAAkB,aAAAC,MAAiB,mBAC1C,OAAS,WAAAC,MAAe,mCACxB,OAAOC,MAAU,YACjB,OAAOC,MAAa,eCgGpB,IAAMC,EAASC,GACNA,EAAI,MAAM,GAAG,EAAE,CAAC,EAInBC,EAAUC,GACP,IAAI,IACTA,EAAM,KAAK,IAAKC,GACP,CAACA,EAAE,KAAMA,CAAC,CAClB,CACH,EAIIC,EAAeC,GACZA,EAAM,cAAgBA,EAAM,aAS/BC,EAAY,CAACC,EAAeF,EAAiBG,IAC7CJ,EAAYC,CAAK,EACZG,EAAQ,GAAGD,CAAK,IAAIF,EAAM,IAAI,EAAE,IAAMA,EAAM,aAAe,QAAU,SAGvEA,EAAM,aAAe,QAAU,QAOlCI,EAAuB,CAC3BC,EACAC,EACAH,IAC4E,CAC5E,IAAMI,EAAY,IAAI,IAChBC,EAAa,IAAI,IAEvB,QAAWb,KAAOU,EAAQ,CACxB,IAAMI,EAAMH,EAAK,IAAIZ,EAAMC,CAAG,CAAC,EAE/B,QAAWe,KAAWD,GAAK,UAAY,CAAC,EAAG,CACzCD,EAAW,IAAIE,EAAQ,YAAaA,EAAQ,QAAQ,EACpD,QAAWV,KAASU,EAAQ,OACtBT,EAAUN,EAAKK,EAAO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MC,EAAKC,EAAkBpB,EAAMU,CAAS,EAE5CQ,EAAY,UAAUC,EAAG,MAAO,EAAI,EACpCD,EAAY,MAAM,EAIlBjE,EAAO,KAAK,uGAA6F,CAC3G,EAGMoE,GAAkB,MAAO9B,EAAwB+B,IAA0C,CAC/F,IAAMd,EAAQ,MAAMjB,EAAQ,QAAQ,CAAE,QAAS,+CAAyC,QAAS,EAAM,CAAC,EAExG,OAAA2B,EAAY,eAAe,EAC3BA,EAAY,UAAUI,EAAQ,EAAI,EAC9Bd,GAAOU,EAAY,UAAU,UAAW,EAAI,EAChDA,EAAY,MAAM,EAEX,CAAE,OAAAI,EAAQ,MAAAd,EAAO,KAAM,EAAM,CACtC,EAGae,EAAgB,UAMhBC,GAAgB,MAAOjC,EAAwBlB,IAAqD,CAC/G,GAAIA,EAAM,QAAQ,SAAW,EAC3B,OAAOgC,EAAgBd,EAASlB,CAAK,EAGvC,IAAMoD,EAAS,MAAMlC,EAAQ,OAAO,CAClC,QAAS,wDACT,QAAS,CACP,GAAGlB,EAAM,QAAQ,IAAKqD,IACb,CAAE,KAAMA,EAAG,MAAOA,CAAE,EAC5B,EACD,IAAIC,EAAU,GAAG,EACjB,CAAE,KAAM,wBAAoB,MAAOJ,CAAc,CACnD,CACF,CAAC,EAED,OAAOE,IAAWF,EAAgBlB,EAAgBd,EAASlB,CAAK,EAAIgD,GAAgB9B,EAASkC,CAAM,CACrG,EAMaG,GAAe,MAC1BrC,EAAyB1D,EACzBsB,EAAe0E,EAAiBjG,EAAQ,IAAI,CAAC,IAEtC4F,GAAcjC,EAAS,MAAMrC,EAAkBC,CAAI,CAAC",
6
- "names": ["inquirerCheckbox", "inquirerConfirm", "inquirerSelect", "Separator", "loadDev", "path", "process", "appOf", "key", "byName", "model", "a", "isTwoOption", "route", "rawSource", "uiKey", "sources", "collectLocalPackages", "uiKeys", "apps", "localPkgs", "ownerByPkg", "app", "backend", "frontendOverrides", "overrides", "anyCloud", "backendLocal", "source", "deriveManualPlan", "selection", "t", "apiOnlyKeys", "presetApps", "cloud", "pkg", "owner", "equivalentCommand", "plan", "parts", "promptContext", "process", "defaultPrompts", "cfg", "withEscape", "context", "inquirerSelect", "inquirerCheckbox", "inquirerConfirm", "groupBackends", "routes", "ownerByPkg", "byPkg", "route", "def", "cap", "existing", "loadBackends", "uiDir", "name", "loadDev", "error", "logger", "gatherWizardModel", "root", "apiApps", "discoverApiApps", "uiApps", "discoverUiApps", "config", "getInfraKitConfig", "a", "apiPkgByName", "uiNames", "apiNames", "allNames", "apps", "hasUi", "path", "store", "readTokenStore", "buildPartChoices", "model", "choices", "app", "paths", "b", "r", "description", "buildAuditContext", "discovered", "apiPkgByApp", "routeToPkg", "auditManualPlan", "presetDef", "validatePresetProxy", "i", "WIZARD_ORCA_VAR", "asksOrca", "promptRouteSources", "prompts", "uiKeys", "sources", "key", "backend", "answer", "findRouteCap", "routePath", "recapSources", "plan", "lines", "source", "suffix", "line", "runManualBranch", "selectedTargets", "t", "watch", "orca", "selection", "deriveManualPlan", "e", "INFRA_KIT_ENV_VAR", "issues", "issue", "echoManual", "k", "commandEcho", "eq", "equivalentCommand", "runPresetBranch", "preset", "MANUAL_CHOICE", "runWizardFlow", "choice", "p", "Separator", "runDevWizard", "findMonorepoRoot"]
7
- }
package/dist/mcp.js DELETED
@@ -1,3 +0,0 @@
1
- import{R as J,U as X,a as w,d as x,ea as Z,ha as Y,t as W}from"./chunk-FWINBDB5.js";import{g as z,i as B}from"./chunk-75BE6MSY.js";import"./chunk-X2HFNQRU.js";import{$ as V,N as R,O as U,P as s,d as q}from"./chunk-H5AAXCRJ.js";import"./chunk-GRWUCPQL.js";import{a as K}from"./chunk-MFAFQVTW.js";import{l as H}from"./chunk-IXWQ7EQT.js";import"./chunk-HHWP3YXW.js";import{a as M,b as $,d as h,l as j,n as L,o as S,q as G}from"./chunk-75URROMU.js";import"./chunk-QWVLAZ6N.js";import{serveStdio as Cn}from"@modelcontextprotocol/server/stdio";import v from"node:process";import{setTimeout as vn}from"node:timers/promises";import g from"node:process";var Q=e=>{g.on("uncaughtException",n=>{e.fatal({err:n,msg:"Uncaught Exception"}),e.error(`Uncaught Exception! Check ${R}. Shutting down...`),e.flush(),g.exit(1)}),g.on("unhandledRejection",(n,o)=>{e.fatal({reason:n,promise:o,msg:"Unhandled Rejection"}),e.error(`Unhandled Rejection! Check ${R}. Shutting down...`),e.flush(),g.exit(1)})};import{McpServer as gn}from"@modelcontextprotocol/server";var Ae="infra-kit://config",Pe="infra-kit://dev-context",Fe="infra-kit://workflow/session",_e=["This procedure moved to the `/infra-kit:session` skill; update the plugin.","Meanwhile: no token \u2192 call `env-load` without `config`; the human's pick is the load.","On a tool error or a refused result naming `config`, call `env-list` and list every row in prose, then ask."].join(`
2
- `),Oe={loadConfig:V,readDevContext:()=>x()},T=(e,n)=>({contents:[{uri:e,mimeType:"application/json",text:JSON.stringify(n,null,2)}]}),ee=async(e,n=Oe)=>{e.registerResource("infra-kit-config",Ae,{title:"infra-kit config",description:"The merged infra-kit.json configuration (all override layers applied). Read-only.",mimeType:"application/json"},async o=>{try{return T(o.toString(),await n.loadConfig())}catch(r){return T(o.toString(),{error:r instanceof Error?r.message:String(r)})}}),e.registerResource("infra-kit-dev-context",Pe,{title:"infra-kit dev context",description:"What `infra-kit dev` last wrote: backends currently up, their ports/origins, and fragment freshness. Read-only and advisory (no liveness probe). No active session resolves to an empty payload.",mimeType:"application/json"},o=>T(o.toString(),n.readDevContext())),e.registerResource("infra-kit-workflow-session",Fe,{title:"session procedure (moved)",description:"Retired: the session procedure now lives in the /infra-kit:session plugin skill. Update the plugin.",mimeType:"text/markdown"},o=>({contents:[{uri:o.toString(),mimeType:"text/markdown",text:_e}]}))};import{CLIENT_CAPABILITIES_META_KEY as mn}from"@modelcontextprotocol/server";import{z as I}from"zod";import{createRequestStateCodec as Ie}from"@modelcontextprotocol/server";import{randomBytes as Ne}from"node:crypto";var Me=new Set(["confirm","confirmToken"]),$e=600,ne=e=>({toolName:e}),E=e=>{if(Array.isArray(e))return e.map(E);if(e!==null&&typeof e=="object"){let n=e;return Object.fromEntries(Object.keys(n).sort().map(o=>[o,E(n[o])]))}return e},b=e=>JSON.stringify(E(e)),u=e=>typeof e!="object"||e===null?{}:Object.fromEntries(Object.entries(e).filter(([n])=>!Me.has(n))),re=(e={})=>{let n=Ie({key:e.key??Ne(32),ttlSeconds:e.ttlSeconds??$e,bind:o=>o.toolName});return{mint:(o,r)=>n.mint(o,ne(r)),verify:(o,r)=>n.verify(o,ne(r))}},oe,te=()=>(oe??=re(),oe),je=e=>{if(typeof e!="object"||e===null)return;let{confirmToken:n}=e;return typeof n=="string"?n:void 0},Le=new Set(["malformed","mac","expired","bind"]),Ge=e=>{let n=e instanceof Error?e.message:"";return Le.has(n)?n:"malformed"},ie=async(e,n,o)=>e.mint({args:b(u(o))},n),se=async(e,n,o)=>{let r=je(o);if(r===void 0)return{ok:!1,reason:"absent"};let t;try{t=await e.verify(r,n)}catch(i){return{ok:!1,reason:Ge(i)}}return t.args!==b(u(o))?{ok:!1,reason:"mismatch"}:{ok:!0}};import qe from"node:fs";import ae from"node:path";import m from"node:process";var me=new Set([...K,h,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),fe=null,C=new Set,D=null,ce=!1;var ue=e=>{try{return qe.statSync(e)}catch{return null}},Ue=()=>{if(ce)return null;try{return G()}catch{return ce=!0,s.warn(`session-env: ${h} unset \u2014 no overlay`),null}},He=e=>{let n=ae.join(e,M),o=ae.join(e,$),r=ue(n),t=ue(o);return r&&!(t&&t.mtimeMs>r.mtimeMs)?{kind:"load",file:n,signature:`load:${r.ino}:${r.mtimeMs}:${r.size}`}:t?{kind:"clear",file:o,signature:`clear:${t.ino}:${t.mtimeMs}`}:{kind:"none",signature:"none"}},Ke=e=>e.kind==="load"?{kind:"load",vars:L(e.file),unset:S(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:S(e.file),signature:e.signature}:e;var Ve=()=>{let e=Ue();if(e===null)return{kind:"no-session"};let n=He(e);return n.signature===D?null:Ke(n)},ze=()=>{for(let e of C){let n=fe[e];n===void 0?delete m.env[e]:m.env[e]=n}C.clear()},le=(e,n,o)=>{if(me.has(n)){e.skipped.push(n);return}m.env[n]=o,C.add(n),e.set.push(n)},de=(e,n)=>{if(me.has(n)){e.skipped.push(n);return}delete m.env[n],C.add(n),e.unset.push(n)},Be=e=>{let n={set:[],unset:[],skipped:[]};if(e.kind==="load"){for(let[o,r]of Object.entries(e.vars))le(n,o,r);for(let o of e.unset)de(n,o)}if(e.kind==="clear"){for(let o of e.unset)de(n,o);le(n,j,"1")}return n},We=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,A=(e=Ve())=>{if(fe??={...m.env},e===null||e.kind==="no-session"||e.signature===D)return{set:[],unset:[],changed:!1};ze();let{set:n,unset:o,skipped:r}=Be(e);return D=e.signature,r.length>0&&s.warn(`session-env: skipped protected names [${r.join(", ")}]`),s.info(`session-env applied: set [${n.join(", ")}] unset [${o.join(", ")}] (${We(e)})`),{set:n,unset:o,changed:!0}};import{acceptedContent as Je,inputRequired as pe,inputResponse as Xe}from"@modelcontextprotocol/server";var P="args",Ce=3e3,ve=e=>{let n=Xe(e,P);return n.kind==="elicit"?n.action:"missing"},ye=async(e,n,o)=>{try{return await J(e.buildRequestedSchema(n),o)}catch{return null}},ke=async(e,n,o)=>{let r=await ye(e,n,o);if(r===null)return null;try{return pe({inputRequests:{[P]:pe.elicit({message:e.message,requestedSchema:r})}})}catch{return null}},F=async(e,n,o,r)=>{let t=await ye(e,n,r);if(t===null)return null;let i;try{i=Je(o,P,t)}catch{return null}if(i===void 0)return null;try{return e.toArgs(i,n)}catch{return null}},ge=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_=(e,n)=>{if(!ge(e))return!1;if(!ge(n))return!0;for(let[o,r]of Object.entries(e)){if(!(o in n))return!0;let t=n[o];if(Array.isArray(r)&&(!Array.isArray(t)||t.length!==r.length))return!0}return!1};var Ze=e=>typeof e=="object"&&e!==null&&e.confirm===!0,Ye=e=>e.gated&&!e.confirmed&&e.responses===void 0&&e.canForm&&e.hasProvider&&e.formable?"form":e.gated&&!e.confirmed&&e.responses!==void 0&&!e.accepted?"declined":e.gated&&!e.confirmed&&(e.responses===void 0||e.accepted)?"gate":e.gated&&e.confirmed?"verify":!e.gated&&e.responses===void 0&&e.canForm&&e.hasProvider&&e.formable?"form":!e.gated&&e.responses!==void 0&&e.hasProvider&&!e.accepted?"declined":!e.gated&&e.responses!==void 0&&e.hasProvider&&e.accepted?"run-form":"run",p=e=>({content:w(JSON.stringify(e,null,2)),structuredContent:e,isError:!0}),Qe="The values you submitted in the form could NOT be applied and were DISCARDED \u2014 they failed validation or narrowed the arguments \u2014 so the arguments shown above are the ORIGINAL ones, not your selection.",en="This tool does not prompt for its arguments; you are being asked to approve the values shown above.",nn=async(e,n,o,r)=>{let t=u(o),i=await ie(e,n,o),d=[r.formDiscarded?Qe:void 0,`${n} mutates external state and is gated. It was NOT executed. Re-call ${n} with the same arguments plus "confirm": true and this "confirmToken" to execute.`,r.hasProvider?void 0:en].filter(y=>y!==void 0).join(" ");return p({status:"confirmation_required",tool:n,resolvedArgs:t,confirmToken:i,formDiscarded:r.formDiscarded,message:d})},on=(e,n)=>p({status:"form_declined",tool:e,action:n,message:`${e} was NOT executed: the argument form came back as "${n}". No confirmation is pending \u2014 call ${e} again to start over.`}),rn={validation:"failed validation",narrowed:"narrowed the arguments"},he=(e,n)=>p({status:"form_discarded",tool:e,reason:n,message:`${e} was NOT executed: the values you submitted in the form ${rn[n]} and were DISCARDED. No confirmation is pending \u2014 call ${e} again to start over.`}),tn={absent:'no "confirmToken" was supplied',malformed:'the "confirmToken" is malformed',mac:'the "confirmToken" was not issued by this server',expired:'the "confirmToken" has expired',bind:'the "confirmToken" was issued for a different tool',mismatch:'the arguments differ from the ones the "confirmToken" was issued for'},sn=(e,n)=>p({status:"confirmation_refused",tool:e,reason:n,message:`${e} was NOT executed: ${tn[n]}. Call ${e} again WITHOUT "confirm" to receive a fresh gate, then re-call with the same arguments plus "confirm": true and the returned "confirmToken".`}),Se=e=>{try{return e()}catch{return!1}},an=async(e,n,o,r)=>{let t=e.formProvider;if(t===void 0||r!=="accept")return{params:n,formDiscarded:!1};let i=await F(t,n,o,e.formDeadlineMs);return i===null?(s.info({msg:`Tool execution form discarded (validation): ${e.toolName}`}),{params:n,formDiscarded:!0}):_(u(n),i)?(s.info({msg:`Tool execution form discarded (narrowed): ${e.toolName}`}),{params:n,formDiscarded:!0}):{params:i,formDiscarded:!1}},l=e=>({kind:"stop",result:e}),f=e=>({kind:"run",params:e}),Re=async(e,n,o,r)=>{let t=await an(e,n,o,r);return s.info({msg:`Tool execution gated (awaiting confirm): ${e.toolName}`}),await nn(e.codec,e.toolName,t.params,{formDiscarded:t.formDiscarded,hasProvider:e.formProvider!==void 0})},cn=async(e,n,o,r,t)=>{let i=e.formProvider===void 0?null:await ke(e.formProvider,n,e.formDeadlineMs);return i!==null?(s.info({msg:`Tool execution form requested: ${e.toolName}`}),l(i)):(s.info({msg:`Tool execution form unavailable: ${e.toolName}`}),t?l(await Re(e,n,o,r)):f(n))},un=async(e,n,o)=>{let r=e.formProvider;if(r===void 0)return f(n);let t=await F(r,n,o,e.formDeadlineMs);return t===null?(s.info({msg:`Tool execution form discarded (validation): ${e.toolName}`}),l(he(e.toolName,"validation"))):_(u(n),t)?(s.info({msg:`Tool execution form discarded (narrowed): ${e.toolName}`}),l(he(e.toolName,"narrowed"))):(s.info({msg:`Tool execution form accepted: ${e.toolName}`}),f(t))},ln=async(e,n)=>{let o=await se(e.codec,e.toolName,n);return o.ok?f(n):(s.info({msg:`Tool execution refused (${o.reason}): ${e.toolName}`}),l(sn(e.toolName,o.reason)))},dn=async(e,n,o)=>{let r=o?.mcpReq?.inputResponses,t=ve(r),i=e.requiresHumanConfirm===!0,d=Ye({gated:i,confirmed:Ze(n),responses:r,canForm:Se(()=>e.getClientCapabilities?.(o)?.elicitation?.form!==void 0),hasProvider:e.formProvider!==void 0,formable:Se(()=>e.formProvider?.isFormable(n)===!0),accepted:t==="accept"});switch(d){case"run":return f(n);case"declined":return s.info({msg:`Tool execution form declined (${t}): ${e.toolName}`}),l(on(e.toolName,t));case"verify":return await ln(e,n);case"run-form":return await un(e,n,r);case"form":return await cn(e,n,r,t,i);case"gate":return l(await Re(e,n,r,t));default:return X(d)}},O=({toolName:e,handler:n,requiresHumanConfirm:o,formProvider:r,getClientCapabilities:t,confirmCodec:i,formDeadlineMs:d,applySessionEnv:y=A})=>{let be={toolName:e,codec:i??te(),requiresHumanConfirm:o,formProvider:r,getClientCapabilities:t,formDeadlineMs:d??Ce};return async(k,N)=>{s.info({msg:`Tool execution started: ${e}`,params:k,sessionId:N?.sessionId});try{await W(),z.reset(),y();let a=await dn(be,k,N);if(a.kind==="stop")return a.result;let De=await n({...a.params,confirmedCommand:!0});return s.info({msg:`Tool execution successful: ${e}`}),De}catch(a){if(s.error({err:a,params:k,msg:`Tool execution failed: ${e}`}),a instanceof B)return{...p(a.structuredContent),content:w(a.message)};throw a}}};var we=async e=>{for(let n of Z())e.registerTool(n.name,{title:n.title,description:n.description,inputSchema:I.object(n.requiresHumanConfirm===!0?fn(n.inputSchema):n.inputSchema),outputSchema:I.object(n.outputSchema),annotations:n.annotations,_meta:n.meta},pn(O({toolName:n.name,handler:n.handler,requiresHumanConfirm:n.requiresHumanConfirm,formProvider:n.formProvider,getClientCapabilities:o=>o?.mcpReq?.envelope?.[mn]??e.server.getClientCapabilities()})))},fn=e=>({...e,confirmToken:I.string().optional().describe("Round-2 only: the token returned by the round-1 gate, proving the arguments are unchanged.")}),pn=e=>(n,o)=>e(n,o);async function xe(){q.source="mcp";let e=new gn({name:"infra-kit",version:H.version},{capabilities:{resources:{listChanged:!0},tools:{}}});return await ee(e),await we(e),e}Y();var c=U(),yn=async()=>{try{return await xe()}catch(e){c.error({err:e,msg:"Failed to create MCP server"}),c.flush(),v.exit(1)}};Q(c);var kn=Cn(yn,{onerror:e=>{c.error({err:e,msg:"MCP stdio entry error"}),c.flush()}});c.info({msg:"MCP stdio entry started."});var Te=!1,Ee=async e=>{if(!Te){Te=!0,c.info({msg:`Received ${e}. Shutting down...`});try{await Promise.race([kn.close(),vn(1500)])}catch(n){c.error({err:n,msg:"MCP stdio close failed during shutdown"})}c.flush(),v.exit(0)}};v.on("SIGINT",()=>{Ee("SIGINT")});v.on("SIGTERM",()=>{Ee("SIGTERM")});
3
- //# sourceMappingURL=mcp.js.map