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.
- package/dist/{boot-BL4EQMZV.js → boot-XLDVLQEG.js} +2 -2
- package/dist/boot-XLDVLQEG.js.map +7 -0
- package/dist/chunk-7AMRJ4IW.js +9 -0
- package/dist/chunk-7AMRJ4IW.js.map +7 -0
- package/dist/{chunk-HHWP3YXW.js → chunk-AWFGP6GY.js} +1 -1
- package/dist/{chunk-HHWP3YXW.js.map → chunk-AWFGP6GY.js.map} +1 -1
- package/dist/chunk-JUNJK2YC.js +3 -0
- package/dist/chunk-JUNJK2YC.js.map +7 -0
- package/dist/chunk-MOVRKV3I.js +4 -0
- package/dist/{chunk-75URROMU.js.map → chunk-MOVRKV3I.js.map} +3 -3
- package/dist/chunk-OPL7C5H6.js +10 -0
- package/dist/{chunk-AOWMCNYY.js.map → chunk-OPL7C5H6.js.map} +4 -4
- package/dist/chunk-WUTG6VMP.js +7 -0
- package/dist/chunk-WUTG6VMP.js.map +7 -0
- package/dist/{chunk-6OFUVD7F.js → chunk-YYC3QGGC.js} +2 -2
- package/dist/chunk-YYC3QGGC.js.map +7 -0
- package/dist/cli.js +457 -13
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +19 -19
- package/dist/dev-server.js.map +4 -4
- package/dist/dev-wizard-run-ITRFKMTL.js +2 -0
- package/dist/dev-wizard-run-ITRFKMTL.js.map +7 -0
- package/dist/mcp-proxy.js +1 -1
- package/dist/update-check.js +1 -1
- package/dist/update-check.js.map +1 -1
- package/package.json +3 -7
- package/readme.md +1 -2
- package/dist/boot-BL4EQMZV.js.map +0 -7
- package/dist/chunk-5XK34MWH.js +0 -442
- package/dist/chunk-5XK34MWH.js.map +0 -7
- package/dist/chunk-6OFUVD7F.js.map +0 -7
- package/dist/chunk-75URROMU.js +0 -4
- package/dist/chunk-AEVL5XWO.js +0 -3
- package/dist/chunk-AEVL5XWO.js.map +0 -7
- package/dist/chunk-AOWMCNYY.js +0 -10
- package/dist/chunk-BVEVERTB.js +0 -7
- package/dist/chunk-BVEVERTB.js.map +0 -7
- package/dist/chunk-GCX3HDDL.js +0 -9
- package/dist/chunk-GCX3HDDL.js.map +0 -7
- package/dist/dev-wizard-run-RPZOX53B.js +0 -2
- package/dist/dev-wizard-run-RPZOX53B.js.map +0 -7
- package/dist/mcp.js +0 -3
- package/dist/mcp.js.map +0 -7
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/dev/proxy/portless-link.ts", "../src/dev/proxy/portless-driver.ts", "../src/lib/shell-quote/shell-quote.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview\n *\n * `~/.infra-kit/portless` \u2014 a stable symlink to the portless PACKAGE directory bundled with the running\n * infra-kit, kept pointing at the current install by every process boot.\n *\n * Why it exists: `portless service install` bakes `process.execPath` and `process.argv[1]` verbatim into\n * the root launchd plist (`ProgramArguments`), and it offers no `--entry` flag to say otherwise. Under\n * pnpm 12 the script half of that pair is version-unstable \u2014 every `pnpm add -g infra-kit@x` mints a\n * fresh `global/v11/{pid}-{timestamp}/` project and removes the previous one, and the path also embeds\n * `infra-kit@<version>`. With silent auto-update on, the daemon's argv dangles after every release,\n * launchd cannot start it at the next boot, and the \"fix\" is another sudo. Node does NOT realpath\n * `argv[1]` (it keeps whatever string it was given) but DOES realpath `execPath`, so only the script half\n * can be made stable: point the plist at `<link>/dist/cli.js` and keep the link current.\n *\n * Why tmp + rename, never unlink first: `rename(2)` replaces a symlink atomically, so there is no\n * instant at which the path is absent. An unlink-then-symlink sequence has one \u2014 and a reboot inside it\n * leaves launchd with no script at all; `KeepAlive` retries the same dangling path forever, and `:443`\n * stays dark until a human runs `service install` again.\n *\n * Why the boot call must run on `version --json`: that is the exact invocation the background updater\n * spawns to verify a fresh install (`run-update-check.ts`, `readInstalledVersion`: `cwd = homedir()`,\n * `--json`, piped stdio). It is the FIRST process the new binary ever runs \u2014 and the one that re-points\n * the link after an auto-update, before any shell command does. So `bootPortlessLink` must not sit\n * behind `warnIfLocalInstall`'s `--json` guard, and it must not have an env opt-out: the link is state,\n * not advisory output.\n *\n * Every write is guarded by `isGlobalInstall`: a checkout or a project-local dependency never aims the\n * root daemon at itself (that would dangle the moment the worktree is removed). Nothing here spawns a\n * subprocess, touches stdout, or throws \u2014 the `ik-mcp` proxy calls it at boot with stdout carrying the\n * JSON-RPC transport, and the CLI calls it before Commander parses argv.\n */\nimport fs from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { fileURLToPath } from 'node:url'\n\nimport { USER_CONFIG_DIR_NAME } from 'src/lib/constants'\nimport { isGlobalInstall, safeRealpath } from 'src/lib/install-manager'\n\nimport { formatPortlessCommand, resolvePortlessBin } from './portless-driver'\nimport type { ExistsCheck } from './portless-driver'\n\n/** `<home>/.infra-kit/portless` \u2014 the link path; the same `home` seam the rest of the config layer uses. */\nexport const portlessLinkPath = (home: string): string => {\n return join(home, USER_CONFIG_DIR_NAME, 'portless')\n}\n\n/**\n * `<link>/dist/cli.js` when the link resolves to a portless with that file, else `null` \u2014 the path the\n * printed `service install` command (and the plist it writes) should carry. `exists` follows the\n * symlink, so a dangling link answers `null` and callers fall back to the real path.\n */\nexport const portlessLinkCliPath = (\n home: string,\n exists: (target: string) => boolean = fs.existsSync,\n): string | null => {\n const cliPath = join(portlessLinkPath(home), 'dist', 'cli.js')\n\n return exists(cliPath) ? cliPath : null\n}\n\n/** Where the link is looked up and which node to print; every seam is injectable so tests never read a real `~/.infra-kit`. */\nexport interface ServiceInstallSeams {\n home: string\n exists?: ExistsCheck\n execPath?: string\n}\n\n/**\n * The one-time, out-of-band, ROOT command that installs the `:443` daemon. infra-kit never runs it \u2014 it\n * only ever prints it (principle 3: infra-kit probes and prints, it never elevates). `doctor`, `setup`\n * and `dev` all print it from here so no two surfaces can disagree about the path that ends up as root.\n *\n * Rendered THROUGH `~/.infra-kit/portless/dist/cli.js` whenever that link resolves: portless bakes the\n * script path it was invoked with into the plist, so the command printed here decides whether the root\n * daemon survives the next `pnpm add -g infra-kit` (the link is re-pointed on every boot; the version-\n * specific path is deleted). `bin` \u2014 the resolved `dist/cli.js`, never a bare `portless` (see\n * {@link formatPortlessCommand}) \u2014 is the fallback only, for a machine where nothing has created the\n * link yet.\n */\nexport const serviceInstallCommand = (bin: string, seams: ServiceInstallSeams): string => {\n return formatPortlessCommand(['service', 'install'], {\n sudo: true,\n bin: portlessLinkCliPath(seams.home, seams.exists) ?? bin,\n execPath: seams.execPath,\n })\n}\n\nexport type PortlessLinkOutcome =\n 'created' | 'repointed' | 'unchanged' | 'skipped-local' | 'skipped-unresolved' | 'failed'\n\nexport interface PortlessLinkResult {\n outcome: PortlessLinkOutcome\n /** The portless package dir the link should point at; `null` only for `'skipped-unresolved'`. */\n target: string | null\n link: string\n}\n\n/**\n * The six fs calls the link needs, as an OBJECT seam. Named `node:fs` imports cannot be intercepted by\n * `vi.spyOn` (the binding is a live import, not a property), so the default export is the injectable\n * shape and tests hand in an in-memory fake instead of touching a real `~/.infra-kit`.\n */\nexport interface PortlessLinkFs {\n mkdirSync: (dir: string, options: { recursive: true }) => unknown\n lstatSync: (target: string, options: { throwIfNoEntry: false }) => { isSymbolicLink: () => boolean } | undefined\n readlinkSync: (target: string) => string\n symlinkSync: (target: string, linkPath: string) => void\n renameSync: (from: string, to: string) => void\n unlinkSync: (target: string) => void\n}\n\nexport interface EnsurePortlessLinkDeps {\n /** `resolvePortlessBin` \u2014 the bundled portless's `dist/cli.js`, or `null` when it is not installed. */\n resolveBin: () => string | null\n /** `isGlobalInstall` bound to this process \u2014 the ONLY gate between a checkout and the root daemon. */\n isGlobal: () => boolean\n home: string\n fs?: PortlessLinkFs\n}\n\n/** What currently sits at the link path, beyond \"a symlink to X\". */\nconst ABSENT = Symbol('absent')\nconst NOT_A_SYMLINK = Symbol('not-a-symlink')\n\nconst readCurrentLink = (link: string, linkFs: PortlessLinkFs): string | typeof ABSENT | typeof NOT_A_SYMLINK => {\n const stat = linkFs.lstatSync(link, { throwIfNoEntry: false })\n\n if (stat === undefined) return ABSENT\n if (!stat.isSymbolicLink()) return NOT_A_SYMLINK\n\n return linkFs.readlinkSync(link)\n}\n\n/**\n * Publish `target` at `link` through a pid-suffixed sibling and one `rename`, so the path never goes\n * absent (see the file header). The sibling is cleared BEFORE the symlink as well as after a failed\n * rename: a crash between the two calls leaves `.tmp-<pid>` behind forever, and pid reuse would then\n * turn a later boot's `symlinkSync` into EEXIST \u2014 a `'failed'` for a link that is fine. The name is\n * ours alone, never user data, so removing whatever sits there is safe; `ENOENT` is the normal case.\n */\nconst writeLink = (target: string, link: string, linkFs: PortlessLinkFs): void => {\n const tmp = `${link}.tmp-${process.pid}`\n\n try {\n linkFs.unlinkSync(tmp)\n } catch {\n // Nothing to clear \u2014 the ordinary path.\n }\n\n linkFs.symlinkSync(target, tmp)\n\n try {\n linkFs.renameSync(tmp, link)\n } catch (error) {\n try {\n linkFs.unlinkSync(tmp)\n } catch {\n // Best effort: the failed rename is the error worth surfacing, not the leftover sibling.\n }\n\n throw error\n }\n}\n\n/**\n * Converge `~/.infra-kit/portless` on the portless bundled with THIS install. Never throws; every\n * outcome is a value so callers can log it without a try/catch of their own.\n *\n * A non-symlink at the link path is `'failed'` and left exactly as found: this code owns a symlink, not\n * whatever a user or another tool put there, and removing a directory to make room would be the one\n * destructive action a boot hook must never take.\n *\n * @example\n * ensurePortlessLink({ resolveBin: () => '/g/node_modules/portless/dist/cli.js', isGlobal: () => true, home: '/Users/x' })\n * // => { outcome: 'created', target: '/g/node_modules/portless', link: '/Users/x/.infra-kit/portless' }\n */\nexport const ensurePortlessLink = (deps: EnsurePortlessLinkDeps): PortlessLinkResult => {\n const { resolveBin, isGlobal, home, fs: linkFs = fs } = deps\n const link = portlessLinkPath(home)\n const bin = resolveBin()\n\n if (bin === null) return { outcome: 'skipped-unresolved', target: null, link }\n\n const target = dirname(dirname(bin))\n\n if (!isGlobal()) return { outcome: 'skipped-local', target, link }\n\n try {\n linkFs.mkdirSync(dirname(link), { recursive: true })\n\n const current = readCurrentLink(link, linkFs)\n\n if (current === target) return { outcome: 'unchanged', target, link }\n if (current === NOT_A_SYMLINK) return { outcome: 'failed', target, link }\n\n writeLink(target, link, linkFs)\n\n return { outcome: current === ABSENT ? 'created' : 'repointed', target, link }\n } catch {\n return { outcome: 'failed', target, link }\n }\n}\n\n/** `(fields, message)` \u2014 the shape of `logger.debug`, so the CLI can pass it straight through. */\ntype PortlessLinkLog = (result: PortlessLinkResult, message: string) => void\n\n/**\n * The real seams. Shared with `setup`, which needs the RESULT back to report its step, so the two\n * writers can never disagree about which install is \"global\" or where the link goes.\n */\nexport const realPortlessLinkDeps = (): EnsurePortlessLinkDeps => {\n const home = homedir()\n\n return {\n resolveBin: resolvePortlessBin,\n isGlobal: () => {\n return isGlobalInstall({\n selfRealPath: fs.realpathSync(fileURLToPath(import.meta.url)),\n env: process.env,\n realpath: safeRealpath,\n home,\n exists: fs.existsSync,\n })\n },\n home,\n }\n}\n\n/**\n * The process-boot entry for both bins. fs-only, no subprocess, never throws, never exits, never\n * writes to stdout; the outcome goes to `log` and nowhere else. `deps` is injectable so the \"`'failed'`\n * is logged\" contract is testable without a real disk.\n */\nexport const bootPortlessLink = (log: PortlessLinkLog, deps?: EnsurePortlessLinkDeps): void => {\n try {\n log(ensurePortlessLink(deps ?? realPortlessLinkDeps()), 'portless link')\n } catch {\n // A link that could not be converged is `doctor`'s to report; it must never be a boot failure.\n }\n}\n", "/**\n * @fileoverview\n *\n * Thin, injectable driver for the `portless` daemon (Layer B \u2014 see `.omc/plans/dev-https-portless.md`).\n *\n * `infra-kit dev` uses it to register `<release>.<package>.localhost \u2192 127.0.0.1:<port>` routes so the\n * hero URLs resolve over **HTTPS on :443, with no port in the URL**. Every call here is **time-bounded and\n * never throws**: a missing binary, a non-zero exit, or a wedged process resolves to `false`/no-op. That is\n * a reporting contract, not a tolerance one \u2014 portless IS a hard dependency of the dev loop, and\n * `DevServerRunner.ensureProxy` turns a `false` from this driver into a fatal, actionable start error.\n *\n * The binary is NOT resolved from `PATH`: `portless` is a normal npm dependency living in\n * `node_modules/.bin`, which is on `PATH` only when the process was launched via pnpm/npm. Since\n * `infra-kit dev` is often launched otherwise (a global bin, a cmux runner, a foreign cwd), we resolve\n * portless's own `dist/cli.js` by walking `node_modules` from this file (see {@link resolvePortlessBin})\n * and run it with the current `node` (`process.execPath`) \u2014 so it works regardless of how `dev` was\n * invoked. Args are fixed literals plus discovered release/package names + a numeric port, never\n * shell-interpolated.\n *\n * **The daemon is PROBED, never started.** `:443` is privileged, and portless binds it by re-execing\n * itself through `sudo` with an inherited stdio \u2014 which a detached `stdio:'ignore'` child can never\n * satisfy: the password prompt has nowhere to go. Setup is one-time and out-of-band: a root\n * `portless service install`, printed for the user by {@link formatPortlessCommand} (never as a bare\n * `portless`, which no shell can resolve \u2014 see there).\n *\n * All process I/O is injected (`run` for awaited commands, `isProxyServing` for the wire probe) so tests\n * never shell out and can assert the exact portless argv.\n */\nimport type { Buffer } from 'node:buffer'\nimport { execFile } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport http from 'node:http'\nimport https from 'node:https'\nimport net from 'node:net'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport tls from 'node:tls'\nimport { fileURLToPath } from 'node:url'\nimport { promisify } from 'node:util'\n\nimport { withoutPackageManagerEnv } from 'src/lib/pm-env'\nimport { shellLine } from 'src/lib/shell-quote'\n\nconst execFileAsync = promisify(execFile)\n\n/** Read `bin.portless` (the `dist/cli.js` relative path) from a portless `package.json` on disk. */\nconst readBinRel = (pkgJsonPath: string): string | null => {\n const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) as { bin?: string | Record<string, string> }\n const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.portless\n\n return rel == null || rel === '' ? null : rel\n}\n\n/**\n * Resolve the absolute path to portless's CLI entry (`portless/dist/cli.js`) from node_modules,\n * independent of `PATH`. Returns `null` when portless is not installed, degrading the whole driver to\n * a no-op.\n *\n * portless is ESM-only (its `.` export exposes only `import`/`types`, no `require`), so\n * `createRequire().resolve` can't see it. We instead walk `node_modules` upward from this file \u2014 the\n * standard resolution path \u2014 and read the package's `package.json` straight off disk, which bypasses the\n * exports map that would otherwise hide both `package.json` and the main entry.\n */\nexport const resolvePortlessBin = (): string | null => {\n try {\n let dir = dirname(fileURLToPath(import.meta.url))\n\n for (;;) {\n const pkgJsonPath = join(dir, 'node_modules', 'portless', 'package.json')\n\n if (existsSync(pkgJsonPath)) {\n const rel = readBinRel(pkgJsonPath)\n\n return rel == null ? null : join(dirname(pkgJsonPath), rel)\n }\n const parent = dirname(dir)\n\n if (parent === dir) return null\n dir = parent\n }\n } catch {\n return null\n }\n}\n\n/** Resolve portless's CLI once per process \u2014 the on-disk location never changes within a run. */\nlet cachedBin: string | null | undefined\nconst portlessBin = (): string | null => {\n if (cachedBin === undefined) cachedBin = resolvePortlessBin()\n\n return cachedBin\n}\n\n/** Seams for {@link formatPortlessCommand}, injected so tests never depend on the real node_modules layout. */\nexport interface FormatPortlessCommandOptions {\n /**\n * Absolute path to portless's `dist/cli.js`. **Required and non-nullable on purpose.** The caller must\n * have resolved portless before it can describe how to run it, so \"I could not find the binary\" cannot be\n * silently rendered as a plausible-looking command \u2014 the type makes that unwritable rather than merely\n * discouraged. A `null` bin is a different report (\"run `pnpm install`\"), which every caller makes first.\n */\n bin: string\n /** Prefix with `sudo` \u2014 only `service install`, which binds the privileged `:443`, needs it. */\n sudo?: boolean\n execPath?: string\n}\n\n/**\n * Render a portless command the user can actually paste into a shell.\n *\n * Prints what the driver itself runs (see {@link defaultRun}): the current interpreter, by absolute path,\n * invoking portless's `dist/cli.js`, by absolute path. Nothing is resolved from `PATH`, so the command\n * works under `sudo`, from any cwd, and however `infra-kit` was launched.\n *\n * @example\n * formatPortlessCommand(['service', 'install'], { sudo: true, bin })\n * // 'sudo /usr/local/bin/node /repo/node_modules/portless/dist/cli.js service install'\n */\n// This exists because the obvious string is a lie. `portless` is a plain npm dependency living in\n// `node_modules/.bin`, which is on `PATH` only inside a pnpm/npm script \u2014 so printing `sudo portless\n// service install` hands the user a command that dies with `sudo: portless: command not found`. `sudo`\n// makes it strictly worse: it replaces `PATH` with `secure_path`, so even a shell that *could* resolve\n// `portless` loses it the moment the command is elevated.\n//\n// This is not merely cosmetic. portless's `service install` writes the interpreter and script path it was\n// invoked with straight into the launchd plist's `ProgramArguments` (`nodePath: process.execPath` plus\n// `process.argv[1]`), so the command printed here is the command that gets installed as a ROOT SYSTEM\n// DAEMON. Printing a name for the shell to resolve would not just fail \u2014 it would decide what runs as\n// root.\nexport const formatPortlessCommand = (args: string[], options: FormatPortlessCommandOptions): string => {\n const words = [options.execPath ?? process.execPath, options.bin, ...args]\n const prefix = options.sudo === true ? 'sudo ' : ''\n\n return prefix + shellLine(words)\n}\n\n/** Awaited portless invocation. Rejects on non-zero exit / timeout; the driver swallows that into a no-op. */\nexport type PortlessRun = (args: string[], opts: { timeoutMs: number }) => Promise<void>\n\n/** Cheap \"is anything at all accepting TCP here?\" pre-filter in front of the wire probe. */\nexport type IsListening = (port: number) => Promise<boolean>\n\n/**\n * Ground-truth identity: is the process serving `port` actually **portless**, and (when `tls`) is it\n * serving **TLS**? See {@link defaultIsProxyServing} for why this cannot be answered from state files.\n */\nexport type IsProxyServing = (port: number, tls: boolean) => Promise<boolean>\n\nconst DEFAULT_TIMEOUT_MS = 1500\nconst PROBE_TIMEOUT_MS = 1500\n\n/** Response header portless sets on every response it serves. Node lower-cases response header names. */\nconst PORTLESS_HEADER = 'x-portless'\n\n/** IPv4 loopback: portless binds and dials `127.0.0.1`. */\nconst LOOPBACK = '127.0.0.1'\n\n/**\n * SNI for the probe. Node sends **no SNI to an IP literal** (RFC 6066), which would drop portless onto its\n * default certificate \u2014 whose SANs are `localhost`, `*.localhost`, `*.local` and contain **no IP entry**.\n * `localhost` is always in that set, so it is the one name guaranteed to work even on a machine with zero\n * aliases registered.\n */\nconst PROBE_SERVERNAME = 'localhost'\n\n/**\n * Whether portless's OS-level service (the thing `service install` registers) is present on disk.\n * `'unknown'` on a platform this check does not cover (currently anything but macOS/Linux) \u2014 a caller must\n * never read `'unknown'` as `'no'`, since doing so would tell an already-provisioned Windows machine to\n * reinstall.\n */\nexport type ServiceInstalled = 'yes' | 'no' | 'unknown'\n\n/**\n * portless's launchd service label (`sh.portless.proxy`, hard-coded in portless's own CLI) and the two\n * fixed paths its `service install`/`uninstall` write to on macOS and Linux. These are read-only constants\n * of portless's OWN implementation, not ours \u2014 see `dist/cli.js`'s `SERVICE_LABEL`/`buildServiceSpec`. There\n * is no per-user or per-project variant: `service install` always targets exactly one of these two paths.\n * Exported so a test can assert against the exact path this check reads, without hard-coding a second copy.\n */\nexport const DARWIN_SERVICE_LABEL = 'sh.portless.proxy'\nexport const DARWIN_SERVICE_PLIST_PATH = `/Library/LaunchDaemons/${DARWIN_SERVICE_LABEL}.plist`\nexport const LINUX_SERVICE_UNIT_PATH = '/etc/systemd/system/portless.service'\n/** The systemd unit name `service install` registers on Linux \u2014 the `systemctl` argument, not a path. */\nexport const LINUX_SERVICE_UNIT_NAME = 'portless'\n\n/** The `existsSync` seam {@link defaultIsServiceInstalled} takes, injected so tests never touch real root paths. */\nexport type ExistsCheck = (path: string) => boolean\n\n/**\n * Cheap, synchronous, never-throwing check for whether portless's OS service is registered \u2014 a plain\n * `existsSync` on the fixed path `service install` writes to, never a `launchctl`/`systemctl` shell-out. This\n * is what lets {@link createPortlessDriver}'s daemon-down classification tell \"never installed\" apart from\n * \"installed, but not currently answering\" without adding a second process spawn to every failed probe.\n *\n * Deliberately does not attempt Windows detection (a Task Scheduler task, which needs `schtasks` to query) \u2014\n * `'unknown'` there is honest; a guessed `'no'` would send an already-provisioned machine back through\n * `service install` for no reason.\n *\n * `exists` defaults to the real `existsSync` but is a normal parameter (not a named-import spy target) so a\n * test can assert both branches without touching `/Library/LaunchDaemons` \u2014 a root-owned path a dev machine\n * may genuinely have populated, which would make an un-injected assertion true or false depending on the\n * author's own machine state rather than the code under test.\n */\nexport const defaultIsServiceInstalled = (exists: ExistsCheck = existsSync): ServiceInstalled => {\n try {\n if (process.platform === 'darwin') return exists(DARWIN_SERVICE_PLIST_PATH) ? 'yes' : 'no'\n if (process.platform === 'linux') return exists(LINUX_SERVICE_UNIT_PATH) ? 'yes' : 'no'\n\n return 'unknown'\n } catch {\n return 'unknown'\n }\n}\n\n/**\n * Fine-grained outcome of probing the proxy port, distinguishing the two ways \"not serving\" happens so\n * {@link createPortlessDriver}'s caller can print a distinct, actionable fix for each:\n * - `'serving'` \u2014 portless answered on the wire (the old boolean `true`).\n * - `'daemon-down'` \u2014 nothing is even accepting TCP on the port (refused). Combined with\n * {@link ServiceInstalled} this splits into \"never installed\" vs \"installed but crashed/stopped\".\n * - `'not-portless'` \u2014 something IS listening, but it did not answer with `X-Portless: 1` \u2014 a squatter has\n * the port, and installing/trusting portless will not free it.\n */\nexport type ProxyProbeOutcome = 'serving' | 'daemon-down' | 'not-portless'\n\nexport const defaultIsListening: IsListening = (port) => {\n return new Promise((resolve) => {\n const socket = net.connect({ host: LOOPBACK, port })\n const finish = (result: boolean): void => {\n socket.destroy()\n resolve(result)\n }\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('connect', () => {\n finish(true)\n })\n socket.once('timeout', () => {\n finish(false)\n })\n socket.once('error', () => {\n finish(false)\n })\n })\n}\n\n/**\n * Is the listener on `port` portless itself, serving `tls`? Proven **on the wire**, by asking it: portless\n * sets `X-Portless: 1` on every response, before route lookup \u2014 so an unrouted host still answers the probe\n * (a 404 with the header is a pass). This mirrors portless's own `isProxyRunning`.\n *\n * `rejectUnauthorized: false` is deliberate and load-bearing: this probe answers *\"is portless serving\n * here?\"*, **never** *\"is its CA trusted?\"*. Trust is a separate, explicitly-validating probe (doctor's\n * CA check).\n */\n// This replaces the old state-file check (`proxy.port` + `proxy.pid`), which was UNSOUND: portless's\n// `resolveStateDir(_port)` ignores its port argument, so `proxy.port` / `proxy.pid` / `proxy.tls` are\n// process-global singletons shared by every daemon on every port. Starting ANY daemon rewrites them, and\n// stopping ANY daemon DELETES them \u2014 so a second, unrelated daemon (or a stale sibling repo still on the\n// old CLI, falling back to an unprivileged port) makes a perfectly healthy `:443` daemon look dead. Both\n// were reproduced against portless 0.15.1; see `.omc/research/portless-https-spike.md`.\n//\n// Validating the chain here would collapse two different failures \u2014 a daemon that is down, and a CA that\n// was never trusted \u2014 into one indistinguishable error, with two different fixes (a root `service install`\n// vs the sudo-free `trust`).\nexport const defaultIsProxyServing: IsProxyServing = (port, tls) => {\n return new Promise((resolve) => {\n const request = tls ? https.request : http.request\n const req = request(\n {\n host: LOOPBACK,\n port,\n method: 'HEAD',\n path: '/',\n timeout: PROBE_TIMEOUT_MS,\n ...(tls ? { rejectUnauthorized: false, servername: PROBE_SERVERNAME } : {}),\n },\n (res) => {\n res.resume()\n resolve(res.headers[PORTLESS_HEADER] === '1')\n },\n )\n\n req.on('error', () => {\n resolve(false)\n })\n req.on('timeout', () => {\n req.destroy()\n resolve(false)\n })\n req.end()\n })\n}\n\nconst defaultRun: PortlessRun = async (args, { timeoutMs }) => {\n const bin = portlessBin()\n\n if (bin == null) throw new Error('portless is not installed (not resolvable from node_modules)')\n await execFileAsync(process.execPath, [bin, ...args], {\n signal: AbortSignal.timeout(timeoutMs),\n encoding: 'utf-8',\n env: withoutPackageManagerEnv(process.env),\n })\n}\n\n/**\n * portless's state directory. Exported so `doctor` reports on the same directory the driver reads.\n *\n * The default is deliberately **unchanged** (`~/.portless`): portless's `service install` bakes\n * `PORTLESS_STATE_DIR`, resolved from `SUDO_USER`, into the launchd plist \u2014 so the root daemon reads the\n * invoking user's* home. Pointing this anywhere else by default would manufacture the very split it looks\n * like it prevents.\n */\nexport const portlessStateDir = (): string => {\n return process.env.PORTLESS_STATE_DIR ?? join(homedir(), '.portless')\n}\n\n/** portless's local CA certificate \u2014 the root every host cert it mints is signed by. */\nconst CA_CERT_FILE = 'ca.pem'\n\n/**\n * Marker portless's `trust` writes: the **hex sha256 of `ca.pem`'s bytes** that was added to the login\n * keychain (`writeTrustMarker` \u2192 `caFingerprint`, `cli.js:78-101`). It records WHICH CA was trusted, so a\n * regenerated CA leaves a marker that no longer matches.\n */\nconst CA_TRUST_MARKER_FILE = 'ca.trusted'\n\n/** A route portless is serving: `<name> \u2192 127.0.0.1:<port>`. */\nexport interface PortlessRoute {\n /**\n * The registered hostname (e.g. `2-4.client-api.localhost`). Usable verbatim as a\n * `portless alias --remove <name>` argument \u2014 portless strips a trailing TLD off the name it is handed\n * (`parseHostnames`, `chunk-SD2PIWJU.js:68-79`) \u2014 and as a TLS `servername`.\n */\n name: string\n port: number\n}\n\n/** Absolute path to portless's local CA certificate, in whichever state dir {@link portlessStateDir} names. */\nexport const readCaPath = (): string => {\n return join(portlessStateDir(), CA_CERT_FILE)\n}\n\n/**\n * Was `portless trust` run for the CA that is on disk right now? Compares `sha256(ca.pem)` against the\n * fingerprint recorded in `ca.trusted`. `false` when either file is missing; never throws.\n *\n * **This proves the marker was written for THIS fingerprint \u2014 not that the keychain still trusts it.** A\n * user who deletes the certificate from Keychain Access by hand leaves the marker behind and gets a false\n * pass here. That residual is accepted (reading the keychain would mean shelling out to `security` on a\n * check that must stay cheap); it is why this is a *separate* check from the chain handshake\n * ({@link handshakeChainsToCa}), which proves what the daemon actually serves.\n */\nexport const caFingerprintMatches = (): boolean => {\n try {\n const recorded = readFileSync(join(portlessStateDir(), CA_TRUST_MARKER_FILE), 'utf-8').trim()\n\n if (recorded === '') return false\n\n const actual = createHash('sha256').update(readFileSync(readCaPath())).digest('hex')\n\n return actual === recorded.toLowerCase()\n } catch {\n return false\n }\n}\n\n/** Outcome of {@link handshakeChainsToCa}: `code` is the Node TLS error code, which the caller discriminates on. */\nexport type HandshakeResult = { ok: true } | { ok: false; code: string }\n\n/**\n * Does the certificate served on `port` chain to the CA in `ca.pem`? A **validating** TLS handshake \u2014 the\n * complement of {@link defaultIsProxyServing}, which deliberately does not validate.\n *\n * `servername` is **mandatory and load-bearing**, never optional: Node sends no SNI to an IP literal\n * (RFC 6066), which drops portless onto its default certificate, whose SANs (`localhost`, `*.localhost`,\n * `*.local`) contain **no IP entry** \u2014 so a validating probe of `127.0.0.1` with no `servername` fails with\n * `ERR_TLS_CERT_ALTNAME_INVALID` against a perfectly healthy daemon. Any such code coming back from here is\n * therefore a bug in the CALLER's probe, never a finding about the user's trust store. Passing an\n * unregistered name is safe: portless's SNI callback mints a cert on demand for any servername.\n *\n * Time-bounded; never throws.\n */\nexport const handshakeChainsToCa = (port: number, servername: string): Promise<HandshakeResult> => {\n return new Promise((resolve) => {\n let ca: Buffer<ArrayBufferLike>\n\n try {\n ca = readFileSync(readCaPath())\n } catch {\n resolve({ ok: false, code: 'ENOENT' })\n\n return\n }\n\n const socket = tls.connect({ host: LOOPBACK, port, servername, ca: [ca], rejectUnauthorized: true }, () => {\n // With `rejectUnauthorized: true` a chain failure normally surfaces as an 'error' event and this\n // callback never runs; the check is here so a future Node that connects-then-reports can't slip a\n // rejected chain through as a pass.\n const authError = socket.authorizationError as NodeJS.ErrnoException | undefined\n const authorized = socket.authorized\n\n socket.destroy()\n resolve(authorized ? { ok: true } : { ok: false, code: authError?.code ?? authError?.message ?? 'UNKNOWN' })\n })\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('timeout', () => {\n socket.destroy()\n resolve({ ok: false, code: 'ETIMEDOUT' })\n })\n socket.once('error', (err: NodeJS.ErrnoException) => {\n socket.destroy()\n resolve({ ok: false, code: err.code ?? 'UNKNOWN' })\n })\n })\n}\n\n/**\n * Routes portless currently has registered, read from `routes.json` in {@link portlessStateDir}. `[]` on any\n * failure (absent file, malformed JSON, unexpected shape) \u2014 an unreadable route list is reported as \"no\n * routes\", never as an error, because every caller uses this for diagnostics only.\n */\nexport const listRoutes = (): PortlessRoute[] => {\n try {\n const raw: unknown = JSON.parse(readFileSync(join(portlessStateDir(), 'routes.json'), 'utf-8'))\n\n if (!Array.isArray(raw)) return []\n\n return raw.flatMap((entry): PortlessRoute[] => {\n const { hostname, port } = (entry ?? {}) as { hostname?: unknown; port?: unknown }\n\n if (typeof hostname !== 'string' || hostname === '' || typeof port !== 'number') return []\n\n return [{ name: hostname, port }]\n })\n } catch {\n return []\n }\n}\n\nexport interface PortlessDriver {\n /**\n * Absolute path to the `dist/cli.js` this driver executes, or `null` when portless is not installed.\n *\n * Exposed so a caller rendering a remediation ({@link formatPortlessCommand}) names the binary THIS driver\n * would run, rather than re-resolving one behind its back \u2014 which, under an injected driver, would print a\n * fix derived from the real machine instead of the one under test.\n */\n binPath: () => string | null\n /** Resolve (and memoize) whether the `portless` binary is usable. Absent \u2192 every other call no-ops. */\n isAvailable: () => Promise<boolean>\n /**\n * Is a portless daemon serving `port` over `tls`? **Probe only \u2014 this never starts anything.** Binding\n * the privileged `:443` needs root, and portless's sudo re-exec cannot prompt from a detached child, so\n * the daemon is installed once, out-of-band (a root `service install`). A `false` here is turned into a\n * fatal, actionable start error by the caller.\n */\n isProxyServing: (port: number, tls: boolean) => Promise<boolean>\n /**\n * Same probe as {@link PortlessDriver.isProxyServing}, but reporting WHICH way it failed instead of\n * collapsing every non-serving case into `false`. `ensureProxy` uses this to print a distinct, actionable\n * message for \"nothing there\", \"something else is there\", and (combined with {@link isServiceInstalled})\n * \"installed but not running\" vs \"never installed\". Never starts anything \u2014 probe only, same as above.\n */\n probeProxy: (port: number, tls: boolean) => Promise<ProxyProbeOutcome>\n /**\n * Is portless's OS-level service (what `service install` registers) present on disk? Cheap, synchronous,\n * never throws. `'unknown'` on a platform this cannot check \u2014 a caller must not read that as `'no'`.\n */\n isServiceInstalled: () => ServiceInstalled\n /**\n * Register `<name> \u2192 127.0.0.1:<port>` (`name` = `<release>.<package>`). Returns `true` on success so\n * the caller shows the hero URL only for an alias that actually resolves (best-effort otherwise).\n */\n registerAlias: (name: string, port: number) => Promise<boolean>\n /** Deregister `<name>`. Best-effort. */\n removeAlias: (name: string) => Promise<void>\n}\n\nexport interface PortlessDriverDeps {\n /** Override the resolved `dist/cli.js` path (default: the real node_modules walk). Injected in tests. */\n bin?: string | null\n run?: PortlessRun\n /** TCP liveness pre-filter (default: real `net` connect). Injected in tests. */\n isListening?: IsListening\n /** Wire-probe identity check (default: real `HEAD /` + `X-Portless`). Injected in tests. */\n isProxyServing?: IsProxyServing\n /** OS-service-on-disk check (default: real `existsSync` on the plist/unit path). Injected in tests. */\n isServiceInstalled?: () => ServiceInstalled\n timeoutMs?: number\n}\n\n/**\n * Build a {@link PortlessDriver}. Inject `run` in tests to assert argv without shelling out.\n * `isAvailable` memoizes so the binary is probed at most once per runner.\n */\nexport const createPortlessDriver = (deps: PortlessDriverDeps = {}): PortlessDriver => {\n const bin = deps.bin === undefined ? portlessBin() : deps.bin\n const run = deps.run ?? defaultRun\n const isListening = deps.isListening ?? defaultIsListening\n const isProxyServing = deps.isProxyServing ?? defaultIsProxyServing\n const isServiceInstalled = deps.isServiceInstalled ?? defaultIsServiceInstalled\n const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS\n let availability: boolean | null = null\n\n /** Run a portless subcommand, swallowing any failure into `false` (best-effort contract). */\n const tryRun = async (args: string[]): Promise<boolean> => {\n try {\n await run(args, { timeoutMs })\n\n return true\n } catch {\n return false\n }\n }\n\n const isAvailable = async (): Promise<boolean> => {\n availability ??= await tryRun(['--version'])\n\n return availability\n }\n\n const serving = async (port: number, tls: boolean): Promise<boolean> => {\n if (!(await isAvailable())) return false\n // Nothing is even accepting TCP \u2192 skip the (more expensive) wire probe entirely.\n if (!(await isListening(port))) return false\n\n return isProxyServing(port, tls)\n }\n\n /**\n * The classifying counterpart of {@link serving}. Deliberately does NOT gate on `isAvailable()` first (unlike\n * `serving`): a broken/missing CLI binary says nothing about whether a daemon a PRIOR install started is\n * still up on the wire, so the two are independent facts and the caller (which already checked availability\n * before ever calling this) must not have that distinction collapsed here.\n */\n const probeProxy = async (port: number, tls: boolean): Promise<ProxyProbeOutcome> => {\n if (!(await isListening(port))) return 'daemon-down'\n\n return (await isProxyServing(port, tls)) ? 'serving' : 'not-portless'\n }\n\n const registerAlias = async (name: string, port: number): Promise<boolean> => {\n if (!(await isAvailable())) return false\n\n return tryRun(['alias', name, String(port)])\n }\n\n const removeAlias = async (name: string): Promise<void> => {\n if (!(await isAvailable())) return\n await tryRun(['alias', '--remove', name])\n }\n\n return {\n binPath: () => {\n return bin\n },\n isAvailable,\n isProxyServing: serving,\n probeProxy,\n isServiceInstalled,\n registerAlias,\n removeAlias,\n }\n}\n", "/**\n * Render an argv array as a line a POSIX shell runs back verbatim.\n *\n * Every surface that PRINTS a command for a human to paste has the same obligation, and `join(' ')` does\n * not meet it. The load-bearing case is `lib/dependency-install`'s refusals: a recipe we decline to run\n * is printed precisely so the human can run it, and joining\n * `['/bin/bash', '-c', 'curl -fsSL \u2026 | bash']` on spaces yields\n * `/bin/bash -c curl -fsSL \u2026 | bash` \u2014 which loses the argument boundary and runs `curl` with `-fsSL`\n * as `$0`, no URL, and the rest piped into a second shell. It fails, and it fails in a way that reads\n * like the tool's fault rather than the transcription's.\n *\n * The implementation began inside `dev/proxy/portless-driver`, which needed it first and is still a\n * caller; a second copy beside the recipes would drift from it.\n */\n\n/**\n * Characters that survive a POSIX shell unquoted. Anything outside this set \u2014 a space, a pipe, a paren,\n * all of which appear in real recipes and real install paths \u2014 gets single-quoted.\n */\nconst SHELL_SAFE = /^[\\w@%+=:,./-]+$/\n\n/** A literal `'` inside single quotes: close, emit an escaped quote, reopen \u2014 the only way a shell allows it. */\nconst SINGLE_QUOTE_ESCAPE = \"'\\\\''\"\n\n/** Single-quote `value` for a POSIX shell unless it is already inert. */\nexport const shellQuote = (value: string): string => {\n return SHELL_SAFE.test(value) ? value : `'${value.replaceAll(\"'\", SINGLE_QUOTE_ESCAPE)}'`\n}\n\n/** One pasteable shell line from an argv array, each word quoted only when it needs to be. */\nexport const shellLine = (argv: readonly string[]): string => {\n return argv.map(shellQuote).join(' ')\n}\n"],
|
|
5
|
-
"mappings": "8FAgCA,OAAOA,MAAQ,UACf,OAAS,WAAAC,OAAe,UACxB,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAOC,MAAa,eACpB,OAAS,iBAAAC,OAAqB,WCP9B,OAAS,YAAAC,MAAgB,qBACzB,OAAS,cAAAC,MAAkB,cAC3B,OAAS,cAAAC,EAAY,gBAAAC,MAAoB,UACzC,OAAOC,MAAU,YACjB,OAAOC,MAAW,aAClB,OAAOC,MAAS,WAChB,OAAS,WAAAC,MAAe,UACxB,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAOC,MAAa,eACpB,OAAOC,MAAS,WAChB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,aAAAC,MAAiB,YCrB1B,IAAMC,EAAa,mBAGbC,EAAsB,QAGfC,EAAcC,GAClBH,EAAW,KAAKG,CAAK,EAAIA,EAAQ,IAAIA,EAAM,WAAW,IAAKF,CAAmB,CAAC,IAI3EG,EAAaC,GACjBA,EAAK,IAAIH,CAAU,EAAE,KAAK,GAAG,EDctC,IAAMI,EAAgBC,EAAUC,CAAQ,EAGlCC,EAAcC,GAAuC,CACzD,IAAMC,EAAM,KAAK,MAAMC,EAAaF,EAAa,OAAO,CAAC,EACnDG,EAAM,OAAOF,EAAI,KAAQ,SAAWA,EAAI,IAAMA,EAAI,KAAK,SAE7D,OAAOE,GAAO,MAAQA,IAAQ,GAAK,KAAOA,CAC5C,EAYaC,EAAqB,IAAqB,CACrD,GAAI,CACF,IAAIC,EAAMC,EAAQC,EAAc,YAAY,GAAG,CAAC,EAEhD,OAAS,CACP,IAAMP,EAAcQ,EAAKH,EAAK,eAAgB,WAAY,cAAc,EAExE,GAAII,EAAWT,CAAW,EAAG,CAC3B,IAAMG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IAAMa,EAAUd,GAAgBC,EAAMC,CAAM,EAE5C,OAAIY,IAAYT,EAAe,CAAE,QAAS,YAAa,OAAAA,EAAQ,KAAAJ,CAAK,EAChEa,IAAYf,EAAsB,CAAE,QAAS,SAAU,OAAAM,EAAQ,KAAAJ,CAAK,GAExEG,GAAUC,EAAQJ,EAAMC,CAAM,EAEvB,CAAE,QAASY,IAAYhB,EAAS,UAAY,YAAa,OAAAO,EAAQ,KAAAJ,CAAK,EAC/E,MAAQ,CACN,MAAO,CAAE,QAAS,SAAU,OAAAI,EAAQ,KAAAJ,CAAK,CAC3C,CACF,EASac,GAAuB,IAA8B,CAChE,IAAM5B,EAAO6B,GAAQ,EAErB,MAAO,CACL,WAAYC,EACZ,SAAU,IACDC,EAAgB,CACrB,aAAc1B,EAAG,aAAa2B,GAAc,YAAY,GAAG,CAAC,EAC5D,IAAKZ,EAAQ,IACb,SAAUa,EACV,KAAAjC,EACA,OAAQK,EAAG,UACb,CAAC,EAEH,KAAAL,CACF,CACF,EAOakC,GAAmB,CAACC,EAAsBZ,IAAwC,CAC7F,GAAI,CACFY,EAAIb,GAAmBC,GAAQK,GAAqB,CAAC,EAAG,eAAe,CACzE,MAAQ,CAER,CACF",
|
|
6
|
-
"names": ["fs", "homedir", "dirname", "join", "process", "fileURLToPath", "execFile", "createHash", "existsSync", "readFileSync", "http", "https", "net", "homedir", "dirname", "join", "process", "tls", "fileURLToPath", "promisify", "SHELL_SAFE", "SINGLE_QUOTE_ESCAPE", "shellQuote", "value", "shellLine", "argv", "execFileAsync", "promisify", "execFile", "readBinRel", "pkgJsonPath", "pkg", "readFileSync", "rel", "resolvePortlessBin", "dir", "dirname", "fileURLToPath", "join", "existsSync", "parent", "cachedBin", "portlessBin", "formatPortlessCommand", "args", "options", "words", "process", "shellLine", "DEFAULT_TIMEOUT_MS", "PROBE_TIMEOUT_MS", "PORTLESS_HEADER", "LOOPBACK", "PROBE_SERVERNAME", "DARWIN_SERVICE_LABEL", "DARWIN_SERVICE_PLIST_PATH", "LINUX_SERVICE_UNIT_PATH", "LINUX_SERVICE_UNIT_NAME", "defaultIsServiceInstalled", "exists", "defaultIsListening", "port", "resolve", "socket", "net", "finish", "result", "defaultIsProxyServing", "tls", "req", "https", "http", "res", "defaultRun", "timeoutMs", "bin", "withoutPackageManagerEnv", "portlessStateDir", "homedir", "CA_CERT_FILE", "CA_TRUST_MARKER_FILE", "readCaPath", "caFingerprintMatches", "recorded", "createHash", "handshakeChainsToCa", "servername", "ca", "authError", "authorized", "err", "listRoutes", "raw", "entry", "hostname", "createPortlessDriver", "deps", "run", "isListening", "isProxyServing", "isServiceInstalled", "availability", "tryRun", "isAvailable", "name", "portlessLinkPath", "home", "join", "USER_CONFIG_DIR_NAME", "portlessLinkCliPath", "exists", "fs", "cliPath", "serviceInstallCommand", "bin", "seams", "formatPortlessCommand", "ABSENT", "NOT_A_SYMLINK", "readCurrentLink", "link", "linkFs", "stat", "writeLink", "target", "tmp", "process", "error", "ensurePortlessLink", "deps", "resolveBin", "isGlobal", "dirname", "current", "realPortlessLinkDeps", "homedir", "resolvePortlessBin", "isGlobalInstall", "fileURLToPath", "safeRealpath", "bootPortlessLink", "log"]
|
|
7
|
-
}
|
package/dist/chunk-75URROMU.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import O from"node:crypto";import R from"node:fs";import C from"node:os";import E from"node:path";import p from"node:process";var x="env-load.sh",S="env-clear.sh",D="projects",K=7200,I="INFRA_KIT_SESSION",L=".infra-kit",f="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",P="INFRA_KIT_ENV_AUTOLOADED",U="INFRA_KIT_ENV_CLEARED",h=/^([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("'")},F=t=>{try{return R.readFileSync(t,"utf-8")}catch{return""}},T=(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=h.exec(s);if(!a){let i=j.exec(s);i&&r?.(i[1]),_=c(s,!1),o+=1;continue}let V=a[1],A=s.slice(a[0].length);if(!A.startsWith("'")){e({name:V,value:A}),_=c(s,!1),o+=1;continue}let m=[A],N=c(A,!1);for(;N&&o+1<n.length;){o+=1;let i=n[o];m.push(i),N=c(i,!0)}e({name:V,value:w(m.join(`
|
|
3
|
-
`))}),_=N,o+=1}},G=t=>{let e=[];return T(F(t),({name:r})=>{e.push(r)}),e},b=t=>{let e={};return T(F(t),({name:r,value:n})=>{e[r]=n}),e},k=t=>{let e=[];return T(F(t),()=>{},r=>{e.push(r)}),e},g=()=>{let t=p.env.XDG_CACHE_HOME,e=t&&t.length>0?t:E.join(C.homedir(),".cache");return E.join(e,"infra-kit")},H=()=>{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(g(),t)},l=t=>O.createHash("sha256").update(t,"utf8").digest("hex"),u=()=>E.join(g(),D),J=t=>E.join(u(),l(t)),M=(t,e,r)=>{let n=`${t}.tmp.${p.pid}`;R.writeFileSync(n,e,{mode:r});try{R.renameSync(n,t)}catch(o){throw R.rmSync(n,{force:!0}),o}},Q="-worktrees";export{x as a,S as b,K as c,I as d,L as e,f,d as g,v as h,W as i,y as j,P as k,U as l,G as m,b as n,k as o,g as p,H as q,u as r,J as s,M as t,Q as u};
|
|
4
|
-
//# sourceMappingURL=chunk-75URROMU.js.map
|
package/dist/chunk-AEVL5XWO.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{a as P,h as R,l as N,m as A,n as M,o as j}from"./chunk-HHWP3YXW.js";import{p as f,t as S}from"./chunk-75URROMU.js";var Ye={name:"infra-kit",type:"module",version:"0.8.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:{inspector:"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug",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","@modelcontextprotocol/server":"^2.0.0","@slip-stream-kit/config":"^0.8.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:{"@modelcontextprotocol/client":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0","@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 L from"node:path";import oe from"node:process";var ie="update-check.lock",le=1800*1e3,ae=()=>L.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(L.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},E=(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}},U=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 xe}from"node:child_process";var k="infra-kit",g="infra-kit@infra-kit",pt="ArthurSaenz/infra-kit";var v="claude",Ee=12e4,q=["--version"],K=["plugin","update",g,"--scope","project","-y"],z=t=>{let e=xe(v,[...t.args],{cwd:t.cwd,encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:Ee});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 Ue 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=Ue.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)})},xt=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("@"),Et=({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},je=t=>t.code==="ENOENT",Le=(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?je(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=>Le(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??U,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&&E(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??U,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(!E(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 x=ee(m[0],m.slice(1),{stdio:"ignore",shell:C.platform==="win32",cwd:X(),env:j(n),windowsHide:!0});return x.error||x.signal||x.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,xt as j,Et as k,Ye as l,E as m,at as n,ct as o,D as p,Jt as q,Ke as r};
|
|
3
|
-
//# sourceMappingURL=chunk-AEVL5XWO.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../package.json", "../src/lib/update-check/run-update-check.ts", "../src/lib/update-check/lock.ts", "../src/lib/update-check/registry.ts", "../src/lib/update-check/semver.ts", "../src/lib/update-check/update-cache.ts", "../src/lib/update-check/update-plugin.ts", "../src/lib/plugin-pointer/claude-cli.ts", "../src/lib/plugin-pointer/names.ts", "../src/lib/plugin-pointer/install-state.ts"],
|
|
4
|
-
"sourcesContent": ["{\n \"name\": \"infra-kit\",\n \"type\": \"module\",\n \"version\": \"0.8.0\",\n \"files\": [\n \"dist\"\n ],\n \"description\": \"infra-kit\",\n \"bin\": {\n \"infra-kit\": \"dist/cli.js\",\n \"ik\": \"dist/cli.js\",\n \"ik-mcp\": \"dist/mcp-proxy.js\"\n },\n \"engines\": {\n \"node\": \">=24.x\"\n },\n \"scripts\": {\n \"inspector\": \"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug\",\n \"build\": \"pnpm run clean-artifacts && node ./scripts/build.js\",\n \"prepack\": \"pnpm run build\",\n \"infra-kit-check\": \"pnpm exec infra-kit audit\",\n \"clean-artifacts\": \"rm -rf dist\",\n \"clean-cache\": \"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc\",\n \"prettier-fix\": \"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"prettier-check\": \"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"eslint-check\": \"pnpm exec eslint --cache --report-unused-disable-directives ./src\",\n \"eslint-fix\": \"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix\",\n \"ts-check\": \"tsc --noEmit\",\n \"test\": \"pnpm exec vitest run --reporter=minimal\",\n \"test-watch\": \"pnpm exec vitest --watch --silent passed-only\",\n \"test-ui\": \"pnpm exec vitest --ui --silent passed-only\",\n \"test-report\": \"pnpm exec vitest run --coverage --silent passed-only\",\n \"qa:pty\": \"INFRA_KIT_REQUIRE_PTY=1 pnpm exec vitest run --reporter=minimal src/tui/__tests__/stdin-pause-pty.test.ts src/entry/__tests__/quit-keys-pty.test.ts src/entry/__tests__/post-run-pause-pty.test.ts\",\n \"qa\": \"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success\",\n \"fix\": \"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa\"\n },\n \"dependencies\": {\n \"@aws-lambda-powertools/logger\": \"^2.35.0\",\n \"@inquirer/checkbox\": \"^5.2.5\",\n \"@inquirer/confirm\": \"^6.3.2\",\n \"@inquirer/input\": \"^5.1.6\",\n \"@inquirer/password\": \"^5.2.2\",\n \"@inquirer/select\": \"^5.2.5\",\n \"@modelcontextprotocol/server\": \"^2.0.0\",\n \"@slip-stream-kit/config\": \"^0.8.0\",\n \"chalk\": \"^6.0.0\",\n \"chokidar\": \"^5.0.0\",\n \"commander\": \"^15.0.0\",\n \"fastify\": \"^5.12.4\",\n \"ink\": \"^7.1.1\",\n \"pino\": \"^10.3.1\",\n \"pino-pretty\": \"^13.1.3\",\n \"portless\": \"^0.15.6\",\n \"react\": \"19.3.0\",\n \"yaml\": \"^2.9.1\",\n \"zod\": \"^4.6.2\",\n \"zx\": \"^8.8.5\"\n },\n \"devDependencies\": {\n \"@modelcontextprotocol/client\": \"^2.0.0\",\n \"@modelcontextprotocol/sdk\": \"^1.30.0\",\n \"@slip-stream-kit/eslint-plugin\": \"workspace:*\",\n \"@types/aws-lambda\": \"catalog:\",\n \"@types/react\": \"catalog:\",\n \"@wl/eslint-config\": \"workspace:*\",\n \"@wl/vitest-config\": \"workspace:*\",\n \"esbuild\": \"^0.28.2\",\n \"ink-testing-library\": \"^4.0.0\",\n \"typescript\": \"^6.0.3\"\n }\n}\n", "/**\n * The CHILD half of the auto-update, spawned detached by `maybeAutoUpdate`. It outlives the CLI\n * invocation that started it, so it may take its time and it may replace the binary.\n *\n * WHY IT WAITS FOR THE PARENT TO EXIT \u2014 the load-bearing invariant of this whole feature:\n * `scripts/build.js` sets esbuild `splitting: true`, so `dist/cli.js` lazily imports sibling\n * `chunk-*.js` files at runtime (that is how the Ink TUI stays off the fast path). A package manager\n * installing over `dist/` mid-command deletes chunks the parent has not imported yet, and the parent\n * dies on a dynamic import of a file that no longer exists. Waiting for the parent to exit is what\n * makes a silent background install safe rather than a random crash under `infra-kit dev`.\n */\nimport { spawnSync } from 'node:child_process'\nimport { homedir } from 'node:os'\nimport process from 'node:process'\n\nimport { PACKAGE_NAME, defaultLazyNpmRoot, detectInstallManager, safeRealpath } from 'src/lib/install-manager'\nimport { packageManagerInstallEnv } from 'src/lib/pm-env'\n\nimport { acquireUpdateLock } from './lock'\nimport { fetchLatestVersion } from './registry'\nimport { isNewerVersion } from './semver'\nimport { writeUpdateCache } from './update-cache'\nimport type { UpdateCache } from './update-cache'\n// Static, like every import in this file \u2014 see the module doc: on the `installed` path the plugin step\n// runs after `dist/` has been replaced, and a lazy `import()` of a chunk from a replaced dist is unsafe.\nimport { updatePlugin } from './update-plugin'\nimport type { UpdatePluginDeps } from './update-plugin'\n\n/** How often to re-check whether the parent is gone. */\nexport const PARENT_POLL_INTERVAL_MS = 200\n\n/**\n * Give up waiting after this long. A long-lived parent (`infra-kit dev` runs for hours) must not leave\n * an immortal child pinned to a stale version: we simply skip this cycle. `lastCheckMs` is already\n * persisted by then, so the next short-lived command re-checks after the normal throttle window.\n */\nexport const PARENT_WAIT_TIMEOUT_MS = 5 * 60 * 1000\n\nexport interface RunUpdateCheckDeps extends UpdatePluginDeps {\n env?: NodeJS.ProcessEnv\n nowMs?: number\n fetchLatest?: (env: NodeJS.ProcessEnv) => Promise<string | null>\n writeCache?: typeof writeUpdateCache\n isProcessAlive?: (pid: number) => boolean\n sleep?: (ms: number) => Promise<void>\n /** Monotonic-ish source for the parent-wait deadline. Injected so the timeout is testable without real time. */\n clock?: () => number\n /** `npm root -g` probe. Defaults to the real subprocess; this child is detached, so it can afford one. */\n lazyNpmRoot?: () => string | undefined\n /** Single-flight guard. Returns a release fn, or null when another worker already holds the lock. */\n acquireLock?: () => (() => void) | null\n spawnSync?: typeof spawnSync\n /**\n * The version the user now gets from the `infra-kit` on their PATH. Consulted once, after the install\n * command returns 0, because that exit code is not proof of anything \u2014 see {@link readInstalledVersion}.\n */\n installedVersion?: (env: NodeJS.ProcessEnv) => string | null\n /** Realpath of the installed `dist/cli.js`, used to identify the owning package manager. */\n selfRealPath: string\n parentPid?: number\n}\n\n/** Bounds the post-install probe; a hung shim must not pin this worker for the parent's 5-minute budget. */\nconst VERSION_PROBE_TIMEOUT_MS = 15_000\n\n/**\n * Ask the freshly installed CLI what it is, the way the user will: the `infra-kit` bin on PATH.\n *\n * Not `<selfRealPath>/../package.json`. pnpm keeps each version in its own directory\n * (`.pnpm/infra-kit@0.5.1/\u2026`, `global/v11/<hash>/\u2026`) and repoints the shim, so the path THIS worker was\n * launched from keeps reporting the old version forever, while the path the user gets has moved.\n *\n * `--json` doubles as the guard that stops the probe spawning a second updater from inside the first:\n * `autoUpdateSkipReason` returns `json` before anything else runs, and piped stdio fails the tty arm too.\n * Anything short of a parseable version is `null` \u2014 a shim that no longer resolves, a bin that crashes on\n * boot, output that is not JSON \u2014 and the caller treats every one of those as \"not verified\".\n */\nconst readInstalledVersion = (env: NodeJS.ProcessEnv): string | null => {\n const result = spawnSync(PACKAGE_NAME, ['version', '--json'], {\n stdio: ['ignore', 'pipe', 'ignore'],\n shell: process.platform === 'win32',\n cwd: homedir(),\n env,\n timeout: VERSION_PROBE_TIMEOUT_MS,\n windowsHide: true,\n encoding: 'utf8',\n })\n\n if (result.error || result.signal || result.status !== 0) return null\n\n try {\n const parsed: unknown = JSON.parse(result.stdout)\n const version = (parsed as { version?: unknown } | null)?.version\n\n return typeof version === 'string' && version !== '' ? version : null\n } catch {\n return null\n }\n}\n\n/** Signal 0 performs the permission/existence check without delivering anything. */\nconst defaultIsProcessAlive = (pid: number): boolean => {\n try {\n process.kill(pid, 0)\n\n return true\n } catch {\n return false\n }\n}\n\nconst defaultSleep = (ms: number): Promise<void> => {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n\n/**\n * Block until `parentPid` exits or {@link PARENT_WAIT_TIMEOUT_MS} elapses. Returns whether the parent\n * is actually gone \u2014 the caller must not install on a timeout.\n */\nconst waitForParentExit = async (\n parentPid: number,\n deps: Required<Pick<RunUpdateCheckDeps, 'isProcessAlive' | 'sleep' | 'clock'>>,\n): Promise<boolean> => {\n const deadline = deps.clock() + PARENT_WAIT_TIMEOUT_MS\n\n while (deps.clock() < deadline) {\n if (!deps.isProcessAlive(parentPid)) return true\n\n await deps.sleep(PARENT_POLL_INTERVAL_MS)\n }\n\n return !deps.isProcessAlive(parentPid)\n}\n\nexport type UpdateCheckOutcome =\n | 'installed'\n | 'install-failed'\n /** The install command returned 0, yet the `infra-kit` on PATH still does not report `latestVersion`. */\n | 'install-stale'\n | 'up-to-date'\n | 'fetch-failed'\n | 'cannot-self-spawn'\n | 'parent-still-running'\n | 'parent-unknown'\n | 'already-running'\n\n/**\n * Fetch, decide, and (when safe) install \u2014 returning WHY it did what it did so tests can distinguish\n * \"no update\" from \"could not install\". Never throws.\n *\n * `lastCheckMs` is written from the ATTEMPT, before any early return. If it were written only on\n * success, an offline user would re-spawn a doomed child on every single command.\n *\n * @example\n * await runUpdateCheck('0.1.130', { selfRealPath: '/usr/local/lib/node_modules/infra-kit/dist/cli.js' })\n * // => 'installed'\n */\nexport const runUpdateCheck = async (currentVersion: string, deps: RunUpdateCheckDeps): Promise<UpdateCheckOutcome> => {\n const acquireLock = deps.acquireLock ?? acquireUpdateLock\n const writeCache = deps.writeCache ?? writeUpdateCache\n\n // Single-flight. N shells launched at once all read the same stale cache and each spawns a worker;\n // the cache throttle cannot stop them because it is only written after the fetch returns. Without\n // this, a pending update means N concurrent `npm install -g` over one global directory.\n const release = acquireLock()\n\n if (!release) return 'already-running'\n\n // Remember the locked function's final cache write so the plugin step can stamp its own outcome\n // onto it instead of reading the file back (a holder, not a `let`: TypeScript cannot see a closure\n // assignment and would narrow a `let` to its initial `null`).\n const written: { last: UpdateCache | null } = { last: null }\n const recordingWriteCache: typeof writeUpdateCache = (cache) => {\n written.last = cache\n writeCache(cache)\n }\n\n try {\n const outcome = await runUpdateCheckLocked(currentVersion, { ...deps, writeCache: recordingWriteCache })\n\n // The plugin step runs AFTER the locked function has returned, on EVERY outcome \u2014 `up-to-date`\n // included, which is what makes a plugin-only bump deliverable \u2014 and never inside its early-return\n // chain or ahead of the fetch. Placement is about the throttle: `lastCheckMs` is stamped only by\n // `finish()` after the fetch, and the lock is reaped as stale at `LOCK_STALE_MS` (30 min). A\n // `claude` probe (up to 120 s) plus an update ahead of the fetch would delay that stamp on every\n // run and eat into the stale window on a slow link. Here the stamp is written, the lock is still\n // held (single-flight), and the step has a bounded budget of its own. \"Every outcome\" has one\n // exception, decided by the cache the locked function wrote rather than by name: see\n // `pluginStepWithheld`.\n recordPluginUpdate(deps, written.last, currentVersion, writeCache)\n\n return outcome\n } finally {\n release()\n }\n}\n\n/**\n * Must the plugin step stand down because the CLI is behind? Reads the `latestVersion` the locked\n * function wrote, not its outcome name: \"a newer CLI exists and this run did not install it\" is\n * exactly what a non-null value newer than `currentVersion` encodes.\n *\n * That covers `cannot-self-spawn` (`:300`), `parent-unknown` (`:305`), `parent-still-running` (`:326`),\n * `install-failed` (`:353`) and `install-stale` (`:364`) \u2014 each leaves the newer version in the cache \u2014\n * and any outcome added later that does the same, without this list needing to know. `installed` clears\n * `latestVersion` (`:367`) and `up-to-date` writes a non-newer one (`:282`), so both still advance the\n * plugin and a plugin-only bump keeps delivering; `fetch-failed` writes null (`:280`) and cannot be\n * gated \u2014 the plugin advances, as before; `already-running` never reaches the wrapper.\n *\n * @example\n * pluginStepWithheld('0.8.0', '0.7.2') // => true\n * pluginStepWithheld(null, '0.7.2') // => false\n */\n// Without this a Homebrew or unknown-location machine advances the plugin on every run while its CLI\n// waits for a hand-typed update, and once a repo serves infra-kit through the plugin, plugin N+1 spawns\n// CLI N \u2014 skills citing tool names that server does not serve, a `doctor` that fails on a key that is\n// meant to be absent, and a `setup` that re-adds it to a tracked `.mcp.json`.\nexport const pluginStepWithheld = (latestVersion: string | null, currentVersion: string): boolean => {\n return latestVersion !== null && isNewerVersion(latestVersion, currentVersion)\n}\n\n/**\n * Run the plugin step and write its outcome beside the CLI outcome. Never throws: `updatePlugin` is\n * total, and a cache write that fails here has nowhere left to record itself \u2014 the CLI outcome the\n * worker already produced is worth more than a plugin diagnostic.\n */\nconst recordPluginUpdate = (\n deps: UpdatePluginDeps,\n base: UpdateCache | null,\n currentVersion: string,\n writeCache: typeof writeUpdateCache,\n): void => {\n const outcome = pluginStepWithheld(base?.latestVersion ?? null, currentVersion)\n ? 'skipped-cli-stale'\n : updatePlugin(deps)\n const checkedMs = (deps.clock ?? Date.now)()\n\n // `finish()` writes on every path the locked function returns through, so `base` is only null if that\n // invariant breaks \u2014 and then there is no throttle stamp to attach the outcome to either.\n if (base === null) return\n\n try {\n writeCache({ ...base, plugin: { outcome, checkedMs } })\n } catch {\n // Recorded nowhere, deliberately: see the function doc.\n }\n}\n\nconst runUpdateCheckLocked = async (currentVersion: string, deps: RunUpdateCheckDeps): Promise<UpdateCheckOutcome> => {\n const env = deps.env ?? process.env\n const nowMs = deps.nowMs ?? Date.now()\n const fetchLatest = deps.fetchLatest ?? fetchLatestVersion\n const writeCache = deps.writeCache ?? writeUpdateCache\n const isProcessAlive = deps.isProcessAlive ?? defaultIsProcessAlive\n const sleep = deps.sleep ?? defaultSleep\n const clock = deps.clock ?? Date.now\n const lazyNpmRoot = deps.lazyNpmRoot ?? defaultLazyNpmRoot\n const spawn = deps.spawnSync ?? spawnSync\n const installedVersion = deps.installedVersion ?? readInstalledVersion\n\n const latestVersion = await fetchLatest(env)\n\n // Every path below writes the cache EXACTLY once, and always with `lastCheckMs: nowMs` \u2014 the throttle\n // burns on the ATTEMPT, never on success. If it burned only on success, an offline user would respawn\n // a doomed child on every command.\n const finish = (\n outcome: UpdateCheckOutcome,\n cache: Omit<UpdateCache, 'lastCheckMs' | 'outcome'>,\n ): UpdateCheckOutcome => {\n // `outcome` is recorded on EVERY write: it is what lets a reader (human or `isStale`) tell a settled\n // `installed`/`up-to-date` from a transient `fetch-failed`, all of which otherwise write an identical\n // `{latestVersion:null}`. See `UpdateCache.outcome`.\n writeCache({ lastCheckMs: nowMs, ...cache, outcome })\n\n return outcome\n }\n\n if (latestVersion === null) return finish('fetch-failed', { latestVersion: null, updateCommand: null })\n if (!isNewerVersion(latestVersion, currentVersion))\n return finish('up-to-date', { latestVersion, updateCommand: null })\n\n // `lazyNpmRoot` is what makes the COMMON case work: a plain `npm i -g infra-kit` leaves no\n // `npm_config_prefix` in the user's shell, so every cheap matcher misses and detection would report\n // `unknown` / `canSelfSpawn: false`. Without this probe the auto-update would silently degrade to a\n // notice for the majority of installs. The subprocess is affordable here and nowhere else.\n // `version` pins the spec to what we just fetched: a `@latest` command is resolved by the package\n // manager from ITS cache, which pnpm does not revalidate \u2014 see `pinSpec` in install-manager.\n const { canSelfSpawn, updateCommand } = detectInstallManager({\n selfRealPath: deps.selfRealPath,\n env,\n realpath: safeRealpath,\n lazyNpmRoot,\n version: latestVersion,\n })\n\n // Homebrew relinks its prefix and may prompt; an unknown location means the command is a guess.\n // Both stay the user's call, so record the command for `maybeAutoUpdate` to print next invocation.\n if (!canSelfSpawn) return finish('cannot-self-spawn', { latestVersion, updateCommand })\n\n // Fail SAFE. Without a parent to outlive we cannot know whether a live CLI is still lazily importing\n // `chunk-*.js` out of the `dist/` we are about to replace, so we skip the cycle rather than install\n // blind. The real spawn always passes `--parent-pid`; only a hand-run worker lands here.\n if (deps.parentPid == null) return finish('parent-unknown', { latestVersion, updateCommand: null })\n\n // Burn the throttle NOW, before the two unbounded-ish operations below (a 5-minute parent wait, then an\n // install of no fixed duration). Everything after this point can take many minutes, and until the cache\n // is written it still reads as STALE \u2014 so every new shell in that window spawns its own worker, and the\n // single-flight lock becomes the only thing standing between them and concurrent `npm install -g` runs\n // over one global directory. The lock is reaped by mtime (LOCK_STALE_MS), so a slow enough install has\n // its live lock stolen and we get exactly the pile-up the lock exists to prevent.\n //\n // Writing the stamp here makes the throttle \u2014 not the lock \u2014 the primary guard, which is what the cache\n // was always for. `finish()` overwrites this with the real outcome; this is the only path that writes\n // the cache twice, and deliberately so.\n //\n // `outcome: 'installing'` marks a mid-install checkpoint: if the worker is killed here (machine sleeps,\n // SIGKILL) and never reaches `finish()`, this stamp is what the next run reads, and the cache says so\n // rather than looking like a settled result. It does not shorten the next window \u2014 see CHECK_INTERVAL_MS.\n writeCache({ lastCheckMs: nowMs, latestVersion, updateCommand: null, outcome: 'installing' })\n\n const parentGone = await waitForParentExit(deps.parentPid, { isProcessAlive, sleep, clock })\n\n // A long-lived parent (`infra-kit dev`) outlasted the wait. Stay silent and retry next window.\n if (!parentGone) return finish('parent-still-running', { latestVersion, updateCommand: null })\n\n // `shell` on win32 so the `.cmd` shims npm/pnpm/yarn ship as global bins resolve.\n //\n // `packageManagerInstallEnv` strips the inherited npx/dlx markers \u2014 which otherwise make\n // pnpm/portless-style tools believe they were invoked via `npx`/`dlx` and refuse to run \u2014 while KEEPING\n // `npm_config_prefix` and `npm_config_registry`. Using the blunt `withoutPackageManagerEnv` here was a\n // bug: it also erased the prefix that `detectInstallManager` had just matched on, so we would detect a\n // global install at prefix P and then install into the default prefix instead \u2014 silently, forever. See\n // the module doc on `packageManagerInstallEnv`.\n //\n // `cwd` is pinned to the home directory, and this is a SECURITY control, not tidiness: npm resolves\n // `registry=` from an `.npmrc` on disk relative to the cwd. Inheriting the caller's cwd would let any\n // repo containing a hostile `.npmrc` silently redirect this unattended `install -g` to an attacker's\n // registry, executing its lifecycle scripts. Stripping `npm_config_registry` from the env does NOT\n // close that hole, because the redirect lives in a file, not the environment.\n const result = spawn(updateCommand[0] as string, updateCommand.slice(1), {\n stdio: 'ignore',\n shell: process.platform === 'win32',\n cwd: homedir(),\n env: packageManagerInstallEnv(env),\n windowsHide: true,\n })\n\n // Record the manual command so a persistently failing silent install (EACCES on a root-owned global\n // dir, say) still surfaces ONE actionable line, instead of failing invisibly forever.\n if (result.error || result.signal || result.status !== 0) {\n return finish('install-failed', { latestVersion, updateCommand })\n }\n\n // Exit 0 is the package manager saying it is content, not that anything changed. `pnpm add -g\n // infra-kit@latest` resolved the tag from its own stale metadata cache, reinstalled the version already\n // present, and returned 0 \u2014 and this function recorded `installed`, cleared `latestVersion`, and\n // repeated the same no-op every cycle. The spec is pinned now, but the check that would have SHOWN\n // that bug is this one: ask the binary the user actually runs. A mismatch keeps `latestVersion` and the\n // command in the cache, so the parent prints the manual line instead of staying silent.\n const nowInstalled = installedVersion(env)\n\n if (nowInstalled !== latestVersion) return finish('install-stale', { latestVersion, updateCommand })\n\n // Verified: clear `latestVersion` so the next run does not re-notify.\n return finish('installed', { latestVersion: null, updateCommand: null })\n}\n", "/**\n * Single-flight lock for the background update worker.\n *\n * Without it, N shells starting at once all read the same stale cache and each spawns a worker \u2014 and\n * once a newer version exists, each of those runs `npm install -g` concurrently, over the same global\n * directory. (Measured: five concurrent `ik` invocations spawn five workers.) The throttle in the cache\n * cannot prevent this: it is only written AFTER the fetch returns, long after the other workers launched.\n *\n * `openSync(path, 'wx')` is the primitive \u2014 an atomic create-if-absent, so exactly one worker wins even\n * if all of them call it in the same millisecond.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { getCacheRoot } from 'src/lib/constants'\n\nexport const LOCK_FILE_NAME = 'update-check.lock'\n\n/**\n * A lock older than this is assumed to belong to a worker that was killed before it could clean up.\n *\n * Must exceed the worker's ENTIRE critical section, and the install is part of it: the lock is held across\n * `fetch` (\u22642.5s) + the parent wait (\u22645min) + `npm install -g`, which has no bound at all \u2014 a cold cache on\n * a slow link can run for many minutes. The previous 10 minutes was budgeted from the wait and the fetch\n * alone, silently omitting the very operation the lock exists to serialise. A slow enough install therefore\n * had its own LIVE lock reaped as stale by the next worker, which then ran a second concurrent\n * `npm install -g` over the same global directory \u2014 precisely the pile-up described above.\n *\n * The throttle, not this timeout, is now the primary guard: `runUpdateCheck` stamps `lastCheckMs` BEFORE\n * the wait and the install, so concurrent shells stop spawning workers at all. This value only has to\n * outlive a plausible install, and is deliberately generous \u2014 the cost of being too large is that a worker\n * killed mid-install delays the next attempt, which the throttle would delay anyway.\n */\nexport const LOCK_STALE_MS = 30 * 60 * 1000\n\nexport const lockFilePath = (): string => {\n return path.join(getCacheRoot(), LOCK_FILE_NAME)\n}\n\nexport interface LockDeps {\n nowMs?: number\n lockPath?: string\n}\n\n/** Delete a lock whose mtime predates the staleness window. Best-effort: losing the race is harmless. */\nconst reapIfStale = (lockPath: string, nowMs: number): void => {\n try {\n if (nowMs - fs.statSync(lockPath).mtimeMs > LOCK_STALE_MS) fs.rmSync(lockPath, { force: true })\n } catch {\n // Vanished under us \u2014 another worker reaped it. Nothing to do.\n }\n}\n\n/**\n * Take the lock, or return null when another worker already holds it.\n *\n * Returns a release function rather than a boolean so the caller cannot forget which path releases:\n * there is exactly one handle, and it is the only thing that can unlink the file.\n *\n * @example\n * const release = acquireUpdateLock()\n * if (!release) return 'already-running'\n * try { ... } finally { release() }\n */\nexport const acquireUpdateLock = (deps: LockDeps = {}): (() => void) | null => {\n const nowMs = deps.nowMs ?? Date.now()\n const lockPath = deps.lockPath ?? lockFilePath()\n\n try {\n fs.mkdirSync(path.dirname(lockPath), { recursive: true })\n } catch {\n return null\n }\n\n const open = (): number | null => {\n try {\n // 'wx' fails with EEXIST if the file is already there: an atomic test-and-set.\n return fs.openSync(lockPath, 'wx', 0o600)\n } catch {\n return null\n }\n }\n\n let fd = open()\n\n if (fd === null) {\n reapIfStale(lockPath, nowMs)\n // One retry only. If a live worker holds the lock, we are the loser and must simply stand down.\n fd = open()\n }\n\n if (fd === null) return null\n\n try {\n fs.writeFileSync(fd, String(process.pid))\n } catch {\n // The pid is a debugging aid, not part of the protocol; the lock is held either way.\n }\n\n return () => {\n try {\n fs.closeSync(fd)\n } catch {\n // Already closed.\n }\n\n try {\n fs.rmSync(lockPath, { force: true })\n } catch {\n // Already gone; a later worker will reap it via LOCK_STALE_MS regardless.\n }\n }\n}\n", "/**\n * Ask the npm registry for the `latest` dist-tag. Node >= 24 (see `engines`), so global `fetch` is\n * available and this needs no dependency.\n */\nimport { PACKAGE_NAME } from 'src/lib/install-manager'\n\nexport const DEFAULT_REGISTRY = 'https://registry.npmjs.org'\n\n/**\n * Bounded so a hanging registry can never keep a detached child alive indefinitely. 5s, not a tighter\n * bound: the abbreviated `/pkg/latest` endpoint is usually ~20-900ms, but a cold TLS/DNS handshake in a\n * freshly-spawned worker can spike past a 2.5s cap \u2014 and a single trip used to cost a `fetch-failed` that\n * pushed the next check a full window out. A detached child that lingers a few extra seconds harms nothing.\n */\nexport const FETCH_TIMEOUT_MS = 5_000\n\n/**\n * The registry this install actually talks to. A user behind a corporate mirror has `npm_config_registry`\n * set; hitting registry.npmjs.org directly would either fail closed (firewall) or, worse, report a public\n * version they cannot install.\n *\n * @example\n * registryUrl({ npm_config_registry: 'https://nexus.corp/repo/npm/' }) // => 'https://nexus.corp/repo/npm'\n */\n/**\n * `npm_config_registry` in WHICHEVER case the environment spells it.\n *\n * A bare `env.npm_config_registry` reads only the lowercase form, but npm itself matches `/^npm_config_/i`,\n * and POSIX `process.env` is case-SENSITIVE \u2014 so a `NPM_CONFIG_REGISTRY` (the form Dockerfiles and CI\n * images export) was invisible here while npm honoured it. The check then queried the public registry that\n * the install would never touch: the two halves of this feature were exactly inverted.\n */\nconst configuredRegistry = (env: NodeJS.ProcessEnv): string | undefined => {\n const hit = Object.entries(env).find(([key, value]) => {\n return /^npm_config_registry$/i.test(key) && value != null && value !== ''\n })\n\n return hit?.[1]\n}\n\nexport const registryUrl = (env: NodeJS.ProcessEnv): string => {\n const configured = configuredRegistry(env)\n\n let base = configured != null && configured !== '' ? configured : DEFAULT_REGISTRY\n\n // A `/\\/+$/` regex would do this in one line, but its backtracking is super-linear on a hostile input.\n while (base.endsWith('/')) {\n base = base.slice(0, -1)\n }\n\n return base\n}\n\n/**\n * The published `latest` version, or null on ANY failure (offline, timeout, non-200, malformed body).\n * Never throws: a failed check must be indistinguishable from \"no update available\" to every caller.\n *\n * @example\n * await fetchLatestVersion(process.env) // => '0.1.131' | null\n */\nexport const fetchLatestVersion = async (\n env: NodeJS.ProcessEnv,\n fetchFn: typeof fetch = fetch,\n): Promise<string | null> => {\n const controller = new AbortController()\n const timer = setTimeout(() => {\n controller.abort()\n }, FETCH_TIMEOUT_MS)\n\n try {\n const response = await fetchFn(`${registryUrl(env)}/${PACKAGE_NAME}/latest`, {\n signal: controller.signal,\n headers: { accept: 'application/json' },\n })\n\n if (!response.ok) return null\n\n const body: unknown = await response.json()\n const version = (body as { version?: unknown } | null)?.version\n\n return typeof version === 'string' && version !== '' ? version : null\n } catch {\n return null\n } finally {\n clearTimeout(timer)\n }\n}\n", "/**\n * Registry-safe version comparison for the auto-update check.\n *\n * Deliberately NOT `src/lib/version-utils`: `parseVersion` there does `versionStr.slice(1)` because it\n * only ever sees `v`-prefixed release tags, so it turns a bare registry version (`0.1.130`) into\n * `[NaN, 1, 130]`. Feeding npm's `dist-tags.latest` through it silently compares NaNs and never fires.\n * These inputs are bare semver from `registry.npmjs.org` and from our own `package.json`.\n */\n\n/** `1.2.3-beta.4+build` \u2192 the `[1, 2, 3]` release triple and the `beta.4` prerelease, or null if unparsable. */\ninterface ParsedVersion {\n release: [number, number, number]\n /** Dot-separated prerelease identifiers, empty when this is a final release. */\n prerelease: string[]\n}\n\nconst RELEASE_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)$/\n\n/**\n * Parse bare semver. Returns null (never throws, never NaNs) for anything that is not\n * `major.minor.patch` with optional `-prerelease` and `+build` \u2014 a garbled registry body must read as\n * \"no update\", not as \"update to NaN\".\n *\n * @example\n * parseSemver('0.1.130') // => { release: [0, 1, 130], prerelease: [] }\n * parseSemver('1.0.0-rc.1+abc') // => { release: [1, 0, 0], prerelease: ['rc', '1'] }\n * parseSemver('v1.0.0') // => null\n */\nexport const parseSemver = (version: string): ParsedVersion | null => {\n // Build metadata is ignored entirely by semver precedence rules.\n const [withoutBuild = ''] = version.trim().split('+')\n const [core = '', ...prereleaseParts] = withoutBuild.split('-')\n const match = RELEASE_PATTERN.exec(core)\n\n if (!match) return null\n\n const [major, minor, patch] = [match[1], match[2], match[3]].map(Number) as [number, number, number]\n\n return {\n release: [major, minor, patch],\n // Re-join on '-' so `1.0.0-rc-1` keeps its hyphen inside a single identifier.\n prerelease: prereleaseParts.length > 0 ? prereleaseParts.join('-').split('.') : [],\n }\n}\n\nconst NUMERIC_IDENTIFIER = /^\\d+$/\n\n/** Compare two unequal prerelease identifiers per semver \u00A711. Numeric ones rank below alphanumeric ones. */\nconst compareIdentifier = (left: string, right: string): number => {\n const leftNumeric = NUMERIC_IDENTIFIER.test(left)\n const rightNumeric = NUMERIC_IDENTIFIER.test(right)\n\n if (leftNumeric && rightNumeric) return Number(left) - Number(right)\n if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1\n\n return left < right ? -1 : 1\n}\n\n/** Compare prerelease identifier lists. A shorter list has lower precedence: `1.0.0-rc` < `1.0.0-rc.1`. */\nconst comparePrerelease = (a: string[], b: string[]): number => {\n for (let index = 0; index < Math.max(a.length, b.length); index += 1) {\n const left = a[index]\n const right = b[index]\n\n if (left === undefined) return -1\n if (right === undefined) return 1\n if (left !== right) return compareIdentifier(left, right)\n }\n\n return 0\n}\n\n/**\n * Is `latest` strictly newer than `current`? False when either is unparsable, so a bad registry\n * response can never trigger an install.\n *\n * The load-bearing case is NUMERIC, not lexical, comparison: `0.1.9` must be older than `0.1.130`.\n * A string compare would order them the other way and pin every user to the older build forever.\n *\n * A final release outranks its own prereleases (`1.0.0` > `1.0.0-rc.1`), so a user on `rc` is offered\n * the release, and a user on the release is never \"downgraded\" to an rc.\n *\n * @example\n * isNewerVersion('0.1.130', '0.1.9') // => true (numeric, not lexical)\n * isNewerVersion('1.0.0', '1.0.0-rc.1') // => true\n * isNewerVersion('0.1.130', '0.1.130') // => false\n * isNewerVersion('garbage', '0.1.0') // => false\n */\nexport const isNewerVersion = (latest: string, current: string): boolean => {\n const parsedLatest = parseSemver(latest)\n const parsedCurrent = parseSemver(current)\n\n if (!parsedLatest || !parsedCurrent) return false\n\n for (let index = 0; index < 3; index += 1) {\n const left = parsedLatest.release[index] as number\n const right = parsedCurrent.release[index] as number\n\n if (left !== right) return left > right\n }\n\n const latestIsFinal = parsedLatest.prerelease.length === 0\n const currentIsFinal = parsedCurrent.prerelease.length === 0\n\n if (latestIsFinal !== currentIsFinal) return latestIsFinal\n\n return comparePrerelease(parsedLatest.prerelease, parsedCurrent.prerelease) > 0\n}\n", "/**\n * The throttle + notice state for the auto-update check, at `$cacheRoot/update-check.json`.\n *\n * `getCacheRoot()` \u2014 NOT `getSessionCacheDir()`, which throws unless `INFRA_KIT_SESSION` is set. A user\n * who installed this CLI globally and never ran `infra-kit setup` has no session, and the update check\n * must still work for exactly that person.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport { atomicWriteFileSync, getCacheRoot } from 'src/lib/constants'\n\nexport const CACHE_FILE_NAME = 'update-check.json'\n\n/**\n * The ONE re-check window, whatever the last outcome was. A background check is cheap \u2014 one\n * detached child and a single registry fetch bounded by `FETCH_TIMEOUT_MS` \u2014 but not once per\n * shell command, which is the storm this throttle exists to stop.\n *\n * MUST stay above a full worker cycle: `runUpdateCheck` stamps `lastCheckMs` BEFORE waiting up to\n * `PARENT_WAIT_TIMEOUT_MS` (5min) for the parent to exit and THEN installing.\n */\n// There is deliberately no shorter \"retry after a transient failure\" window. One used to exist\n// because this interval was 24h, and burning a whole day on a single network blip locked out\n// exactly the publisher pushing a release mid-window. At 20 minutes that gap is gone: a blip costs\n// one window, so a second window buys nothing and cannot pay for what it costs.\n//\n// What it would cost: go below a full worker cycle and the cache reads stale while the first worker\n// is still legitimately working, so the next shell spawns a worker that dies on the live\n// single-flight lock and returns WITHOUT writing \u2014 leaving the cache stale for every command until\n// `LOCK_STALE_MS` (30min) reaps the lock. That is the per-command spawn storm this throttle exists\n// to prevent, and it is why a 5-minute retry window is not an option.\nexport const CHECK_INTERVAL_MS = 20 * 60 * 1000\n\n/**\n * What the worker's Claude Code plugin step did. `skipped` = no project-scope install record on this\n * machine; `updated` = every recorded project whose path still exists took `claude plugin update`\n * with exit 0, \"already at the latest version\" included.\n *\n * `skipped-cli-stale` = the step was withheld because a newer CLI exists that this run did not install\n * (`pluginStepWithheld` in `run-update-check.ts`) \u2014 advancing the plugin past the CLI would hand its\n * skills a server that does not serve the tool names they cite.\n */\nexport type PluginUpdateOutcome = 'updated' | 'failed' | 'claude-missing' | 'skipped' | 'skipped-cli-stale'\n\nexport interface PluginUpdateRecord {\n outcome: PluginUpdateOutcome\n /** When the plugin step ran \u2014 stamped separately from `lastCheckMs`, which it never moves. */\n checkedMs: number\n}\n\nexport interface UpdateCache {\n /**\n * When the last check was ATTEMPTED \u2014 never \"when it last succeeded\". An offline user whose fetch\n * throws must still burn their window, or every single command spawns another doomed child.\n */\n lastCheckMs: number\n /** Latest version seen on the registry, or null when the last attempt failed. */\n latestVersion: string | null\n /**\n * The command the USER must run, set only when the worker was not allowed to install for them\n * (Homebrew, or an install location it could not identify). Null means \"handled, say nothing\".\n *\n * The worker decides this, not the reader: identifying the owning package manager can cost an\n * `npm root -g` subprocess, and the CLI startup path must never pay for one. The background child\n * already pays it, so it writes the verdict down.\n */\n updateCommand: string[] | null\n /**\n * The last check's terminal outcome (`installed`, `fetch-failed`, `up-to-date`, \u2026), or absent on a\n * cache written before this field existed.\n *\n * Diagnostic ONLY \u2014 nothing branches on it, {@link isStale} included. It earns its keep by being the\n * one thing that makes this file legible: a successful `installed` and a failed `fetch-failed` both\n * write a byte-identical `{latestVersion:null, updateCommand:null}`, so without this the cache cannot\n * say which happened, and a silent auto-update leaves no other trace of what it did.\n */\n outcome?: string | null\n /**\n * The plugin step's outcome, written beside the CLI outcome by the same worker; absent on a cache\n * written before the step existed. Diagnostic like `outcome`: the plugin is delivered through the\n * marketplace, and this is the only trace on disk of whether the worker asked for it.\n */\n plugin?: PluginUpdateRecord\n}\n\nexport const cacheFilePath = (): string => {\n return path.join(getCacheRoot(), CACHE_FILE_NAME)\n}\n\nconst isStringArray = (value: unknown): value is string[] => {\n return (\n Array.isArray(value) &&\n value.every((entry) => {\n return typeof entry === 'string'\n })\n )\n}\n\nconst isPluginUpdateRecord = (value: unknown): value is PluginUpdateRecord => {\n if (typeof value !== 'object' || value === null) return false\n\n const { outcome, checkedMs } = value as Partial<PluginUpdateRecord>\n\n return typeof outcome === 'string' && typeof checkedMs === 'number' && Number.isFinite(checkedMs)\n}\n\nconst isUpdateCache = (value: unknown): value is UpdateCache => {\n if (typeof value !== 'object' || value === null) return false\n\n const { lastCheckMs, latestVersion, updateCommand, outcome, plugin } = value as Partial<UpdateCache>\n\n return (\n typeof lastCheckMs === 'number' &&\n Number.isFinite(lastCheckMs) &&\n (latestVersion === null || typeof latestVersion === 'string') &&\n (updateCommand === null || isStringArray(updateCommand)) &&\n (outcome === undefined || outcome === null || typeof outcome === 'string') &&\n (plugin === undefined || isPluginUpdateRecord(plugin))\n )\n}\n\n/**\n * Read the cache, or null when it is missing/unreadable/corrupt. A null read means \"stale\" to every\n * caller, so a first run and a hand-mangled file behave identically: check again.\n *\n * @example\n * readUpdateCache() // => { lastCheckMs: 1770000000000, latestVersion: '0.1.131' } | null\n */\nexport const readUpdateCache = (\n readFile: (p: string) => string = (p) => {\n return fs.readFileSync(p, 'utf8')\n },\n): UpdateCache | null => {\n try {\n const parsed: unknown = JSON.parse(readFile(cacheFilePath()))\n\n return isUpdateCache(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n\n/**\n * Persist the check result. Creates `$cacheRoot` first: `atomicWriteFileSync` writes a temp file\n * beside the target and renames, so it throws ENOENT on a machine that has never had a `~/.cache/infra-kit`.\n * Without this mkdir the write fails, `lastCheckMs` never lands, and the throttle degrades into a\n * detached-child spawn on every invocation.\n *\n * @example\n * writeUpdateCache({ lastCheckMs: Date.now(), latestVersion: '0.1.131' })\n */\nexport const writeUpdateCache = (cache: UpdateCache): void => {\n const root = getCacheRoot()\n\n fs.mkdirSync(root, { recursive: true })\n atomicWriteFileSync(path.join(root, CACHE_FILE_NAME), JSON.stringify(cache), 0o600)\n}\n\n/**\n * Has the throttle window elapsed? A missing cache is stale by definition (first run).\n *\n * A `lastCheckMs` in the future (clock skew, or a restored backup) also reads as stale rather than\n * locking the user out of updates until their clock catches up.\n *\n * The window does NOT depend on `outcome`: every last outcome, transient or settled, is re-checked\n * after {@link CHECK_INTERVAL_MS}. See that constant for why a shorter transient-failure window is not\n * worth its cost here.\n *\n * @example\n * isStale(null, 1_000) // => true\n * isStale({ lastCheckMs: 0, latestVersion: null, updateCommand: null }, CHECK_INTERVAL_MS + 1) // => true\n */\nexport const isStale = (cache: UpdateCache | null, nowMs: number): boolean => {\n if (!cache) return true\n\n const elapsed = nowMs - cache.lastCheckMs\n\n if (elapsed < 0) return true\n\n return elapsed >= CHECK_INTERVAL_MS\n}\n", "/**\n * The Claude Code plugin half of the update worker: `claude plugin update infra-kit@infra-kit` for\n * every project this machine has the plugin installed in.\n *\n * WHY THE WORKER AND NOT CLAUDE CODE: Claude Code never advances an installed plugin on its own and\n * prints nothing for installed-but-old, so a plugin bump on `main` reached nobody until they typed\n * `claude plugin update` by hand \u2014 the CLI kept itself fresh while the skills it ships with rotted.\n * This step rides the same throttled child, so a plugin-only bump is delivered on the next check.\n *\n * Everything here is imported statically (see `run-update-check.ts`): on the `installed` path this runs\n * AFTER `npm install -g` has replaced `dist/`, where a lazy `import()` of a chunk is unsafe.\n */\nimport { spawnSync } from 'node:child_process'\nimport fs from 'node:fs'\nimport process from 'node:process'\n\nimport {\n CLAUDE_BIN,\n CLAUDE_VERSION_ARGV,\n PLUGIN_UPDATE_ARGV,\n defaultClaudeRunner,\n} from 'src/lib/plugin-pointer/claude-cli'\nimport type { ClaudeRunner } from 'src/lib/plugin-pointer/claude-cli'\nimport { listProjectPluginInstallations } from 'src/lib/plugin-pointer/install-state'\nimport type { PluginInstallation } from 'src/lib/plugin-pointer/install-state'\nimport { withoutPackageManagerEnv } from 'src/lib/pm-env'\n\nimport type { PluginUpdateOutcome } from './update-cache'\n\n/**\n * Probe plus every per-project run, end to end. Well inside `LOCK_STALE_MS` (30 min) even after a slow\n * CLI install has already spent minutes of the same lock \u2014 a plugin step that outlived the lock would\n * hand the next shell's worker a reaped lock and the concurrent-install pile-up the lock exists to stop.\n */\nexport const PLUGIN_UPDATE_BUDGET_MS = 5 * 60 * 1000\n\n/** One `claude plugin update` measured at \u22480.7 s; a minute is a wedged network, not a slow one. */\nexport const PLUGIN_UPDATE_RUN_TIMEOUT_MS = 60_000\n\nexport interface UpdatePluginDeps {\n env?: NodeJS.ProcessEnv\n /** Deadline source, injected so the budget is testable without real time. */\n clock?: () => number\n /** The `claude --version` probe. Output is captured and discarded; only `ok` is read. */\n runClaude?: ClaudeRunner\n /** The per-project update spawn \u2014 its own seam, so the CLI-install spawn's call count stays honest. */\n spawnPluginUpdate?: typeof spawnSync\n /** The project-scope install records; defaults to reading `~/.claude/plugins/installed_plugins.json`. */\n listPluginInstallations?: () => readonly PluginInstallation[]\n pathExists?: (target: string) => boolean\n}\n\ntype RecordResult = 'ok' | 'skipped' | 'failed'\n\ninterface UpdateContext {\n spawn: typeof spawnSync\n env: NodeJS.ProcessEnv\n clock: () => number\n deadlineMs: number\n pathExists: (target: string) => boolean\n}\n\n/**\n * The child env: npx/dlx markers stripped like every other child this CLI spawns, plus `CLAUDECODE`\n * \u2014 the marker a nested Claude Code refuses to start under. Whether `plugin update` shares that\n * refusal was not measured; the spike that proved this command ran without it, so it stays out.\n */\nconst pluginUpdateEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n const child = withoutPackageManagerEnv(env)\n\n delete child.CLAUDECODE\n\n return child\n}\n\nconst isEnoent = (error: Error): boolean => {\n return (error as NodeJS.ErrnoException).code === 'ENOENT'\n}\n\n/**\n * One recorded project. `cwd` is the whole mechanism: `claude` resolves WHICH project-scope record an\n * update touches from the cwd, and from a non-project directory it silently picks some other record.\n *\n * A path that no longer exists is skipped, never a failure \u2014 `installed_plugins.json` is append-only,\n * so records for deleted checkouts outlive the checkouts. `ENOENT` from the spawn is the same case\n * caught a moment later (the directory vanished between the check and the spawn).\n */\nconst updateRecordedProject = (record: PluginInstallation, ctx: UpdateContext): RecordResult => {\n const projectPath = record.projectPath\n\n if (projectPath === null || !ctx.pathExists(projectPath)) return 'skipped'\n\n const remainingMs = ctx.deadlineMs - ctx.clock()\n\n if (remainingMs <= 0) return 'failed'\n\n const result = ctx.spawn(CLAUDE_BIN, [...PLUGIN_UPDATE_ARGV], {\n cwd: projectPath,\n // Silent, like the CLI install: this is a detached worker with nowhere to write.\n stdio: 'ignore',\n shell: process.platform === 'win32',\n env: ctx.env,\n timeout: Math.min(PLUGIN_UPDATE_RUN_TIMEOUT_MS, remainingMs),\n windowsHide: true,\n })\n\n if (result.error) return isEnoent(result.error) ? 'skipped' : 'failed'\n\n return result.signal === null && result.status === 0 ? 'ok' : 'failed'\n}\n\nconst updatePluginUnguarded = (deps: UpdatePluginDeps): PluginUpdateOutcome => {\n const clock = deps.clock ?? Date.now\n // The probe's own timeout (`CLAUDE_TIMEOUT_MS`) is inside this budget, not in addition to it.\n const deadlineMs = clock() + PLUGIN_UPDATE_BUDGET_MS\n const runClaude = deps.runClaude ?? defaultClaudeRunner\n\n // The only gate besides the lock. `canSelfSpawn` is a question about where npm put the CLI and says\n // nothing about `claude`; a Homebrew-owned CLI still gets its plugin updated.\n if (!runClaude({ args: CLAUDE_VERSION_ARGV }).ok) return 'claude-missing'\n\n const records = (deps.listPluginInstallations ?? listProjectPluginInstallations)()\n\n if (records.length === 0) return 'skipped'\n\n const ctx: UpdateContext = {\n spawn: deps.spawnPluginUpdate ?? spawnSync,\n env: pluginUpdateEnv(deps.env ?? process.env),\n clock,\n deadlineMs,\n pathExists: deps.pathExists ?? fs.existsSync,\n }\n\n // Every record gets its turn even after one fails: the records are independent projects, and a\n // failure in one is no reason to leave another stale. The verdict is still `failed` \u2014 the manual\n // command is what fixes the one that did not take.\n const results = records.map((record) => {\n return updateRecordedProject(record, ctx)\n })\n\n if (results.includes('failed')) return 'failed'\n\n return results.includes('ok') ? 'updated' : 'skipped'\n}\n\n/**\n * Update the installed plugin in every recorded project. NEVER throws: a plugin failure is a recorded\n * outcome, not a reason to lose the CLI outcome the worker has already produced.\n *\n * @example\n * updatePlugin({ listPluginInstallations: () => [] }) // => 'skipped'\n */\nexport const updatePlugin = (deps: UpdatePluginDeps = {}): PluginUpdateOutcome => {\n try {\n return updatePluginUnguarded(deps)\n } catch {\n return 'failed'\n }\n}\n", "import { spawnSync } from 'node:child_process'\n\nimport { PLUGIN_KEY } from './names'\n\n/**\n * @fileoverview\n *\n * The `claude` binary as a dependency: the argv this CLI hands it and the one seam through which it is\n * spawned. Kept apart from `install-plugin.ts` (and its logger import) because the detached update\n * worker runs `claude plugin update` too, and that worker must stay a bundle of `node:child_process`\n * plus the cache writer \u2014 nothing that constructs a logger at import time.\n */\n\n/** Trust the `claude` binary resolved from `PATH`; there is no configured path and none is wanted. */\nexport const CLAUDE_BIN = 'claude'\n\n/**\n * Ceiling for any one `claude` invocation. `plugin install` clones a marketplace repo, so it is not\n * instant \u2014 but an `initCore` that hangs forever on a wedged network is worse than one that reports a\n * failed install step, and the user's remaining setup steps are behind this call.\n */\nexport const CLAUDE_TIMEOUT_MS = 120_000\n\n/** The PATH probe. Cheapest command that fails loudly when the binary is absent. */\nexport const CLAUDE_VERSION_ARGV: readonly string[] = ['--version']\n\n/**\n * `claude plugin update infra-kit@infra-kit --scope project -y`, as argv.\n *\n * Every flag is load-bearing (measured on Claude Code 2.1.270). Without `--scope project` the command\n * resolves USER scope from every cwd and fails \"not installed at scope user\" \u2014 while still refreshing\n * the marketplace clone as a side effect, so the failure looks like progress. `-y` is required when\n * stdio is not a TTY, which is every spawn from this CLI. WHICH project record the update advances is\n * decided by the command's cwd, not by any flag: callers pass `cwd: <recorded projectPath>`.\n */\nexport const PLUGIN_UPDATE_ARGV: readonly string[] = ['plugin', 'update', PLUGIN_KEY, '--scope', 'project', '-y']\n\n/** One `claude` invocation. `cwd` matters: `--scope project` records the directory it ran in. */\nexport interface ClaudeCommand {\n args: readonly string[]\n cwd?: string\n}\n\nexport interface ClaudeCommandResult {\n ok: boolean\n /** Diagnostic text from the command. Only read when `ok` is false. */\n output?: string\n}\n\n/** The injectable seam. Tests pass a fake so a suite never installs a plugin on the developer's machine. */\nexport type ClaudeRunner = (command: ClaudeCommand) => ClaudeCommandResult\n\n/**\n * Run one `claude` command, capturing its output instead of inheriting the terminal.\n *\n * Captured, not inherited, because `initCore` renders its own progress: a raw `plugin install` transcript\n * dumped between two `INFO:` lines reads as a crash. The captured text is not discarded \u2014 its first\n * line is what the failure warning quotes.\n *\n * @example\n * defaultClaudeRunner({ args: ['--version'] }) // => { ok: true, output: '2.0.0 (Claude Code)' }\n */\nexport const defaultClaudeRunner: ClaudeRunner = (command) => {\n // PATH lookup is the point: `claude` is installed by its own installer to a location this CLI does\n // not know and must not guess, and \"is it on PATH\" is exactly the question step (b) asks.\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n const result = spawnSync(CLAUDE_BIN, [...command.args], {\n cwd: command.cwd,\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'pipe'],\n timeout: CLAUDE_TIMEOUT_MS,\n })\n\n if (result.error !== undefined) return { ok: false, output: result.error.message }\n\n const output = `${result.stderr ?? ''}\\n${result.stdout ?? ''}`.trim()\n\n return { ok: result.status === 0, output }\n}\n", "/**\n * The three names every plugin-pointer module agrees on, in a file that imports NOTHING.\n *\n * Split out of `plugin-pointer.ts` because that module constructs the pino logger at import time,\n * and the detached update worker (`dist/update-check.js`) needs `PLUGIN_KEY` to spawn\n * `claude plugin update` \u2014 a worker that logs to an ignored stderr has no business paying for pino.\n */\n\n/** The marketplace name, as it appears in `extraKnownMarketplaces` and in `<plugin>@<marketplace>`. */\nexport const MARKETPLACE_NAME = 'infra-kit'\n\n/** The `enabledPlugins` key: `<plugin>@<marketplace>`, both `infra-kit`. */\nexport const PLUGIN_KEY = 'infra-kit@infra-kit'\n\n/** The GitHub repo the marketplace is served from. */\nexport const MARKETPLACE_REPO = 'ArthurSaenz/infra-kit'\n", "import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\n\nimport { MARKETPLACE_NAME, PLUGIN_KEY } from './names'\n\n/**\n * @fileoverview\n *\n * HOST-STATE readers: what Claude Code itself records on this machine about the `infra-kit`\n * marketplace and plugin. The consumer repo's own `.mcp.json` is read by `mcp-registration.ts`.\n *\n * All of it is read-only and total \u2014 every reader answers \"not registered / not installed\" for an\n * absent, unreadable or malformed file rather than throwing. `initCore` prints an install hint from\n * these answers and `doctor` reports them as rows, and neither may crash because a user hand-edited\n * a JSON file under `~/.claude/`.\n *\n * These files are Claude Code's, not ours. Nothing here writes to them: installing a plugin is the\n * `claude plugin install` command's job, and a CLI that edited another tool's state directory would\n * be repairing something it does not own.\n */\n\n/** Where Claude Code keeps its plugin bookkeeping, relative to `$HOME`. */\nconst PLUGINS_DIR = ['.claude', 'plugins']\n\n/** One entry of `installed_plugins.json`'s per-plugin array. Extra fields are ignored, not rejected. */\nexport interface PluginInstallation {\n scope: string | null\n projectPath: string | null\n installPath: string | null\n version: string | null\n}\n\nconst readJsonFile = (filePath: string): unknown => {\n try {\n return JSON.parse(fs.readFileSync(filePath, 'utf-8'))\n } catch {\n return undefined\n }\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nconst readString = (source: Record<string, unknown>, key: string): string | null => {\n const value = source[key]\n\n return typeof value === 'string' ? value : null\n}\n\n/** `~/.claude/plugins/<file>`, with `$HOME` injectable so tests never read the developer's own state. */\nconst pluginsPath = (file: string, home: string = os.homedir()): string => {\n return path.join(home, ...PLUGINS_DIR, file)\n}\n\n/**\n * Is the `infra-kit` marketplace registered on this machine?\n *\n * Registration is a machine fact (`~/.claude/plugins/known_marketplaces.json`), distinct from the\n * per-project `extraKnownMarketplaces` pointer `initCore` writes: the pointer says where to look, this\n * says the lookup has actually happened.\n *\n * @example\n * isMarketplaceRegistered() // => true once `claude plugin marketplace add ArthurSaenz/infra-kit` has run\n */\nexport const isMarketplaceRegistered = (home?: string): boolean => {\n const parsed = readJsonFile(pluginsPath('known_marketplaces.json', home))\n\n return isPlainObject(parsed) && MARKETPLACE_NAME in parsed\n}\n\nconst toInstallation = (entry: unknown): PluginInstallation | null => {\n if (!isPlainObject(entry)) return null\n\n return {\n scope: readString(entry, 'scope'),\n projectPath: readString(entry, 'projectPath'),\n installPath: readString(entry, 'installPath'),\n version: readString(entry, 'version'),\n }\n}\n\nconst readInstallations = (home?: string): PluginInstallation[] => {\n const parsed = readJsonFile(pluginsPath('installed_plugins.json', home))\n\n if (!isPlainObject(parsed) || !isPlainObject(parsed.plugins)) return []\n\n const entries = parsed.plugins[PLUGIN_KEY]\n\n if (!Array.isArray(entries)) return []\n\n return entries.flatMap((entry): PluginInstallation[] => {\n const installation = toInstallation(entry)\n\n return installation === null ? [] : [installation]\n })\n}\n\nexport interface PluginInstallationQuery {\n /** Override `$HOME` (tests, and nothing else). */\n home?: string\n /** The project root being asked about. Omitted, only a user-scope entry can count as installed. */\n projectPath?: string\n}\n\n/**\n * Whether the plugin is installed FOR THIS PROJECT \u2014 not merely present somewhere on the machine.\n *\n * `elsewhere` is the distinction that matters: it carries the records that exist, so the caller can\n * say which other project they belong to instead of reporting a bare \"not installed\".\n */\nexport type PluginInstallState =\n | { kind: 'installed'; installation: PluginInstallation }\n | { kind: 'elsewhere'; installations: readonly PluginInstallation[] }\n | { kind: 'absent' }\n\n/**\n * A path in the form the two sides can be compared in. `realpath` on both sides or neither: on macOS\n * `/tmp` resolves to `/private/tmp`, so a resolved path compared against an unresolved one never\n * matches. Falls back to `path.resolve` for a path that no longer exists, which `realpath` rejects.\n */\nconst canonicalPath = (target: string): string => {\n try {\n return fs.realpathSync(target)\n } catch {\n return path.resolve(target)\n }\n}\n\n/**\n * Does one record make the plugin active in `root`?\n *\n * A `user`-scope install is machine-wide and covers every project. Otherwise the record has to NAME\n * this project: `claude plugin install --scope project` stores the directory the session was started\n * in, so an install done for another repo covers that repo and nothing else.\n *\n * A record whose `projectPath` is this root counts whatever scope string it carries \u2014 the path is the\n * stronger signal, and an older Claude Code wrote records with no `scope` field at all.\n */\nconst coversProject = (entry: PluginInstallation, root: string | null): boolean => {\n if (entry.scope === 'user') return true\n if (root === null || entry.projectPath === null) return false\n\n return canonicalPath(entry.projectPath) === root\n}\n\n/**\n * Resolve what `~/.claude/plugins/installed_plugins.json` says about THIS project.\n *\n * @example\n * resolvePluginInstall({ projectPath: '/repo' })\n * // => { kind: 'elsewhere', installations: [{ projectPath: '/other', \u2026 }] } // installed, but not here\n */\nexport const resolvePluginInstall = (query: PluginInstallationQuery = {}): PluginInstallState => {\n const installations = readInstallations(query.home)\n\n if (installations.length === 0) return { kind: 'absent' }\n\n const root = query.projectPath === undefined ? null : canonicalPath(query.projectPath)\n\n const covering = installations.find((entry) => {\n return coversProject(entry, root)\n })\n\n return covering === undefined ? { kind: 'elsewhere', installations } : { kind: 'installed', installation: covering }\n}\n\n/**\n * Every PROJECT-scope record, one per distinct project path \u2014 the set `claude plugin update` has to be\n * run against, because Claude Code resolves which record an update touches from the command's cwd\n * (measured: from a non-project cwd it silently picks some other record, so one run from `$HOME`\n * advances one project, not all).\n *\n * A record with no `scope` but a `projectPath` counts as project scope, the way `coversProject`\n * treats it. User-scope records are excluded: this CLI never installs at user scope, and an update\n * there needs no cwd at all. Duplicates collapse on the canonical path \u2014 the file is append-only, so\n * a reinstalled project may carry two records naming one directory.\n *\n * @example\n * listProjectPluginInstallations()\n * // => [{ scope: 'project', projectPath: '/Users/me/hulyo', installPath: '\u2026/0.7.0', version: '0.7.0' }]\n */\nexport const listProjectPluginInstallations = (home?: string): PluginInstallation[] => {\n const seen = new Set<string>()\n\n return readInstallations(home).filter((entry) => {\n if (entry.scope === 'user' || entry.projectPath === null) return false\n\n const key = canonicalPath(entry.projectPath)\n\n if (seen.has(key)) return false\n\n seen.add(key)\n\n return true\n })\n}\n\n/**\n * The installed plugin's version: the record's own `version`, falling back to the manifest at\n * `<installPath>/.claude-plugin/plugin.json`.\n *\n * The fallback is not redundant. `installed_plugins.json` records a git-commit sha as `version` for\n * marketplaces served from a repo, so the manifest is the only place a human-readable `0.4.0` lives\n * \u2014 and an entry written by an older Claude Code may carry no `version` at all.\n *\n * @example\n * readInstalledPluginVersion({ scope: 'project', projectPath: null, installPath: '/cache/infra-kit', version: null })\n * // => '0.4.0' (read from /cache/infra-kit/.claude-plugin/plugin.json)\n */\nexport const readInstalledPluginVersion = (installation: PluginInstallation): string | null => {\n if (installation.installPath === null) return installation.version\n\n const manifest = readJsonFile(path.join(installation.installPath, '.claude-plugin', 'plugin.json'))\n const declared = isPlainObject(manifest) ? readString(manifest, 'version') : null\n\n return declared ?? installation.version\n}\n\n/**\n * The plugin's directory inside the marketplace clone: `plugins/<plugin name>`, the left half of\n * `<plugin>@<marketplace>`. Derived, not spelled out again, so the two can never disagree.\n */\nconst [PLUGIN_NAME = MARKETPLACE_NAME] = PLUGIN_KEY.split('@')\n\n/**\n * The plugin version the marketplace CLONE carries \u2014 `~/.claude/plugins/marketplaces/<marketplace>/\n * plugins/<plugin>/.claude-plugin/plugin.json` \u2014 which is NOT what a session serves.\n *\n * Measured (plan \u00A76.1 S0-7(b)): sessions load the plugin from the install record's cache\n * `installPath`, and only a successful `claude plugin update --scope project` advances that record,\n * while any `claude plugin update` \u2014 a failing user-scope one included \u2014 refreshes the clone as a\n * side effect. So the clone can sit AHEAD of the served copy, and comparing the two is the one\n * freshness signal readable offline: \"fetched but not applied\". Reads as `null` for a clone that is\n * absent, unreadable or carries no version, so the caller drops the comparison instead of failing.\n *\n * @example\n * readMarketplacePluginVersion() // => '0.8.0' after a `claude plugin update` refreshed the clone\n * readMarketplacePluginVersion({ home: '/tmp/no-such-home' }) // => null\n */\nexport const readMarketplacePluginVersion = ({ home }: Pick<PluginInstallationQuery, 'home'> = {}): string | null => {\n const manifestPath = pluginsPath(\n path.join('marketplaces', MARKETPLACE_NAME, 'plugins', PLUGIN_NAME, '.claude-plugin', 'plugin.json'),\n home,\n )\n const manifest = readJsonFile(manifestPath)\n\n return isPlainObject(manifest) ? readString(manifest, 'version') : null\n}\n"],
|
|
5
|
-
"mappings": "0HAAA,IAAAA,GAAA,CACE,KAAQ,YACR,KAAQ,SACR,QAAW,QACX,MAAS,CACP,MACF,EACA,YAAe,YACf,IAAO,CACL,YAAa,cACb,GAAM,cACN,SAAU,mBACZ,EACA,QAAW,CACT,KAAQ,QACV,EACA,QAAW,CACT,UAAa,iEACb,MAAS,sDACT,QAAW,iBACX,kBAAmB,4BACnB,kBAAmB,cACnB,cAAe,2EACf,eAAgB,4HAChB,iBAAkB,4HAClB,eAAgB,oEAChB,aAAc,kFACd,WAAY,eACZ,KAAQ,0CACR,aAAc,gDACd,UAAW,6CACX,cAAe,uDACf,SAAU,qMACV,GAAM,gHACN,IAAO,6DACT,EACA,aAAgB,CACd,gCAAiC,UACjC,qBAAsB,SACtB,oBAAqB,SACrB,kBAAmB,SACnB,qBAAsB,SACtB,mBAAoB,SACpB,+BAAgC,SAChC,0BAA2B,SAC3B,MAAS,SACT,SAAY,SACZ,UAAa,UACb,QAAW,UACX,IAAO,SACP,KAAQ,UACR,cAAe,UACf,SAAY,UACZ,MAAS,SACT,KAAQ,SACR,IAAO,SACP,GAAM,QACR,EACA,gBAAmB,CACjB,+BAAgC,SAChC,4BAA6B,UAC7B,iCAAkC,cAClC,oBAAqB,WACrB,eAAgB,WAChB,oBAAqB,cACrB,oBAAqB,cACrB,QAAW,UACX,sBAAuB,SACvB,WAAc,QAChB,CACF,EC3DA,OAAS,aAAAC,MAAiB,qBAC1B,OAAS,WAAAC,MAAe,UACxB,OAAOC,MAAa,eCFpB,OAAOC,MAAQ,UACf,OAAOC,MAAU,YACjB,OAAOC,OAAa,eAIb,IAAMC,GAAiB,oBAiBjBC,GAAgB,KAAU,IAE1BC,GAAe,IACnBC,EAAK,KAAKC,EAAa,EAAGJ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,cAAe,KAAM,QAAS,YAAa,CAAC,EAKxF,CAHe,MAAMlB,GAAkBE,EAAK,UAAW,CAAE,eAAAwB,EAAgB,MAAAC,EAAO,MAAAC,CAAM,CAAC,EAG1E,OAAOK,EAAO,uBAAwB,CAAE,cAAAf,EAAe,cAAe,IAAK,CAAC,EAgB7F,IAAM7B,EAAS0C,GAAMI,EAAc,CAAC,EAAaA,EAAc,MAAM,CAAC,EAAG,CACvE,MAAO,SACP,MAAO3C,EAAQ,WAAa,QAC5B,IAAKC,EAAQ,EACb,IAAK6C,EAAyBlD,CAAG,EACjC,YAAa,EACf,CAAC,EAID,OAAIC,EAAO,OAASA,EAAO,QAAUA,EAAO,SAAW,EAC9C4C,EAAO,iBAAkB,CAAE,cAAAf,EAAe,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
|
-
}
|
package/dist/chunk-AOWMCNYY.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{P as l,U as W,W as I,ia as O,l as D,r as M}from"./chunk-GCX3HDDL.js";import{execFile as rr,execFileSync as er}from"node:child_process";import d from"node:process";var tr=5e3,or=100,J=2e3,F="/bin/ps",nr=1e3,j=["-eo","pid=,ppid=,pgid=,lstart="],U=8<<20,q=r=>r.split(`
|
|
2
|
-
`).flatMap(e=>{let[t,o,n,...i]=e.trim().split(/\s+/);if(t==null||o==null||n==null)return[];let s=Number(t),c=Number(o),u=Number(n);return!Number.isInteger(s)||!Number.isInteger(c)||!Number.isInteger(u)?[]:[{pid:s,ppid:c,pgid:u,lstart:i.join(" ")}]}),K=r=>{let e=new Map;for(let t of r)t.pid===t.pgid&&e.set(t.pgid,t.lstart);return e},sr=(r,e,t)=>{let o=K(e);return X(r,e,t).flatMap(n=>{let i=o.get(n);return i==null||i===""?[]:[{pgid:n,leaderStart:i}]})},H=(r,e)=>{let t=K(e);return r.flatMap(({pgid:o,leaderStart:n})=>t.get(o)===n?[o]:[])},B=(r,e)=>H(r,e).flatMap(t=>{try{d.kill(-t,"SIGKILL")}catch{return[]}return[t]}),X=(r,e,t)=>{let o=new Map;for(let c of e){let u=o.get(c.ppid);u?u.push(c):o.set(c.ppid,[c])}let n=new Set([r]),i=new Set([r]),s=[r];for(let c=0;c<s.length;c+=1)for(let u of o.get(s[c]??-1)??[])i.has(u.pid)||(i.add(u.pid),n.add(u.pgid),s.push(u.pid));return[...n].filter(c=>c>1&&c!==t)},R=()=>{try{return q(er(F,[...j],{encoding:"utf8",maxBuffer:U}))}catch{return[]}},ir=async()=>new Promise(r=>{rr(F,[...j],{encoding:"utf8",maxBuffer:U},(e,t)=>{r(e?[]:q(t))})}),ar=(r,e,t)=>t.some(o=>o.pid===r&&o.ppid===e),E=(r,e)=>{let t=e.find(o=>o.pid===d.pid)?.pgid;return X(r,e,t)},Q=r=>{try{return d.kill(-r,0),!0}catch{return!1}},N=(r,e)=>{for(let t of r)try{d.kill(-t,e)}catch{}},x=new Set,cr=(r,e,t)=>{let o=E(r,e),n=t.flatMap(i=>H(i,e));return[...new Set([...o,...n])]},V=()=>{let r=R(),e=[...x].map(t=>t());N(cr(d.pid,r,e),"SIGKILL")},ur=async r=>new Promise(e=>{setTimeout(e,r)}),C=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 ur(or);return o};function Jr(r,e=tr,t,o=R){r.unref();let n=!1,i=!1,s=[],c=null,u=()=>s;x.add(u);let m=()=>{c&&clearInterval(c),c=null},g=async()=>{await C(s.map(a=>a.pgid),J),x.delete(u)},f=a=>{let p=r.pid;if(p==null||i||n||a.length===0)return;let P=a.find(v=>v.pid===d.pid)?.pgid,k=sr(p,a,P);k.length>0&&(s=k)},w=async()=>{r.pid==null||i||n||f(await ir())};f(R()),c=setInterval(()=>{w()},nr),c.unref();let S=a=>{n||t?.(a)};return r.on("exit",(a,p)=>{i=!0,m(),n||(B(s,o()),g()),S(`exited unexpectedly (code=${a??"null"}, signal=${p??"null"})`)}),r.on("error",a=>{S(`failed to spawn: ${a.message}`)}),{kill:async()=>{n=!0,m();let a=r.pid;if(a==null){x.delete(u);return}if(r.exitCode!==null||r.signalCode!==null){B(s,o()),await g();return}let p=o();if(p.length>0&&!ar(a,d.pid,p))return;let P=E(a,p);N(P,"SIGTERM");let k=await C(P,e);if(k.length===0){x.delete(u);return}let v=E(a,o()),_=[...new Set([...k,...v])].filter(Q);N(_,"SIGKILL"),await C(_,J),x.delete(u)}}}import{constants as pr}from"node:os";import h from"node:process";var lr=["SIGINT","SIGTERM","SIGHUP"],dr=pr.signals,mr=2,L=r=>128+(dr[r]??mr),gr=2e4,fr=r=>{h.exit(r)},wr=(r,e)=>{h.on(r,e)},xr=(r,e)=>{h.off(r,e)},yr=(r,e)=>{let t=setTimeout(r,e);return t.unref(),()=>{clearTimeout(t)}},G=r=>{try{h.stderr.write(r)}catch{}},kr=(r,e)=>{let t=e instanceof Error?`${e.message}
|
|
3
|
-
${e.stack??"(no stack)"}`:String(e);G(`
|
|
4
|
-
\u2717 Teardown failed while handling ${r}: ${t}
|
|
5
|
-
`)},qr=({onSignal:r,exit:e=fr,register:t=wr,unregister:o=xr,forceReap:n=V,teardownDeadlineMs:i=gr,setTimer:s=yr,describeStall:c=()=>"unknown",fileReport:u=()=>{}})=>{let m=null,g=null,f=new Map,w=()=>{for(let[a,p]of f)o(a,p);f.clear()},S=a=>{if(m!==null){if(a!==m)return;G(`
|
|
6
|
-
\u26A0 Received ${a} again \u2014 force-quitting.
|
|
7
|
-
`),g?.(),n(),w(),e(L(a));return}m=a,g=s(()=>{let p=`
|
|
8
|
-
\u26A0 Teardown deadline exceeded at stage=${c()} after ${i}ms \u2014 force-quitting.
|
|
9
|
-
`;G(p),u(p),n(),w(),e(L(a))},i),(async()=>{try{await r(a)}catch(p){kr(a,p)}finally{g?.(),w(),e(L(a))}})()};for(let a of lr){let p=()=>S(a);f.set(a,p),t(a,p)}return w};import Sr from"node:process";import{$}from"zx";var Pr=async()=>{try{return await $`cmux --version`.quiet(),!0}catch{return!1}},hr=async r=>{let{cwd:e,title:t,layout:o}=r,n=JSON.stringify(o),s=(await $({env:{...Sr.env,CMUX_QUIET:"1"}})`cmux new-workspace --name ${t} --cwd ${e} --focus false --layout ${n}`).stdout;return vr(s)},br=async r=>{try{await $`cmux close-workspace --workspace ${r}`.quiet()}catch(e){l.debug({error:e,ref:r},"cmux: skipped closing dev workspace")}},vr=r=>{let e=r.match(/workspace:\d+/);if(!e)throw new Error("cmux: could not locate workspace ref in new-workspace output");return e[0]};import{$ as Rr}from"zx";import{realpath as Cr}from"node:fs/promises";import{$ as z}from"zx";var b=async r=>{try{return await Cr(r)}catch{return r}},A=async()=>{try{let[r,e]=await Promise.all([z`cmux workspace list --json`.quiet(),z`cmux workspace-group list --json`.quiet()]),t=JSON.parse(r.stdout).workspaces??[],o=JSON.parse(e.stdout).groups??[],n=new Set(o.map(s=>s.anchor_workspace_ref).filter(s=>typeof s=="string")),i=new Map;for(let s of t)!s.current_directory||n.has(s.ref)||i.set(await b(s.current_directory),s.ref);return i}catch(r){return l.debug({error:r},"cmux: skipped listing workspaces by cwd"),new Map}};var Er=async r=>{try{let t=(await A()).get(await b(r));if(!t)return;await Rr`cmux workspace close ${t}`.quiet()}catch(e){l.debug({error:e,cwd:r},"cmux: skipped closing workspace by cwd")}};import{$ as T}from"zx";var Y=async r=>{try{let e=(await T`cmux workspace-group list --json`.quiet()).stdout;return(JSON.parse(e).groups??[]).find(n=>n.name===r)?.ref??null}catch(e){return l.debug({error:e,name:r},"cmux: skipped group lookup"),null}},Nr=async(r,e)=>{try{let o=(await T`cmux workspace-group create --name ${r} --from ${e.join(",")}`).stdout.match(/workspace_group:\d+/)?.[0]??await Y(r);return o&&await T`cmux workspace-group pin ${o}`.quiet(),o??null}catch(t){return l.warn({error:t,name:r},"\u26A0\uFE0F cmux: failed to create workspace group"),null}};import{$ as y}from"zx";var Lr=async r=>{let{cwd:e,title:t,group:o}=r,n=W(await I()),i=o?(await y`cmux workspace create --cwd ${e} --group ${o} --group-placement end`).stdout:(await y`cmux workspace create --cwd ${e}`).stdout,s=$r(i),c=(await y`cmux list-pane-surfaces --workspace ${s}`).stdout,u=Gr(c);return await y`cmux new-split right --workspace ${s} --surface ${u}`,n==="three-pane"&&await y`cmux new-split down --workspace ${s} --surface ${u}`,t&&await y`cmux workspace rename --workspace ${s} --title ${t}`,s},Gr=r=>{let e=r.match(/surface:\d+/);if(!e)throw new Error("cmux: could not locate initial surface in list-pane-surfaces output");return e[0]},$r=r=>{let e=r.match(/workspace:\d+/);if(!e)throw new Error("cmux: could not locate workspace ref in workspace create output");return e[0]};var Ar=r=>{let{branch:e}=r,t=D(e);return t?M(t):e};var Tr=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),Z=r=>r instanceof Error&&Tr.has(r.name),Se=r=>{if(Z(r))return!0;let e=r?.cause;return Z(e)};import{loadDev as _r}from"@slip-stream-kit/config/internal";import Dr from"node:path";var Mr=(r,e)=>{let t=new Set;for(let o of Object.values(r))for(let n of Object.keys(O(o,e).proxy))t.add(n);return[...t]},Wr=async(r,e)=>{let t={},o=[];return await Promise.all(e.map(async n=>{try{let s=(await _r(Dr.join(r,"apps",n,"ui")))?.proxy?.routes;if(!s)return;t[n]=Object.fromEntries(Object.entries(s).map(([c,u])=>[c,u.packageName]))}catch(i){o.push({app:n,message:i instanceof Error?i.message:String(i)})}})),{routePkg:(n,i)=>t[n]?.[i],loadErrors:o}},Ce=async(r,e,t,o)=>{let{routePkg:n,loadErrors:i}=await Wr(r,Mr(e,t));return{ctx:{discovered:t,apiPkgByApp:Object.fromEntries(o.map(s=>[s.name,s.packageName])),routePkg:n},loadErrors:i}};export{Ce as a,V as b,Jr as c,L as d,qr as e,b as f,A as g,Er as h,Y as i,Nr as j,Pr as k,hr as l,br as m,Lr as n,Ar as o,Se as p};
|
|
10
|
-
//# sourceMappingURL=chunk-AOWMCNYY.js.map
|
package/dist/chunk-BVEVERTB.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{P as g,V as A,d as f,f as p,i as b}from"./chunk-GCX3HDDL.js";import{t as P}from"./chunk-75URROMU.js";import{a as $,b as _}from"./chunk-QWVLAZ6N.js";import v from"node:fs/promises";import u from"node:path";import{z as i}from"zod";var s=class extends Error{env;constructor(t,r=null){super(t),this.name="EnvAuthError",this.env=r}},oe=e=>e instanceof s;import H from"node:fs/promises";import q from"node:os";var J=async e=>{try{return await H.access(e),!0}catch{return!1}},h=e=>{let t=q.homedir();return e.startsWith(t)?`~${e.slice(t.length)}`:e};var K="tokens.json",x=1,D=384,R=448,B=i.object({version:i.literal(x).default(x),envs:i.record(i.string().min(1),i.string().min(1))}).strict(),w=async()=>{let e=await A();return u.join(u.dirname(e.userProject),K)},E=async()=>{let e=await w(),t;try{t=await v.readFile(e,"utf-8")}catch{return null}let r;try{r=JSON.parse(t)}catch(o){throw new s(`Invalid JSON in the token store at ${h(e)}: ${o.message}
|
|
2
|
-
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`)}let n=B.safeParse(r);if(!n.success)throw new s(`Invalid token store at ${h(e)}: ${i.prettifyError(n.error)}
|
|
3
|
-
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return n.data},y=async e=>{let t=await w(),r=u.dirname(t),n=u.dirname(r),o=u.dirname(n);for(let c of[o,n,r])await v.mkdir(c,{recursive:!0,mode:R}),await v.chmod(c,R);P(t,`${JSON.stringify(e,null,2)}
|
|
4
|
-
`,D),await v.chmod(t,D)},L=async(e,t)=>{let r=await E();await y({version:x,envs:{...r?.envs,[e]:t}})},W=async e=>{let t=await E();if(!t||!(e in t.envs))return;let r={...t.envs};delete r[e],await y({version:x,envs:r})};var z=()=>{let e="",t=[],r=!1;return{start(n){e=n,t=[],r=!1},setInteractive(){r=!0},addOption(n,o){t.push({flag:n,value:o})},formatOptions(){return t.map(n=>typeof n.value=="boolean"?n.value?n.flag:"":Array.isArray(n.value)?`${n.flag} "${n.value.join(", ")}"`:`${n.flag} "${n.value}"`).filter(Boolean).join(" ")},snapshot(){return t.length===0?null:{formattedOptions:this.formatOptions()}},print(){!r||t.length===0||!e||g.info(`\u{1F4DF} Equivalent command:
|
|
5
|
-
pnpm exec infra-kit ${e} ${this.formatOptions()}
|
|
6
|
-
`)},reset(){e="",t=[],r=!1}}},S=z();import{isAbsolute as j,resolve as I}from"node:path";import U from"node:process";var O=null,k=null,Y=e=>{O=[...e],k=U.cwd()},G=new Set(["--yes","-y"]),V=(e,t)=>{let r=[...e];for(let[n,o]of r.entries())o==="-C"&&r[n+1]!==void 0&&!j(r[n+1])?r[n+1]=I(t,r[n+1]):o.startsWith("-C")&&o.length>2&&!o.startsWith("--")&&!j(o.slice(2))&&(r[n]=`-C${I(t,o.slice(2))}`);return r},C=()=>{if(O===null||k===null)return["--yes"];let e=V(O.slice(2),k);return e.some(r=>G.has(r))?e:[...e,"--yes"]};import M from"node:process";var a=class extends b{structuredContent;exitCode;constructor(t,r,n){super(void 0,n),this.name="StructuredRefusalError",this.structuredContent=t,this.exitCode=r}};var Q=27,X=e=>e==="mcp"?"an interactive prompt was reached under MCP, where stdin carries JSON-RPC":e===null?"an interactive prompt was reached under --json, which never prompts":`an interactive prompt was reached in agent mode (${e==="flag"?"--agent":"INFRA_KIT_AGENT / CLAUDECODE"}), where there is no human to answer it`,Z=(e,t)=>{let r=t===void 0?"pass the value explicitly instead of relying on the prompt":`pass --${t}`;return e==="mcp"?t===void 0?`${r} \u2014 MCP runs have no human to answer it`:`pass "${t}" \u2014 MCP runs have no human to answer it`:`${r} on the re-run`},ee=e=>{if(typeof e=="object"&&"value"in e)return e.value;let t=typeof e=="object"?e.refuse:void 0,{source:r}=f;throw new a(t===void 0?{status:"refused",agentMode:r}:{status:"argument_required",argument:t,agentMode:r},2,{operation:"interactive prompt",remediation:Z(r,t),stderrExcerpt:X(r)})},N=async(e,t)=>{let r=new AbortController,{whenHeadless:n="refuse",...o}=t??{},c={...o,signal:r.signal};if(p())return ee(n);if(!M.stdin.isTTY)return e(c);let m=M.stdin,T=d=>{d.length===1&&d[0]===Q&&r.abort()};$();try{let d=e(c);return m.isPaused()&&m.resume(),m.on("data",T),await d}finally{m.removeListener("data",T),_()}};import te from"@inquirer/confirm";import re from"node:process";var l=class extends Error{constructor(t="Operation cancelled by the operator"){super(t),this.name="CommandDeclinedError"}},Ie=e=>e instanceof l;var F=(e,t)=>{let{source:r}=f,n=C();throw new a({status:"confirmation_required",message:e,plan:t,rerun:n,agentMode:r},2,{operation:"confirm before running",remediation:r===null?"pass `--yes` to confirm, or drop `--json` to be prompted":`show the plan to the human, then re-run \`infra-kit ${n.join(" ")}\` to confirm`,stderrExcerpt:"confirmation required and nobody to ask"})},ne=async(e,t,r={})=>{!e&&p()&&F(t,r.plan);let n=e?!0:await N(o=>te({message:t},o),{whenHeadless:"refuse"});if(e||S.setInteractive(),!n){if(r.throwOnDecline)throw new l;g.info("Operation cancelled. Exiting..."),re.exit(0)}};export{s as a,oe as b,J as c,h as d,w as e,E as f,L as g,W as h,S as i,Ie as j,a as k,Y as l,N as m,F as n,ne as o};
|
|
7
|
-
//# sourceMappingURL=chunk-BVEVERTB.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/lib/env-tokens/env-tokens.ts", "../src/lib/errors/env-auth-error.ts", "../src/lib/path-display/path-display.ts", "../src/lib/command-echo/command-echo.ts", "../src/lib/parsed-argv/parsed-argv.ts", "../src/lib/prompts/escapable-context.ts", "../src/lib/errors/structured-refusal-error.ts", "../src/lib/command-echo/confirm-or-exit.ts", "../src/lib/errors/command-declined-error.ts"],
|
|
4
|
-
"sourcesContent": ["// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n */\n// HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were\n// dropped for it \u2014 do not re-add either without re-deciding that:\n//\n// - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version\n// key, and a store the CLI refuses to read is a store the human cannot write.\n// - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout.\n// That guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so\n// `~/work/api` and `~/oss/api` share ONE token directory and repo B could load (and then\n// overwrite) repo A's credentials. It was removed anyway, knowingly: it also made the CLI refuse\n// every hand-written store, which carries no such field. Hand-authorability wins; the\n// basename-collision risk is ACCEPTED. A weakened version of the guard (warn-and-continue, or\n// \"only check when present\") is NOT the compromise here \u2014 it would re-introduce the same refusal\n// for anyone who did write the field. If you want the guard back, key the store directory on\n// something collision-free instead.\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 it cannot heal on a 30s retry, only a human can fix it \u2014 and env\n // auto-load's sticky marker is keyed on that CLASS. Thrown as a plain Error these were classified\n // TRANSIENT, so a corrupt store went silent on the backgrounded shell-startup spawn and the user's\n // env simply stopped loading with nothing ever said. `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, [env]: token },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * Throw this (or a subclass) \u2014 never a plain `Error` \u2014 for anything a user must fix before\n * env-load can work: no token minted, a corrupt token store, a foreign token store. Only this\n * class earns the STICKY marker that survives the backgrounded shell-startup spawn and is replayed\n * onto the next interactive command. `DopplerAuthError extends EnvAuthError` for the subset that\n * is specifically \"Doppler refused the token we sent\".\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\n// WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): env auto-load must tell a\n// TRANSIENT failure (network, timeout, Doppler down \u2014 heals itself, 30s backoff, stay quiet) apart\n// from a DURABLE one (never heals, and only a human can fix it). A durable failure misclassified as\n// transient is TOTAL SILENCE, forever, on the one path the whole feature exists to survive.\n//\n// That classification therefore has to travel WITH the error, not be re-derived by grepping a\n// message some other module owns \u2014 and it has to be throwable from EVERY module that can produce\n// the class. `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a\n// Doppler-owned base type could not be thrown there without a layering inversion and an import\n// cycle. Hence a neutral base here in `lib/errors`.\n//\n// The defect class this closes is \"a durable failure that is not type-detectable\". Adding a new\n// durable failure and forgetting to type it is exactly how this shipped silent twice.\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * This is the default `isAuthFailure` of `lib/env-autoload`'s `runEnvAutoLoad`. It is deliberately\n * WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only one of the\n * durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store never reaches\n * the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n", "import fs from 'node:fs/promises'\nimport os from 'node:os'\n\n/**\n * Shared path-display helpers for CLI output. Extracted from `commands/config`\n * and `commands/init/migrate-config` (which each had private copies) so config\n * surfaces print paths consistently. Keep this dependency-light (node builtins\n * only) \u2014 it is imported by several commands.\n */\n\n/**\n * Resolve whether a file is reachable, suppressing ENOENT (and any access error)\n * into a boolean. Used to render `[\u2713]`/`[ ]` existence markers.\n *\n * @example\n * await fileExists('/etc/hosts') // => true\n * await fileExists('/nope.txt') // => false\n */\nexport const fileExists = async (filePath: string): Promise<boolean> => {\n try {\n await fs.access(filePath)\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Replace the user's home prefix with `~` so logged paths stay short and portable\n * across machines. Leaves non-home paths untouched.\n *\n * @example\n * // os.homedir() === '/Users/arthur'\n * tildify('/Users/arthur/.infra-kit/infra-kit.json') // => '~/.infra-kit/infra-kit.json'\n * tildify('/etc/hosts') // => '/etc/hosts'\n */\nexport const tildify = (filePath: string): string => {\n const home = os.homedir()\n\n return filePath.startsWith(home) ? `~${filePath.slice(home.length)}` : filePath\n}\n", "import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n *\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the command ran off the CLI (an MCP tool), where a `pnpm exec` line would be\n * nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import { isAbsolute, resolve } from 'node:path'\nimport process from 'node:process'\n\n/**\n * The argv Commander actually parsed for this run \u2014 captured by `entry/cli.ts` at the one place it\n * hands an argv to `parseAsync`, the interactive-menu re-entry included. Commands that need to name\n * their own invocation (a `confirmation_required` refusal's `rerun`) read it here instead of\n * `process.argv`, which the menu path never rewrites.\n */\n\nlet parsedArgv: readonly string[] | null = null\nlet launchCwd: string | null = null\n\n/**\n * Record the full node-style argv (`[node, script, ...args]`) handed to `parseAsync`, and the cwd it\n * was typed in \u2014 read NOW because the `-C` chdir in `preAction` runs later, and a relative `-C` only\n * means anything against this directory.\n */\nexport const setParsedArgv = (argv: readonly string[]): void => {\n parsedArgv = [...argv]\n launchCwd = process.cwd()\n}\n\nconst YES_FLAGS = new Set(['--yes', '-y'])\n\n/**\n * Make every `-C <dir>` in `args` absolute against `cwd`, in place. Commander accepts both\n * `-C dir` and `-Cdir`; both are handled so the re-run is cwd-independent whichever way it was typed.\n */\nconst absolutizeChangeDir = (args: string[], cwd: string): string[] => {\n const out = [...args]\n\n for (const [index, token] of out.entries()) {\n if (token === '-C' && out[index + 1] !== undefined && !isAbsolute(out[index + 1] as string)) {\n out[index + 1] = resolve(cwd, out[index + 1] as string)\n } else if (token.startsWith('-C') && token.length > 2 && !token.startsWith('--') && !isAbsolute(token.slice(2))) {\n out[index] = `-C${resolve(cwd, token.slice(2))}`\n }\n }\n\n return out\n}\n\n/**\n * The argv an agent re-runs to confirm what this run refused: the captured user args with `--yes`\n * appended and any relative `-C` made absolute, so the next Bash call may run from any cwd.\n *\n * Appending is safe: no leaf uses `passThroughOptions` or `--`, and the only variadic option\n * (`--project <names...>`) stops at `--yes`. An argv that already carries `--yes`/`-y` is returned\n * as-is \u2014 a second copy would be noise, and a confirm that fired despite it is not this function's\n * problem to hide.\n *\n * @example\n * // captured: ['node', 'infra-kit', '-C', 'app', 'release', 'remove', '1.2.3', '--json'], cwd /w\n * rerunArgv() // ['-C', '/w/app', 'release', 'remove', '1.2.3', '--json', '--yes']\n */\nexport const rerunArgv = (): string[] => {\n if (parsedArgv === null || launchCwd === null) return ['--yes']\n\n const args = absolutizeChangeDir(parsedArgv.slice(2), launchCwd)\n\n const alreadyConfirmed = args.some((token) => {\n return YES_FLAGS.has(token)\n })\n\n return alreadyConfirmed ? args : [...args, '--yes']\n}\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport type { AgentModeSource } from 'src/lib/agent-mode'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\n/**\n * What this call site does when there is no human: refuse, refuse NAMING the argument that would have\n * answered the prompt, or answer with a fixed value.\n *\n * - `'refuse'` \u2014 throw `{ status: 'refused' }`: the site has no single argument to name.\n * - `{ refuse: 'version' }` \u2014 throw `{ status: 'argument_required', argument: 'version' }`: the\n * agent is told exactly what to pass on the re-run. The name is the CLI flag / tool field without\n * its dashes; G8 (`headless-policy-guards`) checks it exists on every owning tool's schema.\n * - `{ value: T }` \u2014 answer with `value`, no throw.\n *\n * There is no `'unreachable'` any more: that was a claim about an MCP schema making a field\n * required, and no schema stands between a Bash-driven agent and this prompt.\n */\nexport type HeadlessPolicy<T> = 'refuse' | { refuse: string } | { value: T }\n\n/** {@link withEscape}'s options: the prompt context, plus this site's headless policy. */\nexport type EscapeOptions<T> = PromptContext & { whenHeadless?: HeadlessPolicy<T> }\n\nconst ESC_BYTE = 0x1b\n\n// Widening the existing options object rather than adding a third parameter: six call sites already\n// pass a `PromptContext` (`entry/cli.ts`, `env-load`, `env-token-set`, and the wizard's shared\n// context used by three prompts), all of them `{ output: process.stderr }` for documented reasons \u2014\n// `env-token-set.ts:64-68` notes that some env commands run inside `$(\u2026)`, where a prompt on stdout\n// would leave the user typing a credential into a captured stream. A third parameter would have\n// forced every one of them to grow a positional `undefined`.\n//\n// Optional, and the default is `'refuse'`. That default is safe for the same reason the guard exists\n// at all: under `isAgentMode()` nobody is at the keyboard (and under `'mcp'` `process.stdin` IS the\n// JSON-RPC transport), so no prompt at any site can return a usable answer, and refusing removes no\n// capability that exists. It is what CLI-only sites (the palette, the dev wizard, `env-token-set`)\n// keep, because they face a real human.\n//\n// It is NOT what an MCP-reachable site may keep. There, omitting `whenHeadless` is indistinguishable\n// from never having considered the question, so G7 (`every-inquirer-site-is-escapable`) requires the\n// answer to be written out \u2014 `'refuse'` included.\n//\n// What the default is NOT is *correct* everywhere \u2014 that distinction is the whole point of the\n// parameter. `worktrees-add` documents a `false` fallback for MCP in its own schema, so a refusal\n// there is right-outcome-by-accident at best and a regression at worst. The type cannot tell those\n// apart; G6 (description-to-policy) and G8 (argument-to-schema) are what check the answers,\n// because a wrong answer here compiles and can never fail a test on its own.\n//\n// WORDING IS SOURCE-AWARE. \"stdin carries JSON-RPC\" is true of exactly one caller; a skill driving\n// the CLI over Bash that reads it would go looking for a server that does not exist. Only the\n// `'mcp'` source keeps that text.\nconst headlessExcerpt = (source: AgentModeSource): string => {\n if (source === 'mcp') return 'an interactive prompt was reached under MCP, where stdin carries JSON-RPC'\n if (source === null) return 'an interactive prompt was reached under --json, which never prompts'\n\n return `an interactive prompt was reached in agent mode (${source === 'flag' ? '--agent' : 'INFRA_KIT_AGENT / CLAUDECODE'}), where there is no human to answer it`\n}\n\nconst headlessRemediation = (source: AgentModeSource, argument: string | undefined): string => {\n const passIt =\n argument === undefined ? 'pass the value explicitly instead of relying on the prompt' : `pass --${argument}`\n\n if (source === 'mcp') {\n return argument === undefined\n ? `${passIt} \u2014 MCP runs have no human to answer it`\n : `pass \"${argument}\" \u2014 MCP runs have no human to answer it`\n }\n\n return `${passIt} on the re-run`\n}\n\nconst resolveHeadless = <T>(policy: HeadlessPolicy<T>): T => {\n if (typeof policy === 'object' && 'value' in policy) return policy.value\n\n const argument = typeof policy === 'object' ? policy.refuse : undefined\n const { source } = agentMode\n\n throw new StructuredRefusalError(\n argument === undefined\n ? { status: 'refused', agentMode: source }\n : { status: 'argument_required', argument, agentMode: source },\n 2,\n {\n operation: 'interactive prompt',\n remediation: headlessRemediation(source, argument),\n stderrExcerpt: headlessExcerpt(source),\n },\n )\n}\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation. On Esc the prompt rejects with an\n * `AbortPromptError`, which `entry/cli.ts` already catches at the top level -> \"Operation\n * cancelled.\" -> exit 0.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a sufficient\n * guard \u2014 see lib/agent-mode for why `stdio: 'inherit'` defeats it.\n */\n// The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal goes into the\n// prompt context, `@inquirer/core` rejects with an `AbortPromptError` when it fires, and that name\n// is already in `CANCELLATION_ERROR_NAMES` (lib/errors/is-prompt-cancellation). All this adds is\n// the thing that calls `abort()`.\n//\n// DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b` byte.\n// Deliberately NOT readline `keypress`: that delivers a lone Esc only after its escape-sequence\n// timeout (~523ms measured), and the `escapeCodeTimeout` dial that would shorten it is\n// process-global and first-armer-wins \u2014 a second `emitKeypressEvents` call on `process.stdin` is\n// SILENTLY IGNORED, so the dial degrades to a no-op with no error and no failing test. The raw\n// listener costs ~24ms and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n// (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is involved. Node\n// `data` listeners broadcast, so this one does not steal bytes from readline: arrows and Enter keep\n// working while it is attached.\n//\n// FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk. Focus events\n// (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports (`\\x1b[M\u2026`) are all\n// multi-byte, and inquirer enables none of them.\n//\n// FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE chunk, i.e.\n// Esc immediately followed by another key) is silently dropped and the prompt stays open. The fix\n// would be Ink's 20ms deferred abort \u2014 hold the lone Esc, cancel it if a follow-up chunk lands.\n// That is a logged NON-GOAL; do not pre-build it.\nexport const withEscape = async <T>(\n run: (context: PromptContext) => Promise<T>,\n base?: EscapeOptions<T>,\n): Promise<T> => {\n const controller = new AbortController()\n // `whenHeadless` is ours, not inquirer's \u2014 split it off so it never reaches a prompt's context.\n const { whenHeadless = 'refuse', ...promptBase } = base ?? {}\n const context: PromptContext = { ...promptBase, signal: controller.signal }\n\n // Keyed on `isHeadless()`. `!isTTY` deliberately does NOT ride along: a piped-but-human\n // run (`infra-kit worktrees add > log.txt`) has no TTY and still deserves its prompt, and the two\n // conditions were only ever collapsed here because both merely skipped the Esc listener. Now that\n // this branch decides an ANSWER rather than just a listener, conflating them would refuse prompts\n // no agent is waiting on. `release-picker.ts` keeps its own `!isTTY` clause for its own reason.\n //\n // `--json` joins because a prompt is stdout traffic on a stream a machine is parsing, and because\n // `release-picker`/`source-picker` already treat `--json` as never-prompt \u2014 this makes the 20 sites\n // agree with those two.\n if (isHeadless()) return resolveHeadless(whenHeadless)\n\n if (!process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // STDIN OWNERSHIP \u2014 this is the seam that keeps stdin alive for inquirer, which refs\n // nothing itself. It must sit BELOW the early return above: a non-TTY run never reads\n // stdin, so acquiring there would ref a handle nobody reads and hang the process. See\n // lib/prompts/stdin-ref for why an unref'd stdin kills a prompt with exit 13.\n acquireStdin()\n\n try {\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n //\n // INSIDE the `try`, both of them: `run` is caller-supplied and `@inquirer/core` runs\n // synchronously up to readline construction, so a SYNCHRONOUS throw here would skip a\n // `finally` placed any lower \u2014 leaking the ref and hanging the CLI, which is the exact\n // failure this module exists to prevent.\n const pending = run(context)\n\n // Explicit, because `on('data')` alone is NOT enough to start the flow: `Readable` resumes on a\n // new `data` listener only when `flowing !== false`, and the palette's teardown now pauses stdin\n // (tui/boot.tsx) so a prompt opened after an Ink screen inherits `flowing === false`. Esc would be\n // silently dead. It happens to work anyway today \u2014 `run()` above builds inquirer's readline, whose\n // constructor resumes the stream \u2014 but that is an undocumented side effect of a TRANSITIVE\n // dependency, and the ordering it relies on is the very thing the comment below reserves the right\n // to change. One idempotent call is cheaper than that coupling.\n if (input.isPaused()) input.resume()\n\n input.on('data', onData)\n\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n // Same `finally` as the listener teardown, and for the same reason: every exit path\n // (answer, Esc abort, throw) must give the ref back, or node never exits.\n releaseStdin()\n }\n}\n", "import { OperationError } from './operation-error'\nimport type { OperationErrorContext } from './operation-error'\n\n/**\n * Why the command stopped, for a machine reader. `exitCode` 2 means nothing happened \u2014 re-run with\n * more; 1 means something happened and part of it failed.\n */\nexport type RefusalStatus = 'confirmation_required' | 'argument_required' | 'partial_failure' | 'refused'\n\nexport interface RefusalStructuredContent {\n status: RefusalStatus\n [k: string]: unknown\n}\n\n/**\n * A refusal that carries a payload for whichever agent surface is listening: `entry/cli.ts` emits\n * `structuredContent` under `--json` and exits with `exitCode`; the MCP tool handler renders it as an\n * `isError` result with the same `structuredContent`. The message is the ordinary `OperationError`\n * one (operation / stderr / remediation), so the human-readable line loses nothing.\n *\n * @example\n * throw new StructuredRefusalError(\n * { status: 'argument_required', argument: 'version', agentMode: 'flag' },\n * 2,\n * { operation: 'interactive prompt', remediation: 'pass --version' },\n * )\n */\n// Extends `OperationError`, not `Error`, ON PURPOSE. Seven of the eight confirm sites sit under a\n// handler-level `catch` that passes through only `isPromptCancellation`, `isCommandDeclined` and\n// `instanceof OperationError` and REWRAPS everything else into a generic `OperationError`\n// (`release-remove.ts` near the `gh auth status` remediation, `worktrees-add.ts`, `worktrees-sync.ts`,\n// `release-create.ts`). A plain `Error` subclass would lose the payload and the exit code at exactly\n// the sites this exists for.\nexport class StructuredRefusalError extends OperationError {\n readonly structuredContent: RefusalStructuredContent\n readonly exitCode: 1 | 2\n\n constructor(structuredContent: RefusalStructuredContent, exitCode: 1 | 2, context: OperationErrorContext) {\n super(undefined, context)\n this.name = 'StructuredRefusalError'\n this.structuredContent = structuredContent\n this.exitCode = exitCode\n }\n}\n", "/**\n * @fileoverview\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (CLI `--yes` or an MCP call, which always\n * injects `confirmedCommand: true`) the prompt is skipped and execution\n * proceeds. Otherwise, with no human to ask \u2014 agent mode, or `--json`, whose\n * stdout a machine is parsing \u2014 it throws a `confirmation_required` refusal\n * carrying the argv that confirms (preview-then-execute, no new flag). Otherwise\n * it prompts the user, marks the echo as interactive, and exits cleanly if the\n * user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path, which is\n * unreachable under MCP \u2014 so this stays safe for the long-lived MCP server.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nimport confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport { CommandDeclinedError } from 'src/lib/errors/command-declined-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { logger } from 'src/lib/logger'\nimport { rerunArgv } from 'src/lib/parsed-argv'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\nexport interface ConfirmOrExitOptions {\n /**\n * The structured form of what `message` renders, handed back verbatim in the\n * `confirmation_required` payload so an agent can show the human WHAT it is\n * about to confirm without parsing prose. JSON-safe and secret-free \u2014 it is\n * emitted to stdout. Sites with no structured plan pass nothing.\n */\n plan?: unknown\n /**\n * Throw {@link CommandDeclinedError} on a decline instead of `process.exit(0)`.\n *\n * **Defaults to false, and must stay that way.** Seven commands call this\n * helper; flipping the default would change the exit semantics of all of them\n * at once, inside a change whose tests cover none of them.\n *\n * Opt in when the command has already acquired something that needs releasing\n * by the time it prompts \u2014 `process.exit` skips every `finally`, so for those\n * commands the decline path is precisely where a resource leaks. The caller\n * owns catching it and exiting 0: a decline is a successful outcome.\n */\n throwOnDecline?: boolean\n}\n\n/**\n * Throw the `confirmation_required` refusal an agent (or a `--json` run) gets in place of a confirm\n * prompt: the message, the site's plan, the argv that confirms, and the source. Exit 2 \u2014 nothing ran.\n *\n * Exported for the one confirm site that is not `confirmOrExit` (`lib/release-deploy/confirm-deploy`),\n * so both speak the same shape.\n */\n// Thrown from HERE, not from `withEscape`'s headless branch, because it needs what only a confirm\n// site has: the message, the plan, and the knowledge that `--yes` is the answer. Callers key it on\n// `isHeadless()`, never on `confirmedCommand`, so their short-circuit for the MCP chokepoint and\n// every `--yes` human stays as it was.\nexport const refuseUnconfirmed = (message: string, plan?: unknown): never => {\n const { source } = agentMode\n const rerun = rerunArgv()\n\n throw new StructuredRefusalError({ status: 'confirmation_required', message, plan, rerun, agentMode: source }, 2, {\n operation: 'confirm before running',\n remediation:\n source === null\n ? 'pass `--yes` to confirm, or drop `--json` to be prompted'\n : `show the plan to the human, then re-run \\`infra-kit ${rerun.join(' ')}\\` to confirm`,\n stderrExcerpt: 'confirmation required and nobody to ask',\n })\n}\n\nexport const confirmOrExit = async (\n confirmedCommand: boolean | undefined,\n message: string,\n options: ConfirmOrExitOptions = {},\n): Promise<void> => {\n if (!confirmedCommand && isHeadless()) refuseUnconfirmed(message, options.plan)\n\n const answer = confirmedCommand\n ? true\n : await withEscape(\n (context) => {\n return confirm({ message }, context)\n },\n // Unreachable headless: the guard above already refused every agent / `--json` run that got\n // here without `confirmedCommand`. Written out anyway \u2014 G7 requires every reachable site to\n // answer, and `'refuse'` is the answer that costs nothing if the guard above ever moves.\n { whenHeadless: 'refuse' },\n )\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n if (options.throwOnDecline) {\n throw new CommandDeclinedError()\n }\n\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n", "/**\n * The operator answered \"no\" at a confirmation prompt.\n *\n * Deliberately NOT an {@link OperationError}: nothing failed. It is also not a prompt\n * cancellation \u2014 Esc means \"I never answered\" and has its own handling, while this means\n * \"I answered, and the answer was no.\" Callers that opt in via `throwOnDecline` are\n * responsible for catching it and exiting 0.\n */\n// It exists so a command that acquired a resource before prompting \u2014 a scratch worktree, a temp\n// directory, a lock \u2014 can unwind through its own `finally` blocks and release it, instead of\n// `confirmOrExit` calling `process.exit(0)` and skipping every one of them.\n//\n// That distinction is load-bearing rather than stylistic. In a plan -> confirm -> apply design,\n// declining is a first-class expected outcome, not an edge case, so the most ordinary non-happy\n// path is exactly the one that would leak.\nexport class CommandDeclinedError extends Error {\n constructor(message = 'Operation cancelled by the operator') {\n super(message)\n this.name = 'CommandDeclinedError'\n }\n}\n\n/** Narrow an unknown catch binding to a decline. */\nexport const isCommandDeclined = (error: unknown): error is CommandDeclinedError => {\n return error instanceof CommandDeclinedError\n}\n"],
|
|
5
|
-
"mappings": "2JAKA,OAAOA,MAAQ,mBACf,OAAOC,MAAU,YACjB,OAAS,KAAAC,MAAS,MCsBX,IAAMC,EAAN,cAA2B,KAAM,CAO7B,IAET,YAAYC,EAAiBC,EAAqB,KAAM,CACtD,MAAMD,CAAO,EACb,KAAK,KAAO,eACZ,KAAK,IAAMC,CACb,CACF,EAgBaC,GAAoBC,GACxBA,aAAiBJ,EC5D1B,OAAOK,MAAQ,mBACf,OAAOC,MAAQ,UAiBR,IAAMC,EAAa,MAAOC,GAAuC,CACtE,GAAI,CACF,aAAMH,EAAG,OAAOG,CAAQ,EAEjB,EACT,MAAQ,CACN,MAAO,EACT,CACF,EAWaC,EAAWD,GAA6B,CACnD,IAAME,EAAOJ,EAAG,QAAQ,EAExB,OAAOE,EAAS,WAAWE,CAAI,EAAI,IAAIF,EAAS,MAAME,E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,KAAK,CAAC,CAChB,CACF",
|
|
6
|
-
"names": ["fs", "path", "z", "EnvAuthError", "message", "env", "isEnvAuthFailure", "error", "fs", "os", "fileExists", "filePath", "tildify", "home", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "setToken", "env", "token", "existing", "removeToken", "envs", "createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "isAbsolute", "resolve", "process", "parsedArgv", "launchCwd", "setParsedArgv", "argv", "YES_FLAGS", "absolutizeChangeDir", "args", "cwd", "out", "index", "token", "rerunArgv", "process", "StructuredRefusalError", "OperationError", "structuredContent", "exitCode", "context", "ESC_BYTE", "headlessExcerpt", "source", "headlessRemediation", "argument", "passIt", "resolveHeadless", "policy", "agentMode", "StructuredRefusalError", "withEscape", "run", "base", "controller", "whenHeadless", "promptBase", "context", "isHeadless", "process", "input", "onData", "chunk", "acquireStdin", "pending", "releaseStdin", "confirm", "process", "CommandDeclinedError", "message", "isCommandDeclined", "error", "refuseUnconfirmed", "message", "plan", "source", "agentMode", "rerun", "rerunArgv", "StructuredRefusalError", "confirmOrExit", "confirmedCommand", "options", "isHeadless", "answer", "withEscape", "context", "confirm", "commandEcho", "CommandDeclinedError", "logger", "process"]
|
|
7
|
-
}
|