tenjin-cli 0.1.0-alpha.27 → 0.1.0-alpha.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -17
- package/dist/alive-3J3CHOQP.js +21 -0
- package/dist/{chunk-SKQQOEWH.js → chunk-3QJREVMX.js} +5 -7
- package/dist/{chunk-SKQQOEWH.js.map → chunk-3QJREVMX.js.map} +1 -1
- package/dist/{chunk-BOAI23CX.js → chunk-6KA4HFX5.js} +21 -15
- package/dist/chunk-6KA4HFX5.js.map +1 -0
- package/dist/chunk-6W5GYG3W.js +128 -0
- package/dist/chunk-6W5GYG3W.js.map +1 -0
- package/dist/{chunk-4L7KMA7P.js → chunk-7H3RN4WJ.js} +7 -9
- package/dist/{chunk-4L7KMA7P.js.map → chunk-7H3RN4WJ.js.map} +1 -1
- package/dist/{chunk-O7CUHHYU.js → chunk-7R37M6WV.js} +7 -9
- package/dist/{chunk-O7CUHHYU.js.map → chunk-7R37M6WV.js.map} +1 -1
- package/dist/{chunk-LAIZ2AQA.js → chunk-A5H3E5QA.js} +2 -2
- package/dist/{update-RJDA5ZY3.js → chunk-AO54FM4H.js} +147 -26
- package/dist/chunk-AO54FM4H.js.map +1 -0
- package/dist/{chunk-VNNXAYJE.js → chunk-BRHREK7E.js} +2 -2
- package/dist/{chunk-YQOQ6XEI.js → chunk-DJYAPACT.js} +35 -33
- package/dist/chunk-DJYAPACT.js.map +1 -0
- package/dist/{chunk-GU4GGKYP.js → chunk-DYSDQE7S.js} +36 -2
- package/dist/chunk-DYSDQE7S.js.map +1 -0
- package/dist/{chunk-YKM2ZTA2.js → chunk-FQ6DHINU.js} +36 -38
- package/dist/{chunk-YKM2ZTA2.js.map → chunk-FQ6DHINU.js.map} +1 -1
- package/dist/{chunk-6ZSGER3A.js → chunk-FZTSGQVK.js} +2 -2
- package/dist/{chunk-AWKQSKUL.js → chunk-KAMRYUK2.js} +2 -2
- package/dist/{chunk-2TYQD22Q.js → chunk-MNTQMZJB.js} +6 -8
- package/dist/{chunk-2TYQD22Q.js.map → chunk-MNTQMZJB.js.map} +1 -1
- package/dist/{chunk-VIOUZW7Z.js → chunk-QTND6XWJ.js} +159 -35
- package/dist/chunk-QTND6XWJ.js.map +1 -0
- package/dist/chunk-RLPLYUME.js +115 -0
- package/dist/{chunk-HC3QEZKT.js.map → chunk-RLPLYUME.js.map} +1 -1
- package/dist/{chunk-5NEHH2E5.js → chunk-UEOWNDQG.js} +8 -10
- package/dist/{chunk-5NEHH2E5.js.map → chunk-UEOWNDQG.js.map} +1 -1
- package/dist/{chunk-OHZYNZSD.js → chunk-UOW5JXYY.js} +5 -7
- package/dist/{chunk-OHZYNZSD.js.map → chunk-UOW5JXYY.js.map} +1 -1
- package/dist/chunk-VSUHGRVB.js +1455 -0
- package/dist/chunk-VSUHGRVB.js.map +1 -0
- package/dist/{chunk-64SE3QC5.js → chunk-W6JX4LYF.js} +12 -4
- package/dist/chunk-W6JX4LYF.js.map +1 -0
- package/dist/{chunk-5FGO6TYT.js → chunk-XVTD7UWR.js} +3 -5
- package/dist/{chunk-5FGO6TYT.js.map → chunk-XVTD7UWR.js.map} +1 -1
- package/dist/{chunk-X7I343ZY.js → chunk-YFJJYHVG.js} +2 -2
- package/dist/{chunk-XVYATBKD.js → chunk-ZG6ZZLO7.js} +898 -521
- package/dist/chunk-ZG6ZZLO7.js.map +1 -0
- package/dist/{chunk-DATCR7AU.js → chunk-ZO3X5NPG.js} +4 -6
- package/dist/{chunk-DATCR7AU.js.map → chunk-ZO3X5NPG.js.map} +1 -1
- package/dist/{chunk-VXIBZ6W5.js → chunk-ZP5PV3JB.js} +3 -3
- package/dist/{chunk-G4AM2SOL.js → chunk-ZP7AHN7Z.js} +4 -6
- package/dist/{chunk-G4AM2SOL.js.map → chunk-ZP7AHN7Z.js.map} +1 -1
- package/dist/{cli-6JNIPZQ6.js → cli-234DNHN6.js} +54 -53
- package/dist/{cli-6JNIPZQ6.js.map → cli-234DNHN6.js.map} +1 -1
- package/dist/{config-G75YT6NC.js → config-IY2OJCAK.js} +10 -13
- package/dist/{doctor-3GMDOW4Y.js → doctor-2UZZF44A.js} +267 -242
- package/dist/doctor-2UZZF44A.js.map +1 -0
- package/dist/{fund-3IPR5YRJ.js → fund-RZ2QFULK.js} +92 -38
- package/dist/{fund-3IPR5YRJ.js.map → fund-RZ2QFULK.js.map} +1 -1
- package/dist/hook-command-PZHKS7ES.js +31 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
- package/dist/hosts/claude/tenjin/.mcp.json +11 -0
- package/dist/hosts/claude/tenjin/hooks/hooks.json +206 -0
- package/dist/index.js +12 -3
- package/dist/index.js.map +1 -1
- package/dist/install-O5FJ5EP3.js +48 -0
- package/dist/{install-identity-PM4AGFFX.js → install-identity-QM44IQ6Z.js} +7 -8
- package/dist/{install-wallet-6756NOB5.js → install-wallet-Z52EDLPB.js} +14 -15
- package/dist/{install-wallet-6756NOB5.js.map → install-wallet-Z52EDLPB.js.map} +1 -1
- package/dist/{mcp-33FAAZ7F.js → mcp-33HAADDF.js} +80 -67
- package/dist/{mcp-33FAAZ7F.js.map → mcp-33HAADDF.js.map} +1 -1
- package/dist/package-RT24HTTP.js +37 -0
- package/dist/{pay-XOYR4PCH.js → pay-IR2V76FX.js} +16 -17
- package/dist/{payments-UTQDBO7H.js → payments-GFV4HU5R.js} +9 -10
- package/dist/{payments-UTQDBO7H.js.map → payments-GFV4HU5R.js.map} +1 -1
- package/dist/{send-CVGNOQW3.js → send-PI4NUA7I.js} +12 -14
- package/dist/{send-CVGNOQW3.js.map → send-PI4NUA7I.js.map} +1 -1
- package/dist/{status-NACN4DGX.js → status-ZUHTJK46.js} +6 -7
- package/dist/{status-NACN4DGX.js.map → status-ZUHTJK46.js.map} +1 -1
- package/dist/{status-line-3IQKGRUH.js → status-line-2G5JPQAE.js} +6 -7
- package/dist/{status-line-3IQKGRUH.js.map → status-line-2G5JPQAE.js.map} +1 -1
- package/dist/uninstall-THKUH5ZT.js +136 -0
- package/dist/uninstall-THKUH5ZT.js.map +1 -0
- package/dist/update-NPZDP24E.js +18 -0
- package/dist/update-NPZDP24E.js.map +1 -0
- package/dist/{wallet-B3FVHNTS.js → wallet-53EFH4M5.js} +11 -12
- package/dist/wallet-53EFH4M5.js.map +1 -0
- package/docs/agent-permissions.md +27 -17
- package/package.json +1 -1
- package/dist/chunk-64SE3QC5.js.map +0 -1
- package/dist/chunk-BOAI23CX.js.map +0 -1
- package/dist/chunk-DSNXKUXI.js +0 -172
- package/dist/chunk-DSNXKUXI.js.map +0 -1
- package/dist/chunk-GU4GGKYP.js.map +0 -1
- package/dist/chunk-H2L33M7F.js +0 -944
- package/dist/chunk-H2L33M7F.js.map +0 -1
- package/dist/chunk-HC3QEZKT.js +0 -87
- package/dist/chunk-JLEF5WHM.js +0 -132
- package/dist/chunk-JLEF5WHM.js.map +0 -1
- package/dist/chunk-MAQUL5BD.js +0 -99
- package/dist/chunk-MAQUL5BD.js.map +0 -1
- package/dist/chunk-PY7MQUKP.js +0 -755
- package/dist/chunk-PY7MQUKP.js.map +0 -1
- package/dist/chunk-TGLKKLQG.js +0 -11
- package/dist/chunk-TGLKKLQG.js.map +0 -1
- package/dist/chunk-VIOUZW7Z.js.map +0 -1
- package/dist/chunk-XVYATBKD.js.map +0 -1
- package/dist/chunk-YQOQ6XEI.js.map +0 -1
- package/dist/doctor-3GMDOW4Y.js.map +0 -1
- package/dist/hook-command-ZXX4FT4N.js +0 -32
- package/dist/install-6OROTYHZ.js +0 -72
- package/dist/status-line-wiring-QXBOOY2T.js +0 -31
- package/dist/uninstall-NYFKSYW4.js +0 -175
- package/dist/uninstall-NYFKSYW4.js.map +0 -1
- package/dist/update-RJDA5ZY3.js.map +0 -1
- /package/dist/{config-G75YT6NC.js.map → alive-3J3CHOQP.js.map} +0 -0
- /package/dist/{chunk-LAIZ2AQA.js.map → chunk-A5H3E5QA.js.map} +0 -0
- /package/dist/{chunk-VNNXAYJE.js.map → chunk-BRHREK7E.js.map} +0 -0
- /package/dist/{chunk-6ZSGER3A.js.map → chunk-FZTSGQVK.js.map} +0 -0
- /package/dist/{chunk-AWKQSKUL.js.map → chunk-KAMRYUK2.js.map} +0 -0
- /package/dist/{chunk-X7I343ZY.js.map → chunk-YFJJYHVG.js.map} +0 -0
- /package/dist/{chunk-VXIBZ6W5.js.map → chunk-ZP5PV3JB.js.map} +0 -0
- /package/dist/{hook-command-ZXX4FT4N.js.map → config-IY2OJCAK.js.map} +0 -0
- /package/dist/{install-6OROTYHZ.js.map → hook-command-PZHKS7ES.js.map} +0 -0
- /package/dist/{install-identity-PM4AGFFX.js.map → install-O5FJ5EP3.js.map} +0 -0
- /package/dist/{pay-XOYR4PCH.js.map → install-identity-QM44IQ6Z.js.map} +0 -0
- /package/dist/{status-line-wiring-QXBOOY2T.js.map → package-RT24HTTP.js.map} +0 -0
- /package/dist/{wallet-B3FVHNTS.js.map → pay-IR2V76FX.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../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"],"sourcesContent":["import { readFile, realpath } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\nimport pkg from '../../package.json';\nimport { persistRouterDefaults, ROUTER_DEFAULTS, type RouterLimits } 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 /** 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 * `tenjin update` runs the refresh from home, where nothing proves scope. A\n * project install is taken when this directory, not being home, holds one:\n * the plugin enabled in its `settings.local.json`, its plugin folder, or a\n * settings install's entries.\n */\nasync function inferRefreshProject(\n cwd: string,\n home: string,\n env: NodeJS.ProcessEnv,\n): Promise<boolean> {\n const [cwdPath, homePath] = await Promise.all([\n realpath(cwd).catch(() => cwd),\n realpath(home).catch(() => home),\n ]);\n if (cwdPath === homePath) return false;\n const local = await readFile(join(cwd, '.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 folderState('local', env, home, cwd)).state === 'ours') return true;\n const paths = settingsInstallPaths(true, env, home, cwd);\n return (await inspectLegacyInstall(paths.settingsPath, paths.mcpFile)).events.length > 0;\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 inferRefreshProject(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 });\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 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 if (plugin.id !== null && plugin.method === 'none') {\n return `${plugin.id} keeps serving this machine at the version Claude Code has; run \\`tenjin install\\` 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\\` again.`;\n }\n return 'Run `tenjin doctor` to see the cause, then run `tenjin install` 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 ...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}\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(folder, renderPluginFiles(opts.version));\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/** 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 * 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_COMMAND = 'tenjin hook alive';\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/**\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 *\n * Static text, so no process starts: a fixed answer needs no CLI.\n */\nexport const DENY_HOOK_COMMAND = `echo '${permissionAnswer(\n 'deny',\n `Only the Tenjin hooks call this tool. To make a lookup, call ${REQUEST_TOOL}.`,\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_COMMAND = `echo '${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(text: string): unknown[] {\n return [{ type: 'command', command: text, 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(): { hooks: Record<string, unknown[]> } {\n const plan = [\n { event: 'SessionStart', hooks: command(ALIVE_COMMAND) },\n ...routerHookPlan(),\n { event: 'PreToolUse', matcher: PLUGIN_HOOK_TOOL, hooks: command(DENY_HOOK_COMMAND) },\n { event: 'PreToolUse', matcher: REQUEST_TOOL, hooks: command(ALLOW_HOOK_COMMAND) },\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 on PATH.\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(): { mcpServers: Record<string, unknown> } {\n return { mcpServers: { [MCP_SERVER_NAME]: { command: 'tenjin', args: [...PLUGIN_MCP_ARGS] } } };\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/** The plugin folder's files, by {@link PLUGIN_FILES} path. */\nexport function renderPluginFiles(version?: string): Record<string, string> {\n return {\n '.mcp.json': json(renderPluginMcp()),\n 'hooks/hooks.json': json(renderPluginHooks()),\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAAA,WAAU,gBAAgB;AACnC,SAAS,WAAAC,gBAAe;AACxB,SAAS,cAAAC,aAAY,QAAAC,aAAY;;;ACFjC,SAAS,iBAAiB;AAC1B,SAAS,SAAS,IAAI,aAAa;AACnC,SAAS,SAAS,YAAY;AAU9B,SAAS,gBAAgB,MAAuB;AAC9C,MAAI;AACF,WAAO,UAAU,MAAM,EAAE,gBAAgB,MAAM,CAAC,GAAG,YAAY,MAAM;AAAA,EACvE,SAAS,KAAK;AAGZ,QAAI,QAAQ,KAAK,QAAQ,KAAK,QAAQ,KAAK,SAAS,EAAG,QAAO;AAC9D,UAAM;AAAA,EACR;AACF;AAOA,eAAsB,iBACpB,MACA,WAC+B;AAC/B,MAAI,CAAC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CAAC,8BAA8B,OAAO,YAAY,0BAA0B,KAAK,EAAE;AAC3F,QAAM,SACJ,EAAE,OAAO,WAAW,OAChB,CAAC,IACD;AAAA,IACE,KAAK,8BAA8B,EAAE,OAAO,MAAM,EAAE;AAAA,IACpD,GAAI,EAAE,OAAO,QAAQ,SAAY,CAAC,KAAK,EAAE,OAAO,GAAG,EAAE,IAAI,CAAC;AAAA,EAC5D;AACN,SAAO;AAAA,IACL,EAAE,OAAO,UAAU,WACf,KAAK,gDAAgD,IACrD,EAAE,OAAO,UAAU,aACjB,KAAK,yEAAyE,IAC9E,GAAG,EAAE,6CAA6C,EAAE,OAAO,MAAM,SAAS;AAAA,IAChF,GAAG,YAAY,KAAK,IAAI,EAAE,MAAM;AAAA,IAChC,GAAG;AAAA,IACH,GAAG,YAAY,KAAK,EAAE,MAAM;AAAA,IAC5B,GAAG,YAAY,KAAK,EAAE,MAAM;AAAA,IAC5B,GAAG,eAAe,KAAK,EAAE,SAAS;AAAA,IAClC,GAAG;AAAA,IACH;AAAA,IACA,SAAS,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC;AAAA,EAC9D;AACF;AAGA,SAAS,aACP,KACA,QACA,QACA,WACU;AACV,QAAM,SAAS;AAAA,IACb,GAAG,YAAY,KAAK,MAAM;AAAA,IAC1B,GAAG,YAAY,KAAK,MAAM;AAAA,IAC1B,GAAG,eAAe,KAAK,SAAS;AAAA,EAClC;AACA,QAAM,OACJ,OAAO,UAAU,WACb,MAAM,IAAI,IAAI,UAAU,wDAAwD,IAChF,OAAO,UAAU,aACf,MAAM,IAAI,IAAI,UAAU,+DAA+D,IACvF,GAAG,MAAM,IAAI,IAAI,SAAS,QAAG,CAAC,iCAAiC,OAAO,MAAM,SAAS;AAC7F,SAAO,CAAC,MAAM,GAAG,MAAM;AACzB;","names":["readFile","homedir","isAbsolute","join","join","lines","join","command","command","command","join","readFile","stat","dirname","join","readdir","readFile","rm","rmdir","dirname","join","join","readFile","rm","dirname","rmdir","readdir","join","stat","readFile","dirname","join","readFile","homedir","isAbsolute"]}
|
|
@@ -2,10 +2,10 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
|
|
|
2
2
|
import {
|
|
3
3
|
fetchFailureToCliError,
|
|
4
4
|
httpRequest
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-UOW5JXYY.js";
|
|
6
6
|
import {
|
|
7
7
|
external_exports
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-QTND6XWJ.js";
|
|
9
9
|
|
|
10
10
|
// src/router/decision.ts
|
|
11
11
|
var ROUTER_PATH = "/api/x402-router";
|
|
@@ -77,6 +77,14 @@ var DiscoveredCandidateSchema = external_exports.strictObject({
|
|
|
77
77
|
var ToolSpecSchema = external_exports.strictObject({
|
|
78
78
|
capabilityId: external_exports.string().min(1).max(200),
|
|
79
79
|
provider: external_exports.string().min(1).max(120),
|
|
80
|
+
/** The input field that takes a pending search's query or fetch's URL. */
|
|
81
|
+
holds: external_exports.strictObject({
|
|
82
|
+
WebSearch: external_exports.string().min(1).max(64).optional(),
|
|
83
|
+
WebFetch: external_exports.string().min(1).max(64).optional()
|
|
84
|
+
}).optional(),
|
|
85
|
+
/** What a paid result is. `media` means its files (bytes, links or inline
|
|
86
|
+
* base64) are saved locally; absent on a Bazaar spec. */
|
|
87
|
+
output: external_exports.enum(["json", "text", "media"]).optional(),
|
|
80
88
|
description: external_exports.string().min(1).max(500),
|
|
81
89
|
priceAtomic: external_exports.string().regex(/^\d+$/),
|
|
82
90
|
priceVaries: external_exports.boolean(),
|
|
@@ -204,7 +212,7 @@ function envelope(decision) {
|
|
|
204
212
|
}
|
|
205
213
|
var HookResponseSchema = envelope(HookDecisionSchema);
|
|
206
214
|
var ToolResponseSchema = envelope(ToolDecisionSchema);
|
|
207
|
-
var CLIENT_ACCEPTS = ["
|
|
215
|
+
var CLIENT_ACCEPTS = ["catalog", "spec"];
|
|
208
216
|
var BAZAAR_ACCEPT = "bazaar";
|
|
209
217
|
function acceptsFor(bazaar) {
|
|
210
218
|
return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];
|
|
@@ -364,4 +372,4 @@ export {
|
|
|
364
372
|
reportSpecOutcome,
|
|
365
373
|
isUnreachable
|
|
366
374
|
};
|
|
367
|
-
//# sourceMappingURL=chunk-
|
|
375
|
+
//# sourceMappingURL=chunk-W6JX4LYF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { FetchJsonFailure, HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\n\n/**\n * `POST /api/x402-router`: ONE DECISION PER LOOKUP. On the free path it costs\n * nothing. Inside `tenjin mcp`, while the server answers its paid path, the\n * same body goes to that path through the stock x402 client\n * ({@link DecisionRoute}, `routing-payer.ts`); a call that path cannot take\n * falls back to the free path. The rest of this note describes the free path,\n * which is unchanged.\n *\n * The routing decision costs nothing and nobody signs for it. The hook asks for\n * it from the user's own words, the backend answers with what it would do and\n * what the provider charges, and the only payment on the wire is the one\n * `runPay` makes to that provider. That deletes the router fee and everything\n * built to carry it: the 402 probe, the requirements cache, the stale-quote\n * retry, the settlement accounting and one Base settlement of about 1.5 s from\n * every paid lookup.\n *\n * The bounded packet travels with the hook request and the backend keeps it\n * against the decision id until that id expires. What this client keeps is\n * each offer's spec, by its id (`specs.ts`).\n */\n\nexport const ROUTER_PATH = '/api/x402-router';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, a non-execute with no diagnostics parsed\n * with nothing to act on, and a hook answer carrying a contract parsed as\n * though the hook had quoted a price. Each of those is drift the shared\n * fixtures exist to catch, so each is now a parse failure that names itself.\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.strictObject({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. The `request` tool refuses a live\n * 402 above it; `gateSpend` still caps the amount actually signed. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n};\n\n/**\n * STRUCTURE, NEVER WORDING. A hint lands in the model's context verbatim, so\n * its shape is checked the way the id's alphabet is: one line, no control\n * characters, and it has to be the call it claims to be, naming the id this\n * same answer carries. A hint that fails any of these is a protocol error and\n * the turn falls back to the generic line; nothing here rewrites a word of a\n * hint that passes. Both offering arms, `execute` and `discovered`, hold it.\n */\nfunction checkHint(decision: { id: string; hint: string }, ctx: z.RefinementCtx): void {\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n}\n\n/**\n * A PAY-PER-CALL SERVICE NOBODY CURATED. When a Tenjin list service does the\n * task the gate picked, or no task fits and a listed x402 service could do the\n * step, the server names that one service: who sells it, where, for how much,\n * and the input it takes. A Tenjin list service arrives here under its catalog\n * id, because this build sends `catalog`. The candidate is the seller's own\n * listing, so every field is data for the host to judge, never an instruction;\n * the host builds the `input` and the tool call pays through the same `runPay`\n * path and caps as a curated lookup.\n */\nconst DiscoveredCandidateSchema = z.strictObject({\n source: z.string().min(1).max(64),\n provider: z.string().min(1).max(120),\n url: z.string().min(1).max(2_048),\n method: z.enum(['GET', 'POST']),\n description: z.string().max(500),\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n network: z.string().min(1).max(64),\n payTo: z.string().min(1).max(200),\n input: z.strictObject({\n location: z.enum(['body', 'query']),\n schema: z.record(z.string(), z.unknown()),\n }),\n});\n\n/**\n * A REQUEST SPEC: the offered service's real contract, sent beside the line only\n * because this build asks for it (`accepts: [\"spec\"]`). The hook stores it by\n * the offer's id; `request({id})` shows it and `request({id, input})` fills its\n * request and pays the provider directly, with no second decision. Every field\n * is the server's, and so is checked like the rest of the answer: the payee and\n * price still meet the live 402 and the spend policy in `runPay`.\n */\nexport const ToolSpecSchema = z.strictObject({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n /** The input field that takes a pending search's query or fetch's URL. */\n holds: z\n .strictObject({\n WebSearch: z.string().min(1).max(64).optional(),\n WebFetch: z.string().min(1).max(64).optional(),\n })\n .optional(),\n /** What a paid result is. `media` means its files (bytes, links or inline\n * base64) are saved locally; absent on a Bazaar spec. */\n output: z.enum(['json', 'text', 'media']).optional(),\n description: z.string().min(1).max(500),\n priceAtomic: z.string().regex(/^\\d+$/),\n priceVaries: z.boolean(),\n maxAmountAtomic: z.string().regex(/^\\d+$/),\n payTo: z.string().min(1).max(200),\n network: z.string().min(1).max(64),\n asset: z.string().min(1).max(200),\n request: z.strictObject({\n method: z.enum(['GET', 'POST']),\n url: z.string().min(1).max(2_048),\n fields: z.record(z.string(), z.enum(['path', 'query', 'body'])),\n location: z.enum(['query', 'body']),\n }),\n input: z.record(z.string(), z.unknown()),\n pinned: z.record(z.string(), z.unknown()),\n example: z.record(z.string(), z.unknown()).optional(),\n returns: z.string().min(1).max(200).optional(),\n returnsExample: z.unknown().optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n /** The fields the result promises (type, properties, items, required). The\n * agent is handed only these; the whole body is saved to a file. */\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n});\nexport type ToolSpec = z.infer<typeof ToolSpecSchema>;\n\nexport const OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });\nexport type OfferSpec = z.infer<typeof OfferSpecSchema>;\n\n/** One spec per service the line names: the offer, any other service it\n * lists, and each option of a choice set. */\nconst SpecsSchema = z.array(OfferSpecSchema).min(1).max(8).optional();\n\n/** Words this client shows the model itself, in its own line: one plain line. */\nconst PlainLine = (max: number) =>\n z\n .string()\n .min(1)\n .max(max)\n .refine((text) => !/[\\p{Cc}\\p{Cf}]/u.test(text), 'one plain line');\n\n/**\n * SERVICES THE USER PICKS BETWEEN, OR RUNS ALL OF. Sent only beside a\n * discovered offer, to a build that lists `catalog` in `accepts`. Each option\n * is a real offer: its own id, its own spec in `specs`, and its own one\n * payment, so `request({id, choice})` runs exactly the spec\n * `request({id: option.id})` would. `all` runs every option side by side, one\n * payment each. The set is the server's data: changing it is a deploy there,\n * not a release here. `input` names the open fields the options share, the\n * only ones an `all` call may carry.\n */\nexport const ChoicesSchema = z.strictObject({\n group: PlainLine(64),\n default: PlainLine(64),\n input: z.array(PlainLine(64)).min(1).max(16),\n options: z\n .array(\n z.strictObject({\n key: PlainLine(64),\n label: PlainLine(120),\n strength: PlainLine(300),\n id: IdSchema,\n }),\n )\n .min(2)\n .max(4),\n all: z.strictObject({ totalAtomic: z.string().regex(/^\\d+$/) }),\n});\nexport type Choices = z.infer<typeof ChoicesSchema>;\n\n/** The word that runs every option, so no option may take it as its key. */\nexport const ALL_CHOICES = 'all';\n\n/**\n * A CHOICE NAMES ONLY WHAT THIS ANSWER CARRIES: each key and id once, `all`\n * free for the whole set, a spec for every option, and the default option is\n * the offer this answer's id already names. A set that breaks any of these is\n * a protocol error, and the turn falls back like any unreadable answer.\n */\nfunction checkChoices(\n decision: { id: string; specs?: { id: string }[] | undefined; choices?: Choices | undefined },\n ctx: z.RefinementCtx,\n): void {\n const { choices } = decision;\n if (choices === undefined) return;\n const issue = (message: string) => ctx.addIssue({ code: 'custom', path: ['choices'], message });\n const keys = choices.options.map((option) => option.key);\n const ids = choices.options.map((option) => option.id);\n if (new Set(keys).size !== keys.length) issue('each choice key is named once');\n if (new Set(ids).size !== ids.length) issue('each choice id is named once');\n if (keys.includes(ALL_CHOICES)) issue(`\"${ALL_CHOICES}\" runs every choice, so it is no key`);\n const specIds = new Set((decision.specs ?? []).map((spec) => spec.id));\n if (ids.some((id) => !specIds.has(id))) issue('every choice carries its spec');\n const fallback = choices.options.find((option) => option.key === choices.default);\n if (fallback === undefined) issue('the default is one of the choices');\n else if (fallback.id !== decision.id) issue(\"the default choice is this answer's own offer\");\n}\n\n/** The same answer on both calls: the hook's offer, and the tool's answer\n * when a query with no id found a service nobody curated. */\nconst DiscoveredSchema = z\n .strictObject({\n action: z.literal('discovered'),\n id: IdSchema,\n candidate: DiscoveredCandidateSchema,\n /** THE LINE, FINISHED, as on `execute`: it carries the seller's\n * description and the input it takes. */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n choices: ChoicesSchema.optional(),\n })\n .superRefine(checkHint)\n .superRefine(checkChoices);\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .strictObject({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. */\n endpoint: z.string().min(1).max(2_048),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift. The same\n * bound as a discovered line's.\n */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.strictObject({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n /**\n * A query with no id, answered with the spec of the service the server\n * picked under a fresh `id`: kept like a hook's, and never run in the same\n * call. `hint` is the line, with the skeleton of the next call:\n * `request({id, input: {...}})` with the required fields. `input` is what a\n * router from before the binder's removal still sends on a bound pick: it\n * is accepted so that answer parses, and never read, so it never runs.\n */\n z\n .strictObject({\n action: z.literal('spec'),\n id: IdSchema,\n spec: ToolSpecSchema,\n hint: z.string().min(1).max(2_000),\n input: z.record(z.string(), z.unknown()).optional(),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool';\n\n/**\n * What this client can act on beyond the curated answers, sent on both calls.\n * `catalog` takes Tenjin's reviewed list of third-party services as\n * `discovered` offers under their catalog ids, with each spec's `holds` and\n * `output`, and `choices`, a set of options the user picks between or runs\n * all of, beside a discovered offer from a compare group. A build that sends\n * `discovered` in its place gets the same services under their\n * `discovered:tenjin:` ids. `spec` asks for each offered service's request\n * spec beside its line, and for the picked service's spec in place of a\n * decision on a query with no id, which only a build that parses them can\n * take: the decision schemas are strict. `bazaar` widens discovery to the\n * open Bazaar and is sent only while `experimental.bazaar` is on.\n */\nexport const CLIENT_ACCEPTS: readonly string[] = ['catalog', 'spec'];\nexport const BAZAAR_ACCEPT = 'bazaar';\n\n/** The `accepts` this build sends, with the open Bazaar or without it. */\nexport function acceptsFor(bazaar: boolean): string[] {\n return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];\n}\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route reads it with a strict object, so an extra field is a\n * 400, and a 400 is a turn with no hint.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone. `sessionId` is the harness's own session id, which the\n * server uses only so one session is not offered the same discovered service\n * twice.\n */\nexport function buildHookBody(\n packet: Packet,\n extras: { sessionId?: string; accepts?: readonly string[] } = {},\n): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(extras.sessionId !== undefined ? { sessionId: extras.sessionId } : {}),\n ...(extras.accepts !== undefined ? { accepts: [...extras.accepts] } : {}),\n packet,\n };\n}\n\n/** The exact body the tool call sends. `id` is the offer the query is for,\n * sent only for an offer with no spec kept; `gateHint` is evidence, never\n * authority. */\nexport function buildToolBody(request: {\n query?: string;\n id?: string;\n gateHint?: GateHint;\n accepts?: readonly string[];\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n ...(request.accepts !== undefined ? { accepts: [...request.accepts] } : {}),\n };\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(kind: CallKind, value: unknown): { success: boolean } {\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n return { success: schema.safeParse(value).success };\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n /** `experimental.bazaar`: add {@link BAZAAR_ACCEPT}, so a service from the\n * open Bazaar may come back. Off by default: curated and the Tenjin list. */\n acceptsBazaar?: boolean;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n /** The paid path, when `tenjin mcp` takes it: the body goes to `path` and is\n * sent by `send`, which pays the routing fee with the stock x402 client.\n * Absent is the free path. */\n route?: DecisionRoute;\n}\n\n/** How a routing call reaches the paid path. `send` throws\n * {@link RouteSkipped} when it has no paid answer for the call, which then\n * takes the free path. */\nexport interface DecisionRoute {\n path: string;\n send: (url: string, options: HttpRequestOptions) => Promise<HttpResult>;\n}\n\n/** The paid path gave this call no answer: the wallet locked, low or over\n * its spend limits, the channel busy, or the payment failed. */\nexport class RouteSkipped extends Error {\n /** `unreached`: the paid call could not reach the router\n * ({@link isUnreachable}), so the free path, on the same host, is not\n * tried and the call reads as that transport failure. */\n constructor(\n readonly why: string,\n readonly unreached?: FetchJsonFailure,\n ) {\n super(`routing fee not paid: ${why}`);\n }\n}\n\n/** Another session's call was in flight on the wallet's routing channel. */\nexport const CHANNEL_BUSY = 'channel_busy';\n/** The server answered no paid path. */\nexport const PAID_PATH_ABSENT = 'paid_path_absent';\n/** The paid call got no answer, a refused payment or a server error. */\nexport const PAYMENT_FAILED = 'payment_failed';\n/** The payment went out and the call's budget ran out before its answer:\n * no fault. `tenjin mcp` lets the request finish, so it is recorded. */\nexport const DEADLINE_AFTER_PAYMENT_SENT = 'deadline_after_payment_sent';\n\nexport type DecisionOutcome<T> =\n /** `freePath`: the paid path skipped the call for this reason and it went\n * to the free path instead, unpaid. */\n | { status: 'decided'; decision: T; freePath?: string }\n /** On the free path nothing was paid and nothing could be, so a failure here\n * costs the turn a routing answer and nothing else. */\n | {\n status: 'failed';\n reason: string;\n errorCode?: string;\n freePath?: string;\n /** The router could not be reached at all ({@link isUnreachable}). */\n unreachable?: true;\n /** No answer came back at all: a transport failure or a timeout. */\n noAnswer?: true;\n }\n /** The paid path gave no answer ({@link RouteSkipped}) and no time was left\n * for the free path: the native tool runs. */\n | { status: 'skipped'; why: string };\n\n/**\n * ONE FREE CALL, IN TWO FORMS. The hook sends `{ packet }`: the backend runs\n * the gate, and on `execute` stores that packet under an id and answers with\n * each offered service's spec. The tool sends `{ query }`, which the backend\n * answers with the spec of the service its gate picks, or `{ query, id }` for\n * the free docs offer, which has no spec and is bound from the query. Every\n * provider call is built here, from a spec, or for the docs lookup by the\n * backend from the query.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet; sessionId?: string },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query: string; id?: string; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n sessionId?: string;\n id?: string;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(deps.route?.path ?? ROUTER_PATH, deps.baseUrl).toString();\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet, {\n ...(request.sessionId !== undefined ? { sessionId: request.sessionId } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n })\n : buildToolBody({\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n const started = Date.now();\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n let response: HttpResult;\n try {\n response = await (deps.route?.send ?? httpRequest)(url, options);\n } catch (err) {\n if (!(err instanceof RouteSkipped)) throw err;\n if (err.unreached !== undefined) return readDecision(err.unreached, schema);\n const left = options.timeoutMs - (Date.now() - started);\n if (left <= 0) return { status: 'skipped', why: err.why };\n // A CALL THE PAID PATH COULD NOT TAKE STILL ROUTES, on the free path,\n // unpaid, inside what is left of its budget, and says why.\n response = await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n ...options,\n timeoutMs: left,\n });\n const free = readDecision(response, schema);\n // A failure here ran on what a paid attempt left of the budget, so it says\n // nothing about the router being down: it never starts the backoff.\n if (free.status === 'failed') {\n return {\n status: 'failed',\n reason: free.reason,\n ...(free.errorCode !== undefined ? { errorCode: free.errorCode } : {}),\n // Still no answer, which must not end another call's backoff.\n ...(free.noAnswer === true ? { noAnswer: true as const } : {}),\n freePath: err.why,\n };\n }\n return free.status === 'skipped' ? free : { ...free, freePath: err.why };\n }\n return readDecision(response, schema);\n}\n\n/** Why a call from a spec stopped before anything was signed: the input did\n * not fit, the live terms were not the spec's, the provider answered\n * something else, it could not be reached, or the wallet could not pay. */\nexport type UnpaidReason = 'input' | 'terms' | 'provider' | 'unreachable' | 'wallet';\n\n/** How a call run from a request spec ended, for the server's offer-to-call\n * count. No text: the id, the outcome, the provider's status and the time. */\nexport interface SpecOutcome {\n id: string;\n /** `unpaid`: stopped before anything was signed, which the server never\n * counts as the offer taken. */\n status: 'fulfilled' | 'unverified' | 'failed' | 'needs_approval' | 'unpaid';\n /** On `unpaid` only, where the server requires it. */\n reason?: UnpaidReason;\n httpStatus?: number;\n ms?: number;\n}\n\n/** The outcome report's own deadline: it is telemetry and never holds a result. */\nexport const OUTCOME_TIMEOUT_MS = 3_000;\n\n/**\n * TELL THE SERVER A SPEC WAS USED. The client called and paid the provider\n * itself, so this is the only word the server gets that its offer was taken,\n * or that a call for it stopped before payment and why. Never throws and never\n * waits on anything the caller needs: a lost report costs one count.\n */\nexport async function reportSpecOutcome(\n outcome: SpecOutcome,\n deps: Pick<DecisionDeps, 'ctx' | 'baseUrl' | 'fetchImpl'>,\n): Promise<void> {\n try {\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: OUTCOME_TIMEOUT_MS,\n blockRedirects: true,\n jsonBody: buildOutcomeBody(outcome),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n } catch {\n // Telemetry only.\n }\n}\n\n/** The exact body of an outcome report, pinned to the shared fixtures. */\nexport function buildOutcomeBody(outcome: SpecOutcome): Record<string, unknown> {\n return {\n schemaVersion: 1,\n id: outcome.id,\n status: outcome.status,\n ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}),\n ...(outcome.httpStatus !== undefined ? { httpStatus: outcome.httpStatus } : {}),\n ...(outcome.ms !== undefined ? { ms: Math.max(0, Math.round(outcome.ms)) } : {}),\n };\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason; nothing was paid either way,\n // because there is nothing to pay for on this route.\n if (!response.ok) {\n return {\n status: 'failed',\n reason: fetchFailureToCliError(response).message,\n ...(isUnreachable(response) ? { unreachable: true as const } : {}),\n ...(response.status === undefined ? { noAnswer: true as const } : {}),\n };\n }\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n\n/** A dropped socket, which a fresh connection usually gets past. */\nconst RESET_CODES = new Set(['ECONNRESET', 'UND_ERR_SOCKET']);\n\n/**\n * A ROUTER THAT CANNOT BE REACHED: the transport named the layer that refused\n * the connection (DNS, TLS, a refused connection, a proxy refusing the tunnel)\n * and no status came back. Never the call's own timeout: that is the gate's\n * few seconds, and a slow decision or a cold start must not take the router\n * away from every session. Never a status, even with a body that failed to\n * read, and never a reset socket, which the free path retries on a fresh one.\n */\nexport function isUnreachable(failure: FetchJsonFailure): boolean {\n return (\n failure.kind === 'network' &&\n failure.status === undefined &&\n failure.transport !== undefined &&\n !RESET_CODES.has(failure.transport.code ?? '')\n );\n}\n"],"mappings":";;;;;;;;;;AA2BO,IAAM,cAAc;AAO3B,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EAC7B,KAAK,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM;AAAA,EACjC,QAAQ,iBAAE,KAAK,CAAC,OAAO,QAAQ,OAAO,SAAS,UAAU,QAAQ,SAAS,CAAC;AAAA,EAC3E,SAAS,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,OAAO,CAAC;AAAA,EACxC,MAAM,iBACH,OAAO,EACP,IAAI,MAAM,IAAI,EACd,SAAS;AACd,CAAC;AAED,IAAM,iBAAiB,iBAAE,OAAO;AAAA;AAAA;AAAA,EAG9B,WAAW,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,C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nE,SAAO,EAAE,MAAM,SAAS,KAAK;AAC/B;AAGA,IAAM,cAAc,oBAAI,IAAI,CAAC,cAAc,gBAAgB,CAAC;AAUrD,SAAS,cAAc,SAAoC;AAChE,SACE,QAAQ,SAAS,aACjB,QAAQ,WAAW,UACnB,QAAQ,cAAc,UACtB,CAAC,YAAY,IAAI,QAAQ,UAAU,QAAQ,EAAE;AAEjD;","names":[]}
|
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
|
+
CliError,
|
|
3
4
|
external_exports
|
|
4
|
-
} from "./chunk-
|
|
5
|
-
import {
|
|
6
|
-
CliError
|
|
7
|
-
} from "./chunk-JLEF5WHM.js";
|
|
5
|
+
} from "./chunk-QTND6XWJ.js";
|
|
8
6
|
|
|
9
7
|
// src/lib/output.ts
|
|
10
8
|
import { WriteStream } from "node:tty";
|
|
@@ -236,4 +234,4 @@ export {
|
|
|
236
234
|
style,
|
|
237
235
|
paint
|
|
238
236
|
};
|
|
239
|
-
//# sourceMappingURL=chunk-
|
|
237
|
+
//# sourceMappingURL=chunk-XVTD7UWR.js.map
|