tenjin-cli 0.1.0-alpha.29 → 0.1.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +7 -5
  2. package/dist/{chunk-25GGN553.js → chunk-3O2BQIF6.js} +86 -22
  3. package/dist/chunk-3O2BQIF6.js.map +1 -0
  4. package/dist/{chunk-R4AO7GC2.js → chunk-5LJCEMFD.js} +14 -12
  5. package/dist/{chunk-R4AO7GC2.js.map → chunk-5LJCEMFD.js.map} +1 -1
  6. package/dist/{chunk-QTGUDCIR.js → chunk-AEG2PXBP.js} +3 -3
  7. package/dist/{chunk-AMEUXNJT.js → chunk-AWFUPKTM.js} +2 -2
  8. package/dist/{chunk-XJQ6CH7X.js → chunk-EBVIKMCH.js} +2 -2
  9. package/dist/{chunk-XDYKZRLN.js → chunk-HE2MS4QO.js} +6 -6
  10. package/dist/{chunk-RJEPZMYY.js → chunk-IOODYAXL.js} +3 -3
  11. package/dist/{chunk-SBL4THYT.js → chunk-JMM6YE7J.js} +190 -90
  12. package/dist/chunk-JMM6YE7J.js.map +1 -0
  13. package/dist/{chunk-VKQXVCZR.js → chunk-KHE6L6TD.js} +3 -3
  14. package/dist/chunk-KOGZDMHO.js +21 -0
  15. package/dist/chunk-KOGZDMHO.js.map +1 -0
  16. package/dist/{chunk-TROZ6HL4.js → chunk-KYFZTGMC.js} +2 -2
  17. package/dist/{chunk-LX5OT4TQ.js → chunk-NZIP4PA2.js} +2 -2
  18. package/dist/chunk-O2FRQ2L2.js +168 -0
  19. package/dist/chunk-O2FRQ2L2.js.map +1 -0
  20. package/dist/{chunk-3FY5HG7R.js → chunk-OK2TDZQU.js} +4 -4
  21. package/dist/{chunk-ZQNGTLOC.js → chunk-OSYTBCUC.js} +7 -5
  22. package/dist/{chunk-ZQNGTLOC.js.map → chunk-OSYTBCUC.js.map} +1 -1
  23. package/dist/{chunk-MRUPDSUM.js → chunk-PAYV4XUA.js} +3 -5
  24. package/dist/chunk-PAYV4XUA.js.map +1 -0
  25. package/dist/{chunk-USOLCBKC.js → chunk-QUVVWYJW.js} +7 -5
  26. package/dist/{chunk-USOLCBKC.js.map → chunk-QUVVWYJW.js.map} +1 -1
  27. package/dist/{chunk-MOG7PB3A.js → chunk-RAULEAZ6.js} +3 -3
  28. package/dist/{chunk-MG3G644T.js → chunk-SPAVAYSW.js} +3 -3
  29. package/dist/{chunk-4FYMDRD3.js → chunk-TTBKWWTV.js} +22 -20
  30. package/dist/chunk-TTBKWWTV.js.map +1 -0
  31. package/dist/{chunk-OOSRB3OF.js → chunk-U6YQ6FRI.js} +2 -2
  32. package/dist/{chunk-P4LVLFO4.js → chunk-VFMQTSXG.js} +2 -2
  33. package/dist/{chunk-LRCJ2IZ5.js → chunk-VUFAK2LW.js} +2 -2
  34. package/dist/{chunk-LRCJ2IZ5.js.map → chunk-VUFAK2LW.js.map} +1 -1
  35. package/dist/{chunk-WM7TJEBP.js → chunk-VZGAONSJ.js} +7 -5
  36. package/dist/{chunk-WM7TJEBP.js.map → chunk-VZGAONSJ.js.map} +1 -1
  37. package/dist/{chunk-VVAHFCX2.js → chunk-WO5BJNIB.js} +45 -194
  38. package/dist/chunk-WO5BJNIB.js.map +1 -0
  39. package/dist/chunk-WVUSXNIE.js +39 -0
  40. package/dist/chunk-WVUSXNIE.js.map +1 -0
  41. package/dist/chunk-XKESD27X.js +10 -0
  42. package/dist/chunk-XKESD27X.js.map +1 -0
  43. package/dist/{chunk-SFEQGENI.js → chunk-YFQOA5AU.js} +7 -2
  44. package/dist/{chunk-SFEQGENI.js.map → chunk-YFQOA5AU.js.map} +1 -1
  45. package/dist/{cli-JPTDHGRX.js → cli-O5SN7ZJ4.js} +38 -30
  46. package/dist/{cli-JPTDHGRX.js.map → cli-O5SN7ZJ4.js.map} +1 -1
  47. package/dist/{config-YYKDH2TH.js → config-OJQI27LT.js} +13 -12
  48. package/dist/{doctor-SSTXGCHX.js → doctor-IQQJHGGM.js} +36 -62
  49. package/dist/doctor-IQQJHGGM.js.map +1 -0
  50. package/dist/{fund-QWVWRVDK.js → fund-WEV6DMTD.js} +17 -12
  51. package/dist/{fund-QWVWRVDK.js.map → fund-WEV6DMTD.js.map} +1 -1
  52. package/dist/hook-command-D2P3ILRV.js +32 -0
  53. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  54. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  55. package/dist/index.js +4 -4
  56. package/dist/{install-2GXXD4DK.js → install-TUCRF32I.js} +23 -14
  57. package/dist/{install-identity-FK3YF227.js → install-identity-WHPNMNMQ.js} +7 -6
  58. package/dist/{install-wallet-TC22U52X.js → install-wallet-MA27FTQ5.js} +11 -10
  59. package/dist/{install-wallet-TC22U52X.js.map → install-wallet-MA27FTQ5.js.map} +1 -1
  60. package/dist/{mcp-42H2F4NY.js → mcp-QML7ZMPH.js} +33 -40
  61. package/dist/mcp-QML7ZMPH.js.map +1 -0
  62. package/dist/{package-6DJA3Y2O.js → package-LGKYOEPV.js} +2 -2
  63. package/dist/{pay-LSDJBIAZ.js → pay-2C2UBBXJ.js} +14 -13
  64. package/dist/{payments-SPECLBRQ.js → payments-C44QUFXU.js} +10 -9
  65. package/dist/{payments-SPECLBRQ.js.map → payments-C44QUFXU.js.map} +1 -1
  66. package/dist/{send-MHAOLPK3.js → send-KVJX4XIR.js} +9 -8
  67. package/dist/{send-MHAOLPK3.js.map → send-KVJX4XIR.js.map} +1 -1
  68. package/dist/{status-O2RWLPS5.js → status-S7C3WMSH.js} +10 -9
  69. package/dist/{status-O2RWLPS5.js.map → status-S7C3WMSH.js.map} +1 -1
  70. package/dist/{status-line-45TVCRM3.js → status-line-YR2T5HC4.js} +6 -5
  71. package/dist/{status-line-45TVCRM3.js.map → status-line-YR2T5HC4.js.map} +1 -1
  72. package/dist/{uninstall-VOK2Z5M4.js → uninstall-HY6LKIIT.js} +17 -14
  73. package/dist/{uninstall-VOK2Z5M4.js.map → uninstall-HY6LKIIT.js.map} +1 -1
  74. package/dist/{update-FGP3HNLD.js → update-OJV22LR3.js} +17 -14
  75. package/dist/usdc-JK4RRFFQ.js +39 -0
  76. package/dist/{wallet-DA7OFNEW.js → wallet-PD2IMZDU.js} +11 -10
  77. package/dist/wallet-PD2IMZDU.js.map +1 -0
  78. package/docs/agent-permissions.md +16 -4
  79. package/package.json +1 -1
  80. package/dist/chunk-25GGN553.js.map +0 -1
  81. package/dist/chunk-4FYMDRD3.js.map +0 -1
  82. package/dist/chunk-EWLU46J6.js +0 -100
  83. package/dist/chunk-EWLU46J6.js.map +0 -1
  84. package/dist/chunk-MRUPDSUM.js.map +0 -1
  85. package/dist/chunk-SBL4THYT.js.map +0 -1
  86. package/dist/chunk-VVAHFCX2.js.map +0 -1
  87. package/dist/doctor-SSTXGCHX.js.map +0 -1
  88. package/dist/hook-command-VWJXRT7H.js +0 -31
  89. package/dist/mcp-42H2F4NY.js.map +0 -1
  90. /package/dist/{chunk-QTGUDCIR.js.map → chunk-AEG2PXBP.js.map} +0 -0
  91. /package/dist/{chunk-AMEUXNJT.js.map → chunk-AWFUPKTM.js.map} +0 -0
  92. /package/dist/{chunk-XJQ6CH7X.js.map → chunk-EBVIKMCH.js.map} +0 -0
  93. /package/dist/{chunk-XDYKZRLN.js.map → chunk-HE2MS4QO.js.map} +0 -0
  94. /package/dist/{chunk-RJEPZMYY.js.map → chunk-IOODYAXL.js.map} +0 -0
  95. /package/dist/{chunk-VKQXVCZR.js.map → chunk-KHE6L6TD.js.map} +0 -0
  96. /package/dist/{chunk-TROZ6HL4.js.map → chunk-KYFZTGMC.js.map} +0 -0
  97. /package/dist/{chunk-LX5OT4TQ.js.map → chunk-NZIP4PA2.js.map} +0 -0
  98. /package/dist/{chunk-3FY5HG7R.js.map → chunk-OK2TDZQU.js.map} +0 -0
  99. /package/dist/{chunk-MOG7PB3A.js.map → chunk-RAULEAZ6.js.map} +0 -0
  100. /package/dist/{chunk-MG3G644T.js.map → chunk-SPAVAYSW.js.map} +0 -0
  101. /package/dist/{chunk-OOSRB3OF.js.map → chunk-U6YQ6FRI.js.map} +0 -0
  102. /package/dist/{chunk-P4LVLFO4.js.map → chunk-VFMQTSXG.js.map} +0 -0
  103. /package/dist/{config-YYKDH2TH.js.map → config-OJQI27LT.js.map} +0 -0
  104. /package/dist/{hook-command-VWJXRT7H.js.map → hook-command-D2P3ILRV.js.map} +0 -0
  105. /package/dist/{install-2GXXD4DK.js.map → install-TUCRF32I.js.map} +0 -0
  106. /package/dist/{install-identity-FK3YF227.js.map → install-identity-WHPNMNMQ.js.map} +0 -0
  107. /package/dist/{package-6DJA3Y2O.js.map → package-LGKYOEPV.js.map} +0 -0
  108. /package/dist/{pay-LSDJBIAZ.js.map → pay-2C2UBBXJ.js.map} +0 -0
  109. /package/dist/{update-FGP3HNLD.js.map → update-OJV22LR3.js.map} +0 -0
  110. /package/dist/{wallet-DA7OFNEW.js.map → usdc-JK4RRFFQ.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/update.ts","../src/lib/install-location.ts","../src/router/install.ts","../src/lib/skill-placement.ts","../src/router/claude-cli.ts","../src/router/legacy-install.ts","../src/router/status-line-wiring.ts","../src/router/plugin-registration.ts","../src/router/plugin-files.ts","../src/router/plugin-folder.ts","../src/router/reachability.ts","../src/router/mcp-processes.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { existsSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport pkg from '../../package.json';\nimport { CliError } from '../lib/errors';\nimport { MANAGERS, classifyManager, refuse, resolveManagerScript } from '../lib/install-location';\nimport type { Delegable } from '../lib/install-location';\nimport { emitWriteNotice, sanitizeForTerminal } from '../lib/output';\nimport {\n NUDGE_OPT_OUT,\n channelTag,\n fetchDistTags,\n isNewer,\n resolveTarget,\n} from '../lib/update-check';\nimport { loadRawConfig } from '../lib/config';\nimport { defaultDataDir } from '../lib/paths';\nimport type { CommandContext, CommandResult } from '../context';\nimport { persistRouterProject } from './config';\nimport { projectInstallAt } from '../router/install';\nimport { readMcpServers, type InstalledAt, type ListMcpProcesses } from '../router/mcp-processes';\n\n/**\n * `tenjin update`: replace this install with the newest version npm offers it,\n * by spawning the package manager that OWNS the install rather than\n * reimplementing one. Four invariants:\n *\n * - The argv pins the EXACT version the registry just named, never the tag, so\n * the check and the install cannot disagree about what ships, and the version\n * string is certified parseable by the same `isNewer` gate the nudge trusts\n * before it goes anywhere near an argv.\n * - The owner performs the install. npm, pnpm and bun are each driven with their\n * own global-add command, because the PATH race that makes a second install\n * dangerous comes from CROSS-manager writes, not from asking the owner to do\n * what it already owns. What cannot be driven is refused instead of guessed\n * at: a source checkout updates by git, an npx run has nothing installed to\n * replace, a project-local copy updates where it is declared, and yarn's\n * global install exists only in yarn 1. See lib/install-location.\n * - The child is a binary or `node <script>`, never a shell. That is what makes\n * the pinned argv worth pinning, and it is the only form that works on win32.\n * - The manager's chatter goes to stderr (live, human mode only, sanitized) and\n * its failure into the error envelope; stdout stays the one envelope every\n * command emits.\n */\n\n/** How long the npm child gets before it is killed. npm's own retry budget runs\n * into minutes, and an agent's turn should not hang on a wedged registry. */\nconst INSTALL_TIMEOUT_MS = 300_000;\n\nexport interface UpdateOptions {\n /** Report whether a newer version exists; never install. */\n check: boolean;\n}\n\n/**\n * How the child ended. Never rejects: all three outcomes are envelope-shaped\n * facts the caller reports, not exceptions, and each is separately testable.\n */\nexport type SpawnResult =\n { kind: 'exit'; code: number } | { kind: 'start-failed'; cause: unknown } | { kind: 'timeout' };\n\nexport type UpdateSpawn = (\n cmd: string,\n args: string[],\n opts: {\n cwd: string;\n timeoutMs: number;\n /** Variables layered ONTO this process's environment, for the per-profile\n * `TENJIN_DATA_DIR` the refresh pass sets. Absent means inherit unchanged. */\n env?: Record<string, string>;\n },\n onOutput: (chunk: string) => void,\n) => Promise<SpawnResult>;\n\n/** What to spawn for one manager: a command and any argv that must precede its own. */\ninterface ResolvedManager {\n cmd: string;\n prefix: readonly string[];\n}\n\n/**\n * Turn a manager into a spawnable command. A resolved script runs under THIS\n * node, keeping `shell` unset on every platform; otherwise the bare binary name\n * is used, which is correct for a native binary and fails closed on win32 for a\n * `.cmd` shim.\n */\nfunction resolveManager(manager: Delegable, deps: UpdateDeps): ResolvedManager {\n const script =\n deps.managerScript !== undefined\n ? deps.managerScript\n : resolveManagerScript(manager, process.execPath);\n return script === null\n ? { cmd: MANAGERS[manager].bin, prefix: [] }\n : { cmd: process.execPath, prefix: [script] };\n}\n\nexport interface UpdateDeps {\n fetchImpl?: typeof fetch;\n spawnImpl?: UpdateSpawn;\n /** Where this build's code lives on disk; tests point it at fixture trees. */\n moduleDir?: string;\n /** The running version; defaults to this build's. Injectable for tests. */\n currentVersion?: string;\n /** The owning manager's entry script, or null when it has none to find.\n * Injectable so the argv shape is asserted without depending on the runner. */\n managerScript?: string | null;\n /** Home whose manual-fix command the report names. Defaults to os.homedir(). */\n homeDir?: string;\n /**\n * The CLI entry the refresh child runs. Defaults to `process.argv[1]`, which\n * after the swap resolves to the NEWLY installed script — that is the whole\n * point of spawning rather than calling.\n */\n refreshCommand?: string;\n /** This user's running `tenjin mcp` processes; tests inject them. */\n listMcpProcesses?: ListMcpProcesses;\n /** When the new build was installed; tests inject it. */\n installedAt?: InstalledAt;\n}\n\ninterface UpdateData {\n current: string;\n latest: string;\n updateAvailable: boolean;\n updated: boolean;\n}\n\nexport async function runUpdate(\n opts: UpdateOptions,\n ctx: CommandContext,\n deps: UpdateDeps = {},\n): Promise<CommandResult> {\n const current = deps.currentVersion ?? pkg.version;\n const channel = channelTag(current);\n const moduleDir = deps.moduleDir ?? fileURLToPath(new URL('.', import.meta.url));\n\n // Refused, not defaulted to a channel: a build whose version this package\n // cannot parse has no release line to compare against, and guessing one is how\n // a foreign build gets told it is up to date forever.\n if (channel === null) {\n throw new CliError('REFUSED', `tenjin-cli reports an unrecognizable version (${current})`, {\n fix: 'Reinstall a published build: npm i -g tenjin-cli',\n });\n }\n\n // First stage: everything whose fix string does not need a resolved version,\n // so it answers without the network. An offline contributor in a checkout is\n // told they are in a checkout, not told to go debug their registry access.\n refuse(moduleDir, { check: opts.check, spec: null });\n\n const tags = await fetchDistTags({\n fetchImpl: deps.fetchImpl,\n timeoutMs: ctx.flags.timeout,\n });\n if (tags === null) {\n throw new CliError('NETWORK_ERROR', 'Could not read tenjin-cli dist-tags from npm', {\n fix: 'Check access to registry.npmjs.org and retry',\n });\n }\n const latest = resolveTarget(current, tags);\n // Not a NETWORK_ERROR: nothing about the connection is wrong, and telling the\n // user to check their access sends them after a fault that is not there.\n if (latest === null) {\n const raw = tags[channel];\n throw raw === undefined\n ? new CliError('RESOURCE_NOT_FOUND', 'npm has no published tenjin-cli on the latest tag', {\n fix: 'Pick a version yourself: npm view tenjin-cli versions',\n })\n : new CliError(\n 'RESOURCE_NOT_FOUND',\n // Registry-controlled: bounded here, escaped by the error emitter.\n `npm's latest tenjin-cli (${raw.slice(0, 40)}) is not a version this build can read`,\n {\n fix: 'Install it by name: npm i -g tenjin-cli@<version> (npm view tenjin-cli versions)',\n },\n );\n }\n\n const updateAvailable = isNewer(latest, current);\n const data = (updated: boolean): UpdateData => ({\n current,\n latest,\n updateAvailable,\n updated,\n });\n\n if (!updateAvailable) {\n return {\n data: data(false),\n humanLines: [`tenjin-cli ${current} is up to date`],\n };\n }\n if (opts.check) {\n return {\n data: data(false),\n humanLines: [\n `tenjin-cli ${latest} is available (you have ${current}).`,\n 'Run tenjin update to install it.',\n ],\n };\n }\n\n // `latest` is argv-safe here: isNewer returned true, so it matched VERSION_RE.\n const spec = `tenjin-cli@${latest}`;\n\n // Second stage: the entries whose fix strings name the version just resolved.\n // Reached only on the install path, since --check has already returned.\n refuse(moduleDir, { check: false, spec });\n\n // Live chatter is a human courtesy only; the tail rides in the error envelope\n // so a piped failure is still diagnosable. Sanitized per line, because npm\n // relays publisher-controlled text (deprecation notices) and a line break is\n // the one control character this stream must keep.\n const human = ctx.io.isTTY && !ctx.flags.json;\n let tail = '';\n const onOutput = (chunk: string): void => {\n tail = (tail + chunk).slice(-2000);\n if (human) ctx.io.stderr.write(chunk.split('\\n').map(sanitizeForTerminal).join('\\n'));\n };\n\n // Whoever owns the install performs it. The PATH-race objection that used to\n // make this a refusal only applies to CROSS-manager writes; invoking the owner\n // is exactly what the refusal used to tell the user to type by hand.\n //\n // The cast is sound only because `refuse` ran directly above and yarn is one\n // of its entries, so the one non-delegable manager has already thrown. Move\n // this line above that call and it becomes a lie.\n const manager = classifyManager(moduleDir) as Delegable;\n const plan = MANAGERS[manager];\n // --ignore-scripts where the manager has it (tenjin-cli has no runtime\n // dependencies and no registry install runs its own `prepare`), and cwd is the\n // home directory so the child never reads a project's config by accident.\n const args = plan.args(spec);\n const resolved = resolveManager(manager, deps);\n const manual = `Run it yourself: ${plan.manual(spec)}`;\n\n const outcome = await (deps.spawnImpl ?? spawnCapture)(\n resolved.cmd,\n [...resolved.prefix, ...args],\n { cwd: homedir(), timeoutMs: INSTALL_TIMEOUT_MS },\n onOutput,\n );\n if (outcome.kind === 'start-failed') {\n throw new CliError('UPDATE_FAILED', `Could not start ${manager}`, {\n fix: manual,\n cause: outcome.cause,\n });\n }\n if (outcome.kind === 'timeout') {\n throw new CliError(\n 'UPDATE_FAILED',\n `${manager} did not finish in ${INSTALL_TIMEOUT_MS / 1000}s`,\n { fix: manual, details: { output: tail } },\n );\n }\n if (outcome.code !== 0) {\n throw new CliError('UPDATE_FAILED', `${manager} ${args.join(' ')} exited ${outcome.code}`, {\n // EACCES on a root-owned global prefix is the common cause; the operator\n // fixing that themselves beats this CLI ever escalating.\n fix: manual,\n details: { output: tail },\n });\n }\n\n emitWriteNotice(\n ctx.io,\n `tenjin update: replaced the global tenjin-cli with ${latest} via ${manager}`,\n );\n\n const refresh = await refreshProfiles(ctx, deps);\n // The refresh child's output is captured, so the warning it would print about\n // a `tenjin mcp` still running the old build is checked again here, with the\n // fix the child's migration state calls for.\n const servers = await readMcpServers(deps, {\n settingsInstallPending: refresh.settingsInstallPending,\n });\n return {\n data: { ...data(true), refresh, mcpServer: servers.check },\n humanLines: [\n `Updated tenjin-cli ${current} -> ${latest}.`,\n ...refreshLines(refresh),\n ...projectLines(refresh),\n ...refresh.notices,\n ...(servers.stale > 0\n ? [`! ${servers.check.detail}. ${servers.check.fix ?? ''}`.trim()]\n : []),\n ],\n };\n}\n\n/** How long one `install --refresh` child gets. Local file writes only, no\n * registry: a minute is already generous, and `update` must not hang a turn. */\nconst REFRESH_TIMEOUT_MS = 60_000;\n\n/** One profile this update did not bring up to date, and why. */\nexport interface RefreshFailure {\n /** The profile's data dir. */\n dataDir: string;\n /**\n * Why it is not up to date, in the words of whoever decided that: the child's\n * own `error.message` when it printed a failure envelope, this pass's own\n * account when the child was never run or never got that far. Always present,\n * because a failure whose four causes render identically is the reason this\n * field exists.\n */\n reason: string;\n /** The command that converges THIS profile; see {@link manualFix}. */\n fix: string;\n}\n\n/** What the post-swap re-materialize did, per profile. */\nexport interface RefreshOutcome {\n /** Data dirs a refresh was run for, whether or not it succeeded. */\n profiles: string[];\n /**\n * Profiles this update did not bring up to date, each with its reason and the\n * manual command to finish it. Both halves land here: a refresh that ran and\n * did not report success, and one that was never run at all (no entry to\n * re-exec, a data dir that is not a directory).\n */\n failed: RefreshFailure[];\n /**\n * What a refresh that succeeded said the person must know (the child's\n * `data.notices`): a plugin left for a newer Claude Code, a status line the\n * migration took out. Printed as given, one line each.\n */\n notices: string[];\n /** A refreshed profile still carries an earlier release's settings install. */\n settingsInstallPending: boolean;\n /** Project installs (`install --project`) refreshed from their own directory. */\n projects: string[];\n /** Project installs whose refresh did not succeed, each with its reason and fix. */\n projectsFailed: { project: string; reason: string; fix: string }[];\n}\n\n/**\n * Re-materialize what the swap left stale, on the NEW binary.\n *\n * `update` replaces the package and nothing else, but `install` bakes this\n * build's identity into files: the generated hook scripts carry a version, and\n * the wired skills carry this release's instructions. Until something rewrites\n * them the highest-volume request path keeps reporting the previous version and\n * agents keep reading the previous release's guidance (tenjin-agent#171).\n *\n * SPAWNED, NOT CALLED. This process is the OLD build; it cannot render the new\n * version's copies, and re-exec is the only way to reach code that can. The\n * child is the freshly installed entry, and what it runs is\n * `install --refresh` — a mode that converges existing surfaces and creates\n * none, which is the only kind of write an unattended upgrade may make.\n *\n * ONCE PER HOOK-OWNER PROFILE. `install` bakes its data dir into the scripts it\n * generates, so a machine whose hooks were installed under `TENJIN_DATA_DIR`\n * has hooks belonging to THAT profile while a bare `tenjin update` resolves the\n * default one. Refreshing only the invoking profile there would leave the\n * registered scripts — the ones the harness actually fires — stale forever,\n * which is exactly the shelf runbook's manual re-install step. So the detector\n * reads the harness settings and each profile it names is refreshed with\n * `TENJIN_DATA_DIR` set to it. A machine with no registered hooks has no other\n * profile to find, and gets one refresh for the invoking one.\n *\n * NEVER FAILS THE UPDATE. The swap already happened and is the thing the\n * operator asked for. A refusal, a run with nothing to converge, a crash, a\n * timeout, or an older-binary \"unknown option --refresh\" all land here as a warn\n * naming the manual command.\n *\n * EACH FAILURE CARRIES ITS OWN REASON AND ITS OWN FIX. The four ways a profile\n * misses are not interchangeable — a dir that is not a directory, a settings\n * file that changed underneath, a machine that never ran `install`, and a\n * timeout each want a different next move — so the child's output is collected\n * and its `error.message` reported per profile rather than collapsed into one\n * parent line.\n */\nasync function refreshProfiles(ctx: CommandContext, deps: UpdateDeps): Promise<RefreshOutcome> {\n const home = deps.homeDir ?? homedir();\n // THE INVOKING PROFILE, AND ONLY IT. The pre-daemon installer baked its data\n // dir into eight generated scripts, so an upgrade had to find every profile\n // registered in settings.json and refresh each one's bodies. Nothing is baked\n // any more: the two bundles are the same bytes for every profile, and a\n // profile's daemon picks up the new build the next time its own `tenjin`\n // command runs. So there is nothing left to hunt for, and a detector reading\n // paths out of somebody's settings file is not worth keeping to say so.\n const candidates = [ctx.dataDir];\n const fixFor = (dataDir: string): string => manualFix(dataDir, home, ctx.dataDir);\n\n // The child would CREATE a data dir that is not there: `install --refresh`\n // converges surfaces rather than materializing them, but the process around it\n // mkdirs the tree for the update cache on its way out. So a path that is not\n // already a directory is reported unrefreshed instead of visited.\n const profiles: string[] = [];\n const unrun: RefreshFailure[] = [];\n for (const dataDir of candidates) {\n if (isExistingDir(dataDir)) profiles.push(dataDir);\n else unrun.push({ dataDir, reason: 'It is not a directory.', fix: fixFor(dataDir) });\n }\n\n const entry = versionFreeEntry(deps.refreshCommand ?? process.argv[1]);\n // Nothing safe to re-exec: no argv (an embedder, a stripped argv), or a path\n // that names the version being replaced (see versionFreeEntry). Report the\n // profiles as unrefreshed rather than guessing, since guessing is how a hook\n // script gets rewritten by the wrong binary — and a refresh that ran the OLD\n // build would report success while writing the bytes the update just left.\n if (entry === null) {\n const reason = 'This build has no entry the update could safely re-execute.';\n return {\n profiles: [],\n failed: candidates.map((d) => ({ dataDir: d, reason, fix: fixFor(d) })),\n notices: [],\n settingsInstallPending: false,\n projects: [],\n projectsFailed: [],\n };\n }\n\n const failed = [...unrun];\n const notices: string[] = [];\n let settingsInstallPending = false;\n const heard = (reported: Record<string, unknown> | null): void => {\n for (const notice of noticesOf(reported)) if (!notices.includes(notice)) notices.push(notice);\n const migration = reported?.migration as { state?: unknown } | undefined;\n if (migration?.state === 'pending' || migration?.state === 'blocked') {\n settingsInstallPending = true;\n }\n };\n for (const dataDir of profiles) {\n const { outcome, tail } = await refreshChild(entry, homedir(), dataDir, deps);\n // The child's exit code IS the verdict: `install --refresh` exits non-zero\n // when it refused or found nothing to converge, so a machine that never ran\n // `install` warns here instead of being told its hooks were refreshed. The\n // envelope on the pipe is what turns that verdict into a reason.\n if (outcome.kind !== 'exit' || outcome.code !== 0) {\n failed.push({ dataDir, reason: refreshReason(outcome, tail), fix: fixFor(dataDir) });\n continue;\n }\n heard(envelopeData(tail));\n }\n\n // PROJECT INSTALLS, EACH FROM ITS OWN DIRECTORY. The child above runs from\n // home, where a `--project` install (Claude Code's local scope) is not\n // visible, so each one `install --project` recorded is refreshed where it\n // lives, as `--project`, since the child cannot tell one at home from the\n // user install. A directory that is gone, or that no longer holds one, is\n // forgotten.\n const projects: string[] = [];\n const projectsFailed: RefreshOutcome['projectsFailed'] = [];\n const recorded = profiles.includes(ctx.dataDir)\n ? ((await loadRawConfig(ctx.dataDir).catch(() => null))?.install?.routerProjects ?? [])\n : [];\n for (const project of recorded) {\n const forget = () => persistRouterProject(ctx.dataDir, project, false).catch(() => undefined);\n if (!isExistingDir(project) || !(await projectInstallAt(project, home, process.env))) {\n await forget();\n continue;\n }\n const { outcome, tail } = await refreshChild(entry, project, ctx.dataDir, deps, ['--project']);\n if (outcome.kind !== 'exit' || outcome.code !== 0) {\n projectsFailed.push({\n project,\n reason: refreshReason(outcome, tail),\n fix: `Run \\`tenjin install --project\\` in ${project}.`,\n });\n continue;\n }\n projects.push(project);\n heard(envelopeData(tail));\n }\n return { profiles, failed, notices, settingsInstallPending, projects, projectsFailed };\n}\n\n/**\n * One `install --refresh` child of the new build, from `cwd`, for `dataDir`:\n * how it ended and the end of what it printed.\n *\n * A BOUNDED COLLECTOR, not the manager's live echo. npm's chatter is minutes\n * of progress a human wants to see; this child emits one envelope on a pipe,\n * and painting that JSON into the human's stderr is noise. It is still kept,\n * because the envelope is where the child says WHICH refusal this was.\n */\nasync function refreshChild(\n entry: string,\n cwd: string,\n dataDir: string,\n deps: UpdateDeps,\n flags: string[] = [],\n): Promise<{ outcome: SpawnResult; tail: string }> {\n let tail = '';\n const outcome = await (deps.spawnImpl ?? spawnCapture)(\n process.execPath,\n [entry, 'install', '--refresh', ...flags],\n {\n cwd,\n timeoutMs: REFRESH_TIMEOUT_MS,\n // TENJIN_DATA_DIR aims the child at this profile; the nudge opt-out is\n // what keeps it from touching any other file in there (lib/update-check).\n env: { TENJIN_DATA_DIR: dataDir, [NUDGE_OPT_OUT]: '1' },\n },\n (chunk) => {\n tail = (tail + chunk).slice(-REFRESH_TAIL_LIMIT);\n },\n );\n return { outcome, tail };\n}\n\n/** The `data` of the one success envelope the child printed, or null. */\nfunction envelopeData(output: string): Record<string, unknown> | null {\n const lines = output.split('\\n');\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n if (lines[i]?.trim() !== '{' && !lines[i]?.trim().startsWith('{\"')) continue;\n try {\n const parsed = JSON.parse(lines.slice(i).join('\\n')) as { ok?: unknown; data?: unknown };\n if (parsed?.ok === true && parsed.data !== null && typeof parsed.data === 'object') {\n return parsed.data as Record<string, unknown>;\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n\n/**\n * The child's notices, each bounded and sanitized: the child is the build\n * this update just installed, but its text still reaches a terminal.\n */\nfunction noticesOf(data: Record<string, unknown> | null): string[] {\n const raw = data?.notices;\n if (!Array.isArray(raw)) return [];\n return raw\n .filter((n): n is string => typeof n === 'string')\n .map((n) => sanitizeForTerminal(n).trim().slice(0, REASON_LIMIT))\n .filter((n) => n.length > 0)\n .slice(0, 5);\n}\n\n/** How much of one refresh child's output is kept. It prints a single envelope,\n * not a build log, so this is headroom rather than a budget. */\nconst REFRESH_TAIL_LIMIT = 64_000;\n\n/** How much of a child's own message reaches the parent's report. Long enough\n * for every message `install --refresh` can produce, short enough that a child\n * which somehow printed prose cannot own the operator's terminal. */\nconst REASON_LIMIT = 300;\n\n/**\n * Why this profile is not up to date, preferring the child's own account.\n *\n * The exit code separates success from failure and nothing else, so the four\n * refusals `install --refresh` can reach would otherwise reach the operator as\n * one line that names none of them. The envelope on the pipe carries the\n * distinction; the outcome kind covers the deaths that never printed one.\n */\nfunction refreshReason(outcome: SpawnResult, output: string): string {\n const reported = envelopeMessage(output);\n if (reported !== undefined) return reported;\n if (outcome.kind === 'timeout') return `It did not finish in ${REFRESH_TIMEOUT_MS / 1000}s.`;\n if (outcome.kind === 'start-failed') return 'The refresh could not be started.';\n // An older binary rejecting `--refresh` is the expected shape here: commander\n // writes its own usage error and exits without an envelope of ours.\n return `The refresh exited ${outcome.code} without reporting a reason.`;\n}\n\n/**\n * The `error.message` out of the one failure envelope the child printed.\n *\n * Read from the LAST envelope because stdout carries exactly one while stderr\n * may carry notices ahead of it, and the two pipes are merged here.\n *\n * `writeJson` PRETTY-PRINTS, so the envelope spans many lines and its only line\n * starting with `{` is a bare `{` that does not parse alone. So scan backwards\n * for an opening line and parse from there to the end; a compact single line\n * still parses through the same path, which keeps an older child readable.\n *\n * Sanitized because this text is bound for a human's terminal and the child\n * relays paths and parse errors it did not author.\n */\nfunction envelopeMessage(output: string): string | undefined {\n const lines = output.split('\\n');\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n const line = lines[i]?.trim();\n if (line === undefined || !line.startsWith('{')) continue;\n let parsed: { ok?: unknown; error?: { message?: unknown } };\n try {\n parsed = JSON.parse(lines.slice(i).join('\\n')) as typeof parsed;\n } catch {\n continue;\n }\n if (parsed?.ok !== false || typeof parsed.error?.message !== 'string') continue;\n const message = sanitizeForTerminal(parsed.error.message).trim();\n if (message.length > 0) return message.slice(0, REASON_LIMIT);\n }\n return undefined;\n}\n\n/** A path that already exists AND is a directory. Follows links on purpose: a\n * data dir behind a symlink is an ordinary machine layout, an absent one is not\n * a profile this command may create. */\nfunction isExistingDir(path: string): boolean {\n return statSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n}\n\n/**\n * The manual command that converges THIS profile.\n *\n * A bare `tenjin install` resolves one data dir, so handing it to an operator\n * whose failed profile is a shelf — the case the per-profile loop exists for —\n * is advice that cannot repair the thing it names. The bare form is emitted only\n * for a dir that is the default under this home AND the one this invocation\n * itself resolved, so it is right under either reading of \"what a bare install\n * would do next\"; every other profile gets the explicit env prefix, which is the\n * same form the shelf runbook uses and is right unconditionally.\n */\nfunction manualFix(dataDir: string, home: string, invoking: string): string {\n const bare =\n resolve(dataDir) === resolve(defaultDataDir(home)) && resolve(dataDir) === resolve(invoking);\n const command = bare ? 'tenjin install' : `TENJIN_DATA_DIR=${dataDir} tenjin install`;\n return `Run \\`${command}\\` to bring the Claude Code plugin up to this version.`;\n}\n\n/**\n * The entry to re-exec, or null when there is none this code may trust.\n *\n * `process.argv[1]` is the path Node RESOLVED, symlinks and all (see\n * `classifyManager`, which reads the manager off exactly that property). Under\n * npm and bun that path carries no version, so after the swap it is already the\n * new build. Under pnpm it points into the virtual store, whose directory names\n * PIN A VERSION: `.../node_modules/.pnpm/tenjin-cli@<version>/node_modules/tenjin-cli/dist/index.js`.\n * Re-executing that is the worst available outcome — it runs the build the\n * update just replaced and reports a successful refresh over the previous\n * version's bytes, which is the exact staleness this whole command exists to\n * end (tenjin-agent#171).\n *\n * The virtual store keeps the version-free link one level out, beside `.pnpm`,\n * and the swap repoints it, so the same path with the store segments removed is\n * the new build. It is derived rather than assumed: if the result is not on\n * disk, this returns null and the caller warns instead of running anything.\n */\nexport function versionFreeEntry(entry: string | undefined): string | null {\n if (entry === undefined || entry.length === 0) return null;\n const segs = entry.split(sep);\n const store = segs.indexOf('.pnpm');\n if (store === -1) return segs.join(sep);\n // `.pnpm/<name>@<version>/node_modules/<name>/...`: everything from the second\n // `node_modules` on is the package's own path within the global tree.\n const inner = segs.indexOf('node_modules', store);\n if (inner === -1) return null;\n const derived = [...segs.slice(0, store), ...segs.slice(inner + 1)].join(sep);\n return existsSync(derived) ? derived : null;\n}\n\n/**\n * What the refresh actually did, as lines.\n *\n * It replaces \"New builds pick it up immediately\", which was true of the binary\n * and false of everything install had written — so it read as reassurance about\n * precisely the thing that was NOT handled (tenjin-agent#171).\n *\n * The successes are reported ALONGSIDE the failures rather than instead of them:\n * a machine where 8 of 12 profiles converged is not a machine where the refresh\n * did nothing, and one line per failure is what lets its own reason and its own\n * command travel with it.\n */\nfunction refreshLines(refresh: RefreshOutcome): string[] {\n const failedDirs = new Set(refresh.failed.map((f) => f.dataDir));\n const done = refresh.profiles.filter((p) => !failedDirs.has(p));\n if (refresh.failed.length === 0) {\n return [\n done.length > 1\n ? `Refreshed the Claude Code plugin for ${done.length} profiles: ${done.join(', ')}.`\n : `Refreshed the Claude Code plugin for ${done[0]}.`,\n ];\n }\n const total = done.length + refresh.failed.length;\n const lines =\n done.length > 0\n ? [\n `Refreshed the Claude Code plugin for ${done.length} of ${total} profiles: ${done.join(', ')}.`,\n ]\n : [];\n lines.push(`Could not refresh the Claude Code plugin for ${refresh.failed.length}:`);\n lines.push(...refresh.failed.map((f) => `- ${f.dataDir}: ${f.reason} ${f.fix}`));\n return lines;\n}\n\n/** The project installs the refresh reached, and the ones it could not. */\nfunction projectLines(refresh: RefreshOutcome): string[] {\n return [\n ...(refresh.projects.length > 0\n ? [`Refreshed the project install in ${refresh.projects.join(', ')}.`]\n : []),\n ...(refresh.projectsFailed.length > 0\n ? [\n `Could not refresh the project install in ${refresh.projectsFailed.length}:`,\n ...refresh.projectsFailed.map((p) => `- ${p.project}: ${p.reason} ${p.fix}`),\n ]\n : []),\n ];\n}\n\n/**\n * Default spawn: merged stdout+stderr chunks out, an outcome back, no shell.\n * Bounded by its own timer rather than Node's `timeout` option so that a kill\n * this code ordered is distinguishable from any other death by signal.\n */\nexport const spawnCapture: UpdateSpawn = (cmd, args, opts, onOutput) =>\n new Promise((res) => {\n let child;\n try {\n child = spawn(cmd, args, {\n stdio: ['ignore', 'pipe', 'pipe'],\n cwd: opts.cwd,\n // Layered onto this process's environment rather than replacing it: the\n // child is a Node CLI that needs PATH and HOME, and only the keys named\n // here are being decided.\n ...(opts.env !== undefined ? { env: { ...process.env, ...opts.env } } : {}),\n });\n } catch (cause) {\n // An argv or option Node rejects outright throws here; ENOENT arrives on\n // the 'error' event instead. Both mean the same thing to the caller.\n res({ kind: 'start-failed', cause });\n return;\n }\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill('SIGKILL');\n }, opts.timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => onOutput(chunk.toString()));\n child.stderr?.on('data', (chunk: Buffer) => onOutput(chunk.toString()));\n child.on('error', (cause) => {\n clearTimeout(timer);\n res({ kind: 'start-failed', cause });\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n res(timedOut ? { kind: 'timeout' } : { kind: 'exit', code: code ?? 1 });\n });\n });\n","import { existsSync, realpathSync, statSync } from 'node:fs';\nimport { delimiter, dirname, join, sep } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * WHERE this build is installed, and what that implies about replacing it.\n *\n * Its own module because it answers a different question from the command that\n * uses it: \"what IS this install\" rather than \"how do I replace it\". The\n * refusal set is the load-bearing part, and it got re-cut in three consecutive\n * reviews while it was expressed positionally inside the command body.\n */\n\n/** Managers a global install can be handed back to. yarn is deliberately absent\n * from the delegable set: see the yarn entry in REFUSALS. */\nexport type Delegable = 'npm' | 'pnpm' | 'bun';\n\n/**\n * One reason `npm install -g` would not actually replace THIS build.\n *\n * Each entry carries the three properties that decide WHEN it is evaluated,\n * because expressing them by where the line sat is what made this set get\n * re-cut three times: a missing entry, then a copy on the wrong side of the\n * fetch, then a duplicate that could not run. Declaring them means adding a\n * refusal is a matter of answering three questions, not of guessing a position.\n */\ninterface Refusal {\n /** Does this install location refuse? Pure filesystem, never the network. */\n test: (moduleDir: string) => boolean;\n error: (spec: string, moduleDir: string) => CliError;\n /**\n * Does the fix string name the version the registry just resolved? This is\n * also what decides whether the entry may run BEFORE the fetch: one that does\n * not need a version is evaluated first, so an offline user in a checkout is\n * told they are in a checkout rather than told to go debug their network.\n */\n needsVersion: boolean;\n /**\n * Does it apply to `--check`? Everything here is a reason not to WRITE, and\n * `--check` only reports, so today nothing does. An entry that ever answers\n * yes is one whose test says the REPORT would be wrong, not the install.\n */\n appliesToCheck: boolean;\n}\n\n/**\n * Ordered most-specific first: a checkout and an npx cache are recognizable\n * before any question of which manager or which tree, and the manager entry\n * precedes the global/local one because a pnpm or bun store has its own layout\n * that `isGlobalTree` is not written for.\n */\nexport const REFUSALS: readonly Refusal[] = [\n {\n test: isSourceCheckout,\n error: () =>\n new CliError('REFUSED', 'tenjin-cli is running from a source checkout, not an install', {\n fix: 'Update the checkout instead: git pull && pnpm install',\n }),\n needsVersion: false,\n appliesToCheck: false,\n },\n {\n test: (moduleDir) => moduleDir.split(sep).includes('_npx'),\n error: (spec) =>\n new CliError('REFUSED', 'tenjin-cli is running from the npx cache, not an install', {\n // Writing a global here would \"succeed\" and change nothing: the next\n // `npx tenjin` still resolves its own cached copy.\n fix: `npx fetches its own copy every time. To keep one: npm i -g ${spec}`,\n }),\n needsVersion: true,\n appliesToCheck: false,\n },\n {\n // The ONLY manager still refused. `yarn global add` is yarn-1 only, and\n // berry dropped global installs altogether, so there is no one command this\n // can drive across the versions a user might have. Every other manager is\n // delegated to rather than refused (see MANAGERS).\n test: (moduleDir) => classifyManager(moduleDir) === 'yarn',\n error: (spec) =>\n new CliError(\n 'REFUSED',\n 'This tenjin-cli was installed with yarn, whose global install exists only in yarn 1',\n { fix: `yarn global add ${spec}` },\n ),\n needsVersion: true,\n appliesToCheck: false,\n },\n {\n // Scoped to npm on purpose: the prefix-vs-project-root test is written for\n // npm's layout. pnpm's global store and bun's global dir both keep a\n // package.json beside `node_modules`, so an unscoped test would read either\n // as a project-local install and refuse the very case we now delegate.\n test: (moduleDir) => classifyManager(moduleDir) === 'npm' && !isGlobalTree(moduleDir),\n error: (spec) =>\n new CliError(\n 'REFUSED',\n 'This tenjin-cli is a project-local dependency, not a global install',\n {\n fix: `Update it where it is declared: npm i ${spec}`,\n },\n ),\n needsVersion: true,\n appliesToCheck: false,\n },\n];\n\n/**\n * Evaluate the refusal set, once per stage. `spec` is null before the registry\n * has been asked and the resolved `tenjin-cli@<version>` after, which is what\n * selects the eligible entries: every entry runs in exactly one stage, so no\n * refusal can be reached twice or, as in round three, be written twice and\n * reached once.\n */\nexport function refuse(moduleDir: string, opts: { check: boolean; spec: string | null }): void {\n for (const entry of REFUSALS) {\n if (opts.check && !entry.appliesToCheck) continue;\n if (entry.needsVersion !== (opts.spec !== null)) continue;\n if (entry.test(moduleDir)) throw entry.error(opts.spec ?? '', moduleDir);\n }\n}\n\n/**\n * The published package ships `dist/`, `docs/`, and `skills/` with no `src/`\n * beside them (the `files` array), so a `src/` next to the nearest package.json\n * means a checkout, whose version number says nothing about what HEAD holds.\n * Same test skill-heal uses to keep its hands off working-tree skills.\n */\nexport function isSourceCheckout(moduleDir: string): boolean {\n let dir = moduleDir;\n for (let i = 0; i < 8; i += 1) {\n if (existsSync(join(dir, 'package.json'))) return existsSync(join(dir, 'src'));\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return false;\n}\n\n/**\n * Is this a GLOBAL npm tree? A global install sits under a prefix directory that\n * is not itself a package (`<prefix>/lib/node_modules/tenjin-cli` on POSIX,\n * `<prefix>\\node_modules\\tenjin-cli` on win32), while a project-local one sits\n * under the project root, which by definition has a package.json. That parent is\n * the whole test, which is why it holds for homebrew, nvm, volta and a\n * user-set `npm config prefix` alike without this code enumerating any of them.\n */\nexport function isGlobalTree(moduleDir: string): boolean {\n const segs = moduleDir.split(sep);\n const i = segs.lastIndexOf('node_modules');\n if (i <= 0) return false;\n return !existsSync(join(segs.slice(0, i).join(sep), 'package.json'));\n}\n\n/**\n * Which package manager owns this install, read off the on-disk path. Node\n * resolved the bin symlink before loading us, so the segments name the real\n * store: pnpm's virtual store keeps a literal `.pnpm` segment (or\n * `pnpm/global` for older layouts), bun installs under `.bun`, yarn under\n * `.yarn` or `yarn/global`. Everything else is treated as npm's tree; that\n * covers nvm and volta, both of which route `npm i -g` correctly.\n */\nexport function classifyManager(moduleDir: string): Delegable | 'yarn' {\n const segs = moduleDir.split(sep);\n const pair = (a: string, b: string): boolean => segs.includes(a) && segs.includes(b);\n if (segs.includes('.pnpm') || pair('pnpm', 'global')) return 'pnpm';\n if (segs.includes('.bun')) return 'bun';\n if (segs.includes('.yarn') || pair('yarn', 'global')) return 'yarn';\n return 'npm';\n}\n\n/**\n * How to perform a global install with each manager we delegate to.\n *\n * `scriptSuffixes` is what a PATH shim may resolve to that Node can run\n * directly, which is how win32 is served without a shell: npm and pnpm ship as\n * JS, so the child becomes `node <script>`. An empty list means the binary is\n * native (bun), where spawning it by name already works on every platform.\n */\nexport const MANAGERS: Record<\n Delegable,\n {\n bin: string;\n scriptSuffixes: readonly string[];\n /** Ships beside the running node, as npm does inside the Node distribution. */\n besideNode: boolean;\n args: (spec: string) => string[];\n manual: (spec: string) => string;\n }\n> = {\n npm: {\n bin: 'npm',\n scriptSuffixes: ['npm-cli.js'],\n besideNode: true,\n args: (spec) => ['install', '-g', '--ignore-scripts', spec],\n manual: (spec) => `npm i -g ${spec}`,\n },\n pnpm: {\n bin: 'pnpm',\n // corepack's shim resolves to `pnpm.js`, a standalone install to `pnpm.cjs`.\n scriptSuffixes: ['.cjs', '.js'],\n besideNode: false,\n args: (spec) => ['add', '-g', '--ignore-scripts', spec],\n manual: (spec) => `pnpm add -g ${spec}`,\n },\n bun: {\n bin: 'bun',\n scriptSuffixes: [],\n besideNode: false,\n // No --ignore-scripts: bun's flag surface for it is not stable across the\n // versions in the wild, and an unknown flag would fail the install outright.\n args: (spec) => ['add', '-g', spec],\n manual: (spec) => `bun add -g ${spec}`,\n },\n};\n\n/**\n * npm's own entry script, so the child can be `node npm-cli.js` rather than the\n * `npm` shim.\n *\n * On win32 the shim is `npm.cmd`, which Node refuses to spawn without\n * `shell: true`, and `shell: true` is exactly what this command must not do —\n * it would hand back the argv safety the pinned version buys.\n *\n * Deliberately NOT \"npm ships inside the Node distribution\". That is a property\n * of the installer, not of Node: Homebrew's plain `node` formula keeps only\n * corepack in the keg and puts npm at the brew prefix, so a probe relative to\n * `process.execPath` alone returns null on one of the most common macOS setups.\n * So the layout is searched, not assumed — beside the running binary first\n * (official tarball and installer, nvm, volta, versioned brew kegs), then off\n * PATH, where on POSIX the `npm` shim is itself a symlink to `npm-cli.js` and on\n * win32 `npm.cmd` has `node_modules` beside it. Still null when npm cannot be\n * found at all; the caller then falls back to the bare shim, which works\n * everywhere but win32 and fails closed there into UPDATE_FAILED carrying the\n * manual command.\n */\nexport function resolveNpmCli(\n execPath: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n return resolveManagerScript('npm', execPath, env);\n}\n\n/**\n * The JS entry script for `manager`, or null when it has none to find (a native\n * binary, or a shim this cannot see through). Null means \"spawn the bare name\",\n * which works everywhere but win32 and fails closed there.\n */\nexport function resolveManagerScript(\n manager: Delegable,\n execPath: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n const plan = MANAGERS[manager];\n if (plan.scriptSuffixes.length === 0) return null;\n const beside = plan.besideNode ? scriptNear(dirname(execPath), plan.bin) : null;\n return beside ?? scriptOnPath(plan.bin, plan.scriptSuffixes, env);\n}\n\n/** A manager's script relative to a directory holding `node` or its own shim. */\nfunction scriptNear(dir: string, bin: string): string | null {\n const candidates = [\n join(dir, 'node_modules', bin, 'bin', `${bin}-cli.js`),\n join(dir, '..', 'lib', 'node_modules', bin, 'bin', `${bin}-cli.js`),\n ];\n return candidates.find(isFile) ?? null;\n}\n\n/**\n * Walk PATH for the manager's shim and turn it into its script. Probes the\n * PATHEXT extensions on win32 for the same reason `onPath` in skill-wiring.ts\n * does: the real file there is `npm.cmd`, never a bare `npm`.\n */\nfunction scriptOnPath(\n bin: string,\n suffixes: readonly string[],\n env: NodeJS.ProcessEnv,\n): string | null {\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of (env.PATH ?? '').split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (!isFile(join(part, `${bin}${ext}`))) continue;\n // POSIX package managers link the shim straight at the script, which is\n // what makes this layout-independent rather than a longer guess list.\n //\n // The endsWith is a CORRECTNESS check, not a security guard: it asks \"did\n // this symlink land on npm's script or on something else\", and a shim\n // pointed elsewhere returns null, which falls back to spawning that same\n // retargeted shim anyway. PATH poisoning is out of scope by construction —\n // an attacker ahead of npm on PATH owns every tool the user runs, and the\n // pre-existing fallback `spawn('npm', ...)` resolved through the same PATH.\n const real = realpathOrNull(join(part, `${bin}${ext}`));\n if (real !== null && suffixes.some((suffix) => real.endsWith(suffix))) return real;\n const near = scriptNear(part, bin);\n if (near !== null) return near;\n }\n }\n return null;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\nfunction realpathOrNull(p: string): string | null {\n try {\n return realpathSync(p);\n } catch {\n return null;\n }\n}\n","import { readFile, realpath } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\nimport pkg from '../../package.json';\nimport {\n persistRouterDefaults,\n persistRouterProject,\n ROUTER_DEFAULTS,\n type RouterLimits,\n} from '../commands/config';\nimport { askText, selectOne } from '../lib/clack';\nimport { CliError } from '../lib/errors';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { paint } from '../lib/output';\nimport { resolveContextSettings } from '../lib/settings';\nimport type { SpendPolicy } from '../lib/policy';\nimport { removeRetiredSkills } from '../lib/skill-placement';\nimport { loadRawConfig, type PartialConfig } from '../lib/config';\nimport type { WalletDeps, WalletOutcome } from '../commands/install-wallet';\nimport type { CommandContext, CommandResult } from '../context';\nimport { readAliveStamp } from './alive';\nimport {\n findClaudeBinary,\n readClaudeCode,\n userMcpFile,\n userSettingsPath,\n type ClaudeBinary,\n type ClaudeCodeState,\n} from './claude-cli';\nimport {\n inspectLegacyInstall,\n projectMcpFile,\n removeLegacyInstall,\n type LegacyInstall,\n type LegacyRemoval,\n} from './legacy-install';\nimport { PLUGIN_ID } from './names';\nimport { CLAUDE_CODE_FLOOR } from './claude-cli';\nimport {\n folderState,\n readPluginListing,\n registerPlugin,\n type PluginRegistration,\n type PluginScope,\n} from './plugin-registration';\nimport { probeRouter, type RouterCheck } from './reachability';\nimport { readMcpServers, type InstalledAt, type ListMcpProcesses } from './mcp-processes';\nimport {\n FEE_APPROVAL,\n limitsUsd,\n OWN_LIMITS_COMMANDS,\n ROUTING_FEE_TERMS,\n shownLimits,\n spendQuestion,\n} from './spend-question';\n\n/**\n * `tenjin install` for the router product: the wallet, the spend limits, and\n * the Claude Code plugin `tenjin`, registered with no step left to the person.\n *\n * WHAT IT WRITES. The wallet and the spend defaults under the data dir, as\n * before. The plugin is registered through Claude Code's own `claude plugin`\n * commands from this package's `dist/hosts/claude` folder (see\n * `plugin-registration.ts`), or written as a folder under the config dir's\n * `skills/` where no `claude` binary can be run. The plugin carries the seven\n * routing legs, the `router` MCP server, and the hooks that allow the request\n * tool and deny the legs' own tool to the model, so this command writes\n * nothing into `settings.json` or `~/.claude.json` itself.\n *\n * NO STEP IS LEFT TO THE PERSON. An agent runs this in the person's session:\n * the spend question comes back for the agent to ask there, the `claude`\n * binary is found through `CLAUDE_CODE_EXECPATH` where PATH lacks it, a failed\n * plugin command falls back to the folder, and the one step after it is\n * typing `/reload-plugins` in the same session, or starting the next one.\n *\n * THE SETTINGS INSTALL OF EARLIER RELEASES is left working until the plugin\n * has proven to load on this machine (see {@link migrateSettingsInstall}).\n */\n\nexport { AFTER_CALL_TIMEOUT_SECONDS, ROUTE_HOOK_TIMEOUT_SECONDS } from './plugin-files';\n\nexport const DISCLOSURE: readonly string[] = [\n \"What leaves this machine: the bounded text of each prompt, each native search query or URL (and, when one came back short, its status, size or error), each task handed to a subagent, and each question your assistant asks you with your answers, sent to Tenjin for the free routing gate, beside this session's id. When the gate offers free library docs for a search, that search query also goes to Tenjin's docs lookup, which asks Context7.\",\n 'What is kept when a lookup is paid: the capability chosen, a hash of the contract, a hash of the arguments, and your wallet address. No prompt text, no arguments, no hint text.',\n 'What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere.',\n];\n\n/** What the person does after a successful install, in the session they are in. */\nexport const RELOAD_STEP =\n 'type /reload-plugins in this Claude Code session, or start a new session, so Tenjin loads';\n/**\n * The same step while a settings install is still here: only a new session.\n * `/reload-plugins` would load the plugin beside the pre-upgrade `x402` server\n * that session is still running, and every event would route twice.\n */\nexport const NEW_SESSION_STEP = 'start a new Claude Code session so Tenjin loads';\n\n/** The step that loads the plugin, given whether a settings install is still here. */\nexport function loadStep(settingsInstallPresent: boolean): string {\n return settingsInstallPresent ? NEW_SESSION_STEP : RELOAD_STEP;\n}\n\nexport interface RouterInstallArgs {\n /**\n * Register the plugin for this project only (Claude Code's `local` scope,\n * `.claude/settings.local.json`), or write its folder under the project's\n * `.claude/skills/`.\n */\n project?: boolean;\n /**\n * Bring what this machine ALREADY has up to the running build: the plugin,\n * or a settings install the plugin then replaces, with no config write. A\n * refusal when nothing of ours is here. `tenjin update` spawns exactly this\n * after it swaps the binary, so the flag's name and meaning are a\n * compatibility contract.\n */\n refresh?: boolean;\n /**\n * Accept the limits the question shows instead of asking: the selector's\n * \"Use these limits\", for an agent running the user's yes.\n */\n yes?: boolean;\n /** Create no wallet, for CI and scripted machines. */\n noWallet?: boolean;\n}\n\nexport interface RouterInstallDeps extends WalletDeps {\n /** This user's running `tenjin mcp` processes; tests inject them. */\n listMcpProcesses?: ListMcpProcesses;\n /** When this build was installed; tests inject it. */\n installedAt?: InstalledAt;\n homeDir?: string;\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** Finds the `claude` binary; tests inject one, production reads PATH and `CLAUDE_CODE_EXECPATH`. */\n findClaude?: (env: NodeJS.ProcessEnv) => ClaudeBinary | null;\n /** The marketplace folder; production reads this package's `dist/hosts/claude`. */\n hostsDir?: string | null;\n /** The CLI entry a plugin folder's commands run. Production reads this package's `dist/index.js`. */\n cliEntry?: string;\n /** Whether a person can answer the spend-limit question (a TTY on stdout and\n * stdin, no `--json`); injected in tests. */\n isInteractive?: boolean;\n /** The spend-limit selector; defaults to the clack list. */\n promptLimits?: (message: string) => Promise<LimitsChoice | null>;\n /** One amount question; defaults to the clack text input. */\n promptAmount?: (message: string, placeholder: string) => Promise<string | null>;\n /** The router reachability probe's transport; tests inject it. */\n fetchImpl?: typeof fetch;\n}\n\nexport type LimitsChoice = 'approve' | 'own';\n\n/** Where a settings install of this scope kept its entries and its server. */\nexport interface SettingsInstallPaths {\n settingsPath: string;\n mcpFile: string;\n mcpScope: 'user' | 'project';\n}\n\nexport function settingsInstallPaths(\n project: boolean,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): SettingsInstallPaths {\n return project\n ? {\n settingsPath: join(cwd, '.claude', 'settings.json'),\n mcpFile: projectMcpFile(cwd),\n mcpScope: 'project',\n }\n : {\n settingsPath: userSettingsPath(env, home),\n mcpFile: userMcpFile(env, home),\n mcpScope: 'user',\n };\n}\n\n/** The settings install's state, as install, update, doctor and uninstall report it. */\nexport interface Migration {\n /**\n * `none` (no settings install here), `pending` (left in place until the\n * plugin proves it loads), `done` (removed by this run), or `blocked` (the\n * settings file could not be read).\n */\n state: 'none' | 'pending' | 'done' | 'blocked';\n settingsPath: string;\n /** Why it is still pending or blocked. */\n reason?: string;\n removed?: LegacyRemoval;\n}\n\n/**\n * THE GUARDED MIGRATION. A working settings install is removed only once the\n * plugin has proven to load on this machine: Claude Code at or above the floor\n * and listing the plugin enabled (when a binary can be asked), and the\n * plugin's `alive` leg having stamped the machine from a real session. Until\n * then both stay, and the `alive` marker keeps the old legs silent in any\n * session the plugin serves. Only `install` and `update` migrate; doctor\n * reports.\n */\nexport async function pluginProof(\n claude: ClaudeCodeState,\n dataDir: string,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): Promise<{ proven: true } | { proven: false; reason: string }> {\n if (claude.binary !== null && !claude.meetsFloor) {\n return {\n proven: false,\n reason: `Claude Code ${claude.version ?? '(unknown)'} is older than the plugin needs`,\n };\n }\n if (claude.binary !== null) {\n const listing = await readPluginListing(claude.binary, env, cwd);\n if (!listing.enabled) {\n return { proven: false, reason: 'Claude Code does not list the plugin as enabled yet' };\n }\n }\n if ((await readAliveStamp(dataDir)) === null) {\n return {\n proven: false,\n reason: 'the plugin has not loaded in a Claude Code session on this machine yet',\n };\n }\n return { proven: true };\n}\n\nexport async function migrateSettingsInstall(\n legacy: LegacyInstall,\n claude: ClaudeCodeState,\n opts: { dataDir: string; env: NodeJS.ProcessEnv; cwd: string; mcpScope: 'user' | 'project' },\n): Promise<Migration> {\n if (!legacy.present) return { state: 'none', settingsPath: legacy.settingsPath };\n const proof = await pluginProof(claude, opts.dataDir, opts.env, opts.cwd);\n if (!proof.proven) {\n return { state: 'pending', settingsPath: legacy.settingsPath, reason: proof.reason };\n }\n const removed = await removeLegacyInstall(legacy, {\n binary: claude.binary,\n env: opts.env,\n cwd: opts.cwd,\n mcpScope: opts.mcpScope,\n });\n return { state: 'done', settingsPath: legacy.settingsPath, removed };\n}\n\n/**\n * Is there a project install here? A refresh, a bare doctor and a bare\n * uninstall are given no scope, and `tenjin update` runs its refresh from\n * home, where nothing proves one. A project install is taken when this\n * directory, not being home, holds one: the plugin enabled in its\n * `settings.local.json`, its plugin folder, or a settings install's entries.\n */\nexport async function projectInstallHere(\n cwd: string,\n home: string,\n env: NodeJS.ProcessEnv,\n): Promise<boolean> {\n if (await isHome(cwd, home)) return false;\n return projectInstallAt(cwd, home, env);\n}\n\n/**\n * Does `dir` still hold the project install `install --project` recorded\n * there? Home included: a `--project` install at home is supported, and there\n * its plugin folder and settings file are the user install's own, so only the\n * plugin enabled in `.claude/settings.local.json` proves it.\n */\nexport async function projectInstallAt(\n dir: string,\n home: string,\n env: NodeJS.ProcessEnv,\n): Promise<boolean> {\n const local = await readFile(join(dir, '.claude', 'settings.local.json'), 'utf8')\n .then((raw) => JSON.parse(raw) as { enabledPlugins?: Record<string, unknown> })\n .catch(() => null);\n if (local?.enabledPlugins?.[PLUGIN_ID] === true) return true;\n if (await isHome(dir, home)) return false;\n if ((await folderState('local', env, home, dir)).state === 'ours') return true;\n const paths = settingsInstallPaths(true, env, home, dir);\n return (await inspectLegacyInstall(paths.settingsPath, paths.mcpFile)).events.length > 0;\n}\n\nasync function isHome(dir: string, home: string): Promise<boolean> {\n const [dirPath, homePath] = await Promise.all([\n realpath(dir).catch(() => dir),\n realpath(home).catch(() => home),\n ]);\n return dirPath === homePath;\n}\n\n/** Is any install of ours here for a refresh to bring up to date? */\nasync function somethingToRefresh(\n claude: ClaudeCodeState,\n scope: PluginScope,\n legacy: LegacyInstall,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<boolean> {\n if (legacy.present) return true;\n if ((await folderState(scope, env, home, cwd)).state === 'ours') return true;\n if (claude.binary !== null) {\n const listing = await readPluginListing(claude.binary, env, cwd);\n if (listing.id === PLUGIN_ID) return true;\n }\n return false;\n}\n\nexport async function runRouterInstall(\n args: RouterInstallArgs,\n ctx: CommandContext,\n deps: RouterInstallDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n if (!isAbsolute(home)) {\n throw new CliError('INTERNAL', 'The home directory is not an absolute path.', {\n fix: 'Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`.',\n });\n }\n const config = await loadRawConfig(ctx.dataDir); // Validate before any install writes; retired keys remain readable.\n const cwd = deps.cwd ?? process.cwd();\n // An explicit --project wins, including for a project rooted at home.\n const project =\n args.project ?? (args.refresh === true && (await projectInstallHere(cwd, home, env)));\n const scope: PluginScope = project ? 'local' : 'user';\n const claude = await readClaudeCode(env, cwd, deps.findClaude ?? findClaudeBinary);\n const paths = settingsInstallPaths(project, env, home, cwd);\n const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);\n\n if (args.refresh === true && !(await somethingToRefresh(claude, scope, legacy, env, home, cwd))) {\n throw new CliError(\n 'REFUSED',\n `Nothing to refresh: neither the ${PLUGIN_ID} plugin nor a settings install of Tenjin is registered here.`,\n { fix: 'Run `tenjin install` to set this machine up.' },\n );\n }\n // The shelf install's gate: a refresh, `--json`, or a run with no terminal on\n // either side asks nothing. An agent's install is that run: its shell has no\n // terminal. Install then writes no spend limit at all, the same state a\n // person cancelling at the selector leaves, and its output hands the question\n // to whoever ran it (see {@link spendApproval}). Until someone answers, the\n // bare CLI's zero holds and doctor reports the question as pending.\n const humanOutput = ctx.flags.json === true ? false : (deps.isInteractive ?? ctx.io.isTTY);\n const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n // `--yes` is the selector's \"Use these limits\", answered ahead: the same\n // install, run again by an agent for the user's yes.\n const limits =\n args.refresh === true\n ? undefined\n : args.yes === true\n ? shownLimits(config)\n : canPrompt\n ? await approveLimits(config, deps)\n : {};\n const spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true, limits);\n const removedKeysLines =\n spend.removed.length > 0\n ? [\n `Removed retired settings: ${spend.removed.join(', ')}. Automatic router limits remain in effect; manual pay always requires consent.`,\n ]\n : [];\n const removedSkills = await removeRetiredSkills(home, project ? cwd : undefined);\n // BELOW THE FLOOR, A WORKING SETTINGS INSTALL WINS. The plugin's routing\n // legs need Claude Code 2.1.287, but its `alive` leg is a command that runs\n // on any version and would silence the settings install in every session,\n // leaving the machine unrouted. So nothing is registered until `claude\n // update`, and the settings install keeps routing.\n const plugin: PluginRegistration =\n !claude.meetsFloor && legacy.present\n ? deferredRegistration(scope, claude)\n : await registerPlugin({\n binary: claude.binary,\n scope,\n version: pkg.version,\n env,\n home,\n cwd,\n ...(deps.hostsDir !== undefined ? { hostsDir: deps.hostsDir } : {}),\n ...(deps.cliEntry !== undefined ? { cliEntry: deps.cliEntry } : {}),\n });\n // A PROJECT INSTALL IS RECORDED, so `tenjin update`, which refreshes from\n // home where this scope is not visible, refreshes it from here too.\n if (project && plugin.state !== 'failed') {\n await persistRouterProject(ctx.dataDir, cwd).catch(() => undefined);\n }\n const migration =\n legacy.unreadable !== undefined && !legacy.present\n ? { state: 'blocked' as const, settingsPath: paths.settingsPath, reason: legacy.unreadable }\n : await migrateSettingsInstall(legacy, claude, {\n dataDir: ctx.dataDir,\n env,\n cwd,\n mcpScope: paths.mcpScope,\n });\n // A `tenjin mcp` that started before this install runs the old build until\n // its session reloads it. Named, never killed.\n const pending = settingsInstallStays(migration);\n const servers = await readMcpServers(deps, { settingsInstallPending: pending });\n const serverLines =\n servers.stale > 0\n ? [paint(ctx.io, 'yellow', `! ${servers.check.detail}. ${servers.check.fix ?? ''}`.trim())]\n : [];\n const claudeCode = claudeCodeData(claude);\n const notices = refreshNotices(plugin, claude, migration);\n if (args.refresh === true) {\n // A refresh that could not register the plugin is not a converged install,\n // unless the settings install it would replace still routes here.\n if (plugin.state === 'failed' && migration.state !== 'pending') {\n throw new CliError(\n 'REFUSED',\n `The ${PLUGIN_ID} plugin could not be registered: ${plugin.reason ?? 'unknown reason'}.`,\n { fix: registrationFix(plugin), details: { plugin, claudeCode, migration } },\n );\n }\n return {\n data: {\n plugin,\n claudeCode,\n migration,\n notices,\n refresh: true,\n spend,\n removedSkills,\n scope,\n mcpServer: servers.check,\n },\n humanLines: [\n ...refreshLines(ctx, plugin, claude, migration),\n ...removedKeysLines,\n ...serverLines,\n ],\n };\n }\n // The shelf install's wallet step, unchanged except that it never asks: a\n // lookup cannot be paid without a wallet, so install makes one. A failure is\n // reported, never fatal; everything above is useful without it.\n const { resolveWallet } = await import('../commands/install-wallet');\n const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? 'flag' : undefined, false);\n // Read back AFTER the write: a machine that already carried its own caps\n // keeps them, and a readout quoting the defaults would describe limits this\n // run did not set.\n const effective = await resolveContextSettings(ctx);\n const approval =\n !canPrompt && args.yes !== true && !spend.kept.includes('maxAutoSpend')\n ? spendApproval(config, args)\n : undefined;\n // A warning, never a failure: everything above is written and correct, and\n // the network this machine is on now may not be the one it uses later.\n const router = await probeRouter(effective.baseUrl, {\n timeoutMs: ctx.flags.timeout,\n env,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n const data = {\n plugin,\n claudeCode,\n migration,\n next: nextStep(plugin, claude, wallet, migration),\n // The check for this scope, said outright; a bare doctor in the project\n // also finds it from what the project holds.\n ...(project ? { doctor: 'tenjin doctor --project' } : {}),\n spend: {\n ...spend,\n effective: effectiveLimits(effective.policy),\n ...(approval !== undefined ? { approval } : {}),\n },\n wallet,\n router: {\n status: router.status === 'ok' ? 'ok' : 'warn',\n detail: router.detail,\n ...(router.fix !== undefined ? { fix: router.fix } : {}),\n },\n disclosure: DISCLOSURE,\n removedSkills,\n mcpServer: servers.check,\n };\n return {\n data,\n humanLines: [\n ...lines(ctx, {\n plugin,\n claude,\n migration,\n wallet,\n policy: effective.policy,\n ...(approval !== undefined ? { approval } : {}),\n router,\n }),\n ...removedKeysLines,\n ...serverLines,\n ],\n };\n}\n\nfunction claudeCodeData(claude: ClaudeCodeState): Record<string, unknown> {\n return {\n binary: claude.binary?.path ?? null,\n source: claude.binary?.source ?? null,\n version: claude.version,\n meetsFloor: claude.meetsFloor,\n ...(claude.fix !== undefined ? { fix: claude.fix } : {}),\n };\n}\n\n/**\n * The fix for a registration that did not happen, worded as a step the agent\n * can take in the session: never a command for the person to run elsewhere.\n */\nfunction registrationFix(plugin: PluginRegistration): string {\n // A project install is retried, and checked, as one.\n const flag = plugin.scope === 'local' ? ' --project' : '';\n if (plugin.id !== null && plugin.method === 'none') {\n return `${plugin.id} keeps serving this machine at the version Claude Code has; run \\`tenjin install${flag}\\` again to retry.`;\n }\n if (\n plugin.path !== undefined &&\n plugin.reason?.includes('not a folder this CLI wrote') === true\n ) {\n return `Move ${plugin.path} aside, then run \\`tenjin install${flag}\\` again.`;\n }\n return `Run \\`tenjin doctor${flag}\\` to see the cause, then run \\`tenjin install${flag}\\` again.`;\n}\n\n/** The one step after the install, for the agent to relay in the session. */\nfunction nextStep(\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n wallet: WalletOutcome,\n migration: Migration,\n): string {\n if (plugin.state === 'failed') return registrationFix(plugin);\n const steps: string[] = [];\n if (wallet.status === 'created') steps.push('fund the wallet with `tenjin wallet fund`');\n if (plugin.state === 'deferred') {\n steps.unshift('run `claude update`');\n steps.push(\n 'run `tenjin install` again; until then the earlier Tenjin setup keeps routing as before',\n );\n return steps.join(', then ');\n }\n if (!claude.meetsFloor) steps.unshift('run `claude update`');\n steps.push(loadStep(settingsInstallStays(migration)));\n return steps.join(', then ');\n}\n\n/** Is a settings install still on this machine after this run? */\nfunction settingsInstallStays(migration: Migration): boolean {\n return migration.state === 'pending' || migration.state === 'blocked';\n}\n\nfunction deferredRegistration(scope: PluginScope, claude: ClaudeCodeState): PluginRegistration {\n return {\n method: 'none',\n id: null,\n scope,\n state: 'deferred',\n version: pkg.version,\n steps: [],\n reason: `Claude Code ${claude.version ?? ''} is older than ${CLAUDE_CODE_FLOOR}, which the plugin needs, so it was not registered and the earlier settings setup keeps routing`,\n };\n}\n\n/** The status line a migration took out, in words, or nothing. */\nfunction statusLineNotice(migration: Migration): string | null {\n const status = migration.removed?.statusLine;\n if (status === 'removed') {\n return 'Removed the Tenjin status line (`tenjin status-line`) with the earlier settings setup; the plugin sets none. To keep it, set `tenjin status-line` as your Claude Code status line command.';\n }\n if (status === 'restored') {\n return 'Took the Tenjin footer out of your status line and put your own command back; the plugin sets none.';\n }\n return null;\n}\n\n/**\n * WHAT `tenjin update` PRINTS FROM THIS REFRESH. Update captures this run's\n * output and shows only its failures, so anything a person must know about a\n * refresh that succeeded rides here, as sentences the parent prints verbatim.\n */\nfunction refreshNotices(\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n migration: Migration,\n): string[] {\n const out: string[] = [];\n if (plugin.state === 'deferred') {\n out.push(\n `Claude Code ${claude.version ?? ''} is older than ${CLAUDE_CODE_FLOOR}, so the Tenjin plugin was not registered and the earlier settings setup keeps routing. Run \\`claude update\\`, then \\`tenjin install\\`.`,\n );\n } else if (plugin.state !== 'failed' && settingsInstallStays(migration)) {\n out.push(\n 'Start a new Claude Code session so the Tenjin plugin loads; the earlier settings setup is removed by the next `tenjin update` or `tenjin install` after that.',\n );\n }\n const status = statusLineNotice(migration);\n if (status !== null) out.push(status);\n return out;\n}\n\n/** What turns automatic payment on after an install that left it at zero. */\nconst AUTO_SPEND_FIX = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;\nconst DECLINED =\n 'the router then pays for nothing on its own, and the question stays open until the user answers it';\n\n/** The spend question an install that could not ask hands to its caller. */\nexport interface SpendApproval {\n /** For the agent to put to the user as written: the limits and the routing fee. */\n question: string;\n /** The limits the question shows, in USD, as the selector shows them. */\n limits: { maxAutoSpend: string; sessionBudget: string };\n /** The routing fee's terms, which a yes also approves. */\n routingFee: string;\n /** What the agent does with each answer. */\n next: string;\n /** The one command for a yes: this install again with `--yes`, as the selector's \"Use these limits\". */\n approve: string;\n /** The commands for limits of the user's own. */\n own: string;\n}\n\n/**\n * An agent runs install with `--json` or in a shell with no terminal, so the\n * CLI cannot ask. The agent can: this is what the selector would have shown\n * (the limits and the routing fee) and what to run for each answer, the same\n * shape as the `request` tool's `needs_input` step. A script or CI ignores\n * it, and the zero holds.\n */\nfunction spendApproval(config: PartialConfig, args: RouterInstallArgs): SpendApproval {\n const limits = shownLimits(config);\n const approve = yesCommand(args);\n return {\n question: spendQuestion(limits),\n limits: limitsUsd(limits),\n routingFee: ROUTING_FEE_TERMS,\n next: `In this session, show the user these limits and ask this question before you change any limit. If they say yes, run the same install again with --yes: \\`${approve}\\`. If they give other amounts, run ${OWN_LIMITS_COMMANDS}. If they say no, run nothing: ${DECLINED}.`,\n approve,\n own: OWN_LIMITS_COMMANDS.replaceAll('`', ''),\n };\n}\n\n/** The install this run was, with `--yes`: what an agent runs for the user's yes. */\nfunction yesCommand(args: RouterInstallArgs): string {\n return [\n 'tenjin install',\n ...(args.project === true ? ['--project'] : []),\n ...(args.noWallet === true ? ['--no-wallet'] : []),\n '--yes',\n ].join(' ');\n}\n\n/**\n * The one question install asks, before anything is written: approve the\n * automatic spend limits or set your own. Only a key the file does not already\n * name is asked for, because the write fills absent keys and keeps the rest.\n * The question names the routing fee and its deposits too, and either answer\n * approves it. Cancelling at any step writes nothing.\n */\nasync function approveLimits(\n config: PartialConfig,\n deps: RouterInstallDeps,\n): Promise<RouterLimits | undefined> {\n const shown = shownLimits(config);\n const askCall = config.maxAutoSpend === undefined;\n const askDay = config.sessionBudget === undefined;\n if (!askCall && !askDay) return undefined;\n const daily =\n shown.sessionBudget === 'none'\n ? 'no daily limit'\n : `$${toMoney(shown.sessionBudget).usd} a day`;\n const fee = `\\n${ROUTING_FEE_TERMS}\\n${FEE_APPROVAL}`;\n const choice = await (deps.promptLimits ?? promptLimits)(\n `The router pays for tool calls without asking, up to:\\n $${toMoney(shown.maxAutoSpend).usd} a call, ${daily}${fee}`,\n );\n if (choice === null) throw installCancelled();\n if (choice === 'approve') return shown;\n const ask = deps.promptAmount ?? promptAmount;\n return {\n maxAutoSpend: askCall\n ? await askLimit(ask, 'Most the router may pay for one call, in USD', '0.25', false)\n : shown.maxAutoSpend,\n sessionBudget: askDay\n ? await askLimit(ask, 'Most it may pay in a day, in USD, or none', '5', true)\n : shown.sessionBudget,\n };\n}\n\n/** Asks until the answer is a positive amount (or `none` for the daily limit). */\nasync function askLimit(\n ask: NonNullable<RouterInstallDeps['promptAmount']>,\n question: string,\n placeholder: string,\n allowNone: boolean,\n): Promise<string> {\n let message = question;\n for (;;) {\n const answer = await ask(message, placeholder);\n if (answer === null) throw installCancelled();\n const parsed = parseLimit(answer, allowNone);\n if (!('refusal' in parsed)) return parsed.value;\n message = `${parsed.refusal} ${question}`;\n }\n}\n\n/** Zero is refused: a zero per-call limit means the router can never pay, and\n * `router.enabled false` is how to turn it off. */\nfunction parseLimit(answer: string, allowNone: boolean): { value: string } | { refusal: string } {\n const trimmed = answer.trim();\n if (allowNone && trimmed === 'none') return { value: 'none' };\n let atomic: string;\n try {\n atomic = parseUsdToAtomic(trimmed);\n } catch (err) {\n if (err instanceof CliError) return { refusal: `${err.message}.` };\n throw err;\n }\n if (atomic === '0') return { refusal: 'The limit must be more than zero.' };\n return { value: atomic };\n}\n\nfunction installCancelled(): CliError {\n return new CliError('REFUSED', 'Install cancelled before anything was written.', {\n fix: 'Re-run `tenjin install` and choose the spend limits.',\n });\n}\n\nfunction promptLimits(message: string): Promise<LimitsChoice | null> {\n return selectOne<LimitsChoice>({\n message,\n choices: [\n { value: 'approve', label: 'Use these limits' },\n { value: 'own', label: 'Choose my own' },\n ],\n initialValue: 'approve',\n });\n}\n\nfunction promptAmount(message: string, placeholder: string): Promise<string | null> {\n return askText({ message, placeholder });\n}\n\ninterface EffectiveLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\nfunction effectiveLimits(policy: SpendPolicy): EffectiveLimits {\n return {\n maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,\n sessionBudget:\n policy.sessionBudgetAtomic === null\n ? 'no daily ceiling'\n : toMoney(policy.sessionBudgetAtomic.toString()).usd,\n };\n}\n\nfunction walletLines(ctx: CommandContext, ok: string, w: WalletOutcome): string[] {\n if (w.status === 'created') return [`${ok} Wallet created: ${w.address}`];\n if (w.status === 'existing') return [`${ok} Wallet: ${w.address}`];\n if (w.reason === 'flag') return [' No wallet yet. Create one with: tenjin wallet create'];\n return [\n paint(ctx.io, 'yellow', `! No wallet was created. ${w.warning ?? ''}`.trimEnd()),\n ` ${w.fix ?? 'Create one with: tenjin wallet create'}`,\n ];\n}\n\n/** The plugin line: what Claude Code will list, or why nothing is registered. */\nfunction pluginLines(ctx: CommandContext, plugin: PluginRegistration): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (plugin.state === 'deferred') return [warn(`${plugin.reason ?? ''}`)];\n if (plugin.state === 'failed') {\n return [warn(`The Tenjin plugin was not registered: ${plugin.reason ?? 'unknown reason'}`)];\n }\n if (plugin.method === 'skills-dir') {\n return [\n ` Plugin ${plugin.id ?? ''} written to ${plugin.path ?? ''} (${plugin.fallbackReason ?? ''})`,\n ];\n }\n return [];\n}\n\n/** The settings install's line, when there is one. */\nfunction migrationLines(ctx: CommandContext, migration: Migration): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (migration.state === 'pending') {\n return [\n ` The settings install in ${migration.settingsPath} stays until the plugin has loaded (${migration.reason ?? ''}); \\`tenjin update\\` or \\`tenjin install\\` removes it then.`,\n ];\n }\n if (migration.state === 'blocked') {\n return [warn(`${migration.settingsPath} could not be read: ${migration.reason ?? ''}`)];\n }\n if (migration.state === 'done') {\n const removed = migration.removed;\n const status = statusLineNotice(migration);\n return [\n ` Removed the earlier settings setup from ${migration.settingsPath}: the plugin carries its hooks, permissions and server`,\n ...(status !== null ? [` ${status}`] : []),\n ...(removed?.warnings ?? []).map((w) => warn(w)),\n ];\n }\n return [];\n}\n\nfunction claudeLines(ctx: CommandContext, claude: ClaudeCodeState): string[] {\n if (claude.meetsFloor) return [];\n return [\n paint(\n ctx.io,\n 'yellow',\n `! Claude Code ${claude.version ?? ''} is older than the plugin needs. ${claude.fix ?? ''}`.trim(),\n ),\n ];\n}\n\n/**\n * A few lines a first-time user can read at a glance: it worked, here is your\n * wallet, here is the one thing to do next. Paths, steps and data-handling\n * detail stay in `--json` and the docs; the terminal only grows a line when\n * something needs the user.\n */\nfunction lines(\n ctx: CommandContext,\n s: {\n plugin: PluginRegistration;\n claude: ClaudeCodeState;\n migration: Migration;\n wallet: WalletOutcome;\n policy: SpendPolicy;\n approval?: SpendApproval;\n router: RouterCheck;\n },\n): string[] {\n const ok = paint(ctx.io, 'green', '✓');\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const limits = effectiveLimits(s.policy);\n const daily =\n s.policy.sessionBudgetAtomic === null ? 'no daily limit' : `$${limits.sessionBudget} a day`;\n const spend =\n s.approval !== undefined\n ? [\n warn('Automatic payments are off until the user approves a spend limit'),\n ` Ask the user in this session: ${s.approval.question}`,\n ` Yes: ${s.approval.approve}`,\n ` Other amounts: ${s.approval.own}`,\n ` No: run nothing, ${DECLINED.replaceAll('`', '')}`,\n ]\n : s.policy.maxAutoSpendAtomic === 0n\n ? [\n warn('Automatic payments are off: every paid lookup needs your approval'),\n ` To let the router pay without asking, run: ${AUTO_SPEND_FIX}`,\n ]\n : [` Automatic router: up to $${limits.maxAutoSpend} per call; daily limit ${daily}`];\n const router =\n s.router.status === 'ok'\n ? []\n : [\n warn(`The router did not answer: ${s.router.detail}`),\n ...(s.router.fix !== undefined ? [` ${s.router.fix}`] : []),\n ];\n return [\n s.plugin.state === 'failed'\n ? warn('Tenjin could not finish setting up Claude Code')\n : s.plugin.state === 'deferred'\n ? warn('Tenjin keeps its earlier Claude Code setup until Claude Code is updated')\n : `${ok} Tenjin is set up for Claude Code (plugin ${s.plugin.id ?? PLUGIN_ID})`,\n ...(s.plugin.scope === 'local' && s.plugin.state !== 'failed'\n ? [' For this project only; check it with: tenjin doctor --project']\n : []),\n ...walletLines(ctx, ok, s.wallet),\n ...spend,\n ...pluginLines(ctx, s.plugin),\n ...claudeLines(ctx, s.claude),\n ...migrationLines(ctx, s.migration),\n ...router,\n '',\n `Next: ${nextStep(s.plugin, s.claude, s.wallet, s.migration)}`,\n ];\n}\n\n/** \"Up to date\" only when nothing below it needs the user. */\nfunction refreshLines(\n ctx: CommandContext,\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n migration: Migration,\n): string[] {\n const issues = [\n ...pluginLines(ctx, plugin),\n ...claudeLines(ctx, claude),\n ...migrationLines(ctx, migration),\n ];\n const head =\n plugin.state === 'failed'\n ? paint(ctx.io, 'yellow', '! Tenjin is updated, but its plugin was not registered')\n : plugin.state === 'deferred'\n ? paint(ctx.io, 'yellow', '! Tenjin is updated; its plugin waits for a newer Claude Code')\n : `${paint(ctx.io, 'green', '✓')} Tenjin is up to date (plugin ${plugin.id ?? PLUGIN_ID})`;\n return [head, ...issues];\n}\n","import { lstatSync } from 'node:fs';\nimport { readdir, rm, rmdir } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport {\n CLI_SKILL_NAMES,\n readSkillFile,\n skillFrontmatterName,\n skillsDirsFor,\n} from './skill-wiring';\nimport { RETIRED_SKILL_NAMES, SHIPPED_SKILL_FILES } from './skills-source';\nimport { hasCode } from './errno';\n\nfunction isRealDirectory(path: string): boolean {\n try {\n return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n } catch (err) {\n // Linux reports ENOTDIR when an ancestor is a regular file. Nothing can\n // be installed below it, just as with an absent path. Do not follow symlinks.\n if (hasCode(err, 'ENOENT') || hasCode(err, 'ENOTDIR')) return false;\n throw err;\n }\n}\n\n/**\n * Remove only the files our named skill shipped (SKILL.md last, as the ownership\n * proof), then any directory they leave empty; preserve foreign skills and\n * adjacent user files.\n */\nexport async function removeOwnedSkill(\n name: string,\n skillsDir: string,\n): Promise<{ changed: boolean }> {\n if (!isRealDirectory(skillsDir)) {\n return { changed: false };\n }\n const skillDir = join(skillsDir, name);\n if (!isRealDirectory(skillDir)) {\n return { changed: false };\n }\n const path = join(skillDir, 'SKILL.md');\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return { changed: false };\n if (read.kind !== 'ok' || skillFrontmatterName(read.bytes.toString('utf8')) !== name) {\n return { changed: false }; // not ours to delete for sitting at our path\n }\n const shipped = (SHIPPED_SKILL_FILES as Record<string, readonly string[]>)[name] ?? [];\n const subdirs = new Set<string>();\n for (const rel of shipped) {\n if (rel === 'SKILL.md') continue;\n const file = join(skillDir, rel);\n // A symlinked `references/` would route the delete outside the skill.\n if (!isRealDirectory(dirname(file))) continue;\n subdirs.add(dirname(file));\n if (lstatSync(file, { throwIfNoEntry: false })?.isFile() === true) await rm(file);\n }\n await rm(path, { force: true });\n for (const dir of [...subdirs, skillDir].sort((a, b) => b.length - a.length)) {\n const rest = await readdir(dir).catch(() => null);\n if (rest !== null && rest.length === 0) await rmdir(dir).catch(() => undefined);\n }\n return { changed: true };\n}\n\n/**\n * Refresh retires obsolete skills without needing their old packaged source:\n * the retired names, and the shelf's CLI skills, whose `tenjin search` and\n * `tenjin publish` commands the router CLI does not ship.\n */\nexport async function removeRetiredSkills(home: string, project?: string): Promise<string[]> {\n const removed: string[] = [];\n const dirs = [...skillsDirsFor(home), ...(project ? skillsDirsFor(project) : [])];\n for (const dir of new Set(dirs)) {\n for (const name of [...RETIRED_SKILL_NAMES, ...CLI_SKILL_NAMES]) {\n if ((await removeOwnedSkill(name, dir)).changed) removed.push(join(dir, name));\n }\n }\n return removed;\n}\n","import { execFile } from 'node:child_process';\nimport { statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { delimiter, isAbsolute, join } from 'node:path';\n\n/**\n * CLAUDE CODE'S OWN COMMANDS, AND WHERE ITS CONFIG LIVES. Install, update,\n * uninstall and doctor register and read the plugin through `claude plugin`\n * and `claude mcp` rather than editing Claude Code's files, so every write is\n * Claude Code's and lands where it would put it. This module finds the binary,\n * runs it without a shell, and reads its `--json` answers. It never throws on a\n * failed command: each caller decides what a failure means.\n */\n\n/** The oldest Claude Code the plugin is built for: `mcp_tool` legs on a plugin server. */\nexport const CLAUDE_CODE_FLOOR = '2.1.287';\n\n/**\n * Claude Code's config directory: `CLAUDE_CONFIG_DIR` when set, else\n * `~/.claude`. Every path this CLI reads or writes for Claude Code goes through\n * here, so the plugin, the migration and doctor see the config the `claude`\n * commands they run see.\n */\nexport function claudeConfigDir(env: NodeJS.ProcessEnv, home: string = homedir()): string {\n const dir = env.CLAUDE_CONFIG_DIR;\n return dir !== undefined && dir.length > 0 ? dir : join(home, '.claude');\n}\n\n/** The user settings file, under {@link claudeConfigDir}. */\nexport function userSettingsPath(env: NodeJS.ProcessEnv, home: string = homedir()): string {\n return join(claudeConfigDir(env, home), 'settings.json');\n}\n\n/**\n * Where `claude mcp add -s user` writes: `.claude.json` inside\n * `CLAUDE_CONFIG_DIR` when it is set, else `~/.claude.json` beside `~/.claude`.\n */\nexport function userMcpFile(env: NodeJS.ProcessEnv, home: string = homedir()): string {\n const dir = env.CLAUDE_CONFIG_DIR;\n return dir !== undefined && dir.length > 0\n ? join(dir, '.claude.json')\n : join(home, '.claude.json');\n}\n\nexport interface ClaudeBinary {\n /** The absolute path this run executes. */\n path: string;\n /** `path` when found on PATH, `execpath` when it came from `CLAUDE_CODE_EXECPATH`. */\n source: 'path' | 'execpath';\n}\n\nfunction isFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * THE BINARY, WITHOUT ASKING ANYONE TO INSTALL IT: `claude` on PATH first,\n * then `CLAUDE_CODE_EXECPATH`, which Claude Code exports to the commands its\n * Bash tool runs (so an agent's install finds it even where PATH does not, as\n * in Claude Desktop). Null when neither exists; the caller then writes the\n * plugin folder, which needs no binary.\n */\nexport function findClaudeBinary(env: NodeJS.ProcessEnv): ClaudeBinary | null {\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of (env.PATH ?? '').split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n const candidate = join(part, `claude${ext}`);\n if (isFile(candidate)) return { path: candidate, source: 'path' };\n }\n }\n const exec = env.CLAUDE_CODE_EXECPATH;\n if (exec !== undefined && isAbsolute(exec) && isFile(exec)) {\n return { path: exec, source: 'execpath' };\n }\n return null;\n}\n\nexport interface ClaudeRun {\n /** The exit code, or null when the binary could not be started or was killed. */\n code: number | null;\n stdout: string;\n stderr: string;\n}\n\nexport interface ClaudeRunOptions {\n env: NodeJS.ProcessEnv;\n cwd: string;\n timeoutMs?: number;\n}\n\n/** One `claude` command, no shell. Never rejects. */\nexport function runClaude(\n bin: ClaudeBinary,\n args: string[],\n opts: ClaudeRunOptions,\n): Promise<ClaudeRun> {\n return new Promise((resolve) => {\n execFile(\n bin.path,\n args,\n {\n env: opts.env,\n cwd: opts.cwd,\n timeout: opts.timeoutMs ?? 30_000,\n maxBuffer: 4 * 1024 * 1024,\n windowsHide: true,\n },\n (err, stdout, stderr) => {\n const code =\n err === null\n ? 0\n : typeof (err as { code?: unknown }).code === 'number'\n ? (err as { code: number }).code\n : null;\n resolve({ code, stdout: String(stdout), stderr: String(stderr) });\n },\n );\n });\n}\n\n/**\n * The one result line a `--json` plugin command prints: the last stdout line\n * that parses as an object. Failures also print a human line on stderr, which\n * is ignored here.\n */\nexport function jsonResult(stdout: string): Record<string, unknown> | null {\n const lines = stdout.split('\\n').map((l) => l.trim());\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n const line = lines[i]!;\n if (!line.startsWith('{')) continue;\n try {\n const parsed = JSON.parse(line) as unknown;\n if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n\n/** A `--json` list (`plugin list`, `marketplace list`), or null when it is not one. */\nexport function jsonList(stdout: string): Record<string, unknown>[] | null {\n const start = stdout.indexOf('[');\n if (start === -1) return null;\n try {\n const parsed = JSON.parse(stdout.slice(start)) as unknown;\n return Array.isArray(parsed)\n ? parsed.filter(\n (row): row is Record<string, unknown> =>\n row !== null && typeof row === 'object' && !Array.isArray(row),\n )\n : null;\n } catch {\n return null;\n }\n}\n\n/** `2.1.296 (Claude Code)` to `2.1.296`. */\nexport function parseClaudeVersion(text: string): string | null {\n return /(\\d+)\\.(\\d+)\\.(\\d+)/.exec(text)?.[0] ?? null;\n}\n\n/** Is `version` at or above {@link CLAUDE_CODE_FLOOR}? */\nexport function meetsFloor(version: string, floor: string = CLAUDE_CODE_FLOOR): boolean {\n const a = version.split('.').map(Number);\n const b = floor.split('.').map(Number);\n for (let i = 0; i < 3; i += 1) {\n const x = a[i] ?? 0;\n const y = b[i] ?? 0;\n if (x !== y) return x > y;\n }\n return true;\n}\n\nexport interface ClaudeCodeState {\n binary: ClaudeBinary | null;\n /** The version `claude --version` printed, or null when it could not be read. */\n version: string | null;\n /** False only for a version read and found below the floor. */\n meetsFloor: boolean;\n /** What to do about it, worded for the session the agent runs in. */\n fix?: string;\n}\n\n/**\n * THE FLOOR'S FIX IS ONE THE AGENT RUNS: `claude update` updates the binary in\n * place, and a new session picks it up. Nobody is sent out of the session to\n * do it.\n */\nexport const CLAUDE_UPDATE_FIX =\n 'Run `claude update` in this session, then start a new Claude Code session so the newer version loads.';\n\n/** The binary and its version, read once per command. */\nexport async function readClaudeCode(\n env: NodeJS.ProcessEnv,\n cwd: string,\n find: (env: NodeJS.ProcessEnv) => ClaudeBinary | null = findClaudeBinary,\n): Promise<ClaudeCodeState> {\n const binary = find(env);\n if (binary === null) return { binary, version: null, meetsFloor: true };\n const run = await runClaude(binary, ['--version'], { env, cwd, timeoutMs: 15_000 });\n const version = run.code === 0 ? parseClaudeVersion(run.stdout) : null;\n const ok = version === null || meetsFloor(version);\n return {\n binary,\n version,\n meetsFloor: ok,\n ...(ok ? {} : { fix: CLAUDE_UPDATE_FIX }),\n };\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { inspectHooksFile } from '../lib/harness-hooks';\nimport { runClaude, type ClaudeBinary } from './claude-cli';\nimport { LEGACY_HOOK_TOOL, LEGACY_MCP_SERVER_NAME, LEGACY_REQUEST_TOOL } from './names';\nimport { classifyStatusLine, decomposeCommand, type StatusLineState } from './status-line-wiring';\n\n/**\n * THE SETTINGS-BASED INSTALL, READ AND REMOVED. Releases up to alpha.26 wrote\n * seven hook entries, an allow and a deny rule and a status line into\n * settings.json, and registered an `x402` MCP server with `claude mcp add`.\n * The plugin replaces all of it. `install` and `update` remove it only once the\n * plugin has proven to load on this machine, `uninstall` removes it outright,\n * and doctor only reads it.\n *\n * EXACT SHAPES ONLY. A hook handler is Tenjin's when it is an `mcp_tool` call\n * to the `x402` server's `hook` tool, or a command that is exactly\n * `tenjin hook <leg>` (optionally with a path). Any other command that merely\n * contains `tenjin hook` is the user's, kept and reported. Removal is handler\n * by handler, so a group holding a foreign handler beside ours keeps it. The\n * rules are touched only when the `x402` server is Tenjin's or gone, and a\n * status line only in a file that still held Tenjin's hooks, and only in the\n * exact shapes Tenjin wrote. A file is written only when something was removed\n * from it, and no key is ever added to it.\n *\n * SHIM: this module goes on or after 2026-12-01, the first release cut 30 or\n * more days after the plugin PR 2 ships, and doctor keeps naming an\n * unmigrated machine after that.\n */\n\nconst LEGACY_COMMAND_RE = /^(\\S*\\/)?tenjin hook [a-z]+$/;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** One handler, in an exact shape a settings install wrote. */\nexport function ownsLegacyHandler(handler: unknown): boolean {\n if (!isPlainObject(handler)) return false;\n if (handler.type === 'mcp_tool') {\n return handler.server === LEGACY_MCP_SERVER_NAME && handler.tool === 'hook';\n }\n const command = handler.command;\n return typeof command === 'string' && LEGACY_COMMAND_RE.test(command.trim());\n}\n\n/** A handler that mentions `tenjin hook` without being one of ours: reported, never removed. */\nfunction lookalike(handler: unknown): string | null {\n if (!isPlainObject(handler) || ownsLegacyHandler(handler)) return null;\n const command = handler.command;\n return typeof command === 'string' && command.includes('tenjin hook') ? command : null;\n}\n\nexport type McpEntryState = 'ok' | 'absent' | 'wrong-command' | 'unreadable';\n\n/**\n * What an entry named `x402` actually launches. The name proves nothing: a\n * stale entry pointing at another binary would read as a working request tool.\n */\nexport function classifyMcpEntry(entry: unknown): McpEntryState {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return 'absent';\n const { command, args } = entry as { command?: unknown; args?: unknown };\n if (typeof command !== 'string' || command.length === 0) return 'wrong-command';\n // The basename, so `/opt/homebrew/bin/tenjin` and a bare `tenjin` both pass.\n const binary = command.split(/[\\\\/]/).pop();\n const runsRouter =\n binary === 'tenjin' && Array.isArray(args) && args.length === 1 && args[0] === 'mcp';\n return runsRouter ? 'ok' : 'wrong-command';\n}\n\n/**\n * The `x402` entry in one registration file: `~/.claude.json` (or the one in\n * `CLAUDE_CONFIG_DIR`) for user scope, `<project>/.mcp.json` for project scope.\n * Only \"it is not there\" is an absence: a file that exists and cannot be read\n * or parsed says nothing about what is registered in it.\n */\nexport async function readLegacyMcpEntry(path: string): Promise<McpEntryState> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n return code === 'ENOENT' || code === 'ENOTDIR' ? 'absent' : 'unreadable';\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return 'unreadable';\n }\n const servers = (parsed as { mcpServers?: unknown } | null)?.mcpServers;\n if (servers === undefined) return 'absent';\n if (!isPlainObject(servers)) return 'unreadable';\n const entry = servers[LEGACY_MCP_SERVER_NAME];\n return entry === undefined ? 'absent' : classifyMcpEntry(entry);\n}\n\nexport interface LegacyInstall {\n settingsPath: string;\n /** The registration file the `x402` entry would be in. */\n mcpFile: string;\n /** Anything of the settings install left on this machine. */\n present: boolean;\n /** The events holding a handler of ours. */\n events: string[];\n allowRule: boolean;\n denyRule: boolean;\n statusLine: StatusLineState;\n mcp: McpEntryState;\n /** Commands that mention `tenjin hook` but are not ours, left in place. */\n lookalikes: string[];\n /** Set when the settings file could not be read; nothing is then known or removed. */\n unreadable?: string;\n}\n\n/** What the settings install left in one scope. Reads only. */\nexport async function inspectLegacyInstall(\n settingsPath: string,\n mcpFile: string,\n): Promise<LegacyInstall> {\n const mcp = await readLegacyMcpEntry(mcpFile);\n const base = {\n settingsPath,\n mcpFile,\n events: [] as string[],\n allowRule: false,\n denyRule: false,\n statusLine: 'absent' as StatusLineState,\n mcp,\n lookalikes: [] as string[],\n };\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { ...base, present: mcp === 'ok', unreadable: found.refusal.message };\n }\n const events = Object.entries(found.hooks)\n .filter(([, list]) => list.some((entry) => handlersOf(entry).some(ownsLegacyHandler)))\n .map(([event]) => event);\n const lookalikes = Object.values(found.hooks).flatMap((list) =>\n list.flatMap((entry) =>\n handlersOf(entry)\n .map(lookalike)\n .filter((c) => c !== null),\n ),\n );\n const rulesOurs = mcp === 'ok' || (mcp === 'absent' && events.length > 0);\n const allowRule = rulesOurs && listOf(found.settings, 'allow').includes(LEGACY_REQUEST_TOOL);\n const denyRule = rulesOurs && listOf(found.settings, 'deny').includes(LEGACY_HOOK_TOOL);\n const statusLine = events.length > 0 ? classifyStatusLine(found.settings.statusLine) : 'absent';\n const statusOurs = statusLine === 'ours' || statusLine === 'composed';\n return {\n ...base,\n present: events.length > 0 || allowRule || denyRule || statusOurs || mcp === 'ok',\n events,\n allowRule,\n denyRule,\n statusLine,\n lookalikes,\n };\n}\n\nfunction handlersOf(entry: unknown): unknown[] {\n return isPlainObject(entry) && Array.isArray(entry.hooks) ? entry.hooks : [];\n}\n\nfunction listOf(settings: Record<string, unknown>, key: 'allow' | 'deny'): unknown[] {\n const permissions = settings.permissions;\n if (!isPlainObject(permissions)) return [];\n const list = permissions[key];\n return Array.isArray(list) ? list : [];\n}\n\nexport interface LegacyRemoval {\n /** The events a handler of ours was taken out of. */\n events: string[];\n allowRule: boolean;\n denyRule: boolean;\n /** `removed` (ours alone), `restored` (the user's own command put back), or untouched. */\n statusLine: 'removed' | 'restored' | 'kept';\n /** The `x402` registration: removed, not there, or kept with the reason. */\n mcp: 'removed' | 'absent' | 'kept';\n wroteSettings: boolean;\n warnings: string[];\n}\n\nexport interface RemoveLegacyOptions {\n binary: ClaudeBinary | null;\n env: NodeJS.ProcessEnv;\n cwd: string;\n /** The `claude mcp` scope the `x402` entry was registered at. */\n mcpScope: 'user' | 'project';\n}\n\n/** Take out what {@link inspectLegacyInstall} found, under the exact-shape rules above. */\nexport async function removeLegacyInstall(\n found: LegacyInstall,\n opts: RemoveLegacyOptions,\n): Promise<LegacyRemoval> {\n const out: LegacyRemoval = {\n events: [],\n allowRule: false,\n denyRule: false,\n statusLine: 'kept',\n mcp: found.mcp === 'absent' ? 'absent' : 'kept',\n wroteSettings: false,\n warnings: [],\n };\n if (found.unreadable === undefined) await removeFromSettings(found, out);\n else out.warnings.push(found.unreadable);\n if (found.mcp === 'ok') await removeMcpEntry(opts, out);\n else if (found.mcp === 'wrong-command') {\n out.warnings.push(\n `an MCP server named ${LEGACY_MCP_SERVER_NAME} launches something else, so it is not Tenjin's and was left in place`,\n );\n } else if (found.mcp === 'unreadable') {\n out.warnings.push(`${found.mcpFile} could not be read, so nothing was removed from it`);\n }\n return out;\n}\n\nasync function removeFromSettings(found: LegacyInstall, out: LegacyRemoval): Promise<void> {\n const read = await inspectHooksFile(found.settingsPath);\n if ('refusal' in read) {\n out.warnings.push(read.refusal.message);\n return;\n }\n if (read.raw === null) return;\n const next: Record<string, unknown> = { ...read.settings };\n if (isPlainObject(read.settings.hooks)) {\n const hooks: Record<string, unknown> = {};\n for (const [event, list] of Object.entries(read.hooks)) {\n const kept: unknown[] = [];\n for (const entry of list) {\n const handlers = handlersOf(entry);\n const left = handlers.filter((h) => !ownsLegacyHandler(h));\n if (left.length === handlers.length) kept.push(entry);\n else if (left.length > 0) kept.push({ ...(entry as Record<string, unknown>), hooks: left });\n }\n if (kept.length !== list.length || kept.some((e, i) => e !== list[i])) out.events.push(event);\n // An event WE emptied loses its key; one that was already empty stays.\n if (kept.length > 0 || list.length === 0) hooks[event] = kept;\n }\n next.hooks = hooks;\n }\n if ((found.allowRule || found.denyRule) && isPlainObject(read.settings.permissions)) {\n const permissions = { ...read.settings.permissions };\n if (found.allowRule && Array.isArray(permissions.allow)) {\n permissions.allow = permissions.allow.filter((r) => r !== LEGACY_REQUEST_TOOL);\n out.allowRule = true;\n }\n if (found.denyRule && Array.isArray(permissions.deny)) {\n permissions.deny = permissions.deny.filter((r) => r !== LEGACY_HOOK_TOOL);\n out.denyRule = true;\n }\n next.permissions = permissions;\n }\n if (found.statusLine === 'ours') {\n delete next.statusLine;\n out.statusLine = 'removed';\n } else if (found.statusLine === 'composed' && isPlainObject(read.settings.statusLine)) {\n const command = read.settings.statusLine.command;\n const original = typeof command === 'string' ? decomposeCommand(command) : null;\n if (original !== null) {\n next.statusLine = { ...read.settings.statusLine, command: original };\n out.statusLine = 'restored';\n }\n }\n // Only a removal writes: a file holding nothing of ours keeps its bytes,\n // whatever its formatting.\n const removed =\n out.events.length > 0 || out.allowRule || out.denyRule || out.statusLine !== 'kept';\n if (!removed) return;\n const body = `${JSON.stringify(next, null, 2)}\\n`;\n const mode = await stat(read.path)\n .then((s) => ({ mode: s.mode & 0o777 }))\n .catch(() => ({}));\n // Compared again just before the rename: a concurrent edit is refused, not lost.\n if ((await readFile(read.path, 'utf8').catch(() => null)) !== read.raw) {\n out.warnings.push(`${read.path} changed while it was read, so it was left as it is`);\n Object.assign(out, { events: [], allowRule: false, denyRule: false, statusLine: 'kept' });\n return;\n }\n try {\n await writeFileAtomic(read.path, body, mode);\n out.wroteSettings = true;\n } catch (err) {\n out.warnings.push(err instanceof Error ? err.message : String(err));\n Object.assign(out, { events: [], allowRule: false, denyRule: false, statusLine: 'kept' });\n }\n}\n\n/**\n * THE `x402` REGISTRATION GOES THROUGH CLAUDE'S OWN COMMAND, and only after\n * this CLI's own read of that file found it launching `tenjin mcp`: a server\n * the read did not find is never removed by name, because another tool may\n * own one called `x402`. With no binary it is left and reported; the plugin's\n * server is namespaced and does not collide with it.\n */\nasync function removeMcpEntry(opts: RemoveLegacyOptions, out: LegacyRemoval): Promise<void> {\n if (opts.binary === null) {\n out.warnings.push(\n `the ${LEGACY_MCP_SERVER_NAME} MCP registration stays until a run with the claude binary removes it`,\n );\n return;\n }\n const run = await runClaude(\n opts.binary,\n ['mcp', 'remove', LEGACY_MCP_SERVER_NAME, '-s', opts.mcpScope],\n { env: opts.env, cwd: opts.cwd },\n );\n if (run.code === 0) out.mcp = 'removed';\n else {\n out.warnings.push(\n `claude mcp remove ${LEGACY_MCP_SERVER_NAME} did not succeed: ${(run.stderr || run.stdout).trim().slice(0, 200) || 'no output'}`,\n );\n }\n}\n\n/** The project-scope registration file. */\nexport function projectMcpFile(cwd: string): string {\n return join(cwd, '.mcp.json');\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { CliError } from '../lib/errors';\nimport { inspectHooksFile } from '../lib/harness-hooks';\n\n/**\n * The `statusLine` key in Claude Code's settings file. `install` no longer\n * sets it (a plugin cannot), so the router reads this module only to recognise\n * and take back a status line an earlier release wrote (`legacy-install.ts`).\n * The writer below stays for the shelf code that still imports it.\n *\n * The one setting the live footer needs, and the one piece of harness\n * configuration a person is most likely to have already set for themselves.\n *\n * SO IT IS NEVER REPLACED. An existing status line that is not ours is left\n * exactly as it is, and `install` prints the composition line instead;\n * `--status-line compose` writes that line only because it was asked for by\n * name. Writing over it and saying so in the output destroys a configuration\n * this CLI did not create.\n *\n * OWNERSHIP IS ONE MARKER, the command naming `tenjin status-line`, used by\n * `install`, `install --refresh`, `uninstall` and `doctor` alike, so the four\n * can never disagree about which status line is Tenjin's.\n */\n\n/** The command `install` registers, in the shape the hook entries use: a plain\n * command line on PATH, with no path into this build's dist directory. */\nexport const STATUS_LINE_COMMAND = 'tenjin status-line';\n/** Claude Code re-runs the command on this interval, in seconds. */\nexport const STATUS_LINE_REFRESH_SECONDS = 1;\n/** The marker that makes a status line ours, composed or not. */\nconst OUR_MARKER = STATUS_LINE_COMMAND;\n\n/** What the user asked for, when they asked. Absent means the default path. */\nexport type StatusLineMode = 'own' | 'compose' | 'skip';\n\nconst MODES: readonly StatusLineMode[] = ['own', 'compose', 'skip'];\n\n/** `--status-line <mode>`, refused rather than guessed at. */\nexport function statusLineMode(value: string): StatusLineMode {\n const mode = MODES.find((known) => known === value);\n if (mode === undefined) {\n throw new CliError('USAGE', `--status-line takes ${MODES.join(', ')}, not \"${value}\".`, {\n fix: 'Run `tenjin install --status-line own`.',\n });\n }\n return mode;\n}\n\n/**\n * What is in the file: ours alone, ours appended to someone else's, someone\n * else's alone, or nothing.\n */\nexport type StatusLineState = 'ours' | 'composed' | 'foreign' | 'absent';\n\nexport interface StatusLineResult {\n path: string;\n state: StatusLineState;\n /** True when this run changed the file. */\n wrote: boolean;\n /** The command now registered, when one of ours is. */\n command?: string;\n /** The exact command to set by hand, printed when a foreign line is kept. */\n compose?: string;\n /** Why nothing was written, for a file this run would not touch. */\n warning?: string;\n}\n\nexport function classifyStatusLine(value: unknown): StatusLineState {\n if (value === null || value === undefined) return 'absent';\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n // A status line whose command this build cannot read is still the user's.\n if (typeof command !== 'string' || command.trim().length === 0) return 'foreign';\n if (command.trim() === OUR_MARKER) return 'ours';\n return command.includes(OUR_MARKER) ? 'composed' : 'foreign';\n}\n\nfunction ours(): Record<string, unknown> {\n return {\n type: 'command',\n command: STATUS_LINE_COMMAND,\n refreshInterval: STATUS_LINE_REFRESH_SECONDS,\n };\n}\n\nconst shQuote = (value: string): string => `'${value.replaceAll(\"'\", String.raw`'\\''`)}'`;\nconst shUnquote = (value: string): string => value.replaceAll(String.raw`'\\''`, \"'\");\n\n/** The inner script, with the user's own command as the one hole in it. */\nfunction composedScript(existing: string): string {\n return [\n 'event=$(cat)',\n `yours=$(printf %s \"$event\" | ${existing})`,\n `tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND})`,\n 'printf %s \"$yours${tenjin:+ · $tenjin}\"',\n ].join('; ');\n}\n\n/**\n * The command a composition was built from, or null when this is not a\n * composition this build wrote. It is the exact inverse of\n * {@link composeCommand}: a hand-edited line matches nothing and is kept whole,\n * because guessing at someone's shell is how an uninstall breaks a prompt.\n */\nexport function decomposeCommand(command: string): string | null {\n const trimmed = command.trim();\n if (!trimmed.startsWith(\"sh -c '\") || !trimmed.endsWith(\"'\")) return null;\n const script = shUnquote(trimmed.slice(\"sh -c '\".length, -1));\n const prefix = 'event=$(cat); yours=$(printf %s \"$event\" | ';\n if (!script.startsWith(prefix)) return null;\n const rest = script.slice(prefix.length);\n const suffix = `); tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND}); printf %s \"$yours\\${tenjin:+ · $tenjin}\"`;\n if (!rest.endsWith(suffix)) return null;\n const existing = rest.slice(0, -suffix.length);\n return existing.length > 0 && composedScript(existing) === script ? existing : null;\n}\n\n/**\n * The user's status line with ours appended after a separator, on one line.\n *\n * The harness writes its event on stdin ONCE, so a composition cannot simply\n * run two commands in sequence: the event is captured first and replayed into\n * each. Ours contributes nothing when this session has no activity, and the\n * separator goes with it, so a quiet session looks exactly as it did before.\n */\nexport function composeCommand(existing: string): string {\n return `sh -c ${shQuote(composedScript(existing))}`;\n}\n\n/** The command a status-line setting runs, in either shape it can take. */\nfunction commandOf(value: unknown): string | undefined {\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n return typeof command === 'string' && command.trim().length > 0 ? command.trim() : undefined;\n}\n\n/** What a foreign status line's owner is told to set, verbatim. */\nfunction composeFor(value: unknown): string | undefined {\n const command = commandOf(value);\n return command === undefined ? undefined : composeCommand(command);\n}\n\nexport interface EnsureStatusLineOpts {\n mode?: StatusLineMode;\n /**\n * `install --refresh` and the refresh `tenjin update` spawns: converge a\n * status line of ours that is already registered, and ADD NOTHING. A machine\n * whose owner removed ours, or never had it, keeps that answer across every\n * upgrade without a second place to record it.\n */\n refreshOnly?: boolean;\n}\n\nexport async function ensureStatusLine(\n settingsPath: string,\n opts: EnsureStatusLineOpts = {},\n): Promise<StatusLineResult> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', wrote: false, warning: found.refusal.reason };\n }\n const { path, settings } = found;\n const current = settings.statusLine;\n const state = classifyStatusLine(current);\n if (opts.mode === 'skip') {\n return { path, state, wrote: false, ...(state === 'foreign' ? kept(current) : {}) };\n }\n if (opts.mode === 'compose') {\n const composed = composeFor(current);\n if (composed === undefined) return writeStatusLine(found, ours(), 'ours');\n // THEIR OBJECT, with the command swapped. Rebuilding it from ours would\n // drop whatever else they had set on it, such as their own padding.\n const base =\n typeof current === 'object' && current !== null && !Array.isArray(current)\n ? (current as Record<string, unknown>)\n : ours();\n return state === 'composed'\n ? { path, state, wrote: false, command: composed }\n : writeStatusLine(found, { ...base, command: composed }, 'composed');\n }\n if (state === 'foreign') {\n // NOT REPLACED, AND NOT WRITTEN AROUND. The user keeps what they set, and\n // gets the one command that adds ours to it.\n return { path, state, wrote: false, ...kept(current) };\n }\n if (state === 'composed') return { path, state, wrote: false };\n if (state === 'absent' && opts.refreshOnly === true) {\n return { path, state, wrote: false };\n }\n return writeStatusLine(found, ours(), 'ours');\n}\n\n/** `uninstall`: take out a status line of OURS, and only if it is ours alone. */\nexport async function removeStatusLine(settingsPath: string): Promise<StatusLineResult> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', wrote: false, warning: found.refusal.reason };\n }\n const { path, settings } = found;\n const current = settings.statusLine;\n const state = classifyStatusLine(current);\n if (state === 'ours') return writeStatusLine(found, undefined, 'absent');\n // A COMPOSED LINE IS MOSTLY THE USER'S TEXT, so it is not deleted: the half\n // this build wrote is unwound and their own command is put back exactly as it\n // was. A composition that was hand-edited since inverts to nothing and is\n // left whole, because guessing at someone's shell is the worse failure.\n if (state === 'composed') {\n const command = commandOf(current);\n const original = command === undefined ? null : decomposeCommand(command);\n if (original === null) return { path, state, wrote: false };\n const kept = { ...(current as Record<string, unknown>), command: original };\n return writeStatusLine(found, kept, 'foreign');\n }\n return { path, state, wrote: false };\n}\n\n/** What `doctor` reports, without writing anything. */\nexport async function inspectStatusLine(\n settingsPath: string,\n): Promise<{ path: string; state: StatusLineState; warning?: string }> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', warning: found.refusal.reason };\n }\n return { path: found.path, state: classifyStatusLine(found.settings.statusLine) };\n}\n\nfunction kept(current: unknown): { compose?: string } {\n const compose = composeFor(current);\n return compose === undefined ? {} : { compose };\n}\n\ntype Inspection = { path: string; raw: string | null; settings: Record<string, unknown> };\n\n/**\n * One key, written through the same read-compare-write the hooks writer uses:\n * every other key is copied through in its original order, the bytes are\n * re-read before the rename so a concurrent edit is refused rather than lost,\n * and the file keeps its mode.\n */\nasync function writeStatusLine(\n found: Inspection,\n value: Record<string, unknown> | undefined,\n state: StatusLineState,\n): Promise<StatusLineResult> {\n const { path, raw, settings } = found;\n const next: Record<string, unknown> = { ...settings };\n if (value === undefined) delete next.statusLine;\n else next.statusLine = value;\n const body = `${JSON.stringify(next, null, 2)}\\n`;\n const result: StatusLineResult = {\n path,\n state,\n wrote: false,\n ...(typeof value?.command === 'string' ? { command: value.command } : {}),\n };\n if (body === raw) return result;\n const mode = await stat(path)\n .then((s) => ({ mode: s.mode & 0o777 }))\n .catch(() => ({}));\n if (raw !== null && (await readFile(path, 'utf8').catch(() => null)) !== raw) {\n return {\n ...result,\n state: classifyStatusLine(settings.statusLine),\n warning: 'changed-since-read',\n };\n }\n try {\n await writeFileAtomic(path, body, mode);\n } catch (err) {\n return {\n ...result,\n state: classifyStatusLine(settings.statusLine),\n warning: err instanceof Error ? err.message : String(err),\n };\n }\n return { ...result, wrote: true };\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { versionFreeEntry } from '../commands/update';\nimport {\n claudeConfigDir,\n jsonList,\n jsonResult,\n runClaude,\n type ClaudeBinary,\n type ClaudeRun,\n} from './claude-cli';\nimport { MARKETPLACE_NAME, PLUGIN_ID, PLUGIN_NAME, SKILLS_DIR_PLUGIN_ID } from './names';\nimport { PLUGIN_DIR, renderPluginFiles } from './plugin-files';\nimport {\n inspectPluginFolder,\n pluginFolderPath,\n removePluginFolder,\n writePluginFolder,\n type FolderRemoval,\n} from './plugin-folder';\n\n/**\n * REGISTERING THE PLUGIN, WITH NO STEP LEFT TO THE PERSON. With a `claude`\n * binary (on PATH, or the one Claude Code names in `CLAUDE_CODE_EXECPATH`):\n *\n * claude plugin marketplace add <package>/dist/hosts/claude --json\n * claude plugin install tenjin@tenjin --scope <scope> --json\n * claude plugin update tenjin@tenjin --scope <scope> --json (only when the version moved)\n *\n * The marketplace is a `directory` source read in place from the installed\n * package, so there is no git or network step and the plugin is the CLI's own\n * build. Each command is non-interactive, idempotent and answers one JSON line\n * (lab, Claude Code 2.1.296): a second `add` of the same folder is a no-op, an\n * `add` of a moved folder repoints the marketplace, and `install` of an\n * installed plugin reports both versions. No binary, or a command that fails:\n * the plugin is written as a folder under the config dir's `skills/`, which\n * Claude Code loads with no command at all.\n */\n\nexport type PluginScope = 'user' | 'local';\n\nexport interface RegistrationStep {\n command: string;\n ok: boolean;\n detail?: string;\n}\n\nexport interface PluginRegistration {\n /** `plugin` through Claude's commands, `skills-dir` as a folder, `none` when neither worked. */\n method: 'plugin' | 'skills-dir' | 'none';\n /** The id Claude Code lists it under. */\n id: string | null;\n scope: PluginScope;\n /**\n * `installed` (new), `updated` (the version moved), `current` (already this\n * build), `written` (the folder), `deferred` (left for a newer Claude Code,\n * with a settings install still routing), or `failed` (nothing registered).\n */\n state: 'installed' | 'updated' | 'current' | 'written' | 'deferred' | 'failed';\n /** The marketplace folder or the plugin folder. */\n path?: string;\n version: string;\n steps: RegistrationStep[];\n /** Why the folder was written instead of running the commands. */\n fallbackReason?: string;\n /** Why nothing was registered. */\n reason?: string;\n /** A folder an earlier fallback wrote, removed because the commands now registered the plugin. */\n supersededFolder?: FolderRemoval;\n}\n\nexport interface RegisterOptions {\n binary: ClaudeBinary | null;\n scope: PluginScope;\n /** The CLI version the plugin files carry. */\n version: string;\n env: NodeJS.ProcessEnv;\n home: string;\n cwd: string;\n /** The marketplace folder; defaults to this package's `dist/hosts/claude`. */\n hostsDir?: string | null;\n /** The CLI entry the folder fallback's commands run. Defaults to this package's `dist/index.js`. */\n cliEntry?: string;\n}\n\n/** Where the folder fallback lives for this scope. */\nexport function folderFor(scope: PluginScope, env: NodeJS.ProcessEnv, home: string, cwd: string) {\n return pluginFolderPath(scope === 'local' ? join(cwd, '.claude') : claudeConfigDir(env, home));\n}\n\nexport async function registerPlugin(opts: RegisterOptions): Promise<PluginRegistration> {\n const folder = folderFor(opts.scope, opts.env, opts.home, opts.cwd);\n const steps: RegistrationStep[] = [];\n let fallbackReason: string;\n if (opts.binary !== null) {\n const hosts = opts.hostsDir === undefined ? await packageHostsDir() : opts.hostsDir;\n if (hosts === null) {\n fallbackReason = 'this build carries no plugin marketplace folder (dist/hosts/claude)';\n } else {\n const done = await viaPluginCommands(opts.binary, hosts, opts, steps);\n if (done.ok) {\n // A folder an earlier fallback wrote would load as a second copy.\n const superseded = await removePluginFolder(folder);\n return {\n method: 'plugin',\n id: PLUGIN_ID,\n scope: opts.scope,\n state: done.state,\n path: hosts,\n version: opts.version,\n steps,\n ...(superseded.removed ? { supersededFolder: superseded } : {}),\n };\n }\n fallbackReason = done.reason;\n }\n // NO SECOND COPY. A plugin Claude Code already has (an earlier install\n // whose update just failed, or a `tenjin` from another marketplace) would\n // load beside the folder, and every event would run both sets of legs and\n // pay twice. It is left as it is, and the run reports the failure.\n const existing = await existingCopy(opts.binary, opts.env, opts.home, opts.cwd);\n if (existing !== null) {\n return {\n method: 'none',\n id: existing,\n scope: opts.scope,\n state: 'failed',\n version: opts.version,\n steps,\n reason: `${fallbackReason}; ${existing} is already in Claude Code and was left as it is, so no second copy was written`,\n };\n }\n } else {\n fallbackReason = 'no claude binary on PATH or in CLAUDE_CODE_EXECPATH';\n // A plugin Claude's commands registered earlier must not get a second copy.\n if (await installedThroughCommands(opts.env, opts.home)) {\n return {\n method: 'plugin',\n id: PLUGIN_ID,\n scope: opts.scope,\n state: 'current',\n version: opts.version,\n steps,\n fallbackReason: `${fallbackReason}; ${PLUGIN_ID} is already registered, so it was left as it is`,\n };\n }\n }\n const written = await writePluginFolder(\n folder,\n renderPluginFiles(opts.version, opts.cliEntry ?? packageCliEntry()),\n );\n if (written.state === 'written') {\n return {\n method: 'skills-dir',\n id: SKILLS_DIR_PLUGIN_ID,\n scope: opts.scope,\n state: 'written',\n path: folder,\n version: opts.version,\n steps,\n fallbackReason,\n };\n }\n return {\n method: 'none',\n id: null,\n scope: opts.scope,\n state: 'failed',\n path: folder,\n version: opts.version,\n steps,\n fallbackReason,\n reason: written.reason ?? 'the plugin folder could not be written',\n };\n}\n\ntype CommandsOutcome =\n { ok: true; state: 'installed' | 'updated' | 'current' } | { ok: false; reason: string };\n\nasync function viaPluginCommands(\n binary: ClaudeBinary,\n hosts: string,\n opts: RegisterOptions,\n steps: RegistrationStep[],\n): Promise<CommandsOutcome> {\n const run = (args: string[]) => runClaude(binary, args, { env: opts.env, cwd: opts.cwd });\n const scopeArgs = ['--scope', opts.scope];\n // The marketplace is declared at user scope by default, the form every\n // release since 2.1.287 takes; only a project install names its scope.\n const marketplaceScope = opts.scope === 'user' ? [] : scopeArgs;\n\n // A marketplace called `tenjin` that is not this package's is somebody\n // else's, and `add` would repoint it: it is left alone. So is every\n // marketplace when the list cannot be read, because an unread list cannot\n // prove there is no such marketplace to repoint.\n const known = await run(['plugin', 'marketplace', 'list', '--json']);\n const listed = known.code === 0 ? jsonList(known.stdout) : null;\n steps.push({\n command: 'claude plugin marketplace list --json',\n ok: listed !== null,\n ...(listed === null ? { detail: commandDetail(known) } : {}),\n });\n if (listed === null) {\n return {\n ok: false,\n reason: `claude plugin marketplace list could not be read (${commandDetail(known)}), so no marketplace was added or repointed`,\n };\n }\n const existing = listed.find((m) => m.name === MARKETPLACE_NAME);\n if (existing !== undefined && !(await ownMarketplace(existing))) {\n return {\n ok: false,\n reason: `a marketplace named ${MARKETPLACE_NAME} that this CLI did not add is already configured, so it was left as it is`,\n };\n }\n\n const add = await step(\n steps,\n ['plugin', 'marketplace', 'add', hosts, '--json', ...marketplaceScope],\n run,\n );\n if (!add.ok) return { ok: false, reason: `claude plugin marketplace add failed: ${add.detail}` };\n const install = await step(steps, ['plugin', 'install', PLUGIN_ID, ...scopeArgs, '--json'], run);\n if (!install.ok) return { ok: false, reason: `claude plugin install failed: ${install.detail}` };\n const installed = install.result?.installedVersion;\n const available = install.result?.availableVersion;\n if (typeof installed !== 'string' || typeof available !== 'string') {\n return { ok: true, state: 'installed' };\n }\n if (installed === available) return { ok: true, state: 'current' };\n const update = await step(steps, ['plugin', 'update', PLUGIN_ID, ...scopeArgs, '--json'], run);\n if (!update.ok) return { ok: false, reason: `claude plugin update failed: ${update.detail}` };\n return { ok: true, state: 'updated' };\n}\n\nasync function step(\n steps: RegistrationStep[],\n args: string[],\n run: (args: string[]) => Promise<ClaudeRun>,\n): Promise<{ ok: boolean; detail: string; result: Record<string, unknown> | null }> {\n const out = await run(args);\n const result = jsonResult(out.stdout);\n const ok =\n out.code === 0 && (result === null || result.outcome === undefined || result.outcome === 'ok');\n const detail = commandDetail(out, result);\n steps.push({ command: `claude ${args.join(' ')}`, ok, ...(ok ? {} : { detail }) });\n return { ok, detail, result };\n}\n\n/** What a failed command said: its JSON message, else its output, else how it ended. */\nfunction commandDetail(out: ClaudeRun, result: Record<string, unknown> | null = null): string {\n if (typeof result?.message === 'string') return result.message;\n const text = (out.stderr || out.stdout).trim().slice(0, 300);\n if (text.length > 0) return text;\n return out.code === null ? 'the command could not be run' : `exit ${out.code}`;\n}\n\n/**\n * Is this marketplace one `install` added? A directory source whose plugin\n * folder carries the `tenjin-cli` marker in its manifest, or, when that folder\n * is gone (a package manager removed the old version's directory), one whose\n * path is a `tenjin-cli` package's `dist/hosts/claude`.\n */\nexport async function ownMarketplace(row: Record<string, unknown>): Promise<boolean> {\n const path = typeof row.path === 'string' ? row.path : undefined;\n if (row.source !== 'directory' || path === undefined) return false;\n if ((await stat(path).catch(() => null)) === null) {\n return /tenjin-cli[\\\\/]dist[\\\\/]hosts[\\\\/]claude$/.test(path);\n }\n return (await inspectPluginFolder(join(path, PLUGIN_DIR))) === 'ours';\n}\n\n/**\n * A `tenjin` plugin Claude Code already holds that a folder would duplicate:\n * any enabled `tenjin@<marketplace>`. The folder's own `tenjin@skills-dir` is\n * not a duplicate, since writing the folder updates it in place. When the list\n * cannot be read, Claude Code's own record of installed plugins answers.\n */\nasync function existingCopy(\n binary: ClaudeBinary,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<string | null> {\n const out = await runClaude(binary, ['plugin', 'list', '--json'], { env, cwd });\n const listed = out.code === 0 ? jsonList(out.stdout) : null;\n if (listed === null) return (await installedThroughCommands(env, home)) ? PLUGIN_ID : null;\n const row = listed.find(\n (p) =>\n typeof p.id === 'string' &&\n p.id.startsWith(`${PLUGIN_NAME}@`) &&\n p.id !== SKILLS_DIR_PLUGIN_ID &&\n p.enabled === true,\n );\n return typeof row?.id === 'string' ? row.id : null;\n}\n\n/** Claude Code's own record of installed plugins, read when no binary can be asked. */\nasync function installedThroughCommands(env: NodeJS.ProcessEnv, home: string): Promise<boolean> {\n try {\n const raw = await readFile(\n join(claudeConfigDir(env, home), 'plugins', 'installed_plugins.json'),\n 'utf8',\n );\n const plugins = (JSON.parse(raw) as { plugins?: unknown }).plugins;\n return plugins !== null && typeof plugins === 'object' && PLUGIN_ID in plugins;\n } catch {\n return false;\n }\n}\n\n/**\n * THIS PACKAGE'S MARKETPLACE FOLDER, `dist/hosts/claude`, beside the bundle\n * that is running. Under pnpm the running path pins a version\n * (`.pnpm/tenjin-cli@<v>/...`), and a marketplace registered there would point\n * at a directory the next upgrade deletes, so the version-free path beside the\n * store is used when it exists, as `tenjin update` does for its re-exec.\n */\nexport async function packageHostsDir(\n moduleDir: string = dirname(fileURLToPath(import.meta.url)),\n): Promise<string | null> {\n const catalog = join(moduleDir, 'hosts', 'claude', '.claude-plugin', 'marketplace.json');\n const stable = versionFreeEntry(catalog) ?? catalog;\n if ((await stat(stable).catch(() => null))?.isFile() !== true) return null;\n return dirname(dirname(stable));\n}\n\n/**\n * THIS PACKAGE'S CLI ENTRY, `dist/index.js` beside the running bundle, for a\n * plugin folder outside the package. The version-free path under pnpm, as\n * {@link packageHostsDir} uses, so an upgrade does not strand it.\n */\nexport function packageCliEntry(\n moduleDir: string = dirname(fileURLToPath(import.meta.url)),\n): string {\n const entry = join(moduleDir, 'index.js');\n return versionFreeEntry(entry) ?? entry;\n}\n\n/** Doctor's and the migration's read: is the plugin installed and enabled? */\nexport interface PluginListing {\n /** The row for `tenjin@tenjin` or `tenjin@skills-dir`, when Claude Code lists one. */\n id: string | null;\n enabled: boolean;\n version: string | null;\n /** False when the list itself could not be read. */\n read: boolean;\n}\n\nexport async function readPluginListing(\n binary: ClaudeBinary,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): Promise<PluginListing> {\n const out = await runClaude(binary, ['plugin', 'list', '--json'], { env, cwd });\n const rows = out.code === 0 ? jsonList(out.stdout) : null;\n if (rows === null) return { id: null, enabled: false, version: null, read: false };\n const row =\n rows.find((r) => r.id === PLUGIN_ID && r.enabled === true) ??\n rows.find((r) => r.id === SKILLS_DIR_PLUGIN_ID && r.enabled === true) ??\n rows.find((r) => r.id === PLUGIN_ID || r.id === SKILLS_DIR_PLUGIN_ID);\n if (row === undefined) return { id: null, enabled: false, version: null, read: true };\n return {\n id: String(row.id),\n enabled: row.enabled === true,\n version: typeof row.version === 'string' ? row.version : null,\n read: true,\n };\n}\n\n/** Is a folder of ours there for this scope? */\nexport async function folderState(\n scope: PluginScope,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<{ path: string; state: 'absent' | 'ours' | 'foreign' }> {\n const path = folderFor(scope, env, home, cwd);\n return { path, state: await inspectPluginFolder(path) };\n}\n","import { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { HOOK_TOOL, hookToolInput, type HookKind } from './hook-tool';\nimport {\n MARKETPLACE_NAME,\n MCP_SERVER_NAME,\n PLUGIN_HOOK_TOOL,\n PLUGIN_NAME,\n PLUGIN_SERVER,\n REQUEST_TOOL,\n} from './names';\n\n/**\n * THE CLAUDE CODE PLUGIN, AS FILES. `tenjin install` registers it with Claude\n * Code's own `claude plugin` commands from the package's `dist/hosts/claude`\n * folder, which the build renders from this module, and writes the same plugin\n * folder under the config dir's `skills/` when there is no `claude` binary to\n * run. The checked-in `hosts/claude/` templates are pinned to this render by a\n * test, so the two cannot drift.\n *\n * NOTHING HERE IMPORTS MORE THAN THE NAMES AND THE PRODUCTION ORIGIN:\n * `tsup.config.ts` loads this module to render the shipped files, and its\n * import graph is the build's.\n */\n\n/**\n * The harness's kill budget for each routing leg: a stuck server never holds a\n * prompt longer than this. Every wait inside the leg is cut from it: the gate's\n * 3.5 s, which holds the paid path's 402, the reads before a deposit and the\n * paid request, with 500 ms left for the transcript read and the reply\n * (`wire.test.ts` pins the sum). A whole leg whose call carried a deposit took\n * 2.8 to 3.3 s on Base Sepolia, so it fits; a slower one (a wallet unlock, a\n * slow settlement) loses only that prompt's hint, and the SDK recovers the\n * channel on the next call.\n */\nexport const ROUTE_HOOK_TIMEOUT_SECONDS = 5;\n/**\n * The after-call entries' kill budget, longer than the rest for the one wait\n * a leg makes: a search the pre-call leg is fetching free docs for waits up to\n * `AUGMENT_WAIT_MS` (9 s) for them, and when none came back and the search was\n * short, the gate's 3.5 s follow, with startup to spare (`wire.test.ts` pins\n * the sum). Every other after-call event returns as fast as before, so the\n * number is a ceiling, not a cost.\n */\nexport const AFTER_CALL_TIMEOUT_SECONDS = 15;\n/** The `alive` leg and the two permission answers do no network work. */\nexport const LOCAL_HOOK_TIMEOUT_SECONDS = 5;\n\n/** The subagent tool, under its current name and its older one. */\nexport const DELEGATION_MATCHER = 'Agent|Task';\n/** The native tools both native arms watch. */\nexport const NATIVE_MATCHER = 'WebSearch|WebFetch';\n/** The host's question to the user, watched before it is asked and after. */\nexport const ASK_MATCHER = 'AskUserQuestion';\n\n/**\n * EVERY COMMAND RUNS `node` IN EXEC FORM, with no shell (see `hook-form.ts`).\n * The shipped plugin loads in place from the package's `dist/hosts/claude/tenjin`,\n * so the bundle's entry is three folders above `${CLAUDE_PLUGIN_ROOT}`, which\n * Claude Code substitutes into each argument, and the checked-in template\n * stays static. The folder fallback lives under the config dir instead, and\n * `install` renders it with the absolute entry of the CLI that wrote it.\n */\nexport const PLUGIN_ROOT_ENTRY = '${CLAUDE_PLUGIN_ROOT}/../../../index.js';\n\n/** A process Claude Code spawns directly: a hook's `command` and `args`, or a stdio server's. */\nexport interface ExecLaunch {\n command: string;\n args: string[];\n}\n\n/** The CLI run by `node` from its entry script, never through the `tenjin` shim. */\nexport function cliLaunch(args: readonly string[], entry: string = PLUGIN_ROOT_ENTRY): ExecLaunch {\n return { command: 'node', args: [entry, ...args] };\n}\n\n/**\n * The `alive` leg: the plugin's `SessionStart` entry, so it runs before any\n * other event of a session. It marks the session as one the plugin serves, so\n * a settings-install leg in the same session stays silent, and stamps the\n * machine as one the plugin has loaded on, which the migration waits for. A\n * command, not an `mcp_tool` call: a session's MCP servers may still be\n * connecting when `SessionStart` fires, and a command needs nothing running.\n */\nexport const ALIVE_ARGS = ['hook', 'alive'] as const;\n\n/** A PreToolUse answer, as a hook command's stdout carries it. */\nfunction permissionAnswer(decision: 'allow' | 'deny', reason: string): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: 'PreToolUse',\n permissionDecision: decision,\n permissionDecisionReason: reason,\n },\n });\n}\n\n/** A fixed answer `node -e` prints from its own argument: no shell, no CLI, no quoting. */\nexport const PRINT_ARGUMENT = 'process.stdout.write(process.argv[1])';\n\nfunction printed(answer: string): ExecLaunch {\n return { command: 'node', args: ['-e', PRINT_ARGUMENT, answer] };\n}\n\n/**\n * THE HOOK LEGS' TOOL IS DENIED TO THE MODEL. Its event fields are plain\n * arguments, so the model calling it could forge a routing leg. This blocking\n * hook replaces the settings install's `permissions.deny` rule: a plugin cannot\n * carry permission rules, and a blocking hook takes precedence over allow rules\n * in every mode, bypass included, while Claude Code's own `mcp_tool` hook calls\n * still run (lab, Claude Code 2.1.296). The tool stays in the model's list. The\n * tool's transcript check (`admitHookEvent`) stays for a machine with hooks off.\n */\nexport const DENY_HOOK = printed(\n permissionAnswer(\n 'deny',\n `Only the Tenjin hooks call this tool. To make a lookup, call ${REQUEST_TOOL}.`,\n ),\n);\n\n/**\n * THE REQUEST TOOL IS ALLOWED BY THE PLUGIN ITSELF, replacing the settings\n * install's `permissions.allow` rule, so an install needs no rule the user\n * adds. A hook's allow never overrides the user's own `deny` or `ask` rule for\n * the tool. The tool still pays only within the local spend policy, and an\n * amount over it returns `needs_approval` with nothing paid.\n */\nexport const ALLOW_HOOK = printed(permissionAnswer('allow', 'Tenjin lookup'));\n\n/** One routing leg: Claude Code calls the plugin server's `hook` tool. */\nfunction leg(kind: HookKind, timeout = ROUTE_HOOK_TIMEOUT_SECONDS): unknown[] {\n return [\n {\n type: 'mcp_tool',\n server: PLUGIN_SERVER,\n tool: HOOK_TOOL,\n input: hookToolInput(kind),\n timeout,\n },\n ];\n}\n\nfunction command(launch: ExecLaunch): unknown[] {\n return [{ type: 'command', ...launch, timeout: LOCAL_HOOK_TIMEOUT_SECONDS }];\n}\n\n/**\n * The seven routing legs. The native tools are routed twice over one lookup:\n * BEFORE the call, with a line pointing to a paid lookup when one fits; and\n * AFTER it, only when it came back short and nothing was said before, or to\n * add the free docs the pre-call arm fetched to a search's results. A failed\n * call fires PostToolUseFailure rather than PostToolUse, so the second takes\n * both. The host's question to the user is routed the same two ways: before it\n * is asked, when a service could stand in for what it asks for, and after,\n * with the user's answers read as their own words.\n */\nexport function routerHookPlan(): { event: string; matcher?: string; hooks: unknown[] }[] {\n const afterCall = () => leg('shortfall', AFTER_CALL_TIMEOUT_SECONDS);\n return [\n { event: 'UserPromptSubmit', hooks: leg('prompt') },\n { event: 'PreToolUse', matcher: NATIVE_MATCHER, hooks: leg('native') },\n { event: 'PreToolUse', matcher: DELEGATION_MATCHER, hooks: leg('agent') },\n { event: 'PostToolUse', matcher: NATIVE_MATCHER, hooks: afterCall() },\n { event: 'PostToolUseFailure', matcher: NATIVE_MATCHER, hooks: afterCall() },\n { event: 'PreToolUse', matcher: ASK_MATCHER, hooks: leg('ask') },\n { event: 'PostToolUse', matcher: ASK_MATCHER, hooks: leg('answer') },\n ];\n}\n\n/** `hooks/hooks.json`: the `alive` leg, the seven routing legs and the two permission answers. */\nexport function renderPluginHooks(entry: string = PLUGIN_ROOT_ENTRY): {\n hooks: Record<string, unknown[]>;\n} {\n const plan = [\n { event: 'SessionStart', hooks: command(cliLaunch(ALIVE_ARGS, entry)) },\n ...routerHookPlan(),\n { event: 'PreToolUse', matcher: PLUGIN_HOOK_TOOL, hooks: command(DENY_HOOK) },\n { event: 'PreToolUse', matcher: REQUEST_TOOL, hooks: command(ALLOW_HOOK) },\n ];\n const hooks: Record<string, unknown[]> = {};\n for (const { event, hooks: handlers, ...rest } of plan) {\n (hooks[event] ??= []).push({ ...rest, hooks: handlers });\n }\n return { hooks };\n}\n\n/**\n * `.mcp.json`: the server Claude Code starts for the plugin, the CLI's entry\n * run by `node`, which Windows can spawn where it cannot spawn the shim.\n *\n * `--plugin` KEEPS IT FROM BEING SUPPRESSED. Claude Code drops a plugin's MCP\n * server whose command and arguments match a server the user configured, and\n * a settings install's `x402` entry runs `tenjin mcp`; with the same command\n * the plugin's `router` server would not start while the two coexist, its legs\n * would fail, and the old ones stay silent (checked on Claude Code 2.1.296).\n */\nexport const PLUGIN_MCP_ARGS = ['mcp', '--plugin'] as const;\n\nexport function renderPluginMcp(entry: string = PLUGIN_ROOT_ENTRY): {\n mcpServers: Record<string, unknown>;\n} {\n return { mcpServers: { [MCP_SERVER_NAME]: cliLaunch(PLUGIN_MCP_ARGS, entry) } };\n}\n\n/** The key whose presence marks a plugin manifest as one this CLI wrote. */\nexport const OWNER_MARKER = 'tenjin-cli';\n/** The marker's value in the checked-in templates, which carry no version. */\nconst UNBUILT = 'source';\n\nconst DESCRIPTION =\n 'Tenjin picks the right tool when your agent needs one, and one wallet on this machine pays for every call.';\n\n/**\n * `.claude-plugin/plugin.json`. The version is the CLI's, stamped at build time,\n * so Claude Code's plugin list names the build that runs; the checked-in\n * template carries none. `metadata[tenjin-cli]` is the ownership marker the\n * folder fallback, `update` and `uninstall` check before they touch a folder.\n */\nexport function renderPluginManifest(version?: string): Record<string, unknown> {\n return {\n name: PLUGIN_NAME,\n ...(version !== undefined ? { version } : {}),\n description: DESCRIPTION,\n author: { name: 'Tenjin', url: PRODUCTION_ORIGIN },\n homepage: `${PRODUCTION_ORIGIN}/agents`,\n repository: 'https://github.com/BackTrackCo/tenjin-agent',\n metadata: { [OWNER_MARKER]: version ?? UNBUILT },\n };\n}\n\n/** The plugin's folder inside the marketplace folder. */\nexport const PLUGIN_DIR = PLUGIN_NAME;\n\n/** `.claude-plugin/marketplace.json`: one plugin, read in place from the package. */\nexport function renderMarketplace(version?: string): Record<string, unknown> {\n return {\n name: MARKETPLACE_NAME,\n owner: { name: 'Tenjin', url: PRODUCTION_ORIGIN },\n description: \"Tenjin's tool router for Claude Code, installed by `tenjin install`.\",\n ...(version !== undefined ? { metadata: { version } } : {}),\n plugins: [\n {\n name: PLUGIN_NAME,\n source: `./${PLUGIN_DIR}`,\n description: DESCRIPTION,\n ...(version !== undefined ? { version } : {}),\n },\n ],\n };\n}\n\n/**\n * EVERY FILE THE PLUGIN FOLDER HOLDS, relative to the plugin's root, and the\n * only paths install, update and uninstall ever write or unlink in a folder.\n * The manifest is last: a crash mid-write never leaves a manifest pointing at\n * parts that are not there yet.\n */\nexport const PLUGIN_FILES = [\n '.mcp.json',\n 'hooks/hooks.json',\n '.claude-plugin/plugin.json',\n] as const;\n\nconst json = (value: unknown): string => `${JSON.stringify(value, null, 2)}\\n`;\n\n/**\n * The plugin folder's files, by {@link PLUGIN_FILES} path. `entry` is the CLI\n * entry the commands run, {@link PLUGIN_ROOT_ENTRY} unless the folder lives\n * outside the package.\n */\nexport function renderPluginFiles(version?: string, entry?: string): Record<string, string> {\n return {\n '.mcp.json': json(renderPluginMcp(entry)),\n 'hooks/hooks.json': json(renderPluginHooks(entry)),\n '.claude-plugin/plugin.json': json(renderPluginManifest(version)),\n };\n}\n\n/** The marketplace folder's files: its catalog and the plugin under {@link PLUGIN_DIR}. */\nexport function renderHostFiles(version?: string): Record<string, string> {\n const plugin = Object.entries(renderPluginFiles(version)).map(\n ([path, body]) => [`${PLUGIN_DIR}/${path}`, body] as const,\n );\n return {\n '.claude-plugin/marketplace.json': json(renderMarketplace(version)),\n ...Object.fromEntries(plugin),\n };\n}\n","import { lstat, readdir, readFile, rm, rmdir } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { PLUGIN_NAME } from './names';\nimport { OWNER_MARKER, PLUGIN_FILES } from './plugin-files';\n\n/**\n * THE FOLDER FALLBACK: the plugin as a folder under a config dir's `skills/`,\n * which Claude Code loads in place as `tenjin@skills-dir` with no `claude`\n * command at all (lab, 2026-10-09: the manifest's name wins over the folder's).\n * `install` writes it only where it cannot run `claude plugin`.\n *\n * OWNERSHIP RULES. Only `tenjin-router/` is ever touched, never `skills/tenjin`,\n * where tenjin.sh tells readers to drop its hosted skill. The folder is ours\n * only when it is a real directory (never followed through a link) whose\n * manifest names `tenjin` and carries the `tenjin-cli` marker. Inside it, only\n * the paths in {@link PLUGIN_FILES} are written or unlinked, so a user's own\n * `skills/` or `commands/` there survive every update and uninstall.\n */\n\nexport const FOLDER_NAME = 'tenjin-router';\n\n/** `<base>/skills/tenjin-router`, for a config dir or a project's `.claude`. */\nexport function pluginFolderPath(base: string): string {\n return join(base, 'skills', FOLDER_NAME);\n}\n\nexport type FolderState = 'absent' | 'ours' | 'foreign';\n\nexport async function inspectPluginFolder(dir: string): Promise<FolderState> {\n const entry = await lstat(dir).catch(() => null);\n if (entry === null) return 'absent';\n if (!entry.isDirectory() || entry.isSymbolicLink()) return 'foreign';\n try {\n const manifest = JSON.parse(\n await readFile(join(dir, '.claude-plugin', 'plugin.json'), 'utf8'),\n ) as { name?: unknown; metadata?: Record<string, unknown> };\n const marked =\n manifest.metadata !== null &&\n typeof manifest.metadata === 'object' &&\n OWNER_MARKER in manifest.metadata;\n return manifest.name === PLUGIN_NAME && marked ? 'ours' : 'foreign';\n } catch {\n return 'foreign';\n }\n}\n\nexport interface FolderWrite {\n path: string;\n state: 'written' | 'refused';\n reason?: string;\n}\n\n/**\n * Write the listed files, each atomically (a temp file in its own directory,\n * renamed over the file), the manifest last. A folder that exists and is not\n * ours is refused and reported, never overwritten.\n */\nexport async function writePluginFolder(\n dir: string,\n files: Record<string, string>,\n): Promise<FolderWrite> {\n const state = await inspectPluginFolder(dir);\n if (state === 'foreign') {\n return {\n path: dir,\n state: 'refused',\n reason: `${dir} exists and is not a folder this CLI wrote, so it was left as it is`,\n };\n }\n try {\n for (const path of PLUGIN_FILES) {\n const body = files[path];\n if (body === undefined) continue;\n await writeFileAtomic(join(dir, path), body);\n }\n } catch (err) {\n return {\n path: dir,\n state: 'refused',\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n return { path: dir, state: 'written' };\n}\n\nexport interface FolderRemoval {\n path: string;\n /** False when there was no folder of ours to remove. */\n removed: boolean;\n /** What is left in the folder that is not ours, relative to it. */\n left: string[];\n reason?: string;\n}\n\n/**\n * Unlink the listed files, remove the subfolders they leave empty, deepest\n * first, and the folder itself only when it is then empty. Never recursive.\n */\nexport async function removePluginFolder(dir: string): Promise<FolderRemoval> {\n const state = await inspectPluginFolder(dir);\n if (state === 'absent') return { path: dir, removed: false, left: [] };\n if (state === 'foreign') {\n return {\n path: dir,\n removed: false,\n left: [],\n reason: `${dir} is not a folder this CLI wrote, so nothing in it was removed`,\n };\n }\n for (const path of PLUGIN_FILES) await rm(join(dir, path), { force: true });\n const subdirs = [...new Set(PLUGIN_FILES.map((p) => dirname(p)).filter((d) => d !== '.'))].sort(\n (a, b) => b.split('/').length - a.split('/').length,\n );\n for (const sub of subdirs) await rmdir(join(dir, sub)).catch(() => undefined);\n const left = await listFiles(dir);\n if (left.length === 0) await rmdir(dir).catch(() => undefined);\n return { path: dir, removed: true, left };\n}\n\nasync function listFiles(dir: string): Promise<string[]> {\n const out: string[] = [];\n const walk = async (current: string): Promise<void> => {\n for (const entry of await readdir(current, { withFileTypes: true }).catch(() => [])) {\n const path = join(current, entry.name);\n if (entry.isDirectory()) await walk(path);\n else out.push(relative(dir, path).split(sep).join('/'));\n }\n };\n await walk(dir);\n return out.sort();\n}\n","import { envProxySupported, proxyVariable } from '../lib/env-proxy';\nimport { httpRequest, type HttpResponse } from '../lib/http';\nimport { isSameDeployment, PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { ROUTER_PATH } from './decision';\n\nexport interface RouterCheck {\n name: string;\n status: 'ok' | 'warn' | 'fail';\n required: boolean;\n detail: string;\n fix?: string;\n}\n\n/**\n * One cheap request to the free decision route with an empty body. It checks\n * the route is reachable and enabled, not that it routes: a 400 is the route\n * refusing that body, and a 404 is the route switched off. Nothing is signed\n * and no Jev request is spent. `doctor` fails on it; `install` only warns.\n *\n * A refusal is blamed on the layer that sent it. A proxy, firewall or VPN that\n * blocks the host is not the origin asking for credentials, and on the\n * production base URL the fix is never \"set the base URL\", because that is the\n * one setting that is already right.\n */\nexport async function probeRouter(\n baseUrl: string,\n opts: {\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n env?: NodeJS.ProcessEnv;\n /** Test seam; production asks this Node whether it can use the proxy. */\n proxySupported?: boolean;\n },\n): Promise<RouterCheck> {\n const fail = (detail: string, fix: string): RouterCheck => ({\n name: 'router',\n status: 'fail',\n required: true,\n detail,\n fix,\n });\n // `TENJIN_BASE_URL` and `--base-url` reach here unvalidated. A throw would\n // fail an install that has already written everything else.\n let url: string;\n try {\n url = new URL(ROUTER_PATH, baseUrl).toString();\n } catch {\n return fail(\n `the base URL ${JSON.stringify(baseUrl)} is not a URL`,\n `Check TENJIN_BASE_URL, or set it with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n const host = new URL(url).host;\n const probe = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n blockRedirects: true,\n // A reachability check, not use: it must not count this machine as an install.\n anonymous: true,\n jsonBody: {},\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n });\n const production = isSameDeployment(new URL(url).origin, PRODUCTION_ORIGIN);\n const checkBase = production\n ? 'Try again later.'\n : 'Check that the configured base URL names the Tenjin router (`tenjin config get baseUrl`), then try again later.';\n const env = opts.env ?? process.env;\n const network = networkFix(host, env, production, opts.proxySupported ?? envProxySupported());\n const credentials = proxyCredentialsFix(env);\n // Off production, a host that does not resolve or answer is most likely a\n // typo or a dev server that is not running, not a blocked network.\n const unreached = production ? network : checkBase;\n if (!probe.ok) {\n const t = probe.transport;\n if (t?.layer === 'proxy' && t.proxyStatus === 407) {\n return fail(\n `a proxy between this machine and ${host} asked for its own credentials (407)`,\n credentials,\n );\n }\n if (t?.layer === 'proxy') {\n return fail(\n `a proxy refused the connection to ${host} (${t.proxyStatus}), so the router never answered`,\n unreached,\n );\n }\n if (t?.layer === 'dns') {\n return fail(`${host} did not resolve (${t.code}), so the router was not reached`, unreached);\n }\n if (t?.layer === 'tls') {\n return fail(\n `the TLS connection to ${host} failed (${t.code}). A proxy that inspects TLS causes this`,\n `If this network inspects TLS, set NODE_EXTRA_CA_CERTS to its CA certificate. ${unreached}`,\n );\n }\n if (t?.layer === 'connect') {\n return fail(`could not connect to ${host} (${t.code})`, unreached);\n }\n return fail(`the router at ${url} is unreachable or erroring (${probe.message})`, unreached);\n }\n // 429 is the route's own rate limit: proof the router is there.\n if (probe.status === 200 || probe.status === 400 || probe.status === 429) {\n return { name: 'router', status: 'ok', required: true, detail: `${url} is live` };\n }\n if (probe.status === 404) {\n return fail(`the router is not enabled at ${url}`, checkBase);\n }\n if (probe.status === 407) {\n return fail(\n `a proxy between this machine and ${host} asked for its own credentials (407)`,\n credentials,\n );\n }\n if (probe.status === 401 || probe.status === 403) {\n if (!fromDeployment(probe)) {\n return fail(\n `${host} answered ${probe.status} without the headers a Tenjin deployment sends, so a proxy, firewall or VPN on the way most likely refused the request`,\n network,\n );\n }\n if (production) {\n return fail(`${url} refused this machine (${probe.status})`, checkBase);\n }\n return fail(\n `${url} is not a Tenjin router (it asked for credentials)`,\n `Set the router URL with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n if (probe.status >= 500) {\n return fail(`the router at ${url} is unreachable or erroring (${probe.status})`, checkBase);\n }\n return fail(\n `${url} answered ${probe.status}, which a Tenjin router does not`,\n 'Check that the configured base URL names a Tenjin deployment (`tenjin config get baseUrl`).',\n );\n}\n\n/**\n * Did the origin send this, rather than something in front of it? Every Vercel\n * response carries `x-vercel-id` (its own access protection included), and\n * every Tenjin API route adds `x-request-id`. A block page from a proxy,\n * firewall or VPN carries neither.\n */\nfunction fromDeployment(probe: HttpResponse): boolean {\n return probe.header('x-vercel-id') !== undefined || probe.header('x-request-id') !== undefined;\n}\n\nfunction networkFix(\n host: string,\n env: NodeJS.ProcessEnv,\n production: boolean,\n proxySupported: boolean,\n): string {\n const proxy = proxyVariable(env);\n const config = production ? \" Tenjin's own config is correct and needs no change.\" : '';\n if (proxy !== undefined && !proxySupported) {\n return `This shell sets ${proxy}, but Node ${process.versions.node} cannot send Tenjin's requests through it. Upgrade to Node 24.14 or newer, or run from a network that reaches ${host} directly.${config}`;\n }\n const via = proxy !== undefined ? ` (this shell sets ${proxy})` : '';\n return `Allow ${host} through your proxy, firewall or VPN${via}, or run from a network that reaches it.${config}`;\n}\n\nfunction proxyCredentialsFix(env: NodeJS.ProcessEnv): string {\n const proxy = proxyVariable(env) ?? 'HTTPS_PROXY';\n return `Put the proxy's credentials in ${proxy} (\\`http://user:password@proxy:port\\`), then try again.`;\n}\n","import { execFile } from 'node:child_process';\nimport { stat } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { promisify } from 'node:util';\nimport pkg from '../../package.json';\nimport type { RouterCheck } from './reachability';\n\n/**\n * A `tenjin mcp` STARTED BEFORE THIS INSTALL still runs the code it started\n * with. Claude Code keeps its MCP servers for the life of a session, so after\n * an update the hooks the new install wrote can call a tool the old process\n * does not have (\"Tool hook not found\"), while every file on disk reads as\n * correct. This finds this user's running `tenjin mcp` processes and compares\n * each start time with the installed package's own `package.json`.\n */\n\nexport interface McpProcess {\n pid: number;\n /** Start time in epoch ms, or null when `ps` gave none this could read. */\n startedAt: number | null;\n}\n\n/** This user's running `tenjin mcp` processes, or null where they cannot be listed. */\nexport type ListMcpProcesses = () => Promise<McpProcess[] | null>;\n\n/** When the installed package was written, in epoch ms, or null. */\nexport type InstalledAt = () => Promise<number | null>;\n\nconst exec = promisify(execFile);\n\n/** `ps` on macOS and Linux; null on Windows or when `ps` fails, which is \"unknown\". */\nexport const listMcpProcesses: ListMcpProcesses = async () => {\n if (process.platform === 'win32' || typeof process.getuid !== 'function') return null;\n try {\n const { stdout } = await exec(\n 'ps',\n ['-U', String(process.getuid()), '-o', 'pid=,lstart=,args='],\n { timeout: 5_000, env: { ...process.env, LC_ALL: 'C' }, maxBuffer: 4 * 1024 * 1024 },\n );\n return parsePs(stdout, process.pid);\n } catch {\n return null;\n }\n};\n\nconst PS_LINE = /^\\s*(\\d+)\\s+(\\w{3}\\s+\\w{3}\\s+\\d{1,2}\\s+\\d{2}:\\d{2}:\\d{2}\\s+\\d{4})\\s+(.*)$/;\n\n/** The `tenjin mcp` lines of `ps -o pid=,lstart=,args=`, this process left out. */\nexport function parsePs(stdout: string, selfPid: number): McpProcess[] {\n const found: McpProcess[] = [];\n for (const line of stdout.split('\\n')) {\n const m = PS_LINE.exec(line);\n if (m === null) continue;\n const pid = Number(m[1]);\n if (pid === selfPid || !isTenjinMcp(m[3]!)) continue;\n const startedAt = Date.parse(m[2]!.replace(/\\s+/g, ' '));\n found.push({ pid, startedAt: Number.isNaN(startedAt) ? null : startedAt });\n }\n return found;\n}\n\n/**\n * `tenjin mcp`, however the bin was invoked: `node /path/bin/tenjin mcp`,\n * `tenjin mcp`, or the plugin's `node <plugin root>/../../../index.js mcp`.\n */\nfunction isTenjinMcp(args: string): boolean {\n const tokens = args.trim().split(/\\s+/);\n const bin = tokens.findIndex(\n (t) =>\n /(^|[/\\\\])tenjin(\\.js|\\.cmd)?$/.test(t) ||\n /[/\\\\]tenjin-cli[/\\\\]/.test(t) ||\n /[/\\\\]hosts[/\\\\]claude[/\\\\]tenjin[/\\\\]\\.\\.[/\\\\]\\.\\.[/\\\\]\\.\\.[/\\\\]index\\.js$/.test(t),\n );\n return bin >= 0 && tokens[bin + 1] === 'mcp';\n}\n\n/**\n * When this build's `package.json`, the nearest one above this module, was\n * written. Its ctime, not its mtime: npm extracts a package with the\n * tarball's fixed 1985 mtimes, and setting them is what moves the ctime to\n * the moment of the install.\n */\nexport const installedAt: InstalledAt = async () => {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 6; i += 1) {\n try {\n const st = await stat(join(dir, 'package.json'));\n return Math.max(st.ctimeMs, st.mtimeMs);\n } catch {\n dir = dirname(dir);\n }\n }\n return null;\n};\n\n/** How many running servers predate the install, and what doctor says about it. */\nexport interface McpServersState {\n stale: number;\n check: RouterCheck;\n}\n\n/** Worded for the session the person is in: a slash command there, never a terminal. */\nexport const RECONNECT_FIX =\n 'Type /reload-plugins in this Claude Code session, or start a new session.';\n/**\n * WHILE A SETTINGS INSTALL IS STILL HERE, only a new session. `/reload-plugins`\n * reconnects plugin servers alone, so the plugin would load beside a\n * pre-upgrade `x402` server that does not know to stay silent, and every\n * event would route twice for the rest of that session.\n */\nexport const NEW_SESSION_FIX =\n 'Start a new Claude Code session: the earlier Tenjin setup is still in this one, and /reload-plugins would run both.';\n\n/** The `mcp server` check from a process list and the install time. Never a failure. */\nexport function mcpServersState(\n procs: McpProcess[] | null,\n installed: number | null,\n version: string = pkg.version,\n fix: string = RECONNECT_FIX,\n): McpServersState {\n const check = (detail: string): McpServersState => ({\n stale: 0,\n check: { name: 'mcp server', status: 'ok', required: false, detail },\n });\n if (procs === null) {\n return check('unknown: running `tenjin mcp` processes cannot be listed on this platform');\n }\n if (procs.length === 0) return check('none running (starts with the next session)');\n if (installed === null) {\n return check(`${procs.length} running; when this build was installed is unknown`);\n }\n const stale = procs.filter((p) => p.startedAt !== null && p.startedAt < installed).length;\n if (stale === 0) {\n return check(`${procs.length} running, all started after this install`);\n }\n const which = stale === 1 ? 'process' : 'processes';\n return {\n stale,\n check: {\n name: 'mcp server',\n status: 'warn',\n required: false,\n detail: `${stale} running \\`tenjin mcp\\` ${which} started before this install (${version}), so ${stale === 1 ? 'it runs' : 'they run'} the older build, where the hooks can fail with \"Tool hook not found\"`,\n fix,\n },\n };\n}\n\n/** The check, read from this machine (or the injected sources). */\nexport async function readMcpServers(\n deps: { listMcpProcesses?: ListMcpProcesses; installedAt?: InstalledAt } = {},\n opts: { settingsInstallPending?: boolean } = {},\n): Promise<McpServersState> {\n const [procs, installed] = await Promise.all([\n (deps.listMcpProcesses ?? listMcpProcesses)().catch(() => null),\n (deps.installedAt ?? installedAt)().catch(() => null),\n ]);\n const fix = opts.settingsInstallPending === true ? NEW_SESSION_FIX : RECONNECT_FIX;\n return mcpServersState(procs, installed, pkg.version, fix);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,cAAAA,aAAY,YAAAC,iBAAgB;AACrC,SAAS,WAAAC,gBAAe;AACxB,SAAS,SAAS,OAAAC,YAAW;AAC7B,SAAS,iBAAAC,sBAAqB;;;ACJ9B,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,WAAW,SAAS,MAAM,WAAW;AAkDvC,IAAM,WAA+B;AAAA,EAC1C;AAAA,IACE,MAAM;AAAA,IACN,OAAO,MACL,IAAI,SAAS,WAAW,gEAAgE;AAAA,MACtF,KAAK;AAAA,IACP,CAAC;AAAA,IACH,cAAc;AAAA,IACd,gBAAgB;AAAA,EAClB;AAAA,EACA;AAAA,IACE,MAAM,CAAC,cAAc,UAAU,MAAM,GAAG,EAAE,SAAS,MAAM;AAAA,IACzD,OAAO,CAAC,SACN,IAAI,SAAS,WAAW,4DAA4D;AAAA;AAAA;AAAA,MAGlF,KAAK,8DAA8D,IAAI;AAAA,IACzE,CAAC;AAAA,IACH,cAAc;AAAA,IACd,gBAAgB;AAAA,EAClB;AAAA,EACA;AAAA;AAAA;AAAA;AAAA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,MAAM,CAAC;AAAA,EACrC,CAAC;AACD,QAAM,GAAG,SAAS,CAAC,SAAS;AAC1B,iBAAa,KAAK;AAClB,QAAI,WAAW,EAAE,MAAM,UAAU,IAAI,EAAE,MAAM,QAAQ,MAAM,QAAQ,EAAE,CAAC;AAAA,EACxE,CAAC;AACH,CAAC;","names":["existsSync","statSync","homedir","sep","fileURLToPath","readFile","homedir","isAbsolute","join","dirname","join","join","dirname","statSync","delimiter","join","isFile","exec","resolve","lines","join","command","command","command","join","readFile","stat","dirname","join","readdir","readFile","rm","rmdir","dirname","join","sep","join","readFile","rm","dirname","rmdir","readdir","sep","join","stat","readFile","dirname","execFile","stat","dirname","join","fileURLToPath","execFile","dirname","fileURLToPath","stat","join","join","readFile","homedir","isAbsolute","fileURLToPath","homedir","refreshLines","lines","statSync","command","sep","existsSync"]}