infra-kit 0.8.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 (43) 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-OPL7C5H6.js +10 -0
  12. package/dist/{chunk-AOWMCNYY.js.map → chunk-OPL7C5H6.js.map} +4 -4
  13. package/dist/chunk-WUTG6VMP.js +7 -0
  14. package/dist/chunk-WUTG6VMP.js.map +7 -0
  15. package/dist/{chunk-6OFUVD7F.js → chunk-YYC3QGGC.js} +2 -2
  16. package/dist/chunk-YYC3QGGC.js.map +7 -0
  17. package/dist/cli.js +457 -13
  18. package/dist/cli.js.map +4 -4
  19. package/dist/dev-server.js +19 -19
  20. package/dist/dev-server.js.map +4 -4
  21. package/dist/dev-wizard-run-ITRFKMTL.js +2 -0
  22. package/dist/dev-wizard-run-ITRFKMTL.js.map +7 -0
  23. package/dist/mcp-proxy.js +1 -1
  24. package/dist/update-check.js +1 -1
  25. package/dist/update-check.js.map +1 -1
  26. package/package.json +3 -7
  27. package/readme.md +1 -2
  28. package/dist/boot-BL4EQMZV.js.map +0 -7
  29. package/dist/chunk-5XK34MWH.js +0 -442
  30. package/dist/chunk-5XK34MWH.js.map +0 -7
  31. package/dist/chunk-6OFUVD7F.js.map +0 -7
  32. package/dist/chunk-75URROMU.js +0 -4
  33. package/dist/chunk-AEVL5XWO.js +0 -3
  34. package/dist/chunk-AEVL5XWO.js.map +0 -7
  35. package/dist/chunk-AOWMCNYY.js +0 -10
  36. package/dist/chunk-BVEVERTB.js +0 -7
  37. package/dist/chunk-BVEVERTB.js.map +0 -7
  38. package/dist/chunk-GCX3HDDL.js +0 -9
  39. package/dist/chunk-GCX3HDDL.js.map +0 -7
  40. package/dist/dev-wizard-run-RPZOX53B.js +0 -2
  41. package/dist/dev-wizard-run-RPZOX53B.js.map +0 -7
  42. package/dist/mcp.js +0 -3
  43. package/dist/mcp.js.map +0 -7
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/lib/install-manager/install-manager.ts", "../src/lib/install-manager/safe-realpath.ts", "../src/lib/install-manager/npm-root.ts", "../src/lib/pm-env/pm-env.ts"],
4
- "sourcesContent": ["/**\n * Pure detection of *how* this CLI was installed, so the background updater knows whether it may act at\n * all, and the advisory it prints can name the one command that will actually work. No fs, no spawn, no `process.env` read \u2014 every input is injected, which is\n * what lets the whole matrix be table-tested.\n *\n * Detection is env-first and LAZY: the only signal that costs a subprocess (`npm root -g`) is passed in\n * as `lazyNpmRoot` and consulted solely when every cheaper matcher has missed.\n */\nimport path from 'node:path'\n\n/** The published package this CLI updates itself to. Single source for every suggested argv. */\nexport const PACKAGE_NAME = 'infra-kit'\n\nconst LATEST = `${PACKAGE_NAME}@latest`\n\nexport type InstallManager = 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | 'homebrew' | 'unknown'\n\nexport interface InstallManagerInfo {\n manager: InstallManager\n /** The command to run. Only safe to spawn ourselves when `canSelfSpawn`; otherwise print it. */\n updateCommand: string[]\n /** False when we must not run the command for the user \u2014 either it needs sudo/a tap, or we guessed. */\n canSelfSpawn: boolean\n}\n\n/**\n * Canonicalises a candidate *root* directory. Required, not optional: `selfRealPath` has already had its\n * symlinks followed, so comparing it against a raw `PNPM_HOME`/`npm root -g`/`cwd` compares a resolved\n * path to an unresolved one and silently never matches. macOS is the everyday proof \u2014 `/var` is a symlink\n * to `/private/var`, so a global install under `/var/...` reports `unknown` unless both sides are resolved.\n * Callers inject the real thing; tests inject a stub.\n */\nexport type RealpathFn = (dir: string) => string\n\nexport interface DetectInstallManagerInput {\n /** Fully-resolved (symlinks followed) path to this CLI's entry file. */\n selfRealPath: string\n env: NodeJS.ProcessEnv\n /** Canonicalises each candidate root before comparison. See {@link RealpathFn}. */\n realpath: RealpathFn\n /** `npm root -g`, deferred: invoked at most once, and only when no cheaper matcher hit. */\n lazyNpmRoot?: () => string | undefined\n /**\n * The exact version to install, when the caller has already resolved it. Omitted, the command targets\n * the `latest` dist-tag \u2014 fine to PRINT, unsafe to RUN: see {@link pinSpec}.\n */\n version?: string\n}\n\n/**\n * Swap the `@latest` token for `@<version>`.\n *\n * `pnpm add -g infra-kit@latest` resolves the tag from pnpm's on-disk metadata cache and does not\n * revalidate it when a cached version already satisfies the tag (pnpm 12.3.4, measured: two runs 90+\n * minutes after a publish both reinstalled the stale `latest` while `pnpm view` already reported the new\n * one). The updater had fetched the real latest itself moments earlier, ran the tag command, got exit 0\n * \u2014 nothing was reinstalled \u2014 and recorded `installed`, so the stale binary looked up to date until the\n * next cycle repeated the same no-op. A concrete version the cache has never seen forces the fetch.\n */\nconst pinSpec = (command: string[], version: string | undefined): string[] => {\n if (version === undefined) return command\n\n return command.map((token) => {\n return token === LATEST ? `${PACKAGE_NAME}@${version}` : token\n })\n}\n\n/**\n * Is `child` inside the `parent` subtree? Boundary-aware: a naive `startsWith` would call\n * `/Users/x/pnpm-ish` a child of `/Users/x/pnpm`. `parent` is canonicalised first because it arrives raw\n * from the environment while `child` is already a realpath.\n */\nexport const isWithin = (parent: string, child: string, realpath: RealpathFn): boolean => {\n const rel = path.relative(realpath(path.resolve(parent)), path.resolve(child))\n\n return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)\n}\n\n/** Does `p` contain `name` as a whole path SEGMENT? `/a/node_modules_backup/b` must not match `node_modules`. */\nexport const hasSegment = (p: string, name: string): boolean => {\n return path.resolve(p).split(path.sep).includes(name)\n}\n\n/**\n * Is `p` inside a Homebrew keg belonging to the `name` FORMULA \u2014 i.e. `.../Cellar/<name>/<version>/...`?\n *\n * The formula name is what makes this sound. A bare `Cellar` segment says only \"somewhere under a keg\",\n * and the keg it lands in is routinely someone else's: when npm's global prefix is a node keg\n * (`npm config set prefix \"$(brew --prefix node)\"`, or any keg-only `node@X`), an `npm i -g` package\n * installs to `Cellar/node/<v>/lib/node_modules/<pkg>/...` \u2014 brew has never heard of it, yet the segment\n * is right there. Requiring `<name>` to sit directly after `Cellar` is what separates \"brew installed\n * THIS\" from \"brew installed the runtime that installed this\".\n *\n * Works for both keg layouts, since each is rooted at the formula: a plain formula\n * (`Cellar/infra-kit/1.2.3/bin/infra-kit`) and brew's node-CLI layout\n * (`Cellar/infra-kit/1.2.3/libexec/lib/node_modules/infra-kit/dist/cli.js`). Do NOT try to tell them\n * apart by excluding `node_modules` \u2014 the second one contains it.\n */\nexport const isBrewKegOf = (p: string, name: string): boolean => {\n const segments = path.resolve(p).split(path.sep)\n const cellar = segments.indexOf('Cellar')\n\n return cellar !== -1 && segments[cellar + 1] === name\n}\n\n/**\n * The npm global prefix that owns `binRealPath`, derived from the path ITSELF, or null when the\n * layout is not an npm global one.\n *\n * Matches `<prefix>/lib/node_modules/<packageName>` \u2014 npm's global layout and no other manager's\n * \u2014 requiring BOTH the `lib` parent and our package as the immediate child. Windows global npm has\n * no `lib` segment (`%APPDATA%\\npm\\node_modules`), so this returns null there and detection falls\n * through to `npm root -g`, which is correct on Windows, where there is normally one npm.\n */\n// This is the one signal that cannot point at the wrong tree. Everything else in this module\n// answers \"is this file somewhere inside tool X's directory?\", and containment is not ownership:\n// - `npm root -g` answers for whichever `npm` is first on PATH, which is routinely a DIFFERENT\n// node than the one that installed us (a pnpm/nvm/fnm-managed node, or a node that has since\n// been removed). It then reports a root that does not contain us, every matcher misses, and\n// detection degrades to `unknown` \u2014 a notice printed forever, on the single most common install\n// method. That is the bug this exists to close.\n// - `PNPM_HOME` containment is satisfied by `<PNPM_HOME>/nodejs/<v>/lib/node_modules/<pkg>` (a\n// plain `npm i -g` under a pnpm-managed node), yet `pnpm add -g` installs to\n// `<PNPM_HOME>/global/<v>/...` \u2014 a different directory. That one is worse than a missed update:\n// the install \"succeeds\" while the binary on PATH stays old, silently, with no notice to show\n// for it.\n//\n// Requiring both segments is what makes the match proof rather than a hint. The `lib` requirement\n// is also what keeps a project-local `<repo>/node_modules/<pkg>` out (it has no `lib`), and nesting\n// cannot spoof it: `.../node_modules/foo/node_modules/<pkg>` fails the `lib` test.\nexport const npmPrefixOfPackage = (binRealPath: string, packageName: string): string | null => {\n const segments = path.resolve(binRealPath).split(path.sep)\n const nodeModules = segments.lastIndexOf('node_modules')\n\n if (nodeModules < 2) return null\n if (segments[nodeModules - 1] !== 'lib') return null\n if (segments[nodeModules + 1] !== packageName) return null\n\n // Drop `lib/node_modules/...`; the empty result of a root-level prefix (`/lib/node_modules/...`) is `/`.\n return segments.slice(0, nodeModules - 1).join(path.sep) || path.sep\n}\n\n// The self-scoped reading, kept as the name every call site below already uses. `dependency-registry`\n// asks the same question about OTHER packages (`portless`), which is why the body moved up one level\n// rather than gaining a defaulted parameter \u2014 a default is how the wrong package silently gets probed.\nconst npmPrefixFromSelfPath = (selfRealPath: string): string | null => {\n return npmPrefixOfPackage(selfRealPath, PACKAGE_NAME)\n}\n\n/**\n * `--prefix` is passed EXPLICITLY rather than trusting the ambient one: the whole point of deriving it is\n * that the `npm` we are about to run may default to a different prefix than the one we are installed in.\n * A command-line flag outranks both `npm_config_prefix` and any `.npmrc`, so this targets the tree we\n * actually run from. With `-g`, npm writes `<prefix>/lib/node_modules` and links bins into `<prefix>/bin`.\n */\nconst npmPrefixInstallCommand = (prefix: string): string[] => {\n return ['npm', 'install', '-g', '--prefix', prefix, LATEST]\n}\n\n/**\n * Render argv as a line the user can paste into a shell.\n *\n * A plain `join(' ')` was fine while every token came from a static table; `--prefix <path>` puts a\n * filesystem path in argv, and `/Users/Ada Lovelace/.nvm/...` pasted unquoted is two arguments and a\n * failed install. Single quotes are sound here without escaping because the callers' validation rejects a\n * token containing a quote \u2014 see `SAFE_COMMAND_TOKEN` in src/lib/update-check/auto-update.ts.\n *\n * @example\n * formatUpdateCommand(['npm', 'install', '-g', '--prefix', '/opt/x y', 'infra-kit@latest'])\n * // => \"npm install -g --prefix '/opt/x y' infra-kit@latest\"\n */\nexport const formatUpdateCommand = (command: string[]): string => {\n return command\n .map((token) => {\n return token.includes(' ') ? `'${token}'` : token\n })\n .join(' ')\n}\n\n/** `env[key]` names a directory that contains `selfRealPath`. Absent/empty env var \u2192 no match. */\nconst underEnvDir = (env: NodeJS.ProcessEnv, key: string, selfRealPath: string, realpath: RealpathFn): boolean => {\n const dir = env[key]\n\n return dir != null && dir !== '' && isWithin(dir, selfRealPath, realpath)\n}\n\ninterface Matcher extends Omit<InstallManagerInfo, 'manager'> {\n manager: InstallManager\n test: (input: Required<Pick<DetectInstallManagerInput, 'selfRealPath' | 'env' | 'realpath'>>) => boolean\n}\n\n/**\n * Consulted FIRST, before {@link npmPrefixFromSelfPath}. Both of these legitimately wrap an npm-shaped\n * `lib/node_modules` tree \u2014 volta at `~/.volta/tools/image/node/<v>/lib/node_modules`, brew at\n * `Cellar/<pkg>/<v>/libexec/lib/node_modules` \u2014 so deriving an npm prefix from the path would hijack\n * installs that a wrapper owns and must keep owning.\n */\nconst WRAPPER_MATCHERS: Matcher[] = [\n {\n manager: 'volta',\n // volta owns the shim; `volta install` is the correct tool, not a workaround \u2014 so we may run it.\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'VOLTA_HOME', selfRealPath, realpath) ||\n hasSegment(selfRealPath, '.volta') ||\n hasSegment(selfRealPath, 'volta')\n )\n },\n updateCommand: ['volta', 'install', PACKAGE_NAME],\n canSelfSpawn: true,\n },\n {\n manager: 'homebrew',\n // `brew upgrade` can touch the prefix, relink, and prompt \u2014 never ours to run unattended.\n //\n // Our own keg is the ONLY sound signal \u2014 see `isBrewKegOf`. Two broader tests look plausible\n // and are both wrong, because each answers \"did brew put something here?\" when the question is \"does\n // brew own THIS package?\":\n // - `HOMEBREW_PREFIX` containment: when node comes from brew, npm's global prefix IS\n // $HOMEBREW_PREFIX, so EVERY `npm i -g` package lands under it, unknown to brew.\n // - a bare `Cellar` segment: an npm prefix pointed at a node keg puts packages inside that keg.\n // Either misfire tells macOS users to run `brew upgrade infra-kit` \u2014 a formula that does not exist \u2014\n // and, far worse, makes the background auto-updater bail with `cannot-self-spawn` forever, so the\n // very fix for it can never reach them. Detection runs on the realpath, and a linked brew bin always\n // resolves into its own keg, so the narrow test has no false negatives to trade for this.\n test: ({ selfRealPath }) => {\n return isBrewKegOf(selfRealPath, PACKAGE_NAME)\n },\n updateCommand: ['brew', 'upgrade', PACKAGE_NAME],\n canSelfSpawn: false,\n },\n]\n\n/**\n * Consulted LAST, after {@link npmPrefixFromSelfPath} has had its say. Each of these proves only that we\n * live somewhere inside a tool's directory tree, which is weaker than knowing the layout npm itself\n * created \u2014 see the `PNPM_HOME`/`nodejs` case in that helper's doc for a containment hit whose install\n * command targets the wrong directory.\n */\nconst TREE_MATCHERS: Matcher[] = [\n {\n manager: 'pnpm',\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'PNPM_HOME', selfRealPath, realpath) ||\n (hasSegment(selfRealPath, 'pnpm') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['pnpm', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'bun',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'BUN_INSTALL', selfRealPath, realpath) || hasSegment(selfRealPath, '.bun')\n },\n updateCommand: ['bun', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'yarn',\n test: ({ selfRealPath }) => {\n return (\n hasSegment(selfRealPath, '.yarn') || (hasSegment(selfRealPath, 'yarn') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['yarn', 'global', 'add', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'npm',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'npm_config_prefix', selfRealPath, realpath)\n },\n updateCommand: ['npm', 'install', '-g', LATEST],\n canSelfSpawn: true,\n },\n]\n\nconst NPM_UPDATE_COMMAND = ['npm', 'install', '-g', LATEST]\n\n/**\n * The command to print when nobody has identified this CLI's package manager \u2014 the same guess\n * `detectInstallManager` records for an unrecognised location, pinned to `version`. For a caller that\n * must name a command but has no worker verdict to read (no update cache on an opt-out machine).\n *\n * @example\n * fallbackUpdateCommand('0.8.0') // => ['npm', 'install', '-g', 'infra-kit@0.8.0']\n */\nexport const fallbackUpdateCommand = (version: string): string[] => {\n return pinSpec(NPM_UPDATE_COMMAND, version)\n}\n\n/**\n * Identify the package manager that owns `selfRealPath`.\n *\n * Order, and why it is this one: wrappers that own an npm-shaped tree (volta, brew) first, then the npm\n * prefix DERIVED from our own path, then the env/path containment matchers, then the `npm root -g` probe.\n * The derived prefix sits above containment because it is the only signal that cannot name a directory we\n * do not live in \u2014 see {@link npmPrefixFromSelfPath}.\n *\n * `lazyNpmRoot` is the last resort and is invoked at most once, only after every matcher has missed \u2014 a\n * pnpm or volta install never pays for the subprocess, and neither does any npm global install in the\n * standard layout, which the derived prefix now settles for free. When nothing matches we report `unknown`\n * with an npm command that is a *suggestion only* (`canSelfSpawn: false`): running a guessed global\n * install is worse than printing one.\n *\n * @example\n * detectInstallManager({ selfRealPath: '/Users/x/Library/pnpm/global/5/node_modules/infra-kit/dist/cli.js', env: {} })\n * // => { manager: 'pnpm', updateCommand: ['pnpm', 'add', '-g', 'infra-kit@latest'], canSelfSpawn: true }\n * detectInstallManager({ selfRealPath: '/Users/x/Library/pnpm/global/5/node_modules/infra-kit/dist/cli.js', env: {}, version: '0.5.5' })\n * // => { manager: 'pnpm', updateCommand: ['pnpm', 'add', '-g', 'infra-kit@0.5.5'], canSelfSpawn: true }\n */\nexport const detectInstallManager = (input: DetectInstallManagerInput): InstallManagerInfo => {\n const { selfRealPath, env, realpath, lazyNpmRoot, version } = input\n const detected = detectUnpinned({ selfRealPath, env, realpath, lazyNpmRoot })\n\n return { ...detected, updateCommand: pinSpec(detected.updateCommand, version) }\n}\n\nconst detectUnpinned = (input: DetectInstallManagerInput): InstallManagerInfo => {\n const { selfRealPath, env, realpath, lazyNpmRoot } = input\n const toInfo = (hit: Matcher): InstallManagerInfo => {\n return { manager: hit.manager, updateCommand: hit.updateCommand, canSelfSpawn: hit.canSelfSpawn }\n }\n const matches = ({ test }: Matcher): boolean => {\n return test({ selfRealPath, env, realpath })\n }\n\n const wrapper = WRAPPER_MATCHERS.find(matches)\n\n if (wrapper) return toInfo(wrapper)\n\n const derivedPrefix = npmPrefixFromSelfPath(selfRealPath)\n\n if (derivedPrefix !== null) {\n return { manager: 'npm', updateCommand: npmPrefixInstallCommand(derivedPrefix), canSelfSpawn: true }\n }\n\n const tree = TREE_MATCHERS.find(matches)\n\n if (tree) return toInfo(tree)\n\n const npmRoot = lazyNpmRoot?.()\n\n if (npmRoot != null && npmRoot !== '' && isWithin(npmRoot, selfRealPath, realpath)) {\n return { manager: 'npm', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: true }\n }\n\n return { manager: 'unknown', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: false }\n}\n\n/**\n * Is this CLI running from a *project-local* `node_modules` (as opposed to a global root)?\n *\n * The cwd clause is what does the distinguishing \u2014 BOTH a project install and a global root contain a\n * `/node_modules/` segment (`pnpm root -g` is `~/Library/pnpm/global/5/node_modules`). Without it we\n * would nag every global pnpm user to stop using a local install they do not have.\n *\n * Accepted false-negative: invoked from a subdirectory (cwd `project/apps/x`, deps at\n * `project/node_modules`) this returns false and the advisory stays silent. Under-warning is the safe\n * direction for a best-effort, never-throwing advisory \u2014 do not \"fix\" it by dropping the cwd clause.\n *\n * `cwd` is canonicalised before comparison for the same reason `detectInstallManager` canonicalises its\n * roots: `selfRealPath` is a realpath, and comparing it to an unresolved cwd never matches.\n *\n * @example\n * isLocalNodeModulesInstall('/repo/node_modules/infra-kit/dist/cli.js', '/repo', (p) => p) // => true\n */\nexport const isLocalNodeModulesInstall = (selfRealPath: string, cwd: string, realpath: RealpathFn): boolean => {\n return hasSegment(selfRealPath, 'node_modules') && isWithin(cwd, selfRealPath, realpath)\n}\n\n/** Does this path exist at all \u2014 directory, file, or symlink? Injected so the walk never touches the real disk in tests. */\nexport type ExistsFn = (p: string) => boolean\n\nexport interface IsGlobalInstallInput {\n /** Fully-resolved (symlinks followed) path to this CLI's entry file. */\n selfRealPath: string\n env: NodeJS.ProcessEnv\n /** Canonicalises `home` and every root {@link detectInstallManager} compares against. */\n realpath: RealpathFn\n /** The user's home directory (`os.homedir()`), raw \u2014 canonicalised here before the walk compares it. */\n home: string\n exists: ExistsFn\n}\n\n/** Upper bound on the `.git` walk: deeper than any real install layout, so it only ever guards against a pathological path. */\nconst GIT_WALK_MAX_HOPS = 32\n\n/**\n * Where the `.git` walk starts: the parent of the OUTERMOST `node_modules` segment (`indexOf`, not\n * `lastIndexOf` \u2014 pnpm's `.pnpm/<pkg>@<v>/node_modules/<pkg>` nests two, and the checkout that owns the\n * tree sits above the first). A self path with no `node_modules` at all (a plain brew keg's `bin/`) starts\n * at its own directory, so the walk still inspects every ancestor.\n */\nconst gitWalkStart = (selfRealPath: string): string => {\n const segments = path.resolve(selfRealPath).split(path.sep)\n const outermost = segments.indexOf('node_modules')\n\n if (outermost === -1) return path.dirname(selfRealPath)\n\n return segments.slice(0, outermost).join(path.sep) || path.sep\n}\n\n/** `start` and its ancestors up to but EXCLUDING `homeReal`, bounded \u2014 the directories the `.git` walk may inspect. */\nconst ancestorsBelowHome = (start: string, homeReal: string): string[] => {\n const dirs: string[] = []\n let dir = start\n\n while (dir !== homeReal && dirs.length < GIT_WALK_MAX_HOPS) {\n dirs.push(dir)\n\n const parent = path.dirname(dir)\n\n if (parent === dir) break\n\n dir = parent\n }\n\n return dirs\n}\n\nconst hasGitAncestor = (start: string, homeReal: string, exists: ExistsFn): boolean => {\n return ancestorsBelowHome(start, homeReal).some((dir) => {\n return exists(path.join(dir, '.git'))\n })\n}\n\n/**\n * Is this CLI the machine's *global* install \u2014 the one a root-owned daemon or a system-wide link may be\n * aimed at \u2014 as opposed to a checkout or a project-local dependency? Probe-free: fs + env only, never a\n * subprocess, because it runs on every boot.\n *\n * True iff {@link detectInstallManager} names a manager AND no `.git` entry (directory or file \u2014 a\n * worktree's is a file) exists above the outermost `node_modules`, walking up to but EXCLUDING\n * `realpath(home)`. Never throws: any seam failure reports false, the safe direction for every caller.\n *\n * @example\n * isGlobalInstall({\n * selfRealPath: '/Users/x/Library/pnpm/global/v11/8a83-1/node_modules/.pnpm/infra-kit@0.5.6/node_modules/infra-kit/dist/cli.js',\n * env: { PNPM_HOME: '/Users/x/Library/pnpm' },\n * realpath: (p) => p,\n * home: '/Users/x',\n * exists: (p) => p === '/Users/x/.git',\n * }) // => true \u2014 the only `.git` is $HOME's own, which the walk never inspects\n */\n// Why these two predicates and not the obvious candidates:\n// - Not `canSelfSpawn`: that flag encodes \"may I run an unattended `npm i -g`\", and homebrew is\n// `canSelfSpawn: false` while being unmistakably global \u2014 gating on it would leave a brew install\n// unconverged forever. A global install whose manager cannot be identified in a stripped env (no\n// `PNPM_HOME`, no derivable prefix) reports false: fail-safe, since a skipped write is never wrong and\n// the next shell-run command converges it.\n// - Not `isLocalNodeModulesInstall`: its cwd clause calls every global layout under `$HOME` \"local\" the\n// moment cwd is `$HOME` \u2014 which is exactly the cwd the background updater spawns with, and a plain\n// `cd ~ && infra-kit version` reproduces it. This predicate reads the tree, not the cwd.\n// - Why the `.git` walk at all: the cheap matchers are segment heuristics that also fire on\n// project-local shapes \u2014 a repo with a `volta` path segment, Yarn Berry's `.yarn/unplugged/\u2026`, a\n// checkout cloned under `$PNPM_HOME`, a workspace package literally named `lib` \u2014 and every one of\n// those is a checkout; every checkout has a `.git`, no global root does.\n// - Why `$HOME` is excluded: dotfiles users `git init ~`, and a `~/.git` would refuse the pnpm-global\n// install permanently. Every checkout under `$HOME` (`~/repo/.git`) is still strictly below it.\n// - Why `.git` ONLY, not `pnpm-workspace.yaml`: pnpm 12 writes one INSIDE the global install dir, so\n// that marker would refuse the very install this is for.\nexport const isGlobalInstall = (input: IsGlobalInstallInput): boolean => {\n try {\n const { selfRealPath, env, realpath, home, exists } = input\n\n if (detectInstallManager({ selfRealPath, env, realpath }).manager === 'unknown') return false\n\n return !hasGitAncestor(gitWalkStart(selfRealPath), realpath(path.resolve(home)), exists)\n } catch {\n return false\n }\n}\n\n/**\n * The advisory gate for `warnIfLocalInstall`, pulled out so it is testable without spawning the CLI.\n * Warn only when the install is provably NOT global AND looks project-local: the second clause alone\n * fires on a global pnpm root whenever cwd is `$HOME` (see {@link isGlobalInstall}).\n */\nexport const shouldWarnLocalInstall = (input: IsGlobalInstallInput & { cwd: string }): boolean => {\n const { selfRealPath, cwd, realpath } = input\n\n return !isGlobalInstall(input) && isLocalNodeModulesInstall(selfRealPath, cwd, realpath)\n}\n", "import { realpathSync } from 'node:fs'\nimport path from 'node:path'\n\n/**\n * The impure companion to the pure detection module: canonicalise a directory that may not exist.\n *\n * `realpathSync` throws on a missing path, and candidate roots routinely miss \u2014 `PNPM_HOME` can point at a\n * directory the user never created, `npm root -g` can name a prefix that was removed. A throw there would\n * turn \"we could not identify your install\" into a crash, so an unresolvable path falls back to\n * `path.resolve`, which still normalises `.`/`..` and yields a usable, non-matching absolute path.\n */\nexport const safeRealpath = (dir: string): string => {\n try {\n return realpathSync(dir)\n } catch {\n return path.resolve(dir)\n }\n}\n", "/* eslint-disable sonarjs/no-os-command-from-path */\n/**\n * `npm root -g`, the LAZY fallback for {@link detectInstallManager}.\n *\n * Why it is indispensable: the `npm` matcher keys off `npm_config_prefix`, which npm sets only while npm\n * itself is running. A user who ran `npm i -g infra-kit` months ago and now types `ik` has no such var,\n * so every cheap matcher misses and detection reports `unknown` / `canSelfSpawn: false`. Without this\n * probe the single most common install method can never update itself.\n *\n * Read by the background update worker, and by the `doctor` advisory that names the command a human\n * would run by hand \u2014 one probe so the two can never disagree about who owns the install.\n */\nimport { execFileSync } from 'node:child_process'\nimport process from 'node:process'\n\nconst NPM_ROOT_TIMEOUT_MS = 3_000\n\n/**\n * The global npm root, or undefined when npm is absent, slow, or errors. Costs a subprocess, so\n * `detectInstallManager` invokes it at most once and only after every env/path matcher has missed \u2014 a\n * pnpm or volta install never pays for it.\n *\n * Resolving the user's `npm` from PATH is inherent here: we must ask the very package manager that owns\n * this install where its global root is. Pinning an absolute path would defeat the detection.\n *\n * @example\n * defaultLazyNpmRoot() // => '/usr/local/lib/node_modules' | undefined\n */\nexport const defaultLazyNpmRoot = (): string | undefined => {\n try {\n const out = execFileSync('npm', ['root', '-g'], {\n encoding: 'utf-8',\n timeout: NPM_ROOT_TIMEOUT_MS,\n stdio: ['ignore', 'pipe', 'ignore'],\n shell: process.platform === 'win32',\n })\n const trimmed = out.trim()\n\n return trimmed === '' ? undefined : trimmed\n } catch {\n return undefined\n }\n}\n", "/**\n * `env` minus every package-manager marker a spawned child could mistake for a throwaway install:\n * the whole `npm_*` block plus `PNPM_SCRIPT_SRC_DIR`. The result makes the child look exactly like\n * a direct `node <pkg>/dist/cli.js` run \u2014 which it is.\n */\n// Any child we launch through `node <bin>` (the portless driver, the update worker, the mcp launcher)\n// inherits our env, and a tool that sniffs those markers will conclude it was run via `npx`/`pnpm\n// dlx` and refuse to work. portless is the motivating case; its guard (cli.js `main()`) is:\n//\n// isNpx = npm_command === 'exec' && !npm_lifecycle_event\n// isPnpmDlx = !!PNPM_SCRIPT_SRC_DIR && !npm_lifecycle_event\n// if ((isNpx || isPnpmDlx) && !isLocallyInstalled()) -> abort\n//\n// `isLocallyInstalled()` walks up from the CHILD's cwd, so in a consumer repo (where portless is a\n// transitive dep of infra-kit, absent from the root `node_modules`) it is false and the guard is\n// live. `pnpm exec infra-kit dev` exports `npm_command=exec` with no lifecycle event, so `isNpx`\n// holds, every portless call exits 1, `isAvailable()` is false, and `ensureProxy` aborts the whole\n// dev boot with \"portless is not installed\", on a machine where it plainly is.\n//\n// `PNPM_SCRIPT_SRC_DIR` must be dropped ALONGSIDE the `npm_*` block, not left behind: it is set by\n// `pnpm run <script>`, where `npm_lifecycle_event` is what suppresses `isPnpmDlx`. Stripping only\n// `npm_*` removes that suppressor and creates an abort for the script-style invocation that\n// previously worked. Both markers go, or neither is safe.\nexport const withoutPackageManagerEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n return Object.fromEntries(\n Object.entries(env).filter(([key]) => {\n return !key.startsWith('npm_') && key !== 'PNPM_SCRIPT_SRC_DIR'\n }),\n )\n}\n\n/**\n * npm's own configuration \u2014 as opposed to the npx/dlx *markers* above. Case-insensitive because npm reads\n * `npm_config_*` case-insensitively (its parser matches `/^npm_config_/i`) and real environments export\n * both forms: shells write the lowercase name, Dockerfiles and CI images overwhelmingly write the\n * uppercase one.\n */\nconst NPM_CONFIG_TO_PRESERVE = /^npm_config_(?:prefix|registry)$/i\n\n/**\n * The env for spawning a package-manager INSTALL: npx/dlx markers stripped, but npm's own config\n * kept \u2014 specifically `npm_config_prefix` and `npm_config_registry`.\n *\n * @example\n * packageManagerInstallEnv({ npm_command: 'exec', npm_config_prefix: '/p', PATH: '/bin' })\n * // => { npm_config_prefix: '/p', PATH: '/bin' }\n */\n// `withoutPackageManagerEnv` is deliberately a blunt `npm_*` prefix filter, and it is the\n// right tool for the portless driver \u2014 but it is the WRONG tool for spawning an install, because it\n// also drops the two variables that tell the package manager where, and from where, to install:\n//\n// - `npm_config_prefix` is the npm matcher's ONLY signal (see `install-manager.ts`). Strip it and\n// we detect a global install rooted at prefix P, then run the install with P erased \u2014 so it\n// lands in the DEFAULT prefix instead. That is either a permanent EACCES, or a second global\n// copy that is not the one on PATH. Nothing notices: the install exits 0, we report\n// `installed`, the version on PATH never moves, and the whole cycle repeats every window\n// forever. `export npm_config_prefix=~/.npm-global` is npm's own documented EACCES workaround,\n// so this is a mainstream layout, not an exotic one.\n// - `npm_config_registry` is what the update CHECK already used to pick a registry. Dropping it\n// here means we decide against a corporate mirror and then install from somewhere else.\n//\n// Preserving these cannot re-arm the dlx guard: that guard reads `npm_command`,\n// `npm_lifecycle_event` and `PNPM_SCRIPT_SRC_DIR` \u2014 none of which are npm config, and all of which\n// remain stripped.\nexport const packageManagerInstallEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n const sanitised = withoutPackageManagerEnv(env)\n\n for (const [key, value] of Object.entries(env)) {\n if (NPM_CONFIG_TO_PRESERVE.test(key)) sanitised[key] = value\n }\n\n return sanitised\n}\n"],
4
+ "sourcesContent": ["/**\n * Pure detection of *how* this CLI was installed, so the background updater knows whether it may act at\n * all, and the advisory it prints can name the one command that will actually work. No fs, no spawn, no `process.env` read \u2014 every input is injected, which is\n * what lets the whole matrix be table-tested.\n *\n * Detection is env-first and LAZY: the only signal that costs a subprocess (`npm root -g`) is passed in\n * as `lazyNpmRoot` and consulted solely when every cheaper matcher has missed.\n */\nimport path from 'node:path'\n\n/** The published package this CLI updates itself to. Single source for every suggested argv. */\nexport const PACKAGE_NAME = 'infra-kit'\n\nconst LATEST = `${PACKAGE_NAME}@latest`\n\nexport type InstallManager = 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | 'homebrew' | 'unknown'\n\nexport interface InstallManagerInfo {\n manager: InstallManager\n /** The command to run. Only safe to spawn ourselves when `canSelfSpawn`; otherwise print it. */\n updateCommand: string[]\n /** False when we must not run the command for the user \u2014 either it needs sudo/a tap, or we guessed. */\n canSelfSpawn: boolean\n}\n\n/**\n * Canonicalises a candidate *root* directory. Required, not optional: `selfRealPath` has already had its\n * symlinks followed, so comparing it against a raw `PNPM_HOME`/`npm root -g`/`cwd` compares a resolved\n * path to an unresolved one and silently never matches. macOS is the everyday proof \u2014 `/var` is a symlink\n * to `/private/var`, so a global install under `/var/...` reports `unknown` unless both sides are resolved.\n * Callers inject the real thing; tests inject a stub.\n */\nexport type RealpathFn = (dir: string) => string\n\nexport interface DetectInstallManagerInput {\n /** Fully-resolved (symlinks followed) path to this CLI's entry file. */\n selfRealPath: string\n env: NodeJS.ProcessEnv\n /** Canonicalises each candidate root before comparison. See {@link RealpathFn}. */\n realpath: RealpathFn\n /** `npm root -g`, deferred: invoked at most once, and only when no cheaper matcher hit. */\n lazyNpmRoot?: () => string | undefined\n /**\n * The exact version to install, when the caller has already resolved it. Omitted, the command targets\n * the `latest` dist-tag \u2014 fine to PRINT, unsafe to RUN: see {@link pinSpec}.\n */\n version?: string\n}\n\n/**\n * Swap the `@latest` token for `@<version>`.\n *\n * `pnpm add -g infra-kit@latest` resolves the tag from pnpm's on-disk metadata cache and does not\n * revalidate it when a cached version already satisfies the tag (pnpm 12.3.4, measured: two runs 90+\n * minutes after a publish both reinstalled the stale `latest` while `pnpm view` already reported the new\n * one). The updater had fetched the real latest itself moments earlier, ran the tag command, got exit 0\n * \u2014 nothing was reinstalled \u2014 and recorded `installed`, so the stale binary looked up to date until the\n * next cycle repeated the same no-op. A concrete version the cache has never seen forces the fetch.\n */\nconst pinSpec = (command: string[], version: string | undefined): string[] => {\n if (version === undefined) return command\n\n return command.map((token) => {\n return token === LATEST ? `${PACKAGE_NAME}@${version}` : token\n })\n}\n\n/**\n * Is `child` inside the `parent` subtree? Boundary-aware: a naive `startsWith` would call\n * `/Users/x/pnpm-ish` a child of `/Users/x/pnpm`. `parent` is canonicalised first because it arrives raw\n * from the environment while `child` is already a realpath.\n */\nexport const isWithin = (parent: string, child: string, realpath: RealpathFn): boolean => {\n const rel = path.relative(realpath(path.resolve(parent)), path.resolve(child))\n\n return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)\n}\n\n/** Does `p` contain `name` as a whole path SEGMENT? `/a/node_modules_backup/b` must not match `node_modules`. */\nexport const hasSegment = (p: string, name: string): boolean => {\n return path.resolve(p).split(path.sep).includes(name)\n}\n\n/**\n * Is `p` inside a Homebrew keg belonging to the `name` FORMULA \u2014 i.e. `.../Cellar/<name>/<version>/...`?\n *\n * The formula name is what makes this sound. A bare `Cellar` segment says only \"somewhere under a keg\",\n * and the keg it lands in is routinely someone else's: when npm's global prefix is a node keg\n * (`npm config set prefix \"$(brew --prefix node)\"`, or any keg-only `node@X`), an `npm i -g` package\n * installs to `Cellar/node/<v>/lib/node_modules/<pkg>/...` \u2014 brew has never heard of it, yet the segment\n * is right there. Requiring `<name>` to sit directly after `Cellar` is what separates \"brew installed\n * THIS\" from \"brew installed the runtime that installed this\".\n *\n * Works for both keg layouts, since each is rooted at the formula: a plain formula\n * (`Cellar/infra-kit/1.2.3/bin/infra-kit`) and brew's node-CLI layout\n * (`Cellar/infra-kit/1.2.3/libexec/lib/node_modules/infra-kit/dist/cli.js`). Do NOT try to tell them\n * apart by excluding `node_modules` \u2014 the second one contains it.\n */\nexport const isBrewKegOf = (p: string, name: string): boolean => {\n const segments = path.resolve(p).split(path.sep)\n const cellar = segments.indexOf('Cellar')\n\n return cellar !== -1 && segments[cellar + 1] === name\n}\n\n/**\n * The npm global prefix that owns `binRealPath`, derived from the path ITSELF, or null when the\n * layout is not an npm global one.\n *\n * Matches `<prefix>/lib/node_modules/<packageName>` \u2014 npm's global layout and no other manager's\n * \u2014 requiring BOTH the `lib` parent and our package as the immediate child. Windows global npm has\n * no `lib` segment (`%APPDATA%\\npm\\node_modules`), so this returns null there and detection falls\n * through to `npm root -g`, which is correct on Windows, where there is normally one npm.\n */\n// This is the one signal that cannot point at the wrong tree. Everything else in this module\n// answers \"is this file somewhere inside tool X's directory?\", and containment is not ownership:\n// - `npm root -g` answers for whichever `npm` is first on PATH, which is routinely a DIFFERENT\n// node than the one that installed us (a pnpm/nvm/fnm-managed node, or a node that has since\n// been removed). It then reports a root that does not contain us, every matcher misses, and\n// detection degrades to `unknown` \u2014 a notice printed forever, on the single most common install\n// method. That is the bug this exists to close.\n// - `PNPM_HOME` containment is satisfied by `<PNPM_HOME>/nodejs/<v>/lib/node_modules/<pkg>` (a\n// plain `npm i -g` under a pnpm-managed node), yet `pnpm add -g` installs to\n// `<PNPM_HOME>/global/<v>/...` \u2014 a different directory. That one is worse than a missed update:\n// the install \"succeeds\" while the binary on PATH stays old, silently, with no notice to show\n// for it.\n//\n// Requiring both segments is what makes the match proof rather than a hint. The `lib` requirement\n// is also what keeps a project-local `<repo>/node_modules/<pkg>` out (it has no `lib`), and nesting\n// cannot spoof it: `.../node_modules/foo/node_modules/<pkg>` fails the `lib` test.\nexport const npmPrefixOfPackage = (binRealPath: string, packageName: string): string | null => {\n const segments = path.resolve(binRealPath).split(path.sep)\n const nodeModules = segments.lastIndexOf('node_modules')\n\n if (nodeModules < 2) return null\n if (segments[nodeModules - 1] !== 'lib') return null\n if (segments[nodeModules + 1] !== packageName) return null\n\n // Drop `lib/node_modules/...`; the empty result of a root-level prefix (`/lib/node_modules/...`) is `/`.\n return segments.slice(0, nodeModules - 1).join(path.sep) || path.sep\n}\n\n// The self-scoped reading, kept as the name every call site below already uses. `dependency-registry`\n// asks the same question about OTHER packages (`portless`), which is why the body moved up one level\n// rather than gaining a defaulted parameter \u2014 a default is how the wrong package silently gets probed.\nconst npmPrefixFromSelfPath = (selfRealPath: string): string | null => {\n return npmPrefixOfPackage(selfRealPath, PACKAGE_NAME)\n}\n\n/**\n * `--prefix` is passed EXPLICITLY rather than trusting the ambient one: the whole point of deriving it is\n * that the `npm` we are about to run may default to a different prefix than the one we are installed in.\n * A command-line flag outranks both `npm_config_prefix` and any `.npmrc`, so this targets the tree we\n * actually run from. With `-g`, npm writes `<prefix>/lib/node_modules` and links bins into `<prefix>/bin`.\n */\nconst npmPrefixInstallCommand = (prefix: string): string[] => {\n return ['npm', 'install', '-g', '--prefix', prefix, LATEST]\n}\n\n/**\n * Render argv as a line the user can paste into a shell.\n *\n * A plain `join(' ')` was fine while every token came from a static table; `--prefix <path>` puts a\n * filesystem path in argv, and `/Users/Ada Lovelace/.nvm/...` pasted unquoted is two arguments and a\n * failed install. Single quotes are sound here without escaping because the callers' validation rejects a\n * token containing a quote \u2014 see `SAFE_COMMAND_TOKEN` in src/lib/update-check/auto-update.ts.\n *\n * @example\n * formatUpdateCommand(['npm', 'install', '-g', '--prefix', '/opt/x y', 'infra-kit@latest'])\n * // => \"npm install -g --prefix '/opt/x y' infra-kit@latest\"\n */\nexport const formatUpdateCommand = (command: string[]): string => {\n return command\n .map((token) => {\n return token.includes(' ') ? `'${token}'` : token\n })\n .join(' ')\n}\n\n/** `env[key]` names a directory that contains `selfRealPath`. Absent/empty env var \u2192 no match. */\nconst underEnvDir = (env: NodeJS.ProcessEnv, key: string, selfRealPath: string, realpath: RealpathFn): boolean => {\n const dir = env[key]\n\n return dir != null && dir !== '' && isWithin(dir, selfRealPath, realpath)\n}\n\ninterface Matcher extends Omit<InstallManagerInfo, 'manager'> {\n manager: InstallManager\n test: (input: Required<Pick<DetectInstallManagerInput, 'selfRealPath' | 'env' | 'realpath'>>) => boolean\n}\n\n/**\n * Consulted FIRST, before {@link npmPrefixFromSelfPath}. Both of these legitimately wrap an npm-shaped\n * `lib/node_modules` tree \u2014 volta at `~/.volta/tools/image/node/<v>/lib/node_modules`, brew at\n * `Cellar/<pkg>/<v>/libexec/lib/node_modules` \u2014 so deriving an npm prefix from the path would hijack\n * installs that a wrapper owns and must keep owning.\n */\nconst WRAPPER_MATCHERS: Matcher[] = [\n {\n manager: 'volta',\n // volta owns the shim; `volta install` is the correct tool, not a workaround \u2014 so we may run it.\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'VOLTA_HOME', selfRealPath, realpath) ||\n hasSegment(selfRealPath, '.volta') ||\n hasSegment(selfRealPath, 'volta')\n )\n },\n updateCommand: ['volta', 'install', PACKAGE_NAME],\n canSelfSpawn: true,\n },\n {\n manager: 'homebrew',\n // `brew upgrade` can touch the prefix, relink, and prompt \u2014 never ours to run unattended.\n //\n // Our own keg is the ONLY sound signal \u2014 see `isBrewKegOf`. Two broader tests look plausible\n // and are both wrong, because each answers \"did brew put something here?\" when the question is \"does\n // brew own THIS package?\":\n // - `HOMEBREW_PREFIX` containment: when node comes from brew, npm's global prefix IS\n // $HOMEBREW_PREFIX, so EVERY `npm i -g` package lands under it, unknown to brew.\n // - a bare `Cellar` segment: an npm prefix pointed at a node keg puts packages inside that keg.\n // Either misfire tells macOS users to run `brew upgrade infra-kit` \u2014 a formula that does not exist \u2014\n // and, far worse, makes the background auto-updater bail with `cannot-self-spawn` forever, so the\n // very fix for it can never reach them. Detection runs on the realpath, and a linked brew bin always\n // resolves into its own keg, so the narrow test has no false negatives to trade for this.\n test: ({ selfRealPath }) => {\n return isBrewKegOf(selfRealPath, PACKAGE_NAME)\n },\n updateCommand: ['brew', 'upgrade', PACKAGE_NAME],\n canSelfSpawn: false,\n },\n]\n\n/**\n * Consulted LAST, after {@link npmPrefixFromSelfPath} has had its say. Each of these proves only that we\n * live somewhere inside a tool's directory tree, which is weaker than knowing the layout npm itself\n * created \u2014 see the `PNPM_HOME`/`nodejs` case in that helper's doc for a containment hit whose install\n * command targets the wrong directory.\n */\nconst TREE_MATCHERS: Matcher[] = [\n {\n manager: 'pnpm',\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'PNPM_HOME', selfRealPath, realpath) ||\n (hasSegment(selfRealPath, 'pnpm') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['pnpm', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'bun',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'BUN_INSTALL', selfRealPath, realpath) || hasSegment(selfRealPath, '.bun')\n },\n updateCommand: ['bun', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'yarn',\n test: ({ selfRealPath }) => {\n return (\n hasSegment(selfRealPath, '.yarn') || (hasSegment(selfRealPath, 'yarn') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['yarn', 'global', 'add', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'npm',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'npm_config_prefix', selfRealPath, realpath)\n },\n updateCommand: ['npm', 'install', '-g', LATEST],\n canSelfSpawn: true,\n },\n]\n\nconst NPM_UPDATE_COMMAND = ['npm', 'install', '-g', LATEST]\n\n/**\n * The command to print when nobody has identified this CLI's package manager \u2014 the same guess\n * `detectInstallManager` records for an unrecognised location, pinned to `version`. For a caller that\n * must name a command but has no worker verdict to read (no update cache on an opt-out machine).\n *\n * @example\n * fallbackUpdateCommand('0.8.0') // => ['npm', 'install', '-g', 'infra-kit@0.8.0']\n */\nexport const fallbackUpdateCommand = (version: string): string[] => {\n return pinSpec(NPM_UPDATE_COMMAND, version)\n}\n\n/**\n * Identify the package manager that owns `selfRealPath`.\n *\n * Order, and why it is this one: wrappers that own an npm-shaped tree (volta, brew) first, then the npm\n * prefix DERIVED from our own path, then the env/path containment matchers, then the `npm root -g` probe.\n * The derived prefix sits above containment because it is the only signal that cannot name a directory we\n * do not live in \u2014 see {@link npmPrefixFromSelfPath}.\n *\n * `lazyNpmRoot` is the last resort and is invoked at most once, only after every matcher has missed \u2014 a\n * pnpm or volta install never pays for the subprocess, and neither does any npm global install in the\n * standard layout, which the derived prefix now settles for free. When nothing matches we report `unknown`\n * with an npm command that is a *suggestion only* (`canSelfSpawn: false`): running a guessed global\n * install is worse than printing one.\n *\n * @example\n * detectInstallManager({ selfRealPath: '/Users/x/Library/pnpm/global/5/node_modules/infra-kit/dist/cli.js', env: {} })\n * // => { manager: 'pnpm', updateCommand: ['pnpm', 'add', '-g', 'infra-kit@latest'], canSelfSpawn: true }\n * detectInstallManager({ selfRealPath: '/Users/x/Library/pnpm/global/5/node_modules/infra-kit/dist/cli.js', env: {}, version: '0.5.5' })\n * // => { manager: 'pnpm', updateCommand: ['pnpm', 'add', '-g', 'infra-kit@0.5.5'], canSelfSpawn: true }\n */\nexport const detectInstallManager = (input: DetectInstallManagerInput): InstallManagerInfo => {\n const { selfRealPath, env, realpath, lazyNpmRoot, version } = input\n const detected = detectUnpinned({ selfRealPath, env, realpath, lazyNpmRoot })\n\n return { ...detected, updateCommand: pinSpec(detected.updateCommand, version) }\n}\n\nconst detectUnpinned = (input: DetectInstallManagerInput): InstallManagerInfo => {\n const { selfRealPath, env, realpath, lazyNpmRoot } = input\n const toInfo = (hit: Matcher): InstallManagerInfo => {\n return { manager: hit.manager, updateCommand: hit.updateCommand, canSelfSpawn: hit.canSelfSpawn }\n }\n const matches = ({ test }: Matcher): boolean => {\n return test({ selfRealPath, env, realpath })\n }\n\n const wrapper = WRAPPER_MATCHERS.find(matches)\n\n if (wrapper) return toInfo(wrapper)\n\n const derivedPrefix = npmPrefixFromSelfPath(selfRealPath)\n\n if (derivedPrefix !== null) {\n return { manager: 'npm', updateCommand: npmPrefixInstallCommand(derivedPrefix), canSelfSpawn: true }\n }\n\n const tree = TREE_MATCHERS.find(matches)\n\n if (tree) return toInfo(tree)\n\n const npmRoot = lazyNpmRoot?.()\n\n if (npmRoot != null && npmRoot !== '' && isWithin(npmRoot, selfRealPath, realpath)) {\n return { manager: 'npm', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: true }\n }\n\n return { manager: 'unknown', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: false }\n}\n\n/**\n * Is this CLI running from a *project-local* `node_modules` (as opposed to a global root)?\n *\n * The cwd clause is what does the distinguishing \u2014 BOTH a project install and a global root contain a\n * `/node_modules/` segment (`pnpm root -g` is `~/Library/pnpm/global/5/node_modules`). Without it we\n * would nag every global pnpm user to stop using a local install they do not have.\n *\n * Accepted false-negative: invoked from a subdirectory (cwd `project/apps/x`, deps at\n * `project/node_modules`) this returns false and the advisory stays silent. Under-warning is the safe\n * direction for a best-effort, never-throwing advisory \u2014 do not \"fix\" it by dropping the cwd clause.\n *\n * `cwd` is canonicalised before comparison for the same reason `detectInstallManager` canonicalises its\n * roots: `selfRealPath` is a realpath, and comparing it to an unresolved cwd never matches.\n *\n * @example\n * isLocalNodeModulesInstall('/repo/node_modules/infra-kit/dist/cli.js', '/repo', (p) => p) // => true\n */\nexport const isLocalNodeModulesInstall = (selfRealPath: string, cwd: string, realpath: RealpathFn): boolean => {\n return hasSegment(selfRealPath, 'node_modules') && isWithin(cwd, selfRealPath, realpath)\n}\n\n/** Does this path exist at all \u2014 directory, file, or symlink? Injected so the walk never touches the real disk in tests. */\nexport type ExistsFn = (p: string) => boolean\n\nexport interface IsGlobalInstallInput {\n /** Fully-resolved (symlinks followed) path to this CLI's entry file. */\n selfRealPath: string\n env: NodeJS.ProcessEnv\n /** Canonicalises `home` and every root {@link detectInstallManager} compares against. */\n realpath: RealpathFn\n /** The user's home directory (`os.homedir()`), raw \u2014 canonicalised here before the walk compares it. */\n home: string\n exists: ExistsFn\n}\n\n/** Upper bound on the `.git` walk: deeper than any real install layout, so it only ever guards against a pathological path. */\nconst GIT_WALK_MAX_HOPS = 32\n\n/**\n * Where the `.git` walk starts: the parent of the OUTERMOST `node_modules` segment (`indexOf`, not\n * `lastIndexOf` \u2014 pnpm's `.pnpm/<pkg>@<v>/node_modules/<pkg>` nests two, and the checkout that owns the\n * tree sits above the first). A self path with no `node_modules` at all (a plain brew keg's `bin/`) starts\n * at its own directory, so the walk still inspects every ancestor.\n */\nconst gitWalkStart = (selfRealPath: string): string => {\n const segments = path.resolve(selfRealPath).split(path.sep)\n const outermost = segments.indexOf('node_modules')\n\n if (outermost === -1) return path.dirname(selfRealPath)\n\n return segments.slice(0, outermost).join(path.sep) || path.sep\n}\n\n/** `start` and its ancestors up to but EXCLUDING `homeReal`, bounded \u2014 the directories the `.git` walk may inspect. */\nconst ancestorsBelowHome = (start: string, homeReal: string): string[] => {\n const dirs: string[] = []\n let dir = start\n\n while (dir !== homeReal && dirs.length < GIT_WALK_MAX_HOPS) {\n dirs.push(dir)\n\n const parent = path.dirname(dir)\n\n if (parent === dir) break\n\n dir = parent\n }\n\n return dirs\n}\n\nconst hasGitAncestor = (start: string, homeReal: string, exists: ExistsFn): boolean => {\n return ancestorsBelowHome(start, homeReal).some((dir) => {\n return exists(path.join(dir, '.git'))\n })\n}\n\n/**\n * Is this CLI the machine's *global* install \u2014 the one a root-owned daemon or a system-wide link may be\n * aimed at \u2014 as opposed to a checkout or a project-local dependency? Probe-free: fs + env only, never a\n * subprocess, because it runs on every boot.\n *\n * True iff {@link detectInstallManager} names a manager AND no `.git` entry (directory or file \u2014 a\n * worktree's is a file) exists above the outermost `node_modules`, walking up to but EXCLUDING\n * `realpath(home)`. Never throws: any seam failure reports false, the safe direction for every caller.\n *\n * @example\n * isGlobalInstall({\n * selfRealPath: '/Users/x/Library/pnpm/global/v11/8a83-1/node_modules/.pnpm/infra-kit@0.5.6/node_modules/infra-kit/dist/cli.js',\n * env: { PNPM_HOME: '/Users/x/Library/pnpm' },\n * realpath: (p) => p,\n * home: '/Users/x',\n * exists: (p) => p === '/Users/x/.git',\n * }) // => true \u2014 the only `.git` is $HOME's own, which the walk never inspects\n */\n// Why these two predicates and not the obvious candidates:\n// - Not `canSelfSpawn`: that flag encodes \"may I run an unattended `npm i -g`\", and homebrew is\n// `canSelfSpawn: false` while being unmistakably global \u2014 gating on it would leave a brew install\n// unconverged forever. A global install whose manager cannot be identified in a stripped env (no\n// `PNPM_HOME`, no derivable prefix) reports false: fail-safe, since a skipped write is never wrong and\n// the next shell-run command converges it.\n// - Not `isLocalNodeModulesInstall`: its cwd clause calls every global layout under `$HOME` \"local\" the\n// moment cwd is `$HOME` \u2014 which is exactly the cwd the background updater spawns with, and a plain\n// `cd ~ && infra-kit version` reproduces it. This predicate reads the tree, not the cwd.\n// - Why the `.git` walk at all: the cheap matchers are segment heuristics that also fire on\n// project-local shapes \u2014 a repo with a `volta` path segment, Yarn Berry's `.yarn/unplugged/\u2026`, a\n// checkout cloned under `$PNPM_HOME`, a workspace package literally named `lib` \u2014 and every one of\n// those is a checkout; every checkout has a `.git`, no global root does.\n// - Why `$HOME` is excluded: dotfiles users `git init ~`, and a `~/.git` would refuse the pnpm-global\n// install permanently. Every checkout under `$HOME` (`~/repo/.git`) is still strictly below it.\n// - Why `.git` ONLY, not `pnpm-workspace.yaml`: pnpm 12 writes one INSIDE the global install dir, so\n// that marker would refuse the very install this is for.\nexport const isGlobalInstall = (input: IsGlobalInstallInput): boolean => {\n try {\n const { selfRealPath, env, realpath, home, exists } = input\n\n if (detectInstallManager({ selfRealPath, env, realpath }).manager === 'unknown') return false\n\n return !hasGitAncestor(gitWalkStart(selfRealPath), realpath(path.resolve(home)), exists)\n } catch {\n return false\n }\n}\n\n/**\n * The advisory gate for `warnIfLocalInstall`, pulled out so it is testable without spawning the CLI.\n * Warn only when the install is provably NOT global AND looks project-local: the second clause alone\n * fires on a global pnpm root whenever cwd is `$HOME` (see {@link isGlobalInstall}).\n */\nexport const shouldWarnLocalInstall = (input: IsGlobalInstallInput & { cwd: string }): boolean => {\n const { selfRealPath, cwd, realpath } = input\n\n return !isGlobalInstall(input) && isLocalNodeModulesInstall(selfRealPath, cwd, realpath)\n}\n", "import { realpathSync } from 'node:fs'\nimport path from 'node:path'\n\n/**\n * The impure companion to the pure detection module: canonicalise a directory that may not exist.\n *\n * `realpathSync` throws on a missing path, and candidate roots routinely miss \u2014 `PNPM_HOME` can point at a\n * directory the user never created, `npm root -g` can name a prefix that was removed. A throw there would\n * turn \"we could not identify your install\" into a crash, so an unresolvable path falls back to\n * `path.resolve`, which still normalises `.`/`..` and yields a usable, non-matching absolute path.\n */\nexport const safeRealpath = (dir: string): string => {\n try {\n return realpathSync(dir)\n } catch {\n return path.resolve(dir)\n }\n}\n", "/* eslint-disable sonarjs/no-os-command-from-path */\n/**\n * `npm root -g`, the LAZY fallback for {@link detectInstallManager}.\n *\n * Why it is indispensable: the `npm` matcher keys off `npm_config_prefix`, which npm sets only while npm\n * itself is running. A user who ran `npm i -g infra-kit` months ago and now types `ik` has no such var,\n * so every cheap matcher misses and detection reports `unknown` / `canSelfSpawn: false`. Without this\n * probe the single most common install method can never update itself.\n *\n * Read by the background update worker, and by the `doctor` advisory that names the command a human\n * would run by hand \u2014 one probe so the two can never disagree about who owns the install.\n */\nimport { execFileSync } from 'node:child_process'\nimport process from 'node:process'\n\nconst NPM_ROOT_TIMEOUT_MS = 3_000\n\n/**\n * The global npm root, or undefined when npm is absent, slow, or errors. Costs a subprocess, so\n * `detectInstallManager` invokes it at most once and only after every env/path matcher has missed \u2014 a\n * pnpm or volta install never pays for it.\n *\n * Resolving the user's `npm` from PATH is inherent here: we must ask the very package manager that owns\n * this install where its global root is. Pinning an absolute path would defeat the detection.\n *\n * @example\n * defaultLazyNpmRoot() // => '/usr/local/lib/node_modules' | undefined\n */\nexport const defaultLazyNpmRoot = (): string | undefined => {\n try {\n const out = execFileSync('npm', ['root', '-g'], {\n encoding: 'utf-8',\n timeout: NPM_ROOT_TIMEOUT_MS,\n stdio: ['ignore', 'pipe', 'ignore'],\n shell: process.platform === 'win32',\n })\n const trimmed = out.trim()\n\n return trimmed === '' ? undefined : trimmed\n } catch {\n return undefined\n }\n}\n", "/**\n * `env` minus every package-manager marker a spawned child could mistake for a throwaway install:\n * the whole `npm_*` block plus `PNPM_SCRIPT_SRC_DIR`. The result makes the child look exactly like\n * a direct `node <pkg>/dist/cli.js` run \u2014 which it is.\n */\n// Any child we launch through `node <bin>` (the portless driver, the update worker, the dependency installer)\n// inherits our env, and a tool that sniffs those markers will conclude it was run via `npx`/`pnpm\n// dlx` and refuse to work. portless is the motivating case; its guard (cli.js `main()`) is:\n//\n// isNpx = npm_command === 'exec' && !npm_lifecycle_event\n// isPnpmDlx = !!PNPM_SCRIPT_SRC_DIR && !npm_lifecycle_event\n// if ((isNpx || isPnpmDlx) && !isLocallyInstalled()) -> abort\n//\n// `isLocallyInstalled()` walks up from the CHILD's cwd, so in a consumer repo (where portless is a\n// transitive dep of infra-kit, absent from the root `node_modules`) it is false and the guard is\n// live. `pnpm exec infra-kit dev` exports `npm_command=exec` with no lifecycle event, so `isNpx`\n// holds, every portless call exits 1, `isAvailable()` is false, and `ensureProxy` aborts the whole\n// dev boot with \"portless is not installed\", on a machine where it plainly is.\n//\n// `PNPM_SCRIPT_SRC_DIR` must be dropped ALONGSIDE the `npm_*` block, not left behind: it is set by\n// `pnpm run <script>`, where `npm_lifecycle_event` is what suppresses `isPnpmDlx`. Stripping only\n// `npm_*` removes that suppressor and creates an abort for the script-style invocation that\n// previously worked. Both markers go, or neither is safe.\nexport const withoutPackageManagerEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n return Object.fromEntries(\n Object.entries(env).filter(([key]) => {\n return !key.startsWith('npm_') && key !== 'PNPM_SCRIPT_SRC_DIR'\n }),\n )\n}\n\n/**\n * npm's own configuration \u2014 as opposed to the npx/dlx *markers* above. Case-insensitive because npm reads\n * `npm_config_*` case-insensitively (its parser matches `/^npm_config_/i`) and real environments export\n * both forms: shells write the lowercase name, Dockerfiles and CI images overwhelmingly write the\n * uppercase one.\n */\nconst NPM_CONFIG_TO_PRESERVE = /^npm_config_(?:prefix|registry)$/i\n\n/**\n * The env for spawning a package-manager INSTALL: npx/dlx markers stripped, but npm's own config\n * kept \u2014 specifically `npm_config_prefix` and `npm_config_registry`.\n *\n * @example\n * packageManagerInstallEnv({ npm_command: 'exec', npm_config_prefix: '/p', PATH: '/bin' })\n * // => { npm_config_prefix: '/p', PATH: '/bin' }\n */\n// `withoutPackageManagerEnv` is deliberately a blunt `npm_*` prefix filter, and it is the\n// right tool for the portless driver \u2014 but it is the WRONG tool for spawning an install, because it\n// also drops the two variables that tell the package manager where, and from where, to install:\n//\n// - `npm_config_prefix` is the npm matcher's ONLY signal (see `install-manager.ts`). Strip it and\n// we detect a global install rooted at prefix P, then run the install with P erased \u2014 so it\n// lands in the DEFAULT prefix instead. That is either a permanent EACCES, or a second global\n// copy that is not the one on PATH. Nothing notices: the install exits 0, we report\n// `installed`, the version on PATH never moves, and the whole cycle repeats every window\n// forever. `export npm_config_prefix=~/.npm-global` is npm's own documented EACCES workaround,\n// so this is a mainstream layout, not an exotic one.\n// - `npm_config_registry` is what the update CHECK already used to pick a registry. Dropping it\n// here means we decide against a corporate mirror and then install from somewhere else.\n//\n// Preserving these cannot re-arm the dlx guard: that guard reads `npm_command`,\n// `npm_lifecycle_event` and `PNPM_SCRIPT_SRC_DIR` \u2014 none of which are npm config, and all of which\n// remain stripped.\nexport const packageManagerInstallEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n const sanitised = withoutPackageManagerEnv(env)\n\n for (const [key, value] of Object.entries(env)) {\n if (NPM_CONFIG_TO_PRESERVE.test(key)) sanitised[key] = value\n }\n\n return sanitised\n}\n"],
5
5
  "mappings": "AAQA,OAAOA,MAAU,YAGV,IAAMC,EAAe,YAEtBC,EAAS,GAAGD,CAAY,UA8CxBE,EAAU,CAACC,EAAmBC,IAC9BA,IAAY,OAAkBD,EAE3BA,EAAQ,IAAKE,GACXA,IAAUJ,EAAS,GAAGD,CAAY,IAAII,CAAO,GAAKC,CAC1D,EAQUC,EAAW,CAACC,EAAgBC,EAAeC,IAAkC,CACxF,IAAMC,EAAMX,EAAK,SAASU,EAASV,EAAK,QAAQQ,CAAM,CAAC,EAAGR,EAAK,QAAQS,CAAK,CAAC,EAE7E,OAAOE,IAAQ,IAAM,CAACA,EAAI,WAAW,IAAI,GAAK,CAACX,EAAK,WAAWW,CAAG,CACpE,EAGaC,EAAa,CAACC,EAAWC,IAC7Bd,EAAK,QAAQa,CAAC,EAAE,MAAMb,EAAK,GAAG,EAAE,SAASc,CAAI,EAkBzCC,EAAc,CAACF,EAAWC,IAA0B,CAC/D,IAAME,EAAWhB,EAAK,QAAQa,CAAC,EAAE,MAAMb,EAAK,GAAG,EACzCiB,EAASD,EAAS,QAAQ,QAAQ,EAExC,OAAOC,IAAW,IAAMD,EAASC,EAAS,CAAC,IAAMH,CACnD,EA2BaI,EAA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AOG,IAAY,GAAK,OAAYA,CACtC,MAAQ,CACN,MACF,CACF,ECnBO,IAAMC,EAA4BC,GAChC,OAAO,YACZ,OAAO,QAAQA,CAAG,EAAE,OAAO,CAAC,CAACC,CAAG,IACvB,CAACA,EAAI,WAAW,MAAM,GAAKA,IAAQ,qBAC3C,CACH,EASIC,EAAyB,oCA2BlBC,EAA4BH,GAA8C,CACrF,IAAMI,EAAYL,EAAyBC,CAAG,EAE9C,OAAW,CAACC,EAAKI,CAAK,IAAK,OAAO,QAAQL,CAAG,EACvCE,EAAuB,KAAKD,CAAG,IAAGG,EAAUH,CAAG,EAAII,GAGzD,OAAOD,CACT",
6
6
  "names": ["path", "PACKAGE_NAME", "LATEST", "pinSpec", "command", "version", "token", "isWithin", "parent", "child", "realpath", "rel", "hasSegment", "p", "name", "isBrewKegOf", "segments", "cellar", "npmPrefixOfPackage", "binRealPath", "packageName", "nodeModules", "npmPrefixFromSelfPath", "selfRealPath", "npmPrefixInstallCommand", "prefix", "formatUpdateCommand", "underEnvDir", "env", "key", "dir", "WRAPPER_MATCHERS", "TREE_MATCHERS", "NPM_UPDATE_COMMAND", "fallbackUpdateCommand", "detectInstallManager", "input", "lazyNpmRoot", "detected", "detectUnpinned", "toInfo", "hit", "matches", "test", "wrapper", "derivedPrefix", "tree", "npmRoot", "isLocalNodeModulesInstall", "cwd", "GIT_WALK_MAX_HOPS", "gitWalkStart", "outermost", "ancestorsBelowHome", "start", "homeReal", "dirs", "hasGitAncestor", "exists", "isGlobalInstall", "home", "shouldWarnLocalInstall", "realpathSync", "path", "safeRealpath", "dir", "execFileSync", "process", "NPM_ROOT_TIMEOUT_MS", "defaultLazyNpmRoot", "trimmed", "withoutPackageManagerEnv", "env", "key", "NPM_CONFIG_TO_PRESERVE", "packageManagerInstallEnv", "sanitised", "value"]
7
7
  }
@@ -0,0 +1,3 @@
1
+ import{a as P,h as R,l as N,m as A,n as M,o as L}from"./chunk-AWFGP6GY.js";import{o as f,s as S}from"./chunk-MOVRKV3I.js";var Ye={name:"infra-kit",type:"module",version:"0.10.0",files:["dist"],description:"infra-kit",bin:{"infra-kit":"dist/cli.js",ik:"dist/cli.js","ik-mcp":"dist/mcp-proxy.js"},engines:{node:">=24.x"},scripts:{build:"pnpm run clean-artifacts && node ./scripts/build.js",prepack:"pnpm run build","infra-kit-check":"pnpm exec infra-kit audit","clean-artifacts":"rm -rf dist","clean-cache":"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc","prettier-fix":"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","eslint-check":"pnpm exec eslint --cache --report-unused-disable-directives ./src","eslint-fix":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix","ts-check":"tsc --noEmit",test:"pnpm exec vitest run --reporter=minimal","test-watch":"pnpm exec vitest --watch --silent passed-only","test-ui":"pnpm exec vitest --ui --silent passed-only","test-report":"pnpm exec vitest run --coverage --silent passed-only","qa:pty":"INFRA_KIT_REQUIRE_PTY=1 pnpm exec vitest run --reporter=minimal src/tui/__tests__/stdin-pause-pty.test.ts src/entry/__tests__/quit-keys-pty.test.ts src/entry/__tests__/post-run-pause-pty.test.ts",qa:"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success",fix:"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa"},dependencies:{"@aws-lambda-powertools/logger":"^2.35.0","@inquirer/checkbox":"^5.2.5","@inquirer/confirm":"^6.3.2","@inquirer/input":"^5.1.6","@inquirer/password":"^5.2.2","@inquirer/select":"^5.2.5","@slip-stream-kit/config":"^0.10.0",chalk:"^6.0.0",chokidar:"^5.0.0",commander:"^15.0.0",fastify:"^5.12.4",ink:"^7.1.1",pino:"^10.3.1","pino-pretty":"^13.1.3",portless:"^0.15.6",react:"19.3.0",yaml:"^2.9.1",zod:"^4.6.2",zx:"^8.8.5"},devDependencies:{"@slip-stream-kit/eslint-plugin":"workspace:*","@types/aws-lambda":"catalog:","@types/react":"catalog:","@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.2","ink-testing-library":"^4.0.0",typescript:"^6.0.3"}};import{spawnSync as Q}from"node:child_process";import{homedir as X}from"node:os";import C from"node:process";import u from"node:fs";import j from"node:path";import oe from"node:process";var ie="update-check.lock",le=1800*1e3,ae=()=>j.join(f(),ie),ce=(t,e)=>{try{e-u.statSync(t).mtimeMs>le&&u.rmSync(t,{force:!0})}catch{}},T=(t={})=>{let e=t.nowMs??Date.now(),n=t.lockPath??ae();try{u.mkdirSync(j.dirname(n),{recursive:!0})}catch{return null}let r=()=>{try{return u.openSync(n,"wx",384)}catch{return null}},s=r();if(s===null&&(ce(n,e),s=r()),s===null)return null;try{u.writeFileSync(s,String(oe.pid))}catch{}return()=>{try{u.closeSync(s)}catch{}try{u.rmSync(n,{force:!0})}catch{}}};var ue="https://registry.npmjs.org",pe=5e3,de=t=>Object.entries(t).find(([n,r])=>/^npm_config_registry$/i.test(n)&&r!=null&&r!=="")?.[1],me=t=>{let e=de(t),n=e!=null&&e!==""?e:ue;for(;n.endsWith("/");)n=n.slice(0,-1);return n},D=async(t,e=fetch)=>{let n=new AbortController,r=setTimeout(()=>{n.abort()},pe);try{let s=await e(`${me(t)}/${P}/latest`,{signal:n.signal,headers:{accept:"application/json"}});if(!s.ok)return null;let i=(await s.json())?.version;return typeof i=="string"&&i!==""?i:null}catch{return null}finally{clearTimeout(r)}};var fe=/^(\d+)\.(\d+)\.(\d+)$/,O=t=>{let[e=""]=t.trim().split("+"),[n="",...r]=e.split("-"),s=fe.exec(n);if(!s)return null;let[o,i,l]=[s[1],s[2],s[3]].map(Number);return{release:[o,i,l],prerelease:r.length>0?r.join("-").split("."):[]}},V=/^\d+$/,ge=(t,e)=>{let n=V.test(t),r=V.test(e);return n&&r?Number(t)-Number(e):n!==r?n?-1:1:t<e?-1:1},he=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n+=1){let r=t[n],s=e[n];if(r===void 0)return-1;if(s===void 0)return 1;if(r!==s)return ge(r,s)}return 0},U=(t,e)=>{let n=O(t),r=O(e);if(!n||!r)return!1;for(let i=0;i<3;i+=1){let l=n.release[i],h=r.release[i];if(l!==h)return l>h}let s=n.prerelease.length===0,o=r.prerelease.length===0;return s!==o?s:he(n.prerelease,r.prerelease)>0};import G from"node:fs";import F from"node:path";var J="update-check.json",Pe=1200*1e3,ke=()=>F.join(f(),J),ye=t=>Array.isArray(t)&&t.every(e=>typeof e=="string"),we=t=>{if(typeof t!="object"||t===null)return!1;let{outcome:e,checkedMs:n}=t;return typeof e=="string"&&typeof n=="number"&&Number.isFinite(n)},Ce=t=>{if(typeof t!="object"||t===null)return!1;let{lastCheckMs:e,latestVersion:n,updateCommand:r,outcome:s,plugin:o}=t;return typeof e=="number"&&Number.isFinite(e)&&(n===null||typeof n=="string")&&(r===null||ye(r))&&(s==null||typeof s=="string")&&(o===void 0||we(o))},at=(t=e=>G.readFileSync(e,"utf8"))=>{try{let e=JSON.parse(t(ke()));return Ce(e)?e:null}catch{return null}},x=t=>{let e=f();G.mkdirSync(e,{recursive:!0}),S(F.join(e,J),JSON.stringify(t),384)},ct=(t,e)=>{if(!t)return!0;let n=e-t.lastCheckMs;return n<0?!0:n>=Pe};import{spawnSync as Se}from"node:child_process";import Re from"node:fs";import W from"node:process";import{spawnSync as Ee}from"node:child_process";var k="infra-kit",g="infra-kit@infra-kit",pt="ArthurSaenz/infra-kit";var v="claude",Ue=12e4,q=["--version"],K=["plugin","update",g,"--scope","project","-y"],z=t=>{let e=Ee(v,[...t.args],{cwd:t.cwd,encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:Ue});if(e.error!==void 0)return{ok:!1,output:e.error.message};let n=`${e.stderr??""}
2
+ ${e.stdout??""}`.trim();return{ok:e.status===0,output:n}};import $ from"node:fs";import xe from"node:os";import y from"node:path";var ve=[".claude","plugins"],w=t=>{try{return JSON.parse($.readFileSync(t,"utf-8"))}catch{return}},d=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),p=(t,e)=>{let n=t[e];return typeof n=="string"?n:null},_=(t,e=xe.homedir())=>y.join(e,...ve,t),wt=t=>{let e=w(_("known_marketplaces.json",t));return d(e)&&k in e},_e=t=>d(t)?{scope:p(t,"scope"),projectPath:p(t,"projectPath"),installPath:p(t,"installPath"),version:p(t,"version")}:null,H=t=>{let e=w(_("installed_plugins.json",t));if(!d(e)||!d(e.plugins))return[];let n=e.plugins[g];return Array.isArray(n)?n.flatMap(r=>{let s=_e(r);return s===null?[]:[s]}):[]},b=t=>{try{return $.realpathSync(t)}catch{return y.resolve(t)}},be=(t,e)=>t.scope==="user"?!0:e===null||t.projectPath===null?!1:b(t.projectPath)===e,Ct=(t={})=>{let e=H(t.home);if(e.length===0)return{kind:"absent"};let n=t.projectPath===void 0?null:b(t.projectPath),r=e.find(s=>be(s,n));return r===void 0?{kind:"elsewhere",installations:e}:{kind:"installed",installation:r}},B=t=>{let e=new Set;return H(t).filter(n=>{if(n.scope==="user"||n.projectPath===null)return!1;let r=b(n.projectPath);return e.has(r)?!1:(e.add(r),!0)})},Et=t=>{if(t.installPath===null)return t.version;let e=w(y.join(t.installPath,".claude-plugin","plugin.json"));return(d(e)?p(e,"version"):null)??t.version},[Ie=k]=g.split("@"),Ut=({home:t}={})=>{let e=_(y.join("marketplaces",k,"plugins",Ie,".claude-plugin","plugin.json"),t),n=w(e);return d(n)?p(n,"version"):null};var Ne=300*1e3,Ae=6e4,Me=t=>{let e=M(t);return delete e.CLAUDECODE,e},Le=t=>t.code==="ENOENT",je=(t,e)=>{let n=t.projectPath;if(n===null||!e.pathExists(n))return"skipped";let r=e.deadlineMs-e.clock();if(r<=0)return"failed";let s=e.spawn(v,[...K],{cwd:n,stdio:"ignore",shell:W.platform==="win32",env:e.env,timeout:Math.min(Ae,r),windowsHide:!0});return s.error?Le(s.error)?"skipped":"failed":s.signal===null&&s.status===0?"ok":"failed"},Te=t=>{let e=t.clock??Date.now,n=e()+Ne;if(!(t.runClaude??z)({args:q}).ok)return"claude-missing";let s=(t.listPluginInstallations??B)();if(s.length===0)return"skipped";let o={spawn:t.spawnPluginUpdate??Se,env:Me(t.env??W.env),clock:e,deadlineMs:n,pathExists:t.pathExists??Re.existsSync},i=s.map(l=>je(l,o));return i.includes("failed")?"failed":i.includes("ok")?"updated":"skipped"},Y=(t={})=>{try{return Te(t)}catch{return"failed"}};var De=200,Oe=300*1e3,Ve=15e3,Ge=t=>{let e=Q(P,["version","--json"],{stdio:["ignore","pipe","ignore"],shell:C.platform==="win32",cwd:X(),env:t,timeout:Ve,windowsHide:!0,encoding:"utf8"});if(e.error||e.signal||e.status!==0)return null;try{let r=JSON.parse(e.stdout)?.version;return typeof r=="string"&&r!==""?r:null}catch{return null}},Fe=t=>{try{return C.kill(t,0),!0}catch{return!1}},Je=t=>new Promise(e=>{setTimeout(e,t)}),qe=async(t,e)=>{let n=e.clock()+Oe;for(;e.clock()<n;){if(!e.isProcessAlive(t))return!0;await e.sleep(De)}return!e.isProcessAlive(t)},Jt=async(t,e)=>{let n=e.acquireLock??T,r=e.writeCache??x,s=n();if(!s)return"already-running";let o={last:null},i=l=>{o.last=l,r(l)};try{let l=await $e(t,{...e,writeCache:i});return ze(e,o.last,t,r),l}finally{s()}},Ke=(t,e)=>t!==null&&U(t,e),ze=(t,e,n,r)=>{let s=Ke(e?.latestVersion??null,n)?"skipped-cli-stale":Y(t),o=(t.clock??Date.now)();if(e!==null)try{r({...e,plugin:{outcome:s,checkedMs:o}})}catch{}},$e=async(t,e)=>{let n=e.env??C.env,r=e.nowMs??Date.now(),s=e.fetchLatest??D,o=e.writeCache??x,i=e.isProcessAlive??Fe,l=e.sleep??Je,h=e.clock??Date.now,Z=e.lazyNpmRoot??N,ee=e.spawnSync??Q,te=e.installedVersion??Ge,a=await s(n),c=(I,re)=>(o({lastCheckMs:r,...re,outcome:I}),I);if(a===null)return c("fetch-failed",{latestVersion:null,updateCommand:null});if(!U(a,t))return c("up-to-date",{latestVersion:a,updateCommand:null});let{canSelfSpawn:ne,updateCommand:m}=R({selfRealPath:e.selfRealPath,env:n,realpath:A,lazyNpmRoot:Z,version:a});if(!ne)return c("cannot-self-spawn",{latestVersion:a,updateCommand:m});if(e.parentPid==null)return c("parent-unknown",{latestVersion:a,updateCommand:null});if(o({lastCheckMs:r,latestVersion:a,updateCommand:null,outcome:"installing"}),!await qe(e.parentPid,{isProcessAlive:i,sleep:l,clock:h}))return c("parent-still-running",{latestVersion:a,updateCommand:null});let E=ee(m[0],m.slice(1),{stdio:"ignore",shell:C.platform==="win32",cwd:X(),env:L(n),windowsHide:!0});return E.error||E.signal||E.status!==0?c("install-failed",{latestVersion:a,updateCommand:m}):te(n)!==a?c("install-stale",{latestVersion:a,updateCommand:m}):c("installed",{latestVersion:null,updateCommand:null})};export{k as a,g as b,pt as c,v as d,q as e,K as f,z as g,wt as h,Ct as i,Et as j,Ut as k,Ye as l,U as m,at as n,ct as o,D as p,Jt as q,Ke as r};
3
+ //# sourceMappingURL=chunk-JUNJK2YC.js.map
@@ -0,0 +1,7 @@
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.10.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 \"build\": \"pnpm run clean-artifacts && node ./scripts/build.js\",\n \"prepack\": \"pnpm run build\",\n \"infra-kit-check\": \"pnpm exec infra-kit audit\",\n \"clean-artifacts\": \"rm -rf dist\",\n \"clean-cache\": \"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc\",\n \"prettier-fix\": \"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"prettier-check\": \"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"eslint-check\": \"pnpm exec eslint --cache --report-unused-disable-directives ./src\",\n \"eslint-fix\": \"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix\",\n \"ts-check\": \"tsc --noEmit\",\n \"test\": \"pnpm exec vitest run --reporter=minimal\",\n \"test-watch\": \"pnpm exec vitest --watch --silent passed-only\",\n \"test-ui\": \"pnpm exec vitest --ui --silent passed-only\",\n \"test-report\": \"pnpm exec vitest run --coverage --silent passed-only\",\n \"qa:pty\": \"INFRA_KIT_REQUIRE_PTY=1 pnpm exec vitest run --reporter=minimal src/tui/__tests__/stdin-pause-pty.test.ts src/entry/__tests__/quit-keys-pty.test.ts src/entry/__tests__/post-run-pause-pty.test.ts\",\n \"qa\": \"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success\",\n \"fix\": \"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa\"\n },\n \"dependencies\": {\n \"@aws-lambda-powertools/logger\": \"^2.35.0\",\n \"@inquirer/checkbox\": \"^5.2.5\",\n \"@inquirer/confirm\": \"^6.3.2\",\n \"@inquirer/input\": \"^5.1.6\",\n \"@inquirer/password\": \"^5.2.2\",\n \"@inquirer/select\": \"^5.2.5\",\n \"@slip-stream-kit/config\": \"^0.10.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 \"@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,SACX,MAAS,CACP,MACF,EACA,YAAe,YACf,IAAO,CACL,YAAa,cACb,GAAM,cACN,SAAU,mBACZ,EACA,QAAW,CACT,KAAQ,QACV,EACA,QAAW,CACT,MAAS,sDACT,QAAW,iBACX,kBAAmB,4BACnB,kBAAmB,cACnB,cAAe,2EACf,eA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AAe,cAAAiB,CAAc,CAAC,EAS7CH,GAAiB5C,CAAG,IAEpB8B,EAAsBe,EAAO,gBAAiB,CAAE,cAAAf,EAAe,cAAAiB,CAAc,CAAC,EAG5FF,EAAO,YAAa,CAAE,cAAe,KAAM,cAAe,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
+ }
@@ -0,0 +1,4 @@
1
+ import O from"node:crypto";import A from"node:fs";import C from"node:os";import E from"node:path";import p from"node:process";var S="env-load.sh",x="env-clear.sh",D="projects",K=7200,I="INFRA_KIT_SESSION",f=".infra-kit",L="INFRA_KIT_ENV",d="INFRA_KIT_ENV_CONFIG",v="INFRA_KIT_ENV_PROJECT",W="INFRA_KIT_ENV_PROJECT_ROOT",y="INFRA_KIT_ENV_LOADED_AT",U="INFRA_KIT_ENV_AUTOLOADED",P="INFRA_KIT_ENV_CLEARED",V=/^([A-Z_]\w*)=/i,j=/^unset ([A-Z_]\w*)$/i,c=(t,e)=>{let r=e;for(let n=0;n<t.length;n++){if(!r&&t[n]==="\\"){n++;continue}t[n]==="'"&&(r=!r)}return r},w=t=>{let e=t.startsWith("'")?t.slice(1):t;return(e.endsWith("'")?e.slice(0,-1):e).split("'\\''").join("'")},m=t=>{try{return A.readFileSync(t,"utf-8")}catch{return""}},h=(t,e,r)=>{let n=t.split(`
2
+ `).map(s=>s.endsWith("\r")?s.slice(0,-1):s),o=0,_=!1;for(;o<n.length;){let s=n[o];if(_){_=c(s,_),o+=1;continue}let a=V.exec(s);if(!a){let i=j.exec(s);i&&r?.(i[1]),_=c(s,!1),o+=1;continue}let T=a[1],R=s.slice(a[0].length);if(!R.startsWith("'")){e({name:T,value:R}),_=c(s,!1),o+=1;continue}let g=[R],N=c(R,!1);for(;N&&o+1<n.length;){o+=1;let i=n[o];g.push(i),N=c(i,!0)}e({name:T,value:w(g.join(`
3
+ `))}),_=N,o+=1}},b=t=>{let e=[];return h(m(t),({name:r})=>{e.push(r)}),e},G=t=>{let e={};return h(m(t),({name:r,value:n})=>{e[r]=n}),e};var F=()=>{let t=p.env.XDG_CACHE_HOME,e=t&&t.length>0?t:E.join(C.homedir(),".cache");return E.join(e,"infra-kit")},J=()=>{let t=p.env[I];if(!t)throw new Error(`${I} is not set. Run \`infra-kit setup --skip-tools\` then \`source ~/.zshrc\`.`);return E.join(F(),t)},l=t=>O.createHash("sha256").update(t,"utf8").digest("hex"),u=()=>E.join(F(),D),M=t=>E.join(u(),l(t)),k=(t,e,r)=>{let n=`${t}.tmp.${p.pid}`;A.writeFileSync(n,e,{mode:r});try{A.renameSync(n,t)}catch(o){throw A.rmSync(n,{force:!0}),o}},H="-worktrees";export{S as a,x as b,K as c,I as d,f as e,L as f,d as g,v as h,W as i,y as j,U as k,P as l,b as m,G as n,F as o,J as p,u as q,M as r,k as s,H as t};
4
+ //# sourceMappingURL=chunk-MOVRKV3I.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/lib/constants/constants.ts"],
4
- "sourcesContent": ["import crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nexport const ENV_LOAD_FILE = 'env-load.sh'\nexport const ENV_CLEAR_FILE = 'env-clear.sh'\n\n/** Subdir of the cache root holding the project-scoped WARM caches (one dir per\n * project, keyed by {@link warmCacheKey}). Kept in sync with the zsh block in\n * init.ts, which reads `$cache_root/projects/$key/env-load.sh`. */\nexport const WARM_CACHE_SUBDIR = 'projects'\n\n/**\n * Default warm-cache TTL in seconds (2h). Governs BOTH the node-side eviction\n * sweep and the zsh-side source gate (`_INFRA_KIT_WARM_TTL` in the shell block);\n * the two MUST stay equal, so this constant is the single source of truth and the\n * shell default is emitted from it. Short by design: a warm file older than this\n * is never sourced (bounds a revoked/rotated secret served at prompt-0) and is\n * deleted on the next write. The background refresh lands in ~1-2s regardless.\n */\nexport const DEFAULT_WARM_TTL_SECONDS = 2 * 60 * 60\n\nexport const INFRA_KIT_SESSION_VAR = 'INFRA_KIT_SESSION'\n/**\n * Directory under the user's home that holds all machine-local infra-kit config:\n * the runtime `infra-kit.json` merge layer, per-project overrides, the factory\n * registry (`vendor.json`), and the `portless` package link. Single source of\n * truth for `.infra-kit`.\n *\n * Defined HERE, not in `lib/infra-kit-config`, because that module pulls in zod\n * and the `ik-mcp` proxy bundle must stay Node-builtins-only (guarded in\n * `entry/__tests__/dist-shebang.test.ts`); `lib/infra-kit-config` re-exports it\n * for its existing consumers.\n */\nexport const USER_CONFIG_DIR_NAME = '.infra-kit'\n/**\n * The active environment/config NAME (e.g. `dev`, `arthur`), exported plainly so\n * non-shell consumers can read it from `process.env`. Notably `infra-kit/vite`'s\n * `infraKitDev()` reads this to interpolate the `<env>` placeholder in cloud proxy\n * targets. Mirrors {@link INFRA_KIT_ENV_CONFIG_VAR} (same value) but is the stable,\n * purpose-named handle for tooling rather than the shell session-metadata var.\n */\nexport const INFRA_KIT_ENV_VAR = 'INFRA_KIT_ENV'\nexport const INFRA_KIT_ENV_CONFIG_VAR = 'INFRA_KIT_ENV_CONFIG'\nexport const INFRA_KIT_ENV_PROJECT_VAR = 'INFRA_KIT_ENV_PROJECT'\n/**\n * Absolute project root (git top-level) the loaded env belongs to. Lets the shell\n * startup gate tell a same-project subshell (skip) from a NEW project (load), so a\n * different project's secrets are never silently kept after `cd`/new shell.\n */\nexport const INFRA_KIT_ENV_PROJECT_ROOT_VAR = 'INFRA_KIT_ENV_PROJECT_ROOT'\nexport const INFRA_KIT_ENV_LOADED_AT_VAR = 'INFRA_KIT_ENV_LOADED_AT'\n/**\n * Marker exported into env-load.sh ONLY when the load was triggered automatically\n * (see lib/env-autoload). Its presence is the sole signal distinguishing an\n * auto-loaded env from a deliberate manual `env-load`, so auto-load never\n * clobbers a manual choice. A manual load unsets it.\n */\nexport const INFRA_KIT_ENV_AUTOLOADED_VAR = 'INFRA_KIT_ENV_AUTOLOADED'\n/**\n * Suppression sentinel exported by env-clear. While set in a shell, cli-invocation\n * auto-load stays silent (a deliberate clear must not be immediately re-loaded).\n * Lifted by a manual `env-load` or a new shell.\n */\nexport const INFRA_KIT_ENV_CLEARED_VAR = 'INFRA_KIT_ENV_CLEARED'\n\n/**\n * Matches a line of the form `KEY=...` where KEY is an env-var identifier\n * (letter or underscore, then word chars). Capture group 1 is the name. Shared\n * between env-load (validation, var counting) and parseVarNamesFromEnvFile.\n */\nexport const ENV_VAR_LINE_PATTERN = /^([A-Z_]\\w*)=/i\n\n/**\n * The `unset NAME` line env-clear.sh is made of and a manual env-load.sh ends with. Anchored at\n * both ends so a value that merely starts with the word is not a match.\n */\nconst UNSET_LINE_PATTERN = /^unset ([A-Z_]\\w*)$/i\n\n/**\n * Track whether a physical line leaves us inside an open single-quoted value,\n * mirroring how `shellSingleQuote` emits values (`'\u2026'`, with literal quotes as\n * `'\\''`). Outside a quote a backslash escapes the next char; inside a quote a\n * `'` closes it. Lets the parser skip the continuation lines of a multiline value.\n */\nconst advanceSingleQuoteState = (line: string, startInQuote: boolean): boolean => {\n let inQuote = startInQuote\n\n for (let i = 0; i < line.length; i++) {\n if (!inQuote && line[i] === '\\\\') {\n i++\n continue\n }\n\n if (line[i] === \"'\") {\n inQuote = !inQuote\n }\n }\n\n return inQuote\n}\n\n/** One `KEY=value` assignment recovered from an env file, value already unescaped. */\nexport interface EnvAssignment {\n name: string\n value: string\n}\n\n/**\n * Undo {@link shellSingleQuote}: drop the wrapping quotes, then turn each `'\\''`\n * back into a literal `'`. Order matters \u2014 unescaping first would let an embedded\n * `'\\''` be mistaken for the closing quote.\n */\nconst decodeSingleQuoted = (raw: string): string => {\n const withoutOpen = raw.startsWith(\"'\") ? raw.slice(1) : raw\n const body = withoutOpen.endsWith(\"'\") ? withoutOpen.slice(0, -1) : withoutOpen\n\n return body.split(\"'\\\\''\").join(\"'\")\n}\n\n/** File contents, or '' when the path is absent, a directory, or unreadable. */\nconst readEnvFileContent = (filePath: string): string => {\n try {\n return fs.readFileSync(filePath, 'utf-8')\n } catch {\n return ''\n }\n}\n\n/**\n * Walk every assignment in an env-load.sh body, skipping the continuation lines of\n * multiline values. {@link parseVarNamesFromEnvFile}, {@link parseVarsFromEnvFile}\n * and {@link parseUnsetNamesFromEnvFile} all go through here, so they can never\n * disagree about where a value ends \u2014 an `unset X` inside a quoted value is a\n * continuation line to every one of them.\n */\nconst forEachAssignment = (\n content: string,\n visit: (assignment: EnvAssignment) => void,\n visitUnset?: (name: string) => void,\n): void => {\n // A trailing CR is stripped per line: a CRLF file would otherwise hand back values\n // ending in '\\r' \u2014 a token that looks right in a diff and fails every request.\n const lines = content.split('\\n').map((line) => {\n return line.endsWith('\\r') ? line.slice(0, -1) : line\n })\n let index = 0\n let inQuote = false\n\n while (index < lines.length) {\n const line = lines[index]!\n\n // Only a line that starts OUTSIDE a quoted value can be a real assignment;\n // continuation lines of a multiline secret value are skipped.\n if (inQuote) {\n inQuote = advanceSingleQuoteState(line, inQuote)\n index += 1\n continue\n }\n\n const match = ENV_VAR_LINE_PATTERN.exec(line)\n\n if (!match) {\n const unset = UNSET_LINE_PATTERN.exec(line)\n\n if (unset) visitUnset?.(unset[1]!)\n\n inQuote = advanceSingleQuoteState(line, false)\n index += 1\n continue\n }\n\n const name = match[1]!\n const rest = line.slice(match[0].length)\n\n // An unquoted value cannot span lines (`CONNECTION_STRING=host=db;user=admin`).\n if (!rest.startsWith(\"'\")) {\n visit({ name, value: rest })\n inQuote = advanceSingleQuoteState(line, false)\n index += 1\n continue\n }\n\n const parts = [rest]\n let open = advanceSingleQuoteState(rest, false)\n\n while (open && index + 1 < lines.length) {\n index += 1\n const continuation = lines[index]!\n\n parts.push(continuation)\n open = advanceSingleQuoteState(continuation, true)\n }\n\n visit({ name, value: decodeSingleQuoted(parts.join('\\n')) })\n inQuote = open\n index += 1\n }\n}\n\nexport const parseVarNamesFromEnvFile = (filePath: string): string[] => {\n const names: string[] = []\n\n forEachAssignment(readEnvFileContent(filePath), ({ name }) => {\n names.push(name)\n })\n\n return names\n}\n\n/**\n * Same walk as {@link parseVarNamesFromEnvFile}, but keeping the values. Later\n * assignments win, matching what `source`ing the file would do.\n */\nexport const parseVarsFromEnvFile = (filePath: string): Record<string, string> => {\n const vars: Record<string, string> = {}\n\n forEachAssignment(readEnvFileContent(filePath), ({ name, value }) => {\n vars[name] = value\n })\n\n return vars\n}\n\n/**\n * The names the file `unset`s \u2014 everything env-clear.sh does, and the marker lines a\n * manual env-load.sh ends with. Absent file \u2192 `[]`, like its siblings.\n */\nexport const parseUnsetNamesFromEnvFile = (filePath: string): string[] => {\n const names: string[] = []\n\n forEachAssignment(\n readEnvFileContent(filePath),\n () => {},\n (name) => {\n names.push(name)\n },\n )\n\n return names\n}\n\n/**\n * Root cache dir for infra-kit across all sessions. Resolved from\n * $XDG_CACHE_HOME when set, falling back to ~/.cache/infra-kit. Keep in sync\n * with the shell block emitted by `infra-kit setup` (src/commands/init/init.ts).\n */\nexport const getCacheRoot = (): string => {\n const xdg = process.env.XDG_CACHE_HOME\n const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), '.cache')\n\n return path.join(base, 'infra-kit')\n}\n\nexport const getSessionCacheDir = (): string => {\n const session = process.env[INFRA_KIT_SESSION_VAR]\n\n if (!session) {\n throw new Error(\n `${INFRA_KIT_SESSION_VAR} is not set. Run \\`infra-kit setup --skip-tools\\` then \\`source ~/.zshrc\\`.`,\n )\n }\n\n return path.join(getCacheRoot(), session)\n}\n\n/**\n * The warm-cache key for a project: the hex SHA-256 of its CANONICAL (realpath'd)\n * directory. This MUST be byte-identical to the zsh block's\n * `printf %s \"$canon\" | shasum -a 256 | cut -c1-64` \u2014 same input string (no\n * trailing newline), same digest, full 64-hex output \u2014 or a warm file written by\n * node is never found by the shell. The shell passes the already-canonicalized\n * dir via `--project-dir`, so node hashes that VERBATIM (it does not re-resolve).\n */\nexport const warmCacheKey = (canonicalProjectDir: string): string => {\n return crypto.createHash('sha256').update(canonicalProjectDir, 'utf8').digest('hex')\n}\n\n/** Root holding all project-scoped warm caches: `$cacheRoot/projects`. */\nexport const getWarmCacheRoot = (): string => {\n return path.join(getCacheRoot(), WARM_CACHE_SUBDIR)\n}\n\n/** This project's warm-cache dir: `$cacheRoot/projects/<warmCacheKey>`. */\nexport const getProjectWarmCacheDir = (canonicalProjectDir: string): string => {\n return path.join(getWarmCacheRoot(), warmCacheKey(canonicalProjectDir))\n}\n\n/**\n * Write content atomically: write to a pid-suffixed temp file in the same\n * directory, then rename. fs.renameSync is atomic on a single filesystem, so\n * concurrent writers can't produce a half-written secret file.\n */\nexport const atomicWriteFileSync = (filePath: string, content: string, mode: number): void => {\n const tmpPath = `${filePath}.tmp.${process.pid}`\n\n fs.writeFileSync(tmpPath, content, { mode })\n\n try {\n fs.renameSync(tmpPath, filePath)\n } catch (error) {\n fs.rmSync(tmpPath, { force: true })\n throw error\n }\n}\n\nexport const WORKTREES_DIR_SUFFIX = '-worktrees'\n// eslint-disable-next-line sonarjs/publicly-writable-directories\nexport const LOG_FILE_PATH = '/tmp/mcp-infra-kit.log'\n"],
5
- "mappings": "AAAA,OAAOA,MAAY,cACnB,OAAOC,MAAQ,UACf,OAAOC,MAAQ,UACf,OAAOC,MAAU,YACjB,OAAOC,MAAa,eAEb,IAAMC,EAAgB,cAChBC,EAAiB,eAKjBC,EAAoB,WAUpBC,EAA2B,KAE3BC,EAAwB,oBAYxBC,EAAuB,aAQvBC,EAAoB,gBACpBC,EAA2B,uBAC3BC,EAA4B,wBAM5BC,EAAiC,6BACjCC,EAA8B,0BAO9BC,EAA+B,2BAM/BC,EAA4B,wBAO5BC,EAAuB,iBAM9BC,EAAqB,uBAQrBC,EAA0B,CAACC,EAAcC,IAAmC,CAChF,IAAIC,EAAUD,EAEd,QAASE,EAAI,EAAGA,EAAIH,EAAK,OAAQG,IAAK,CACpC,GAAI,CAACD,GAAWF,EAAKG,CAAC,IAAM,KAAM,CAChCA,IACA,QACF,CAEIH,EAAKG,CAAC,IAAM,MACdD,EAAU,CAACA,EAEf,CAEA,OAAOA,CACT,EAaME,EAAsBC,GAAwB,CAClD,IAAMC,EAAcD,EAAI,WAAW,GAAG,EAAIA,EAAI,MAAM,CAAC,EAAIA,EAGzD,OAFaC,EAAY,SAAS,GAAG,EAAIA,EAAY,MAAM,EAAG,EAAE,EAAIA,GAExD,MAAM,OAAO,EAAE,KAAK,GAAG,CACrC,EAGMC,EAAsBC,GAA6B,CACvD,GAAI,CACF,OAAO5B,EAAG,aAAa4B,EAAU,OAAO,CAC1C,MAAQ,CACN,MAAO,EACT,CACF,EASMC,EAAoB,CACxBC,EACAC,EACAC,IACS,CAGT,IAAMC,EAAQH,E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ACjC,OAASgC,EAAO,CACd,MAAA5D,EAAG,OAAO2D,EAAS,CAAE,MAAO,EAAK,CAAC,EAC5BC,CACR,CACF,EAEaC,EAAuB",
6
- "names": ["crypto", "fs", "os", "path", "process", "ENV_LOAD_FILE", "ENV_CLEAR_FILE", "WARM_CACHE_SUBDIR", "DEFAULT_WARM_TTL_SECONDS", "INFRA_KIT_SESSION_VAR", "USER_CONFIG_DIR_NAME", "INFRA_KIT_ENV_VAR", "INFRA_KIT_ENV_CONFIG_VAR", "INFRA_KIT_ENV_PROJECT_VAR", "INFRA_KIT_ENV_PROJECT_ROOT_VAR", "INFRA_KIT_ENV_LOADED_AT_VAR", "INFRA_KIT_ENV_AUTOLOADED_VAR", "INFRA_KIT_ENV_CLEARED_VAR", "ENV_VAR_LINE_PATTERN", "UNSET_LINE_PATTERN", "advanceSingleQuoteState", "line", "startInQuote", "inQuote", "i", "decodeSingleQuoted", "raw", "withoutOpen", "readEnvFileContent", "filePath", "forEachAssignment", "content", "visit", "visitUnset", "lines", "index", "match", "unset", "name", "rest", "parts", "open", "continuation", "parseVarNamesFromEnvFile", "names", "parseVarsFromEnvFile", "vars", "value", "parseUnsetNamesFromEnvFile", "getCacheRoot", "xdg", "base", "getSessionCacheDir", "session", "warmCacheKey", "canonicalProjectDir", "getWarmCacheRoot", "getProjectWarmCacheDir", "atomicWriteFileSync", "mode", "tmpPath", "error", "WORKTREES_DIR_SUFFIX"]
4
+ "sourcesContent": ["import crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nexport const ENV_LOAD_FILE = 'env-load.sh'\nexport const ENV_CLEAR_FILE = 'env-clear.sh'\n\n/** Subdir of the cache root holding the project-scoped WARM caches (one dir per\n * project, keyed by {@link warmCacheKey}). Kept in sync with the zsh block in\n * init.ts, which reads `$cache_root/projects/$key/env-load.sh`. */\nexport const WARM_CACHE_SUBDIR = 'projects'\n\n/**\n * Default warm-cache TTL in seconds (2h). Governs BOTH the node-side eviction\n * sweep and the zsh-side source gate (`_INFRA_KIT_WARM_TTL` in the shell block);\n * the two MUST stay equal, so this constant is the single source of truth and the\n * shell default is emitted from it. Short by design: a warm file older than this\n * is never sourced (bounds a revoked/rotated secret served at prompt-0) and is\n * deleted on the next write. The background refresh lands in ~1-2s regardless.\n */\nexport const DEFAULT_WARM_TTL_SECONDS = 2 * 60 * 60\n\nexport const INFRA_KIT_SESSION_VAR = 'INFRA_KIT_SESSION'\n/**\n * Directory under the user's home that holds all machine-local infra-kit config:\n * the runtime `infra-kit.json` merge layer, per-project overrides, the factory\n * registry (`vendor.json`), and the `portless` package link. Single source of\n * truth for `.infra-kit`.\n *\n * Defined HERE, not in `lib/infra-kit-config`, because that module pulls in zod\n * and the `ik-mcp` proxy bundle must stay Node-builtins-only (guarded in\n * `entry/__tests__/dist-shebang.test.ts`); `lib/infra-kit-config` re-exports it\n * for its existing consumers.\n */\nexport const USER_CONFIG_DIR_NAME = '.infra-kit'\n/**\n * The active environment/config NAME (e.g. `dev`, `arthur`), exported plainly so\n * non-shell consumers can read it from `process.env`. Notably `infra-kit/vite`'s\n * `infraKitDev()` reads this to interpolate the `<env>` placeholder in cloud proxy\n * targets. Mirrors {@link INFRA_KIT_ENV_CONFIG_VAR} (same value) but is the stable,\n * purpose-named handle for tooling rather than the shell session-metadata var.\n */\nexport const INFRA_KIT_ENV_VAR = 'INFRA_KIT_ENV'\nexport const INFRA_KIT_ENV_CONFIG_VAR = 'INFRA_KIT_ENV_CONFIG'\nexport const INFRA_KIT_ENV_PROJECT_VAR = 'INFRA_KIT_ENV_PROJECT'\n/**\n * Absolute project root (git top-level) the loaded env belongs to. Lets the shell\n * startup gate tell a same-project subshell (skip) from a NEW project (load), so a\n * different project's secrets are never silently kept after `cd`/new shell.\n */\nexport const INFRA_KIT_ENV_PROJECT_ROOT_VAR = 'INFRA_KIT_ENV_PROJECT_ROOT'\nexport const INFRA_KIT_ENV_LOADED_AT_VAR = 'INFRA_KIT_ENV_LOADED_AT'\n/**\n * Marker exported into env-load.sh ONLY when the load was triggered automatically\n * (see lib/env-autoload). Its presence is the sole signal distinguishing an\n * auto-loaded env from a deliberate manual `env-load`, so auto-load never\n * clobbers a manual choice. A manual load unsets it.\n */\nexport const INFRA_KIT_ENV_AUTOLOADED_VAR = 'INFRA_KIT_ENV_AUTOLOADED'\n/**\n * Suppression sentinel exported by env-clear. While set in a shell, cli-invocation\n * auto-load stays silent (a deliberate clear must not be immediately re-loaded).\n * Lifted by a manual `env-load` or a new shell.\n */\nexport const INFRA_KIT_ENV_CLEARED_VAR = 'INFRA_KIT_ENV_CLEARED'\n\n/**\n * Matches a line of the form `KEY=...` where KEY is an env-var identifier\n * (letter or underscore, then word chars). Capture group 1 is the name. Shared\n * between env-load (validation, var counting) and parseVarNamesFromEnvFile.\n */\nexport const ENV_VAR_LINE_PATTERN = /^([A-Z_]\\w*)=/i\n\n/**\n * The `unset NAME` line env-clear.sh is made of and a manual env-load.sh ends with. Anchored at\n * both ends so a value that merely starts with the word is not a match.\n */\nconst UNSET_LINE_PATTERN = /^unset ([A-Z_]\\w*)$/i\n\n/**\n * Track whether a physical line leaves us inside an open single-quoted value,\n * mirroring how `shellSingleQuote` emits values (`'\u2026'`, with literal quotes as\n * `'\\''`). Outside a quote a backslash escapes the next char; inside a quote a\n * `'` closes it. Lets the parser skip the continuation lines of a multiline value.\n */\nconst advanceSingleQuoteState = (line: string, startInQuote: boolean): boolean => {\n let inQuote = startInQuote\n\n for (let i = 0; i < line.length; i++) {\n if (!inQuote && line[i] === '\\\\') {\n i++\n continue\n }\n\n if (line[i] === \"'\") {\n inQuote = !inQuote\n }\n }\n\n return inQuote\n}\n\n/** One `KEY=value` assignment recovered from an env file, value already unescaped. */\nexport interface EnvAssignment {\n name: string\n value: string\n}\n\n/**\n * Undo {@link shellSingleQuote}: drop the wrapping quotes, then turn each `'\\''`\n * back into a literal `'`. Order matters \u2014 unescaping first would let an embedded\n * `'\\''` be mistaken for the closing quote.\n */\nconst decodeSingleQuoted = (raw: string): string => {\n const withoutOpen = raw.startsWith(\"'\") ? raw.slice(1) : raw\n const body = withoutOpen.endsWith(\"'\") ? withoutOpen.slice(0, -1) : withoutOpen\n\n return body.split(\"'\\\\''\").join(\"'\")\n}\n\n/** File contents, or '' when the path is absent, a directory, or unreadable. */\nconst readEnvFileContent = (filePath: string): string => {\n try {\n return fs.readFileSync(filePath, 'utf-8')\n } catch {\n return ''\n }\n}\n\n/**\n * Walk every assignment in an env-load.sh body, skipping the continuation lines of\n * multiline values. {@link parseVarNamesFromEnvFile}, {@link parseVarsFromEnvFile}\n * and {@link parseUnsetNamesFromEnvFile} all go through here, so they can never\n * disagree about where a value ends \u2014 an `unset X` inside a quoted value is a\n * continuation line to every one of them.\n */\nconst forEachAssignment = (\n content: string,\n visit: (assignment: EnvAssignment) => void,\n visitUnset?: (name: string) => void,\n): void => {\n // A trailing CR is stripped per line: a CRLF file would otherwise hand back values\n // ending in '\\r' \u2014 a token that looks right in a diff and fails every request.\n const lines = content.split('\\n').map((line) => {\n return line.endsWith('\\r') ? line.slice(0, -1) : line\n })\n let index = 0\n let inQuote = false\n\n while (index < lines.length) {\n const line = lines[index]!\n\n // Only a line that starts OUTSIDE a quoted value can be a real assignment;\n // continuation lines of a multiline secret value are skipped.\n if (inQuote) {\n inQuote = advanceSingleQuoteState(line, inQuote)\n index += 1\n continue\n }\n\n const match = ENV_VAR_LINE_PATTERN.exec(line)\n\n if (!match) {\n const unset = UNSET_LINE_PATTERN.exec(line)\n\n if (unset) visitUnset?.(unset[1]!)\n\n inQuote = advanceSingleQuoteState(line, false)\n index += 1\n continue\n }\n\n const name = match[1]!\n const rest = line.slice(match[0].length)\n\n // An unquoted value cannot span lines (`CONNECTION_STRING=host=db;user=admin`).\n if (!rest.startsWith(\"'\")) {\n visit({ name, value: rest })\n inQuote = advanceSingleQuoteState(line, false)\n index += 1\n continue\n }\n\n const parts = [rest]\n let open = advanceSingleQuoteState(rest, false)\n\n while (open && index + 1 < lines.length) {\n index += 1\n const continuation = lines[index]!\n\n parts.push(continuation)\n open = advanceSingleQuoteState(continuation, true)\n }\n\n visit({ name, value: decodeSingleQuoted(parts.join('\\n')) })\n inQuote = open\n index += 1\n }\n}\n\nexport const parseVarNamesFromEnvFile = (filePath: string): string[] => {\n const names: string[] = []\n\n forEachAssignment(readEnvFileContent(filePath), ({ name }) => {\n names.push(name)\n })\n\n return names\n}\n\n/**\n * Same walk as {@link parseVarNamesFromEnvFile}, but keeping the values. Later\n * assignments win, matching what `source`ing the file would do.\n */\nexport const parseVarsFromEnvFile = (filePath: string): Record<string, string> => {\n const vars: Record<string, string> = {}\n\n forEachAssignment(readEnvFileContent(filePath), ({ name, value }) => {\n vars[name] = value\n })\n\n return vars\n}\n\n/**\n * The names the file `unset`s \u2014 everything env-clear.sh does, and the marker lines a\n * manual env-load.sh ends with. Absent file \u2192 `[]`, like its siblings.\n */\nexport const parseUnsetNamesFromEnvFile = (filePath: string): string[] => {\n const names: string[] = []\n\n forEachAssignment(\n readEnvFileContent(filePath),\n () => {},\n (name) => {\n names.push(name)\n },\n )\n\n return names\n}\n\n/**\n * Root cache dir for infra-kit across all sessions. Resolved from\n * $XDG_CACHE_HOME when set, falling back to ~/.cache/infra-kit. Keep in sync\n * with the shell block emitted by `infra-kit setup` (src/commands/init/init.ts).\n */\nexport const getCacheRoot = (): string => {\n const xdg = process.env.XDG_CACHE_HOME\n const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), '.cache')\n\n return path.join(base, 'infra-kit')\n}\n\nexport const getSessionCacheDir = (): string => {\n const session = process.env[INFRA_KIT_SESSION_VAR]\n\n if (!session) {\n throw new Error(\n `${INFRA_KIT_SESSION_VAR} is not set. Run \\`infra-kit setup --skip-tools\\` then \\`source ~/.zshrc\\`.`,\n )\n }\n\n return path.join(getCacheRoot(), session)\n}\n\n/**\n * The warm-cache key for a project: the hex SHA-256 of its CANONICAL (realpath'd)\n * directory. This MUST be byte-identical to the zsh block's\n * `printf %s \"$canon\" | shasum -a 256 | cut -c1-64` \u2014 same input string (no\n * trailing newline), same digest, full 64-hex output \u2014 or a warm file written by\n * node is never found by the shell. The shell passes the already-canonicalized\n * dir via `--project-dir`, so node hashes that VERBATIM (it does not re-resolve).\n */\nexport const warmCacheKey = (canonicalProjectDir: string): string => {\n return crypto.createHash('sha256').update(canonicalProjectDir, 'utf8').digest('hex')\n}\n\n/** Root holding all project-scoped warm caches: `$cacheRoot/projects`. */\nexport const getWarmCacheRoot = (): string => {\n return path.join(getCacheRoot(), WARM_CACHE_SUBDIR)\n}\n\n/** This project's warm-cache dir: `$cacheRoot/projects/<warmCacheKey>`. */\nexport const getProjectWarmCacheDir = (canonicalProjectDir: string): string => {\n return path.join(getWarmCacheRoot(), warmCacheKey(canonicalProjectDir))\n}\n\n/**\n * Write content atomically: write to a pid-suffixed temp file in the same\n * directory, then rename. fs.renameSync is atomic on a single filesystem, so\n * concurrent writers can't produce a half-written secret file.\n */\nexport const atomicWriteFileSync = (filePath: string, content: string, mode: number): void => {\n const tmpPath = `${filePath}.tmp.${process.pid}`\n\n fs.writeFileSync(tmpPath, content, { mode })\n\n try {\n fs.renameSync(tmpPath, filePath)\n } catch (error) {\n fs.rmSync(tmpPath, { force: true })\n throw error\n }\n}\n\nexport const WORKTREES_DIR_SUFFIX = '-worktrees'\n"],
5
+ "mappings": "AAAA,OAAOA,MAAY,cACnB,OAAOC,MAAQ,UACf,OAAOC,MAAQ,UACf,OAAOC,MAAU,YACjB,OAAOC,MAAa,eAEb,IAAMC,EAAgB,cAChBC,EAAiB,eAKjBC,EAAoB,WAUpBC,EAA2B,KAE3BC,EAAwB,oBAYxBC,EAAuB,aAQvBC,EAAoB,gBACpBC,EAA2B,uBAC3BC,EAA4B,wBAM5BC,EAAiC,6BACjCC,EAA8B,0BAO9BC,EAA+B,2BAM/BC,EAA4B,wBAO5BC,EAAuB,iBAM9BC,EAAqB,uBAQrBC,EAA0B,CAACC,EAAcC,IAAmC,CAChF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,EAAE,OAAOD,EAAqB,MAAM,EAAE,OAAO,KAAK,EAIxEE,EAAmB,IACvBR,EAAK,KAAKJ,EAAa,EAAGa,CAAiB,EAIvCC,EAA0BJ,GAC9BN,EAAK,KAAKQ,EAAiB,EAAGH,EAAaC,CAAmB,CAAC,EAQ3DK,EAAsB,CAACC,EAAkBC,EAAiBC,IAAuB,CAC5F,IAAMC,EAAU,GAAGH,CAAQ,QAAQd,EAAQ,GAAG,GAE9CkB,EAAG,cAAcD,EAASF,EAAS,CAAE,KAAAC,CAAK,CAAC,EAE3C,GAAI,CACFE,EAAG,WAAWD,EAASH,CAAQ,CACjC,OAASK,EAAO,CACd,MAAAD,EAAG,OAAOD,EAAS,CAAE,MAAO,EAAK,CAAC,EAC5BE,CACR,CACF,EAEaC,EAAuB",
6
+ "names": ["crypto", "fs", "os", "path", "process", "ENV_LOAD_FILE", "ENV_CLEAR_FILE", "WARM_CACHE_SUBDIR", "DEFAULT_WARM_TTL_SECONDS", "INFRA_KIT_SESSION_VAR", "USER_CONFIG_DIR_NAME", "INFRA_KIT_ENV_VAR", "INFRA_KIT_ENV_CONFIG_VAR", "INFRA_KIT_ENV_PROJECT_VAR", "INFRA_KIT_ENV_PROJECT_ROOT_VAR", "INFRA_KIT_ENV_LOADED_AT_VAR", "INFRA_KIT_ENV_AUTOLOADED_VAR", "INFRA_KIT_ENV_CLEARED_VAR", "ENV_VAR_LINE_PATTERN", "UNSET_LINE_PATTERN", "advanceSingleQuoteState", "line", "startInQuote", "inQuote", "i", "decodeSingleQuoted", "raw", "withoutOpen", "readEnvFileContent", "filePath", "forEachAssignment", "content", "visit", "visitUnset", "lines", "index", "match", "unset", "name", "rest", "parts", "open", "continuation", "parseVarNamesFromEnvFile", "names", "parseVarsFromEnvFile", "vars", "value", "getCacheRoot", "xdg", "process", "base", "path", "os", "getSessionCacheDir", "session", "INFRA_KIT_SESSION_VAR", "warmCacheKey", "canonicalProjectDir", "crypto", "getWarmCacheRoot", "WARM_CACHE_SUBDIR", "getProjectWarmCacheDir", "atomicWriteFileSync", "filePath", "content", "mode", "tmpPath", "fs", "error", "WORKTREES_DIR_SUFFIX"]
7
7
  }
@@ -0,0 +1,10 @@
1
+ import{N as f,l as D,la as W,r as G}from"./chunk-7AMRJ4IW.js";import{execFile as re,execFileSync as te}from"node:child_process";import w from"node:process";var oe=5e3,ne=100,$=2e3,F="/bin/ps",ae=1e3,U=["-eo","pid=,ppid=,pgid=,lstart="],V=8<<20,B=r=>r.split(`
2
+ `).flatMap(e=>{let[t,o,n,...a]=e.trim().split(/\s+/);if(t==null||o==null||n==null)return[];let c=Number(t),s=Number(o),l=Number(n);return!Number.isInteger(c)||!Number.isInteger(s)||!Number.isInteger(l)?[]:[{pid:c,ppid:s,pgid:l,lstart:a.join(" ")}]}),j=r=>{let e=new Map;for(let t of r)t.pid===t.pgid&&e.set(t.pgid,t.lstart);return e},se=(r,e,t)=>{let o=j(e);return H(r,e,t).flatMap(n=>{let a=o.get(n);return a==null||a===""?[]:[{pgid:n,leaderStart:a}]})},K=(r,e)=>{let t=j(e);return r.flatMap(({pgid:o,leaderStart:n})=>t.get(o)===n?[o]:[])},J=(r,e)=>K(r,e).flatMap(t=>{try{w.kill(-t,"SIGKILL")}catch{return[]}return[t]}),H=(r,e,t)=>{let o=new Map;for(let s of e){let l=o.get(s.ppid);l?l.push(s):o.set(s.ppid,[s])}let n=new Set([r]),a=new Set([r]),c=[r];for(let s=0;s<c.length;s+=1)for(let l of o.get(c[s]??-1)??[])a.has(l.pid)||(a.add(l.pid),n.add(l.pgid),c.push(l.pid));return[...n].filter(s=>s>1&&s!==t)},L=()=>{try{return B(te(F,[...U],{encoding:"utf8",maxBuffer:V}))}catch{return[]}},ie=async()=>new Promise(r=>{re(F,[...U],{encoding:"utf8",maxBuffer:V},(e,t)=>{r(e?[]:B(t))})}),ce=(r,e,t)=>t.some(o=>o.pid===r&&o.ppid===e),_=(r,e)=>{let t=e.find(o=>o.pid===w.pid)?.pgid;return H(r,e,t)},q=r=>{try{return w.kill(-r,0),!0}catch{return!1}},C=(r,e)=>{for(let t of r)try{w.kill(-t,e)}catch{}},P=new Set,le=(r,e,t)=>{let o=_(r,e),n=t.flatMap(a=>K(a,e));return[...new Set([...o,...n])]},z=()=>{let r=L(),e=[...P].map(t=>t());C(le(w.pid,r,e),"SIGKILL")},ue=async r=>new Promise(e=>{setTimeout(e,r)}),v=async(r,e)=>{let t=Date.now()+e,o=r;for(;o.length>0&&Date.now()<t&&(o=o.filter(q),o.length!==0);)await ue(ne);return o};function er(r,e=oe,t,o=L){r.unref();let n=!1,a=!1,c=[],s=null,l=()=>c;P.add(l);let m=()=>{s&&clearInterval(s),s=null},b=async()=>{await v(c.map(i=>i.pgid),$),P.delete(l)},y=i=>{let u=r.pid;if(u==null||a||n||i.length===0)return;let T=i.find(E=>E.pid===w.pid)?.pgid,S=se(u,i,T);S.length>0&&(c=S)},h=async()=>{r.pid==null||a||n||y(await ie())};y(L()),s=setInterval(()=>{h()},ae),s.unref();let R=i=>{n||t?.(i)};return r.on("exit",(i,u)=>{a=!0,m(),n||(J(c,o()),b()),R(`exited unexpectedly (code=${i??"null"}, signal=${u??"null"})`)}),r.on("error",i=>{R(`failed to spawn: ${i.message}`)}),{kill:async()=>{n=!0,m();let i=r.pid;if(i==null){P.delete(l);return}if(r.exitCode!==null||r.signalCode!==null){J(c,o()),await b();return}let u=o();if(u.length>0&&!ce(i,w.pid,u))return;let T=_(i,u);C(T,"SIGTERM");let S=await v(T,e);if(S.length===0){P.delete(l);return}let E=_(i,o()),M=[...new Set([...S,...E])].filter(q);C(M,"SIGKILL"),await v(M,$),P.delete(l)}}}import{constants as pe}from"node:os";import k from"node:process";var de=["SIGINT","SIGTERM","SIGHUP"],me=pe.signals,fe=2,N=r=>128+(me[r]??fe),ge=2e4,Oe=r=>{k.exit(r)},we=(r,e)=>{k.on(r,e)},be=(r,e)=>{k.off(r,e)},ye=(r,e)=>{let t=setTimeout(r,e);return t.unref(),()=>{clearTimeout(t)}},A=r=>{try{k.stderr.write(r)}catch{}},he=(r,e)=>{let t=e instanceof Error?`${e.message}
3
+ ${e.stack??"(no stack)"}`:String(e);A(`
4
+ \u2717 Teardown failed while handling ${r}: ${t}
5
+ `)},ar=({onSignal:r,exit:e=Oe,register:t=we,unregister:o=be,forceReap:n=z,teardownDeadlineMs:a=ge,setTimer:c=ye,describeStall:s=()=>"unknown",fileReport:l=()=>{}})=>{let m=null,b=null,y=new Map,h=()=>{for(let[i,u]of y)o(i,u);y.clear()},R=i=>{if(m!==null){if(i!==m)return;A(`
6
+ \u26A0 Received ${i} again \u2014 force-quitting.
7
+ `),b?.(),n(),h(),e(N(i));return}m=i,b=c(()=>{let u=`
8
+ \u26A0 Teardown deadline exceeded at stage=${s()} after ${a}ms \u2014 force-quitting.
9
+ `;A(u),l(u),n(),h(),e(N(i))},a),(async()=>{try{await r(i)}catch(u){he(i,u)}finally{b?.(),h(),e(N(i))}})()};for(let i of de){let u=()=>R(i);y.set(i,u),t(i,u)}return h};var Pe=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),X=r=>r instanceof Error&&Pe.has(r.name),ir=r=>{if(X(r))return!0;let e=r?.cause;return X(e)};import{loadDev as xe}from"@slip-stream-kit/config/internal";import Se from"node:path";var Re=(r,e)=>{let t=new Set;for(let o of Object.values(r))for(let n of Object.keys(W(o,e).proxy))t.add(n);return[...t]},Te=async(r,e)=>{let t={},o=[];return await Promise.all(e.map(async n=>{try{let c=(await xe(Se.join(r,"apps",n,"ui")))?.proxy?.routes;if(!c)return;t[n]=Object.fromEntries(Object.entries(c).map(([s,l])=>[s,l.packageName]))}catch(a){o.push({app:n,message:a instanceof Error?a.message:String(a)})}})),{routePkg:(n,a)=>t[n]?.[a],loadErrors:o}},dr=async(r,e,t,o)=>{let{routePkg:n,loadErrors:a}=await Te(r,Re(e,t));return{ctx:{discovered:t,apiPkgByApp:Object.fromEntries(o.map(c=>[c.name,c.packageName])),routePkg:n},loadErrors:a}};import{$ as ke}from"zx";var d=class extends Error{code;data;constructor(e){super(e.message),this.name="OrcaError",this.code=e.code,this.data=e.data}},x=class extends Error{exitCode;stderrTail;constructor(e,t){super(`orca: stdout is not a JSON envelope (exit ${e??"signal"})`),this.name="OrcaMalformedError",this.exitCode=e,this.stderrTail=t}},g=class extends Error{constructor(){super("orca: command not found \u2014 the CLI is registered from Orca \u2192 Settings \u2192 Experimental \u2192 CLI"),this.name="OrcaAbsentError"}},Ee=400,ve=127,Le=r=>typeof r=="object"&&r!==null&&r.code==="ENOENT",_e=async r=>{try{return await ke({nothrow:!0,quiet:!0})`orca ${r} --json`}catch(e){throw Le(e)?new g:e}},Ce=r=>{try{let e=JSON.parse(r);return typeof e=="object"&&e!==null&&typeof e.ok=="boolean"?e:null}catch{return null}},p=async r=>{let e=await _e(r),t=Ce(e.stdout);if(f.debug({argv:r,ok:t?.ok,code:t?.error?.code,exitCode:e.exitCode},"orca"),!t)throw e.exitCode===ve?new g:new x(e.exitCode,e.stderr.slice(-Ee));if(!t.ok)throw new d(t.error??{code:"unknown",message:"orca: ok:false without an error payload"});return t.result};var Ne=async()=>{try{let r=await p(["status"]);return f.debug({appVersion:r.runtime?.appVersion},"orca: status"),r.app?.running===!0&&r.runtime?.reachable===!0?"ready":"unreachable"}catch(r){return r instanceof g?"absent":(f.debug({error:r},"orca: status probe failed"),"unreachable")}};import{realpath as Ae}from"node:fs/promises";var O=async r=>{try{return await Ae(r)}catch{return r}};var Ie=async r=>{let[{repos:e=[]},t]=await Promise.all([p(["repo","list"]),O(r)]);for(let o of e)if(await O(o.path)===t)return{registered:!0,visibility:o.externalWorktreeVisibility};return{registered:!1}},Me=async r=>{let{repo:e}=await p(["repo","add","--path",r]);return{visibility:e?.externalWorktreeVisibility}};var De="500",Ge=async(r,e)=>{let[{worktrees:t=[]},o]=await Promise.all([p(["worktree","list","--repo",`path:${r}`,"--limit",De]),O(e)]);for(let n of t)if(await O(n.path)===o)return!0;return!1};import We from"node:process";var Y="::",$e=r=>{let e=r.ORCA_WORKTREE_ID;if(!e)return null;let t=e.indexOf(Y);if(t<0)return null;let o=e.slice(t+Y.length);return o.length>0?o:null},Je=async(r,e=We.env)=>{let t=$e(e);if(t===null)return null;let o=await O(t);for(let n of r)if(await O(n)===o)return n;return null};var Q="200",I=async r=>{try{let e=await p(["terminal","list","--worktree",`path:${r}`,"--limit",Q]),t=e.truncated===!0;return t&&f.debug({cwd:r,limit:Q},"orca: terminal list truncated"),{terminals:e.terminals??[],truncated:t}}catch(e){if(e instanceof d&&e.code==="selector_not_found")return{terminals:[],truncated:!1};throw e}};var Fe=async r=>{try{return await p(["terminal","close","--worktree",`path:${r}`,"--all"]),"retired"}catch(e){if(e instanceof d&&e.code==="selector_not_found")return"not_found";if(e instanceof d&&e.code==="terminal_close_incomplete")return f.debug({cwd:r,error:e},"orca: surfaces not retired"),"retired";throw e}},Ue=async r=>{let{terminals:e}=await I(r);for(let o of e)await p(["terminal","close","--terminal",o.handle]);let t=await Fe(r);return e.length===0&&t==="not_found"?{closed:!1,skipped:"not_found"}:{closed:!0,count:e.length}},Ve=(r,e)=>e instanceof g?{closed:!1,skipped:"absent"}:e instanceof d?{closed:!1,error:e}:e instanceof x?{closed:!1,error:new d({code:"orca_malformed_output",message:e.message,data:{exitCode:e.exitCode,stderrTail:e.stderrTail}})}:(f.debug({cwd:r,error:e},"orca: close failed outside the Orca contract"),{closed:!1,error:new d({code:"orca_close_failed",message:e instanceof Error?e.message:String(e)})}),Be=async(r,e)=>{if(e!=="ready")return{closed:!1,skipped:e};try{return await Ue(r)}catch(t){return Ve(r,t)}};import{setTimeout as je}from"node:timers/promises";var Ke=3,He=300,ee=(r={})=>({attempts:r.attempts??Ke,delayMs:r.delayMs??He,exhausted:!1}),qe=async r=>{try{return{created:await p(r)}}catch(e){if(e instanceof d&&e.code==="selector_not_found")return{notSelectable:e};throw e}},ze=async(r,e,t)=>{let o=t.exhausted?1:t.attempts,n=Array.from({length:o},(c,s)=>s+1),a;for(let c of n){let s=await qe(r);if("created"in s)return s.created.terminal.handle;a=s.notSelectable,c<o&&await je(t.delayMs)}throw t.exhausted=!0,new d({code:"orca_worktree_not_selectable",message:`orca: worktree ${e} is not selectable after ${o} attempt(s): ${a?.message??""}`,data:{cwd:e,attempts:o,cause:a?.data}})},Z=async(r,e)=>(await p(["terminal","split","--terminal",r,"--direction",e])).split.handle,Xe=async r=>{let{cwd:e,title:t,focus:o,layout:n,panes:a,poll:c=ee()}=r,s=["terminal","create","--worktree",`path:${e}`,"--title",t,...o?["--focus"]:[]],l=await ze(s,e,c),m=[l];return n==="full"&&(m.push(await Z(l,"horizontal")),a==="three-pane"&&m.push(await Z(l,"vertical"))),{handles:m,layout:n}};var Ye=r=>{let{branch:e}=r,t=D(e);return t?G(t):e};export{dr as a,d as b,p as c,Ne as d,Je as e,I as f,Be as g,Ie as h,Me as i,Ge as j,ee as k,Xe as l,Ye as m,z as n,er as o,N as p,ar as q,ir as r};
10
+ //# sourceMappingURL=chunk-OPL7C5H6.js.map