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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +18 -26
  2. package/dist/alive-3J3CHOQP.js +21 -0
  3. package/dist/{chunk-XVYATBKD.js → chunk-25GGN553.js} +897 -522
  4. package/dist/chunk-25GGN553.js.map +1 -0
  5. package/dist/{chunk-B2L53TMK.js → chunk-2SNUOHAT.js} +28 -23
  6. package/dist/chunk-2SNUOHAT.js.map +1 -0
  7. package/dist/{chunk-5NEHH2E5.js → chunk-3FY5HG7R.js} +86 -19
  8. package/dist/chunk-3FY5HG7R.js.map +1 -0
  9. package/dist/{chunk-YQOQ6XEI.js → chunk-4FYMDRD3.js} +51 -41
  10. package/dist/chunk-4FYMDRD3.js.map +1 -0
  11. package/dist/chunk-6W5GYG3W.js +128 -0
  12. package/dist/chunk-6W5GYG3W.js.map +1 -0
  13. package/dist/{chunk-G4AM2SOL.js → chunk-AMEUXNJT.js} +4 -8
  14. package/dist/{chunk-G4AM2SOL.js.map → chunk-AMEUXNJT.js.map} +1 -1
  15. package/dist/chunk-EWLU46J6.js +100 -0
  16. package/dist/chunk-EWLU46J6.js.map +1 -0
  17. package/dist/chunk-LRCJ2IZ5.js +115 -0
  18. package/dist/{chunk-HC3QEZKT.js.map → chunk-LRCJ2IZ5.js.map} +1 -1
  19. package/dist/{chunk-X7I343ZY.js → chunk-LX5OT4TQ.js} +3 -3
  20. package/dist/{chunk-X7I343ZY.js.map → chunk-LX5OT4TQ.js.map} +1 -1
  21. package/dist/{chunk-DATCR7AU.js → chunk-MG3G644T.js} +5 -7
  22. package/dist/{chunk-DATCR7AU.js.map → chunk-MG3G644T.js.map} +1 -1
  23. package/dist/{chunk-BOAI23CX.js → chunk-MOG7PB3A.js} +21 -15
  24. package/dist/chunk-MOG7PB3A.js.map +1 -0
  25. package/dist/{chunk-GU4GGKYP.js → chunk-MRUPDSUM.js} +14 -59
  26. package/dist/chunk-MRUPDSUM.js.map +1 -0
  27. package/dist/{chunk-AWKQSKUL.js → chunk-OOSRB3OF.js} +2 -2
  28. package/dist/{chunk-PZ5N6BAL.js → chunk-ORWL5BSN.js} +5 -4
  29. package/dist/chunk-ORWL5BSN.js.map +1 -0
  30. package/dist/chunk-P4LVLFO4.js +29 -0
  31. package/dist/chunk-P4LVLFO4.js.map +1 -0
  32. package/dist/{chunk-VXIBZ6W5.js → chunk-QTGUDCIR.js} +5 -5
  33. package/dist/{chunk-YKM2ZTA2.js → chunk-R4AO7GC2.js} +462 -105
  34. package/dist/chunk-R4AO7GC2.js.map +1 -0
  35. package/dist/{chunk-OHZYNZSD.js → chunk-RJEPZMYY.js} +12 -8
  36. package/dist/chunk-RJEPZMYY.js.map +1 -0
  37. package/dist/chunk-SBL4THYT.js +2074 -0
  38. package/dist/chunk-SBL4THYT.js.map +1 -0
  39. package/dist/{chunk-VNNXAYJE.js → chunk-SFEQGENI.js} +2 -2
  40. package/dist/{chunk-K6AXXYCG.js → chunk-SJLTEINJ.js} +10 -2
  41. package/dist/{chunk-K6AXXYCG.js.map → chunk-SJLTEINJ.js.map} +1 -1
  42. package/dist/{chunk-5FGO6TYT.js → chunk-TROZ6HL4.js} +3 -5
  43. package/dist/{chunk-5FGO6TYT.js.map → chunk-TROZ6HL4.js.map} +1 -1
  44. package/dist/{chunk-SKQQOEWH.js → chunk-USOLCBKC.js} +6 -8
  45. package/dist/{chunk-SKQQOEWH.js.map → chunk-USOLCBKC.js.map} +1 -1
  46. package/dist/{chunk-64SE3QC5.js → chunk-VKQXVCZR.js} +54 -5
  47. package/dist/chunk-VKQXVCZR.js.map +1 -0
  48. package/dist/{chunk-VIOUZW7Z.js → chunk-VVAHFCX2.js} +209 -37
  49. package/dist/chunk-VVAHFCX2.js.map +1 -0
  50. package/dist/{chunk-4L7KMA7P.js → chunk-WM7TJEBP.js} +8 -10
  51. package/dist/{chunk-4L7KMA7P.js.map → chunk-WM7TJEBP.js.map} +1 -1
  52. package/dist/{chunk-2TYQD22Q.js → chunk-XDYKZRLN.js} +23 -16
  53. package/dist/chunk-XDYKZRLN.js.map +1 -0
  54. package/dist/{chunk-LAIZ2AQA.js → chunk-XJQ6CH7X.js} +3 -2
  55. package/dist/{chunk-O7CUHHYU.js → chunk-ZQNGTLOC.js} +8 -10
  56. package/dist/{chunk-O7CUHHYU.js.map → chunk-ZQNGTLOC.js.map} +1 -1
  57. package/dist/{cli-6JNIPZQ6.js → cli-JPTDHGRX.js} +58 -52
  58. package/dist/{cli-6JNIPZQ6.js.map → cli-JPTDHGRX.js.map} +1 -1
  59. package/dist/{config-G75YT6NC.js → config-YYKDH2TH.js} +12 -15
  60. package/dist/{doctor-3GMDOW4Y.js → doctor-SSTXGCHX.js} +298 -269
  61. package/dist/doctor-SSTXGCHX.js.map +1 -0
  62. package/dist/{fund-3IPR5YRJ.js → fund-QWVWRVDK.js} +95 -43
  63. package/dist/{fund-3IPR5YRJ.js.map → fund-QWVWRVDK.js.map} +1 -1
  64. package/dist/hook-command-VWJXRT7H.js +31 -0
  65. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  66. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
  67. package/dist/hosts/claude/tenjin/.mcp.json +12 -0
  68. package/dist/hosts/claude/tenjin/hooks/hooks.json +221 -0
  69. package/dist/index.js +13 -4
  70. package/dist/index.js.map +1 -1
  71. package/dist/install-2GXXD4DK.js +51 -0
  72. package/dist/{install-identity-PM4AGFFX.js → install-identity-FK3YF227.js} +7 -9
  73. package/dist/{install-wallet-6756NOB5.js → install-wallet-TC22U52X.js} +21 -17
  74. package/dist/{install-wallet-6756NOB5.js.map → install-wallet-TC22U52X.js.map} +1 -1
  75. package/dist/{mcp-33FAAZ7F.js → mcp-42H2F4NY.js} +2128 -372
  76. package/dist/mcp-42H2F4NY.js.map +1 -0
  77. package/dist/package-6DJA3Y2O.js +37 -0
  78. package/dist/{paths-MUXHUOCM.js → paths-POPTXJO6.js} +6 -2
  79. package/dist/{pay-XOYR4PCH.js → pay-LSDJBIAZ.js} +20 -18
  80. package/dist/payments-SPECLBRQ.js +105 -0
  81. package/dist/payments-SPECLBRQ.js.map +1 -0
  82. package/dist/{send-CVGNOQW3.js → send-MHAOLPK3.js} +13 -17
  83. package/dist/{send-CVGNOQW3.js.map → send-MHAOLPK3.js.map} +1 -1
  84. package/dist/status-O2RWLPS5.js +114 -0
  85. package/dist/status-O2RWLPS5.js.map +1 -0
  86. package/dist/{status-line-3IQKGRUH.js → status-line-45TVCRM3.js} +7 -9
  87. package/dist/{status-line-3IQKGRUH.js.map → status-line-45TVCRM3.js.map} +1 -1
  88. package/dist/uninstall-VOK2Z5M4.js +146 -0
  89. package/dist/uninstall-VOK2Z5M4.js.map +1 -0
  90. package/dist/update-FGP3HNLD.js +33 -0
  91. package/dist/update-FGP3HNLD.js.map +1 -0
  92. package/dist/{wallet-B3FVHNTS.js → wallet-DA7OFNEW.js} +18 -14
  93. package/dist/wallet-DA7OFNEW.js.map +1 -0
  94. package/docs/agent-permissions.md +35 -22
  95. package/docs/safety-model.md +3 -1
  96. package/package.json +2 -2
  97. package/dist/chunk-2TYQD22Q.js.map +0 -1
  98. package/dist/chunk-5NEHH2E5.js.map +0 -1
  99. package/dist/chunk-64SE3QC5.js.map +0 -1
  100. package/dist/chunk-6ZSGER3A.js +0 -52
  101. package/dist/chunk-6ZSGER3A.js.map +0 -1
  102. package/dist/chunk-B2L53TMK.js.map +0 -1
  103. package/dist/chunk-BOAI23CX.js.map +0 -1
  104. package/dist/chunk-DSNXKUXI.js +0 -172
  105. package/dist/chunk-DSNXKUXI.js.map +0 -1
  106. package/dist/chunk-GU4GGKYP.js.map +0 -1
  107. package/dist/chunk-H2L33M7F.js +0 -944
  108. package/dist/chunk-H2L33M7F.js.map +0 -1
  109. package/dist/chunk-HC3QEZKT.js +0 -87
  110. package/dist/chunk-JLEF5WHM.js +0 -132
  111. package/dist/chunk-JLEF5WHM.js.map +0 -1
  112. package/dist/chunk-MAQUL5BD.js +0 -99
  113. package/dist/chunk-MAQUL5BD.js.map +0 -1
  114. package/dist/chunk-OHZYNZSD.js.map +0 -1
  115. package/dist/chunk-PY7MQUKP.js +0 -755
  116. package/dist/chunk-PY7MQUKP.js.map +0 -1
  117. package/dist/chunk-PZ5N6BAL.js.map +0 -1
  118. package/dist/chunk-TGLKKLQG.js +0 -11
  119. package/dist/chunk-TGLKKLQG.js.map +0 -1
  120. package/dist/chunk-VIOUZW7Z.js.map +0 -1
  121. package/dist/chunk-XVYATBKD.js.map +0 -1
  122. package/dist/chunk-YKM2ZTA2.js.map +0 -1
  123. package/dist/chunk-YQOQ6XEI.js.map +0 -1
  124. package/dist/doctor-3GMDOW4Y.js.map +0 -1
  125. package/dist/hook-command-ZXX4FT4N.js +0 -32
  126. package/dist/install-6OROTYHZ.js +0 -72
  127. package/dist/mcp-33FAAZ7F.js.map +0 -1
  128. package/dist/payments-UTQDBO7H.js +0 -48
  129. package/dist/payments-UTQDBO7H.js.map +0 -1
  130. package/dist/status-NACN4DGX.js +0 -72
  131. package/dist/status-NACN4DGX.js.map +0 -1
  132. package/dist/status-line-wiring-QXBOOY2T.js +0 -31
  133. package/dist/uninstall-NYFKSYW4.js +0 -175
  134. package/dist/uninstall-NYFKSYW4.js.map +0 -1
  135. package/dist/update-RJDA5ZY3.js +0 -442
  136. package/dist/update-RJDA5ZY3.js.map +0 -1
  137. /package/dist/{config-G75YT6NC.js.map → alive-3J3CHOQP.js.map} +0 -0
  138. /package/dist/{chunk-AWKQSKUL.js.map → chunk-OOSRB3OF.js.map} +0 -0
  139. /package/dist/{chunk-VXIBZ6W5.js.map → chunk-QTGUDCIR.js.map} +0 -0
  140. /package/dist/{chunk-VNNXAYJE.js.map → chunk-SFEQGENI.js.map} +0 -0
  141. /package/dist/{chunk-LAIZ2AQA.js.map → chunk-XJQ6CH7X.js.map} +0 -0
  142. /package/dist/{hook-command-ZXX4FT4N.js.map → config-YYKDH2TH.js.map} +0 -0
  143. /package/dist/{install-6OROTYHZ.js.map → hook-command-VWJXRT7H.js.map} +0 -0
  144. /package/dist/{install-identity-PM4AGFFX.js.map → install-2GXXD4DK.js.map} +0 -0
  145. /package/dist/{paths-MUXHUOCM.js.map → install-identity-FK3YF227.js.map} +0 -0
  146. /package/dist/{pay-XOYR4PCH.js.map → package-6DJA3Y2O.js.map} +0 -0
  147. /package/dist/{status-line-wiring-QXBOOY2T.js.map → paths-POPTXJO6.js.map} +0 -0
  148. /package/dist/{wallet-B3FVHNTS.js.map → pay-LSDJBIAZ.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/doctor.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport pkg from '../../package.json';\nimport { loadRawConfig } from '../lib/config';\nimport { CliError } from '../lib/errors';\nimport { toMoney } from '../lib/money';\nimport { evaluateSpendPolicy, type SpendPolicy } from '../lib/policy';\nimport { resolveContextSettings, type ResolvedSettings } from '../lib/settings';\nimport { spentOf } from '../lib/spend-ledger';\nimport { isNewer } from '../lib/update-check';\nimport { readUsdcBalance } from '../lib/usdc-balance';\nimport { describeWallet, resolveWalletProvider, type WalletProvider } from '../lib/wallet';\nimport { readSpendSummary } from '../lib/wallet/spend';\nimport { walletFileExists } from '../lib/wallet/store';\nimport type { CommandContext, CommandResult } from '../context';\nimport { agentsWithoutRequestTool } from './agent-tools';\nimport { readAliveStamp } from './alive';\nimport {\n CLAUDE_CODE_FLOOR,\n claudeConfigDir,\n findClaudeBinary,\n readClaudeCode,\n runClaude,\n type ClaudeBinary,\n type ClaudeCodeState,\n} from './claude-cli';\nimport {\n CHANNEL_DEPOSIT_ATOMIC,\n feeRefusal,\n MIN_DEPOSIT_ATOMIC,\n ROUTING_FEE_ATOMIC,\n SUGGESTED_FUND_USD,\n unpaid,\n usd,\n} from './fee';\nimport { channelCredit } from './channel-credit';\nimport { loadStep, pluginProof, projectInstallHere, settingsInstallPaths } from './install';\nimport { inspectLegacyInstall, type LegacyInstall } from './legacy-install';\nimport { routerSettings, type RouterSettings } from './settings';\nimport { PLUGIN_ID, PLUGIN_SERVER, REQUEST_TOOL } from './names';\nimport { folderState, readPluginListing, type PluginScope } from './plugin-registration';\nimport { probeRouter, type RouterCheck } from './reachability';\nimport { readMcpServers, type InstalledAt, type ListMcpProcesses } from './mcp-processes';\nimport { clearRouterMemo, readRouterMemo, type RouterMemo } from './router-memo';\nimport {\n ACCEPT_COMMAND,\n OWN_LIMITS_COMMANDS,\n shownLimits,\n spendQuestion,\n type RouterLimits,\n} from './spend-question';\n\n/**\n * `tenjin doctor` for the router product: the things that decide whether a\n * lookup can happen at all, read and never written.\n *\n * THE PLUGIN IS ASKED ABOUT THROUGH CLAUDE CODE ITSELF: `claude --version`\n * against the floor, `claude plugin list --json` for the plugin and its\n * version, and `claude mcp get` for its `router` server. With no binary, the\n * plugin folder and the `alive` stamp stand in. A settings install of an\n * earlier release is reported with its migration state; doctor never migrates.\n *\n * EVERY FIX IS A STEP THE AGENT TAKES IN THE SESSION: a command it runs, or a\n * slash command the person types there. None sends anyone out of Claude Code.\n *\n * THE SHELF'S DOCTOR IS NOT THIS ONE. It stays with the product it belongs to\n * (`src/commands/doctor.ts`, unregistered), and this one reports the router's\n * own wiring.\n */\n\nexport type { RouterCheck };\n\nexport interface RouterDoctorDeps {\n homeDir?: string;\n cwd?: string;\n /** Check the project install, as `install --project` registered it. Absent,\n * a project install in `cwd` is found ({@link projectInstallHere}). */\n project?: boolean;\n env?: NodeJS.ProcessEnv;\n /** Finds the `claude` binary; tests inject one. */\n findClaude?: (env: NodeJS.ProcessEnv) => ClaudeBinary | null;\n fetchImpl?: typeof fetch;\n /** Node's own version, for the floor check. */\n nodeVersion?: string;\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 now?: () => number;\n}\n\nconst NODE_FLOOR = 22;\n/** The stamp row's fix: a new session first, since a reload never stamps, then the Node it runs. */\nconst STAMP_FIX =\n \"Start a new Claude Code session and run `tenjin doctor` again: `/reload-plugins` does not run the plugin's `SessionStart`, so only a new session writes the stamp. If it still warns, run `node --version` in that session's shell: Claude Code starts the plugin with the Node on its own PATH, and it must be 22 or newer. Restart Claude Code after installing or updating Node.\";\n\nexport async function runRouterDoctor(\n ctx: CommandContext,\n deps: RouterDoctorDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n const cwd = deps.cwd ?? process.cwd();\n // WITHOUT THE FLAG, THE INSTALL THIS DIRECTORY HOLDS: a project install\n // found here is the one a session here runs, so it is the one checked.\n const project = deps.project ?? (await projectInstallHere(cwd, home, env));\n // From the directory doctor runs in, which is the one a session there would use.\n const router = await routerSettings(\n { cwd, dataDir: ctx.dataDir },\n deps.homeDir !== undefined ? { homeDir: deps.homeDir } : {},\n ).catch((err: unknown) => (err instanceof Error ? err : new Error(String(err))));\n const settings = await resolveContextSettings(ctx);\n const claude = await readClaudeCode(env, cwd, deps.findClaude ?? findClaudeBinary);\n const scope: PluginScope = project ? 'local' : 'user';\n const paths = settingsInstallPaths(project, env, home, cwd);\n const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);\n\n const checks: RouterCheck[] = [nodeCheck(deps.nodeVersion ?? process.version)];\n checks.push(claudeCodeCheck(claude));\n const plugin = await pluginCheck(claude, { scope, env, home, cwd, dataDir: ctx.dataDir, legacy });\n checks.push(plugin.check);\n if (plugin.registered && claude.binary !== null) {\n checks.push(await serverCheck(claude.binary, env, cwd));\n }\n if (legacy.present || legacy.unreadable !== undefined) {\n checks.push(await migrationCheck(legacy, claude, ctx.dataDir, env, cwd));\n }\n checks.push(routingCheck(router));\n checks.push((await readMcpServers(deps, { settingsInstallPending: legacy.present })).check);\n const rawConfig = await loadRawConfig(ctx.dataDir);\n const unanswered =\n rawConfig.maxAutoSpend === undefined ? { limits: shownLimits(rawConfig) } : null;\n checks.push(\n spendCheck(settings.policy.maxAutoSpendAtomic, settings.policy.sessionBudgetAtomic, unanswered),\n );\n checks.push(experimentalCheck(settings.experimentalBazaar));\n checks.push(await routingFeeCheck(ctx, settings, deps.fetchImpl, unanswered));\n checks.push(...(await walletCheck(ctx)));\n const now = deps.now?.() ?? Date.now();\n const probe = await probeRouter(settings.baseUrl, {\n timeoutMs: ctx.flags.timeout,\n env,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n // A probe the router answered ends the routing legs' backoff at once.\n if (probe.status === 'ok') {\n await clearRouterMemo(ctx.dataDir, 'unreachable', settings.baseUrl);\n checks.push(probe);\n } else {\n checks.push(\n withBackoff(\n probe,\n await readRouterMemo(ctx.dataDir, 'unreachable', settings.baseUrl, now),\n now,\n ),\n );\n }\n const agents = await subagentsCheck(cwd, home);\n if (agents !== null) checks.push(agents);\n\n const failure = checks.find((c) => c.status === 'fail' && c.required);\n const data = {\n checks,\n dataDir: ctx.dataDir,\n baseUrl: settings.baseUrl,\n scope,\n settingsPath: paths.settingsPath,\n };\n if (failure !== undefined) {\n // REFUSED, the exit-3 class: a machine this command found unready is\n // understood and refused, not a runtime failure of the command itself.\n throw new CliError('REFUSED', failure.detail, {\n ...(failure.fix !== undefined ? { fix: failure.fix } : {}),\n details: data,\n });\n }\n return { data, humanLines: doctorLines(checks) };\n}\n\n/** The human report: one line a check, and under each row to look at, its\n * fix, as `--json` carries it. */\nexport function doctorLines(checks: RouterCheck[]): string[] {\n const bad = checks.filter((c) => c.status !== 'ok').length;\n return [\n ...checks.flatMap((c) => [\n `${c.status === 'ok' ? 'ok ' : c.status === 'warn' ? 'warn' : 'fail'} ${c.name}: ${c.detail}`,\n ...(c.status !== 'ok' && c.fix !== undefined ? [` fix: ${c.fix}`] : []),\n ]),\n bad === 0\n ? `${checks.length} checks, all pass.`\n : `${checks.length} checks, ${bad} to look at.`,\n ];\n}\n\n/**\n * The routing legs' backoff, named on a router line whose probe failed too.\n * It ends by itself after its minute, or when a probe here reaches the router.\n */\nfunction withBackoff(check: RouterCheck, memo: RouterMemo | null, now: number): RouterCheck {\n if (memo === null) return check;\n const left = Math.max(1, Math.ceil((memo.until - now) / 1000));\n return {\n ...check,\n status: check.status === 'ok' ? 'warn' : check.status,\n detail: `${check.detail}; routing calls skip the router for ${left}s more, after one did not reach it`,\n };\n}\n\n/**\n * INFORMATIONAL, NEVER A FAILURE. A custom agent whose `tools:` leave the\n * request tool out is a choice its author may have meant, so this names those\n * agents and the one line that would change it, and counts as passing. It is\n * absent when there is nothing to name. The files are only read.\n */\nasync function subagentsCheck(cwd: string, homeDir: string): Promise<RouterCheck | null> {\n const excluded = await agentsWithoutRequestTool({ cwd, homeDir }, REQUEST_TOOL);\n if (excluded.length === 0) return null;\n return {\n name: 'subagents',\n status: 'ok',\n required: false,\n detail: `${excluded.join(', ')} ${excluded.length === 1 ? 'is' : 'are'} offered no paid lookups: add ${REQUEST_TOOL} to tools: to allow paid lookups there`,\n };\n}\n\nfunction nodeCheck(version: string): RouterCheck {\n const major = Number(/^v(\\d+)/.exec(version)?.[1] ?? '0');\n return major >= NODE_FLOOR\n ? { name: 'node', status: 'ok', required: true, detail: version }\n : {\n name: 'node',\n status: 'fail',\n required: true,\n detail: `${version} is below the Node ${NODE_FLOOR} floor.`,\n fix: `Install Node ${NODE_FLOOR} or newer, then re-run \\`tenjin doctor\\`.`,\n };\n}\n\n/** Claude Code's version against the plugin's floor. */\nfunction claudeCodeCheck(claude: ClaudeCodeState): RouterCheck {\n const name = 'claude code';\n if (claude.binary === null) {\n return {\n name,\n status: 'warn',\n required: false,\n detail:\n 'no claude binary on PATH or in CLAUDE_CODE_EXECPATH, so the plugin was checked from its folder only',\n fix: 'Run `tenjin doctor` from a Claude Code session, where CLAUDE_CODE_EXECPATH names the binary.',\n };\n }\n if (claude.version === null) {\n return {\n name,\n status: 'warn',\n required: false,\n detail: `${claude.binary.path} did not report a version`,\n };\n }\n if (!claude.meetsFloor) {\n return {\n name,\n status: 'fail',\n required: true,\n detail: `Claude Code ${claude.version} is older than ${CLAUDE_CODE_FLOOR}, which the Tenjin plugin needs`,\n ...(claude.fix !== undefined ? { fix: claude.fix } : {}),\n };\n }\n return {\n name,\n status: 'ok',\n required: true,\n detail: `${claude.version}${claude.binary.source === 'execpath' ? ' (from CLAUDE_CODE_EXECPATH)' : ''}`,\n };\n}\n\ninterface PluginContext {\n scope: PluginScope;\n env: NodeJS.ProcessEnv;\n home: string;\n cwd: string;\n dataDir: string;\n legacy: LegacyInstall;\n}\n\n/**\n * The plugin: listed and enabled at this CLI's version and stamped by a\n * session at it, or, with no binary to ask, its folder and the `alive` stamp. A machine that still routes through a\n * settings install of an earlier release warns rather than fails.\n */\nasync function pluginCheck(\n claude: ClaudeCodeState,\n c: PluginContext,\n): Promise<{ check: RouterCheck; registered: boolean }> {\n const name = 'plugin';\n const missing = (detail: string): { check: RouterCheck; registered: boolean } => ({\n registered: false,\n check: c.legacy.present\n ? {\n name,\n status: 'warn',\n required: false,\n detail: `${detail}; the settings install of an earlier release still routes here`,\n fix: claude.meetsFloor\n ? `Run \\`tenjin install${c.scope === 'local' ? ' --project' : ''}\\` to move this machine to the plugin.`\n : `Run \\`claude update\\`, then \\`tenjin install${c.scope === 'local' ? ' --project' : ''}\\` to move this machine to the plugin.`,\n }\n : {\n name,\n status: 'fail',\n required: true,\n detail,\n fix: `Run \\`tenjin install${c.scope === 'local' ? ' --project' : ''}\\`.`,\n },\n });\n if (claude.binary !== null) {\n const listing = await readPluginListing(claude.binary, c.env, c.cwd);\n if (!listing.read) {\n return {\n registered: false,\n check: {\n name,\n status: 'warn',\n required: false,\n detail: \"Claude Code's plugin list could not be read, so the plugin was not checked\",\n fix: 'Run `tenjin doctor` again in a moment.',\n },\n };\n }\n if (listing.id === null) return missing(`${PLUGIN_ID} is not installed in Claude Code`);\n if (!listing.enabled) {\n return {\n registered: false,\n check: {\n name,\n status: 'fail',\n required: true,\n detail: `${listing.id} is installed but disabled, so no lookup is routed`,\n fix: `Run \\`claude plugin enable ${listing.id}\\`, then ${loadStep(c.legacy.present)}.`,\n },\n };\n }\n if (listing.version !== pkg.version) {\n return {\n registered: true,\n check: {\n name,\n status: 'warn',\n required: false,\n detail: `${listing.id} is enabled at ${listing.version ?? 'an unknown version'}, and this CLI is ${pkg.version}`,\n fix: 'Run `tenjin install --refresh` to register this version.',\n },\n };\n }\n // Claude Code's own environment shows only in the `alive` stamp, which the\n // plugin's SessionStart leg writes from a real session: doctor's PATH may\n // find a Node that Claude Code's does not.\n const stamp = await readAliveStamp(c.dataDir);\n if (stamp === null || isNewer(pkg.version, stamp.version)) {\n return {\n registered: true,\n check: {\n name,\n status: 'warn',\n required: false,\n detail: `${listing.id} ${pkg.version} is enabled, and no session has started it at this version${stamp !== null ? ` (last ${stamp.version}, at ${stamp.at})` : ''}`,\n fix: STAMP_FIX,\n },\n };\n }\n return {\n registered: true,\n check: { name, status: 'ok', required: true, detail: `${listing.id} ${pkg.version} enabled` },\n };\n }\n const folder = await folderState(c.scope, c.env, c.home, c.cwd);\n if (folder.state === 'foreign') {\n return {\n registered: false,\n check: {\n name,\n status: 'fail',\n required: true,\n detail: `${folder.path} is there and is not a folder this CLI wrote, so the plugin cannot be written`,\n fix: `Move ${folder.path} aside, then run \\`tenjin install\\` again.`,\n },\n };\n }\n if (folder.state === 'ours') {\n const stamp = await readAliveStamp(c.dataDir);\n return {\n registered: true,\n check:\n stamp === null\n ? {\n name,\n status: 'warn',\n required: false,\n detail: `the plugin folder is at ${folder.path} and has not loaded in a session yet`,\n fix: `To load it, ${loadStep(c.legacy.present)}.`,\n }\n : {\n name,\n status: 'ok',\n required: true,\n detail: `the plugin folder at ${folder.path} loaded, last at ${stamp.at}`,\n },\n };\n }\n if (await listedInClaudeFiles(c.env, c.home)) {\n return {\n registered: true,\n check: {\n name,\n status: 'warn',\n required: false,\n detail: `${PLUGIN_ID} is registered, and there is no claude binary here to check it`,\n fix: 'Run `tenjin doctor` from a Claude Code session to check it.',\n },\n };\n }\n return missing(`${PLUGIN_ID} is not registered`);\n}\n\n/** Claude Code's own record, read when no binary can be asked. */\nasync function listedInClaudeFiles(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 * The plugin's `router` server, through `claude mcp get`, which starts it the\n * way a session would and reports whether it answered. `claude mcp get` runs\n * with doctor's own environment, so it starts `node` from doctor's PATH, not\n * the PATH a running Claude Code started with: a connected server here does\n * not prove a session can start it. The `plugin` row's `alive` stamp is the\n * proof from a real session.\n */\nasync function serverCheck(\n binary: ClaudeBinary,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): Promise<RouterCheck> {\n const name = 'router server';\n const run = await runClaude(binary, ['mcp', 'get', PLUGIN_SERVER], {\n env,\n cwd,\n timeoutMs: 45_000,\n });\n const status = /Status:\\s*(.+)/.exec(run.stdout)?.[1]?.trim();\n if (\n run.code === 0 &&\n status !== undefined &&\n /connected/i.test(status) &&\n !/fail/i.test(status)\n ) {\n return { name, status: 'ok', required: true, detail: `${PLUGIN_SERVER} connected` };\n }\n return {\n name,\n status: 'fail',\n required: true,\n detail: `${PLUGIN_SERVER} did not connect${status !== undefined ? `: ${status.slice(0, 200)}` : ''}`,\n fix: 'Restart Claude Code (quit it from the tray) or sign out and in: the plugin starts the CLI with `node` from the PATH Claude Code started with, so a Claude Code opened before Node was installed cannot find it.',\n };\n}\n\n/**\n * A settings install of an earlier release: what is left, and whether the\n * next `tenjin install` or `tenjin update` removes it. Never a failure, and\n * never written here.\n */\nasync function migrationCheck(\n legacy: LegacyInstall,\n claude: ClaudeCodeState,\n dataDir: string,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): Promise<RouterCheck> {\n const name = 'settings install';\n if (legacy.unreadable !== undefined) {\n return { name, status: 'warn', required: false, detail: legacy.unreadable };\n }\n const parts = [\n ...(legacy.events.length > 0 ? [`hook entries (${legacy.events.join(', ')})`] : []),\n ...(legacy.allowRule || legacy.denyRule ? ['permission rules'] : []),\n ...(legacy.statusLine === 'ours' || legacy.statusLine === 'composed' ? ['a status line'] : []),\n ...(legacy.mcp === 'ok' ? ['the x402 MCP server'] : []),\n ];\n const found = `${parts.join(', ')} from an earlier release in ${legacy.settingsPath}`;\n const lookalikes =\n legacy.lookalikes.length > 0\n ? `; not Tenjin's and left alone: ${legacy.lookalikes.join(', ')}`\n : '';\n const proof = await pluginProof(claude, dataDir, env, cwd);\n return proof.proven\n ? {\n name,\n status: 'warn',\n required: false,\n detail: `${found}, ready to remove: the plugin has loaded here${lookalikes}`,\n fix: 'Run `tenjin install --refresh` to remove it.',\n }\n : {\n name,\n status: 'warn',\n required: false,\n detail: `${found}, kept until the plugin loads: ${proof.reason}${lookalikes}`,\n fix: claude.meetsFloor\n ? `To load the plugin, ${loadStep(true)}; the next \\`tenjin install\\` or \\`tenjin update\\` then removes the old entries.`\n : 'Run `claude update`, then `tenjin install`: until then the old entries keep routing.',\n };\n}\n\n/**\n * WIRED BUT SWITCHED OFF is a choice, not a fault, so it warns and names the\n * file that made it.\n */\nfunction routingCheck(router: RouterSettings | Error): RouterCheck {\n const name = 'routing';\n if (router instanceof Error) {\n return {\n name,\n status: 'warn',\n required: false,\n detail: `the router is off here: ${router.message}`,\n fix: 'Fix or delete that file.',\n };\n }\n if (!router.enabled.value) {\n const file = router.enabled.path ?? 'the config';\n return {\n name,\n status: 'warn',\n required: false,\n detail: `router.enabled is false in ${file}, so nothing is routed from this directory`,\n fix:\n router.enabled.source === 'file'\n ? 'Run `tenjin config set router.enabled true` to route again.'\n : `Remove router.enabled from ${file} to route here again.`,\n };\n }\n return { name, status: 'ok', required: false, detail: 'on' };\n}\n\n/**\n * THE ROUTING FEE, AS THE NEXT PAID CALL WOULD MEET IT: the reasons the session\n * notice gives (`unpaid`), worked out here from the wallet, the spend limits,\n * the ledger and the channel the SDK keeps. Never a failure: a call the fee\n * cannot pay takes the free path. A payment that failed in a session leaves\n * nothing to read here; these are the causes this can check.\n */\nasync function routingFeeCheck(\n ctx: CommandContext,\n settings: ResolvedSettings,\n fetchImpl: typeof fetch | undefined,\n unanswered: { limits: RouterLimits } | null,\n): Promise<RouterCheck> {\n let host: string;\n try {\n host = new URL(settings.baseUrl).host;\n } catch {\n // The router check below names the bad base URL and its fix.\n return {\n name: 'routing fee',\n status: 'warn',\n required: false,\n detail: 'not checked, because the base URL is not a URL',\n };\n }\n const why = await routingFeeBlock({\n dataDir: ctx.dataDir,\n policy: settings.policy,\n rpcUrl: settings.rpcUrl,\n host,\n timeoutMs: ctx.flags.timeout,\n provider: (await walletFileExists(ctx.dataDir)) ? resolveWalletProvider(ctx) : null,\n ...(fetchImpl !== undefined ? { fetchImpl } : {}),\n }).catch(() => null);\n return routingFeeRow(why, host, unanswered);\n}\n\n/** The routing-fee row for what {@link routingFeeBlock} found. */\nexport function routingFeeRow(\n why: string | null,\n host: string,\n unanswered: { limits: RouterLimits } | null,\n): RouterCheck {\n const u = why === null ? null : unpaid(why);\n if (why === null || u === null) {\n return {\n name: 'routing fee',\n status: 'ok',\n required: false,\n detail: `$${usd(ROUTING_FEE_ATOMIC)} a call, paid from channel deposits of up to $${usd(CHANNEL_DEPOSIT_ATOMIC)} that count against the spend limits`,\n };\n }\n if (why === 'limit_below_deposit' && unanswered !== null) {\n // The zero is the open spend question, not a limit anyone chose: the fix\n // is the question itself, with the fee terms it approves.\n return {\n name: 'routing fee',\n status: 'warn',\n required: false,\n detail: 'the spend limits are not answered yet, so routing calls take the free path',\n fix: `Answer the spend question: ${spendQuestion(unanswered.limits)} For a yes, run \\`${ACCEPT_COMMAND}\\`; for other amounts, ${OWN_LIMITS_COMMANDS}.`,\n };\n }\n const fixes: Record<string, string> = {\n no_wallet: `Run \\`tenjin wallet create\\`, then \\`tenjin wallet fund ${SUGGESTED_FUND_USD}\\`.`,\n limit_below_deposit: `Raise it with \\`tenjin config set maxAutoSpend ${usd(CHANNEL_DEPOSIT_ATOMIC)}\\`.`,\n budget_reached:\n 'Room comes back as the rolling day passes, or raise it with `tenjin config set sessionBudget <usd>`.',\n not_allowlisted: `Add ${host} to allowlistCreators, or clear the allowlist.`,\n };\n return {\n name: 'routing fee',\n status: 'warn',\n required: false,\n detail: `${u.reason}, so routing calls take the free path`,\n fix: fixes[why] ?? u.fix,\n };\n}\n\n/** What {@link routingFeeBlock} reads; `provider` is null with no wallet. */\nexport interface RoutingFeeInput {\n dataDir: string;\n policy: SpendPolicy;\n rpcUrl: string;\n /** The router's host, the creator a deposit pays. */\n host: string;\n timeoutMs: number;\n provider: WalletProvider | null;\n fetchImpl?: typeof fetch;\n}\n\n/** Why the next deposit would be refused, or null when the fee can be paid. */\nexport async function routingFeeBlock(input: RoutingFeeInput): Promise<string | null> {\n const { provider, policy } = input;\n // The fee's per-payment checks first, before the wallet, as the payer runs\n // them on every call: a channel with credit pays nothing they refuse, and\n // unanswered limits are the question to name, not the passphrase.\n const refused = feeRefusal(policy, input.host);\n if (refused !== null) return refused;\n if (provider === null) return 'no_wallet';\n const verified = await provider.verify?.().catch(() => null);\n if (verified !== undefined && verified !== null && verified.status !== 'verified') {\n return 'wallet_locked';\n }\n const ledger = await readSpendSummary(input.dataDir);\n const spent = ledger === null ? 0n : spentOf(ledger);\n const { address } = await describeWallet(provider);\n if ((await channelCredit(input.dataDir, address)) >= ROUTING_FEE_ATOMIC) return null;\n const deposit =\n policy.maxAutoSpendAtomic < CHANNEL_DEPOSIT_ATOMIC\n ? policy.maxAutoSpendAtomic\n : CHANNEL_DEPOSIT_ATOMIC;\n if (deposit < MIN_DEPOSIT_ATOMIC) return 'limit_below_deposit';\n const evaluation = evaluateSpendPolicy(policy, {\n mode: 'automatic',\n amountAtomic: deposit,\n creator: input.host,\n sessionSpentAtomic: spent,\n });\n if (evaluation.reason === 'not_allowlisted') return 'not_allowlisted';\n if (evaluation.reason === 'session_budget_exceeded') return 'budget_reached';\n const balance = await readUsdcBalance(address, input.rpcUrl, {\n timeoutMs: input.timeoutMs,\n ...(input.fetchImpl !== undefined ? { fetchImpl: input.fetchImpl } : {}),\n });\n return balance !== null && balance < deposit ? 'wallet_low' : null;\n}\n\n/** INFORMATIONAL: which experiment is on, in one line. Either state passes. */\nfunction experimentalCheck(bazaar: boolean): RouterCheck {\n return {\n name: 'experimental',\n status: 'ok',\n required: false,\n detail: bazaar\n ? 'list: on; bazaar: on (experimental): the router may also suggest unreviewed sellers from the open x402 Bazaar'\n : 'list: on; bazaar: off (experimental): `tenjin config set experimental.bazaar on` to add the open x402 Bazaar',\n };\n}\n\n/**\n * `unanswered` is set when the config file names no `maxAutoSpend`: the state\n * an install that could not ask leaves, the same as a cancel at its selector.\n * The code default's zero holds, and that is a question still open, not a\n * broken machine, so it warns with the question and its one-step yes, and the\n * checks after it (the router probe above all) still print. A 0 the user\n * wrote is their answer and stays a failure.\n */\nfunction spendCheck(\n maxAutoSpendAtomic: bigint,\n sessionBudgetAtomic: bigint | null,\n unanswered: { limits: RouterLimits } | null,\n): RouterCheck {\n if (sessionBudgetAtomic === 0n) {\n return {\n name: 'spend',\n status: 'fail',\n required: true,\n detail: 'The daily limit is 0, so positive payments are refused even with --yes.',\n fix: 'Choose a daily limit with `tenjin config set sessionBudget <usd|none>`.',\n };\n }\n if (maxAutoSpendAtomic === 0n && unanswered !== null) {\n return {\n name: 'spend',\n status: 'warn',\n required: false,\n detail: `the spend limits are not answered yet, so automatic payments are off and every lookup needs approval. Ask the user: ${spendQuestion(unanswered.limits)}`,\n fix: `Answer the spend question: for a yes, run \\`${ACCEPT_COMMAND}\\`; for other amounts, ${OWN_LIMITS_COMMANDS}.`,\n };\n }\n if (maxAutoSpendAtomic === 0n) {\n return {\n name: 'spend',\n status: 'fail',\n required: true,\n detail: 'maxAutoSpend is 0, so every lookup needs approval and none can pay',\n fix: 'Set a per-call limit with `tenjin config set maxAutoSpend <usd>`.',\n };\n }\n const budget =\n sessionBudgetAtomic === null\n ? 'no daily ceiling'\n : `${toMoney(sessionBudgetAtomic.toString()).usd} USD a day`;\n return {\n name: 'spend',\n status: sessionBudgetAtomic === null ? 'warn' : 'ok',\n required: false,\n detail: `automatic approval up to ${toMoney(maxAutoSpendAtomic.toString()).usd} USD a call, ${budget}`,\n ...(sessionBudgetAtomic === null\n ? { fix: 'Set one with `tenjin config set sessionBudget 1.00`.' }\n : {}),\n };\n}\n\nasync function walletCheck(ctx: CommandContext): Promise<RouterCheck[]> {\n if (!(await walletFileExists(ctx.dataDir))) {\n return [\n {\n name: 'wallet',\n status: 'fail',\n required: true,\n detail: 'no wallet on this machine, so nothing can pay',\n fix: `Run \\`tenjin wallet create\\`, then \\`tenjin wallet fund ${SUGGESTED_FUND_USD}\\`.`,\n },\n ];\n }\n try {\n const described = await describeWallet(resolveWalletProvider(ctx));\n return [{ name: 'wallet', status: 'ok', required: true, detail: described.address }];\n } catch (err) {\n return [\n {\n name: 'wallet',\n status: 'fail',\n required: true,\n detail: err instanceof CliError ? err.message : String(err),\n ...(err instanceof CliError && err.fix !== undefined ? { fix: err.fix } : {}),\n },\n ];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,YAAY;AA0FrB,IAAM,aAAa;AAEnB,IAAM,YACJ;AAEF,eAAsB,gBACpB,KACA,OAAyB,CAAC,GACF;AACxB,QAAM,MAAM,KAAK,OAAO,QAAQ;AAChC,QAAM,OAAO,KAAK,WAAW,QAAQ;AACrC,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AAGpC,QAAM,UAAU,KAAK,WA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AI,OAAO,GAAI;AAC1C,WAAO;AAAA,MACL;AAAA,QACE,MAAM;AAAA,QACN,QAAQ;AAAA,QACR,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,KAAK,2DAA2D,kBAAkB;AAAA,MACpF;AAAA,IACF;AAAA,EACF;AACA,MAAI;AACF,UAAM,YAAY,MAAM,eAAe,sBAAsB,GAAG,CAAC;AACjE,WAAO,CAAC,EAAE,MAAM,UAAU,QAAQ,MAAM,UAAU,MAAM,QAAQ,UAAU,QAAQ,CAAC;AAAA,EACrF,SAAS,KAAK;AACZ,WAAO;AAAA,MACL;AAAA,QACE,MAAM;AAAA,QACN,QAAQ;AAAA,QACR,UAAU;AAAA,QACV,QAAQ,eAAe,WAAW,IAAI,UAAU,OAAO,GAAG;AAAA,QAC1D,GAAI,eAAe,YAAY,IAAI,QAAQ,SAAY,EAAE,KAAK,IAAI,IAAI,IAAI,CAAC;AAAA,MAC7E;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -3,23 +3,29 @@ import {
3
3
  SIWX_HEADER,
4
4
  buildSiwxHeader
5
5
  } from "./chunk-7EKYXMUO.js";
6
- import "./chunk-EL56RW2J.js";
7
- import "./chunk-TTNESUPQ.js";
8
- import "./chunk-HPWO4O6S.js";
9
- import "./chunk-POUWHWID.js";
10
- import "./chunk-XZKD7DIF.js";
11
6
  import {
12
7
  addressQrLines
13
- } from "./chunk-PZ5N6BAL.js";
8
+ } from "./chunk-ORWL5BSN.js";
14
9
  import {
15
10
  getUsdcBalance
16
- } from "./chunk-VNNXAYJE.js";
11
+ } from "./chunk-SFEQGENI.js";
12
+ import "./chunk-EL56RW2J.js";
17
13
  import {
18
14
  describeWallet,
19
15
  resolveWalletProvider
20
- } from "./chunk-O7CUHHYU.js";
21
- import "./chunk-VXIBZ6W5.js";
22
- import "./chunk-X7I343ZY.js";
16
+ } from "./chunk-ZQNGTLOC.js";
17
+ import "./chunk-QTGUDCIR.js";
18
+ import "./chunk-LX5OT4TQ.js";
19
+ import "./chunk-TTNESUPQ.js";
20
+ import "./chunk-HPWO4O6S.js";
21
+ import "./chunk-POUWHWID.js";
22
+ import "./chunk-XZKD7DIF.js";
23
+ import "./chunk-MEFB5KHA.js";
24
+ import "./chunk-2SNUOHAT.js";
25
+ import {
26
+ emitNotice,
27
+ emitWriteNotice
28
+ } from "./chunk-TROZ6HL4.js";
23
29
  import "./chunk-AWQPGIR6.js";
24
30
  import "./chunk-N35E6CM2.js";
25
31
  import "./chunk-JRGFKVAZ.js";
@@ -34,28 +40,18 @@ import "./chunk-BPMWXTFX.js";
34
40
  import {
35
41
  fetchFailureToCliError,
36
42
  httpRequest
37
- } from "./chunk-OHZYNZSD.js";
38
- import "./chunk-MEFB5KHA.js";
39
- import "./chunk-B2L53TMK.js";
40
- import {
41
- emitNotice,
42
- emitWriteNotice
43
- } from "./chunk-5FGO6TYT.js";
44
- import "./chunk-HC3QEZKT.js";
43
+ } from "./chunk-RJEPZMYY.js";
45
44
  import "./chunk-2I4QTOLB.js";
46
45
  import {
47
- toMoney
48
- } from "./chunk-6ZSGER3A.js";
49
- import {
46
+ CliError,
50
47
  PRODUCTION_ORIGIN,
51
48
  external_exports,
52
49
  loadRawConfig,
53
- resolveSettings
54
- } from "./chunk-VIOUZW7Z.js";
55
- import {
56
- CliError
57
- } from "./chunk-JLEF5WHM.js";
58
- import "./chunk-K6AXXYCG.js";
50
+ resolveSettings,
51
+ toMoney
52
+ } from "./chunk-VVAHFCX2.js";
53
+ import "./chunk-SJLTEINJ.js";
54
+ import "./chunk-LRCJ2IZ5.js";
59
55
  import "./chunk-ZXTAQYNA.js";
60
56
 
61
57
  // src/lib/session-key.ts
@@ -104,28 +100,83 @@ var subtle2 = webcrypto2.subtle;
104
100
 
105
101
  // src/lib/open-url.ts
106
102
  import { execFile } from "node:child_process";
103
+ import { existsSync } from "node:fs";
104
+ import { homedir } from "node:os";
105
+ import { join } from "node:path";
107
106
  var OPEN_TIMEOUT_MS = 5e3;
108
- function openerFor(platform) {
109
- if (platform === "darwin") return { cmd: "open", args: [] };
107
+ var MAC_OPEN = "/usr/bin/open";
108
+ var XDG_OPEN_CANDIDATES = [
109
+ "/usr/bin/xdg-open",
110
+ "/bin/xdg-open",
111
+ "/usr/local/bin/xdg-open"
112
+ ];
113
+ var BUNDLE_ID = /^[A-Za-z0-9][A-Za-z0-9.-]*$/;
114
+ function openerFor(platform, existsImpl = existsSync) {
115
+ if (platform === "darwin") return { cmd: MAC_OPEN, args: [] };
110
116
  if (platform === "win32") return { cmd: "rundll32", args: ["url.dll,FileProtocolHandler"] };
111
- return { cmd: "xdg-open", args: [] };
117
+ const found = XDG_OPEN_CANDIDATES.find((p) => existsImpl(p));
118
+ return { cmd: found ?? XDG_OPEN_CANDIDATES[0], args: [] };
119
+ }
120
+ function openerEnv(base) {
121
+ const env = { ...base };
122
+ delete env.BROWSER;
123
+ return env;
124
+ }
125
+ async function macDefaultBrowserBundleId(run, homeDir, env) {
126
+ const plist = join(
127
+ homeDir,
128
+ "Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"
129
+ );
130
+ const out = await new Promise((resolve) => {
131
+ run(
132
+ "/usr/bin/plutil",
133
+ ["-convert", "json", "-o", "-", plist],
134
+ { timeout: OPEN_TIMEOUT_MS, env },
135
+ (err, stdout) => resolve(err === null ? String(stdout) : void 0)
136
+ );
137
+ });
138
+ if (out === void 0) return void 0;
139
+ try {
140
+ const parsed = JSON.parse(out);
141
+ if (!Array.isArray(parsed.LSHandlers)) return void 0;
142
+ for (const entry of parsed.LSHandlers) {
143
+ const scheme = entry.LSHandlerURLScheme;
144
+ if (typeof scheme !== "string" || scheme.toLowerCase() !== "https") continue;
145
+ const id = entry.LSHandlerRoleAll ?? entry.LSHandlerRoleViewer;
146
+ if (typeof id === "string" && BUNDLE_ID.test(id)) return id;
147
+ }
148
+ } catch {
149
+ return void 0;
150
+ }
151
+ return void 0;
112
152
  }
113
153
  async function openInBrowser(url, opts = {}) {
114
- const { cmd, args } = openerFor(opts.platform ?? process.platform);
154
+ const platform = opts.platform ?? process.platform;
115
155
  const run = opts.execFileImpl ?? execFile;
116
- return await new Promise((resolve) => {
156
+ const env = openerEnv(opts.env ?? process.env);
157
+ const { cmd, args } = openerFor(platform, opts.existsImpl);
158
+ const launch = (extra) => new Promise((resolve) => {
117
159
  run(
118
160
  cmd,
119
- [...args, url],
120
- { timeout: OPEN_TIMEOUT_MS, windowsHide: true },
161
+ [...args, ...extra, url],
162
+ { timeout: OPEN_TIMEOUT_MS, windowsHide: true, env },
121
163
  (err) => resolve(err === null)
122
164
  );
123
165
  });
166
+ if (platform === "darwin") {
167
+ const bundleId = await macDefaultBrowserBundleId(run, opts.homeDir ?? homedir(), env);
168
+ if (bundleId !== void 0 && await launch(["-b", bundleId])) return true;
169
+ }
170
+ return await launch([]);
124
171
  }
125
172
 
126
173
  // src/commands/fund.ts
127
- var CHECKOUT_HOST = "pay.coinbase.com";
174
+ var COINBASE_CHECKOUT_HOST = "pay.coinbase.com";
128
175
  var FUND_ORIGIN = PRODUCTION_ORIGIN;
176
+ var ALLOWED_CHECKOUT_HOSTS = [
177
+ new URL(FUND_ORIGIN).host,
178
+ COINBASE_CHECKOUT_HOST
179
+ ];
129
180
  var MAX_PRESET_USD = 1e5;
130
181
  var POLL_INTERVAL_MS = 5e3;
131
182
  var POLL_TIMEOUT_MS = 6e5;
@@ -147,27 +198,28 @@ async function runFund(ctx, opts = {}) {
147
198
  timeoutMs: ctx.flags.timeout,
148
199
  headers: { [SIWX_HEADER]: siwxHeader },
149
200
  jsonBody: {
150
- mode: "onramp",
151
201
  address,
152
202
  ...preset !== void 0 ? { presetAmount: preset } : {}
153
203
  },
154
204
  ...opts.fetchImpl !== void 0 ? { fetchImpl: opts.fetchImpl } : {}
155
205
  };
156
- const res = await httpRequest(`${baseUrl}/api/cdp/session`, request);
206
+ const res = await httpRequest(`${baseUrl}/api/fund/link`, request);
157
207
  if (!res.ok) {
158
208
  throw fetchFailureToCliError(res, {
159
209
  fix: "Check your network, then retry."
160
210
  });
161
211
  }
162
212
  const url = checkoutUrlFrom(res.status, res.json);
163
- emitWriteNotice(ctx.io, `Coinbase Onramp checkout for ${address}:`);
213
+ const willOpen = opts.open !== false && ctx.io.isTTY;
214
+ const hosted = new URL(url).host === COINBASE_CHECKOUT_HOST;
215
+ emitWriteNotice(ctx.io, `Checkout for ${address}:`);
164
216
  emitWriteNotice(ctx.io, ` ${url}`);
165
217
  emitWriteNotice(
166
218
  ctx.io,
167
- "The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required."
219
+ hosted ? "The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required." : "The link expires in ~10 minutes. In the US, pay with Apple Pay or Google Pay, no Coinbase account needed."
168
220
  );
169
221
  let opened = false;
170
- if (opts.open !== false && ctx.io.isTTY) {
222
+ if (willOpen) {
171
223
  opened = await (opts.openUrl ?? openInBrowser)(url);
172
224
  emitNotice(
173
225
  ctx.io,
@@ -236,13 +288,13 @@ function checkoutUrlFrom(status, json) {
236
288
  } catch {
237
289
  parsed = void 0;
238
290
  }
239
- if (parsed !== void 0 && parsed.protocol === "https:" && parsed.host === CHECKOUT_HOST) {
291
+ if (parsed !== void 0 && parsed.protocol === "https:" && ALLOWED_CHECKOUT_HOSTS.includes(parsed.host)) {
240
292
  return url;
241
293
  }
242
294
  }
243
295
  throw new CliError(
244
296
  "CONTRACT_MISMATCH",
245
- `The server's checkout URL was missing or not https://${CHECKOUT_HOST}; refusing to open it.`
297
+ `The server's checkout URL was missing or not https on ${ALLOWED_CHECKOUT_HOSTS.join(" or ")}; refusing to open it.`
246
298
  );
247
299
  }
248
300
  const code = errorCode(json);
@@ -305,4 +357,4 @@ async function pollForFunds(ctx, desc, rpcUrl, startBalance, opts) {
305
357
  export {
306
358
  runFund
307
359
  };
308
- //# sourceMappingURL=fund-3IPR5YRJ.js.map
360
+ //# sourceMappingURL=fund-QWVWRVDK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/session-key.ts","../src/lib/session-present.ts","../src/lib/open-url.ts","../src/commands/fund.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport { sessionPath } from './paths';\nimport { writeFileAtomic } from './atomic-json';\nimport { buildSiwxHeader } from './siwx';\nimport { originOf } from './url';\nimport {\n isSessionUsable,\n loadSessionFile,\n signWithSession,\n type SessionFile,\n type SessionKeyDeps,\n type SessionScope,\n type SignableRequest,\n} from './session-present';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * Session-key delegation (RFC 9421 signed HTTP, RFC 9530-shaped Content-Digest),\n * verified byte-for-byte against the live \"Auth — session keys\" contract in\n * https://tenjin.sh/llms-full.txt (D35).\n *\n * The point: a plain SIWX write burns a single-use nonce, so every write needs a\n * fresh WALLET signature. A session key trades that for ONE wallet signature per\n * session: generate a P-256 keypair, wallet-sign a SIWX message binding its\n * pubkey/exp/scope, then sign each subsequent write with the P-256 key (no wallet\n * popup) until the delegation expires. The delegated key is short-lived (≤24h,\n * server-clamped) and cached 0600, address-bound so a wallet change invalidates it.\n *\n * This module is the MINT half — everything that needs a wallet signer, i.e.\n * `establishSession`, the cache writer, and the two `WriteAuth` implementations.\n * The present-only half (load a file, sign one request with it) lives in\n * `session-present.ts` and is re-exported below, so `posts-api`/`publish`/`edit`\n * keep importing one module while a caller that only wants to present a live\n * delegation — `read`, on the reuse path — imports that half alone and touches\n * no keystore. Do not move a signer-touching function down into\n * `session-present.ts`: that free reuse path is what it buys.\n *\n * A minted delegation is a wallet-derived credential, so it is bound to the\n * ORIGIN it was minted against and every presenter re-checks that binding.\n *\n * Never hand-rolls crypto: P-256 keygen is node:crypto webcrypto (subtle) and the\n * wallet delegation reuses the siwx.ts seam.\n */\n\nexport {\n contentDigest,\n isSessionPresentable,\n readSessionFile,\n isSessionUsable,\n keyidFor,\n loadSessionFile,\n scopeSatisfies,\n signatureBase,\n signatureParams,\n signWithSession,\n targetUri,\n} from './session-present';\nexport type {\n SessionFile,\n SessionFileState,\n SessionKeyDeps,\n SessionScope,\n SignableRequest,\n SignatureParamsInput,\n} from './session-present';\n\n/**\n * The chain a session delegation is signed over. Writes require Base mainnet per\n * the server's SIWX chain constraint, and a session covers reads and writes\n * alike, so there is exactly ONE session chain id rather than a per-caller\n * choice: the read path and the write path must mint against the same chain or\n * the file they share would flip between two delegations.\n */\nexport const SESSION_CHAIN_ID = 'eip155:8453';\n\nconst SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h; the server clamps to ≤24h.\n\n/**\n * The write-auth seam a posts client signs through. `headersFor` attaches the\n * signature headers (establishing the session lazily on first use); `recover`\n * reacts to a 401 by returning whether a retry is worthwhile.\n */\nexport interface WriteAuth {\n headersFor(req: SignableRequest): Promise<Record<string, string>>;\n /** React to a write's 401 `code`; true ⇒ the next headersFor retry may succeed. */\n recover(code: string | undefined): Promise<boolean>;\n}\n\nexport interface SessionKeyConfig {\n signer: TenjinSigner;\n baseUrl: string;\n chainId: string;\n dataDir: string;\n /**\n * The scope this session is minted at, and the scope a cached session must\n * cover to be reused. Required, not defaulted: over-granting silently is the\n * failure mode worth making impossible, so every caller states what it needs.\n */\n scope: SessionScope;\n}\n\nconst subtle = webcrypto.subtle;\n\nfunction generateP256KeyPair(): Promise<webcrypto.CryptoKeyPair> {\n return subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]) as Promise<webcrypto.CryptoKeyPair>;\n}\n\n/** base64url (no padding) of raw bytes — the pubkey/keyid encoding. */\nfunction toBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** The three URNs bound into the delegation's SIWX `resources` array (D35). */\nexport function delegationResources(\n publicKeyRaw: string,\n expIso: string,\n scope: SessionScope,\n): string[] {\n return [\n `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,\n `urn:tenjin:session:exp:${expIso}`,\n `urn:tenjin:session:scope:${scope}`,\n ];\n}\n\n/**\n * Establish a session with ONE wallet signature: generate a P-256 keypair, bind\n * its pubkey/exp/scope into a SIWX message, wallet-sign it, and cache the result\n * 0600 address-bound. The returned file's `delegation` is the constant\n * `Tenjin-Session-Delegation` header for the session's life.\n */\nexport async function establishSession(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): Promise<SessionFile> {\n const now = deps.now ?? Date.now;\n const pair = await generateP256KeyPair();\n const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));\n const publicKeyRaw = toBase64Url(rawPub);\n const jwk = (await subtle.exportKey('jwk', pair.privateKey)) as SessionFile['privateKeyJwk'];\n\n const expIso = new Date(now() + SESSION_TTL_MS).toISOString();\n const delegation = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n ttlMs: SESSION_TTL_MS,\n statement: 'Delegate a Tenjin session key.',\n resources: delegationResources(publicKeyRaw, expIso, config.scope),\n });\n\n const file: SessionFile = {\n address: config.signer.address.toLowerCase(),\n origin: originOf(config.baseUrl),\n delegation,\n exp: expIso,\n scope: config.scope,\n publicKeyRaw,\n privateKeyJwk: jwk,\n };\n await saveSessionFile(config.dataDir, file);\n return file;\n}\n\n// ---------------------------------------------------------------------------\n// Cache writes (0600, address-bound). The reader lives in session-present.\n// ---------------------------------------------------------------------------\n\nexport async function saveSessionFile(dir: string, file: SessionFile): Promise<void> {\n await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n// ---------------------------------------------------------------------------\n// The WriteAuth implementation: lazy establish, cache reuse, 401 recovery.\n// ---------------------------------------------------------------------------\n\n/** How each 401 `code` maps to recovery (per the llms-full.txt policy section). */\ntype Recovery = 'resign' | 'reestablish' | 'fatal';\n\nexport function recoveryFor(code: string | undefined): Recovery {\n switch (code) {\n case 'proof_expired':\n // The per-request signature is too old; just re-sign (no wallet).\n return 'resign';\n case 'session_expired':\n case 'proof_revoked':\n case 'insufficient_scope':\n // The delegation itself is gone/insufficient; re-establish (one wallet sig).\n return 'reestablish';\n case 'session_key_unbound':\n // keyid ≠ the delegation-bound key: retrying cannot fix it.\n return 'fatal';\n default:\n return 'fatal';\n }\n}\n\n/**\n * A session-key WriteAuth: mints (or loads) the delegation on first use and signs\n * every write with the P-256 key — so a returning agent never wallet-signs again\n * until the session expires. On a 401 it re-signs or re-establishes per the code.\n */\nexport function createSessionKeyAuth(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): WriteAuth {\n const now = deps.now ?? Date.now;\n let cached: SessionFile | null = null;\n let forceReestablish = false;\n\n const ensure = async (): Promise<SessionFile> => {\n if (\n !forceReestablish &&\n cached !== null &&\n isSessionUsable(cached, config.signer.address, now(), config.scope, originOf(config.baseUrl))\n ) {\n return cached;\n }\n if (!forceReestablish) {\n const onDisk = await loadSessionFile(config.dataDir);\n const origin = originOf(config.baseUrl);\n if (\n onDisk !== null &&\n isSessionUsable(onDisk, config.signer.address, now(), config.scope, origin)\n ) {\n cached = onDisk;\n return cached;\n }\n }\n cached = await establishSession(config, deps);\n forceReestablish = false;\n return cached;\n };\n\n return {\n async headersFor(req) {\n const file = await ensure();\n return signWithSession(file, req, deps);\n },\n async recover(code) {\n const recovery = recoveryFor(code);\n if (recovery === 'fatal') return false;\n if (recovery === 'reestablish') {\n cached = null;\n forceReestablish = true;\n }\n // 'resign' needs no state change: the next headersFor mints a fresh\n // created/nonce over the same (still-valid) delegation.\n return true;\n },\n };\n}\n\n/**\n * The plain-SIWX fallback (no session): every write carries its own fresh\n * wallet-signed `SIGN-IN-WITH-X` header. Used when session establishment is\n * disabled; a burned/stale nonce (401) is recovered by re-signing.\n */\nexport function createSiwxAuth(config: SessionKeyConfig): WriteAuth {\n return {\n async headersFor() {\n const header = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n });\n return { 'SIGN-IN-WITH-X': header };\n },\n async recover(code) {\n // A single-use nonce burns on every write; a stale/burned nonce (or an\n // expired proof) is recovered by re-signing with a fresh nonce + issuedAt.\n return code === 'nonce_already_used' || code === 'invalid_proof' || code === 'proof_expired';\n },\n };\n}\n","import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split earns its keep on the reuse path: presenting a live delegation costs\n * no keystore decryption, so `tenjin read` reaches this half alone whenever one\n * is cached and only falls through to the mint half (and one passphrase) when\n * there is none. Neither half says anything about what an already-minted\n * delegation is worth to whoever holds it — see `origin` below, and the tier\n * note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.sh/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET or DELETE has no body to\n * cover at all, so content-digest drops out of the covered set. As a union,\n * \"GET with a body\" and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET' | 'DELETE'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache (`~/.tenjin/session.json`); the next read or write mints a fresh one.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends. Keyed on\n // the presence of a body rather than on the method list, so a bodiless method\n // added to the union above needs no second edit here to stay bodiless.\n const digest = 'body' in req ? contentDigest(req.body) : undefined;\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n /** An OLDER CLI's file, missing a field the shape has since required. Unusable\n * and re-mintable like an absent one, so NOT the tamper signal `corrupt` is. */\n | { kind: 'outdated'; field: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\n/**\n * Fields an OLDER CLI's file can legitimately lack. An allowlist, not \"any missing\n * key\": a file with no `privateKeyJwk.d` cannot sign and is broken whoever wrote\n * it. Add a name when the schema grows a required field, never to quiet a test.\n */\nconst LATER_ADDED_FIELDS: readonly string[] = ['origin'];\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const legacy = (i: (typeof issues)[number]): boolean =>\n LATER_ADDED_FIELDS.includes(i.path.join('.')) && !hasPath(json, i.path);\n // Report the first NON-legacy issue when there is one: a file missing both\n // `origin` and its private scalar is corrupt because of the scalar, and naming\n // the benign field points the operator at the wrong thing.\n const issue = issues.find((i) => !legacy(i)) ?? issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // EVERY failure must be an allowlisted later field the file genuinely lacks.\n // One legacy omission cannot vouch for the rest of the file, and zod reports in\n // schema order, so the first issue alone would let a broken key ride in.\n const legacyOnly = issues.length > 0 && issues.every(legacy);\n if (legacyOnly && field !== undefined) return { kind: 'outdated', field };\n // Field-qualified: the message alone names none. zod never echoes the received\n // VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** Does `value` actually carry the key at `path`, whatever it holds there? */\nfunction hasPath(value: unknown, path: readonly PropertyKey[]): boolean {\n let cur: unknown = value;\n for (const key of path) {\n if (typeof cur !== 'object' || cur === null) return false;\n if (!Object.hasOwn(cur, key)) return false;\n cur = (cur as Record<PropertyKey, unknown>)[key];\n }\n return true;\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n","import { execFile } from 'node:child_process';\n\n/**\n * Open a URL in the platform's default browser, best-effort. Follows the\n * passphrase.ts subprocess rules: an argv array (never a shell), a hard\n * timeout, and failure as a return value rather than a throw — callers print\n * the URL first, so a machine without an opener degrades to copy/paste.\n * Windows uses rundll32's FileProtocolHandler because `start` exists only\n * inside cmd.exe, and spawning a shell around an attacker-influenced string is\n * the injection shape this module exists to avoid.\n */\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n execFileImpl?: typeof execFile;\n}\n\nconst OPEN_TIMEOUT_MS = 5000;\n\nexport function openerFor(platform: NodeJS.Platform): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: 'open', args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n return { cmd: 'xdg-open', args: [] };\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const { cmd, args } = openerFor(opts.platform ?? process.platform);\n const run = opts.execFileImpl ?? execFile;\n return await new Promise((resolve) => {\n run(cmd, [...args, url], { timeout: OPEN_TIMEOUT_MS, windowsHide: true }, (err) =>\n resolve(err === null),\n );\n });\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { buildSiwxHeader, SIWX_HEADER } from '../lib/siwx';\nimport { SESSION_CHAIN_ID } from '../lib/session-key';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { toMoney } from '../lib/money';\nimport { emitNotice, emitWriteNotice } from '../lib/output';\nimport { addressQrLines } from '../lib/qr';\nimport { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin wallet fund`: card-fund THIS wallet via Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend to mint a\n * Coinbase-hosted checkout URL for that same address (the server refuses any\n * other address, per Coinbase's onboarding-verified auth model). The money\n * moves entirely on Coinbase's side; the minted session grants no spending\n * power over the wallet. Two Coinbase properties shape the UX here: the URL is\n * single-use and expires in ~5 minutes (mint fresh per run, open immediately,\n * never persist), and it is bound to this machine's public IP at mint time, so\n * it must be opened in a browser on this machine/network.\n */\n\n/** The only host a minted checkout URL may point at; anything else is refused unopened. */\nconst CHECKOUT_HOST = 'pay.coinbase.com';\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = PRODUCTION_ORIGIN;\n/** Matches the server's presetAmount bound (app/api/cdp/session bodySchema). */\nconst MAX_PRESET_USD = 100_000;\nconst POLL_INTERVAL_MS = 5_000;\nconst POLL_TIMEOUT_MS = 600_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline won. Only `timed-out` says anything about the purchase.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to Coinbase (clamped upward to its own floor there). */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** `--no-qr`: skip the QR block a TTY otherwise gets for sending USDC from a phone. */\n qr?: boolean;\n /** Poll the balance after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n pollIntervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n const signer = await provider.getSigner();\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const baseUrl = FUND_ORIGIN;\n const rpcUrl = settings.rpcUrl.value;\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting, because\n // the envelope carrying the link is written only after runFund returns, and a\n // link that expires in ~5 minutes is worthless after a 10-minute poll.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n\n // Read the balance BEFORE minting so the poll has a baseline; an RPC flake\n // here only disables the wait, it never blocks funding.\n const startBalance = shouldWait ? await balanceOrUndefined(desc, rpcUrl) : undefined;\n\n const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: SESSION_CHAIN_ID });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n jsonBody: {\n mode: 'onramp',\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/cdp/session`, request);\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n const url = checkoutUrlFrom(res.status, res.json);\n\n // The link goes out on EVERY surface and before any waiting: it is single-use\n // with a ~5 minute expiry, and the stdout envelope that also carries it is\n // written only after this function returns. A piped or agent-driven run is\n // exactly the case that must not get the link after it has died, so these\n // three lines are write-notices (stderr, no TTY gate, no --json gate) rather\n // than human-mode notices. stdout stays exactly one JSON object.\n emitWriteNotice(ctx.io, `Coinbase Onramp checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\n 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required.',\n );\n\n let opened = false;\n if (opts.open !== false && ctx.io.isTTY) {\n opened = await (opts.openUrl ?? openInBrowser)(url);\n emitNotice(\n ctx.io,\n opened ? 'Opened in your default browser.' : 'Could not open a browser; use the link above.',\n { json: ctx.flags.json },\n );\n }\n\n // Human mode only, and before the wait: the poll below also sees USDC sent\n // straight to the address, so a phone wallet is a second way to finish.\n const qrLines =\n opts.qr !== false && ctx.io.isTTY && !ctx.flags.json\n ? addressQrLines(address, ctx.io.stderr)\n : [];\n if (qrLines.length > 0) {\n ctx.io.stderr.write(\n [`Or send USDC from a phone wallet to ${address}:`, ...qrLines].join('\\n') + '\\n',\n );\n }\n\n const funded =\n shouldWait && startBalance !== undefined\n ? await pollForFunds(ctx, desc, rpcUrl, startBalance, opts)\n : undefined;\n if (funded !== undefined) {\n emitWriteNotice(ctx.io, 'USDC arrived - you can close the checkout tab.');\n }\n const pollStatus: FundPollStatus = !shouldWait\n ? 'skipped'\n : startBalance === undefined\n ? 'unavailable'\n : funded !== undefined\n ? 'arrived'\n : 'timed-out';\n\n const balanceAtomic = funded ?? startBalance;\n return {\n data: {\n address,\n checkoutUrl: url,\n opened,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n funded: funded !== undefined,\n pollStatus,\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n },\n humanLines:\n funded !== undefined\n ? [`Funded: balance is now ${toMoney(funded.toString()).usd} USDC on Base.`]\n : [\n 'Checkout link issued (printed above).',\n ...(pollStatus === 'unavailable'\n ? ['Could not read the balance to wait on it; the link is unaffected.']\n : []),\n 'Confirm arrival later with `tenjin wallet balance`.',\n ],\n };\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin wallet fund 5',\n });\n }\n return n;\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on Coinbase's\n * checkout host before anything else sees it: a compromised or misconfigured\n * server must not be able to steer the user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (parsed !== undefined && parsed.protocol === 'https:' && parsed.host === CHECKOUT_HOST) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https://${CHECKOUT_HOST}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Coinbase Onramp is not available in your region.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', 'The funding endpoint rejected the signed proof.', {\n fix: 'Check this machine’s clock, then retry.',\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'The funding endpoint is rate limited right now.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError(\n 'API_UNREACHABLE',\n 'Production has no Coinbase Onramp configured right now.',\n {\n fix: 'Retry later.',\n },\n );\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(\n desc: { address: string },\n rpcUrl: string,\n): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(desc.address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wait for the purchased USDC to land: any balance above the pre-mint baseline\n * counts (Coinbase clamps presets, so an exact-amount check would be wrong).\n * RPC flakes mid-poll are tolerated; the deadline is the only exit besides\n * arrival, and timing out is a normal outcome (the human may still be paying),\n * not an error.\n */\nasync function pollForFunds(\n ctx: CommandContext,\n desc: { address: string },\n rpcUrl: string,\n startBalance: bigint,\n opts: FundOptions,\n): Promise<bigint | undefined> {\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;\n const deadline = Date.now() + (opts.pollTimeoutMs ?? POLL_TIMEOUT_MS);\n emitNotice(ctx.io, 'Waiting for the USDC to arrive (Ctrl-C is safe; the purchase is not).', {\n json: ctx.flags.json,\n });\n while (Date.now() < deadline) {\n await sleep(interval);\n const balance = await balanceOrUndefined(desc, rpcUrl);\n if (balance !== undefined && balance > startBalance) return balance;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,kBAAiB;;;ACA1B,SAAS,YAAY,aAAa,iBAAiB;AAoDnD,IAAM,gBAAgB,iBACnB,OAAO;AAAA,EACN,KAAK,iBAAE,QAAQ,IAAI;AAAA,EACnB,KAAK,iBAAE,QAAQ,OAAO;AAAA,EACtB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AACrB,CAAC,EACA,YAAY;AAGf,IAAM,oBAAoB,iBAAE,OAAO;AAAA;AAAA,EAEjC,SAAS,iBAAE,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAalB,QAAQ,iBAAE,OAAO;AAAA;AAAA,EAEjB,YAAY,iBAAE,OAAO;AAAA;AAAA,EAErB,KAAK,iBAAE,OAAO;AAAA,EACd,OAAO,iBAAE,OAAO;AAAA;AAAA,EAEhB,cAAc,iBAAE,OAAO;AAAA,EACvB,eAAe;AACjB,CAAC;AAmBD,IAAM,SAAS,UAAU;;;ADjClB,IAAM,mBA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Q,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAM,OAAQ,IAA2B;AACzC,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;AAEA,eAAe,mBACb,MACA,QAC6B;AAC7B,MAAI;AACF,WAAO,MAAM,eAAe,KAAK,SAA0B,MAAM;AAAA,EACnE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASA,eAAe,aACb,KACA,MACA,QACA,cACA,MAC6B;AAC7B,QAAM,QACJ,KAAK,UAAU,CAAC,OAAe,IAAI,QAAc,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACvF,QAAM,WAAW,KAAK,kBAAkB;AACxC,QAAM,WAAW,KAAK,IAAI,KAAK,KAAK,iBAAiB;AACrD,aAAW,IAAI,IAAI,yEAAyE;AAAA,IAC1F,MAAM,IAAI,MAAM;AAAA,EAClB,CAAC;AACD,SAAO,KAAK,IAAI,IAAI,UAAU;AAC5B,UAAM,MAAM,QAAQ;AACpB,UAAM,UAAU,MAAM,mBAAmB,MAAM,MAAM;AACrD,QAAI,YAAY,UAAa,UAAU,aAAc,QAAO;AAAA,EAC9D;AACA,SAAO;AACT;","names":["webcrypto","subtle","webcrypto"]}
1
+ {"version":3,"sources":["../src/lib/session-key.ts","../src/lib/session-present.ts","../src/lib/open-url.ts","../src/commands/fund.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport { sessionPath } from './paths';\nimport { writeFileAtomic } from './atomic-json';\nimport { buildSiwxHeader } from './siwx';\nimport { originOf } from './url';\nimport {\n isSessionUsable,\n loadSessionFile,\n signWithSession,\n type SessionFile,\n type SessionKeyDeps,\n type SessionScope,\n type SignableRequest,\n} from './session-present';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * Session-key delegation (RFC 9421 signed HTTP, RFC 9530-shaped Content-Digest),\n * verified byte-for-byte against the live \"Auth — session keys\" contract in\n * https://tenjin.sh/llms-full.txt (D35).\n *\n * The point: a plain SIWX write burns a single-use nonce, so every write needs a\n * fresh WALLET signature. A session key trades that for ONE wallet signature per\n * session: generate a P-256 keypair, wallet-sign a SIWX message binding its\n * pubkey/exp/scope, then sign each subsequent write with the P-256 key (no wallet\n * popup) until the delegation expires. The delegated key is short-lived (≤24h,\n * server-clamped) and cached 0600, address-bound so a wallet change invalidates it.\n *\n * This module is the MINT half — everything that needs a wallet signer, i.e.\n * `establishSession`, the cache writer, and the two `WriteAuth` implementations.\n * The present-only half (load a file, sign one request with it) lives in\n * `session-present.ts` and is re-exported below, so `posts-api`/`publish`/`edit`\n * keep importing one module while a caller that only wants to present a live\n * delegation — `read`, on the reuse path — imports that half alone and touches\n * no keystore. Do not move a signer-touching function down into\n * `session-present.ts`: that free reuse path is what it buys.\n *\n * A minted delegation is a wallet-derived credential, so it is bound to the\n * ORIGIN it was minted against and every presenter re-checks that binding.\n *\n * Never hand-rolls crypto: P-256 keygen is node:crypto webcrypto (subtle) and the\n * wallet delegation reuses the siwx.ts seam.\n */\n\nexport {\n contentDigest,\n isSessionPresentable,\n readSessionFile,\n isSessionUsable,\n keyidFor,\n loadSessionFile,\n scopeSatisfies,\n signatureBase,\n signatureParams,\n signWithSession,\n targetUri,\n} from './session-present';\nexport type {\n SessionFile,\n SessionFileState,\n SessionKeyDeps,\n SessionScope,\n SignableRequest,\n SignatureParamsInput,\n} from './session-present';\n\n/**\n * The chain a session delegation is signed over. Writes require Base mainnet per\n * the server's SIWX chain constraint, and a session covers reads and writes\n * alike, so there is exactly ONE session chain id rather than a per-caller\n * choice: the read path and the write path must mint against the same chain or\n * the file they share would flip between two delegations.\n */\nexport const SESSION_CHAIN_ID = 'eip155:8453';\n\nconst SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h; the server clamps to ≤24h.\n\n/**\n * The write-auth seam a posts client signs through. `headersFor` attaches the\n * signature headers (establishing the session lazily on first use); `recover`\n * reacts to a 401 by returning whether a retry is worthwhile.\n */\nexport interface WriteAuth {\n headersFor(req: SignableRequest): Promise<Record<string, string>>;\n /** React to a write's 401 `code`; true ⇒ the next headersFor retry may succeed. */\n recover(code: string | undefined): Promise<boolean>;\n}\n\nexport interface SessionKeyConfig {\n signer: TenjinSigner;\n baseUrl: string;\n chainId: string;\n dataDir: string;\n /**\n * The scope this session is minted at, and the scope a cached session must\n * cover to be reused. Required, not defaulted: over-granting silently is the\n * failure mode worth making impossible, so every caller states what it needs.\n */\n scope: SessionScope;\n}\n\nconst subtle = webcrypto.subtle;\n\nfunction generateP256KeyPair(): Promise<webcrypto.CryptoKeyPair> {\n return subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]) as Promise<webcrypto.CryptoKeyPair>;\n}\n\n/** base64url (no padding) of raw bytes — the pubkey/keyid encoding. */\nfunction toBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** The three URNs bound into the delegation's SIWX `resources` array (D35). */\nexport function delegationResources(\n publicKeyRaw: string,\n expIso: string,\n scope: SessionScope,\n): string[] {\n return [\n `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,\n `urn:tenjin:session:exp:${expIso}`,\n `urn:tenjin:session:scope:${scope}`,\n ];\n}\n\n/**\n * Establish a session with ONE wallet signature: generate a P-256 keypair, bind\n * its pubkey/exp/scope into a SIWX message, wallet-sign it, and cache the result\n * 0600 address-bound. The returned file's `delegation` is the constant\n * `Tenjin-Session-Delegation` header for the session's life.\n */\nexport async function establishSession(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): Promise<SessionFile> {\n const now = deps.now ?? Date.now;\n const pair = await generateP256KeyPair();\n const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));\n const publicKeyRaw = toBase64Url(rawPub);\n const jwk = (await subtle.exportKey('jwk', pair.privateKey)) as SessionFile['privateKeyJwk'];\n\n const expIso = new Date(now() + SESSION_TTL_MS).toISOString();\n const delegation = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n ttlMs: SESSION_TTL_MS,\n statement: 'Delegate a Tenjin session key.',\n resources: delegationResources(publicKeyRaw, expIso, config.scope),\n });\n\n const file: SessionFile = {\n address: config.signer.address.toLowerCase(),\n origin: originOf(config.baseUrl),\n delegation,\n exp: expIso,\n scope: config.scope,\n publicKeyRaw,\n privateKeyJwk: jwk,\n };\n await saveSessionFile(config.dataDir, file);\n return file;\n}\n\n// ---------------------------------------------------------------------------\n// Cache writes (0600, address-bound). The reader lives in session-present.\n// ---------------------------------------------------------------------------\n\nexport async function saveSessionFile(dir: string, file: SessionFile): Promise<void> {\n await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n// ---------------------------------------------------------------------------\n// The WriteAuth implementation: lazy establish, cache reuse, 401 recovery.\n// ---------------------------------------------------------------------------\n\n/** How each 401 `code` maps to recovery (per the llms-full.txt policy section). */\ntype Recovery = 'resign' | 'reestablish' | 'fatal';\n\nexport function recoveryFor(code: string | undefined): Recovery {\n switch (code) {\n case 'proof_expired':\n // The per-request signature is too old; just re-sign (no wallet).\n return 'resign';\n case 'session_expired':\n case 'proof_revoked':\n case 'insufficient_scope':\n // The delegation itself is gone/insufficient; re-establish (one wallet sig).\n return 'reestablish';\n case 'session_key_unbound':\n // keyid ≠ the delegation-bound key: retrying cannot fix it.\n return 'fatal';\n default:\n return 'fatal';\n }\n}\n\n/**\n * A session-key WriteAuth: mints (or loads) the delegation on first use and signs\n * every write with the P-256 key — so a returning agent never wallet-signs again\n * until the session expires. On a 401 it re-signs or re-establishes per the code.\n */\nexport function createSessionKeyAuth(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): WriteAuth {\n const now = deps.now ?? Date.now;\n let cached: SessionFile | null = null;\n let forceReestablish = false;\n\n const ensure = async (): Promise<SessionFile> => {\n if (\n !forceReestablish &&\n cached !== null &&\n isSessionUsable(cached, config.signer.address, now(), config.scope, originOf(config.baseUrl))\n ) {\n return cached;\n }\n if (!forceReestablish) {\n const onDisk = await loadSessionFile(config.dataDir);\n const origin = originOf(config.baseUrl);\n if (\n onDisk !== null &&\n isSessionUsable(onDisk, config.signer.address, now(), config.scope, origin)\n ) {\n cached = onDisk;\n return cached;\n }\n }\n cached = await establishSession(config, deps);\n forceReestablish = false;\n return cached;\n };\n\n return {\n async headersFor(req) {\n const file = await ensure();\n return signWithSession(file, req, deps);\n },\n async recover(code) {\n const recovery = recoveryFor(code);\n if (recovery === 'fatal') return false;\n if (recovery === 'reestablish') {\n cached = null;\n forceReestablish = true;\n }\n // 'resign' needs no state change: the next headersFor mints a fresh\n // created/nonce over the same (still-valid) delegation.\n return true;\n },\n };\n}\n\n/**\n * The plain-SIWX fallback (no session): every write carries its own fresh\n * wallet-signed `SIGN-IN-WITH-X` header. Used when session establishment is\n * disabled; a burned/stale nonce (401) is recovered by re-signing.\n */\nexport function createSiwxAuth(config: SessionKeyConfig): WriteAuth {\n return {\n async headersFor() {\n const header = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n });\n return { 'SIGN-IN-WITH-X': header };\n },\n async recover(code) {\n // A single-use nonce burns on every write; a stale/burned nonce (or an\n // expired proof) is recovered by re-signing with a fresh nonce + issuedAt.\n return code === 'nonce_already_used' || code === 'invalid_proof' || code === 'proof_expired';\n },\n };\n}\n","import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split earns its keep on the reuse path: presenting a live delegation costs\n * no keystore decryption, so `tenjin read` reaches this half alone whenever one\n * is cached and only falls through to the mint half (and one passphrase) when\n * there is none. Neither half says anything about what an already-minted\n * delegation is worth to whoever holds it — see `origin` below, and the tier\n * note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.sh/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET or DELETE has no body to\n * cover at all, so content-digest drops out of the covered set. As a union,\n * \"GET with a body\" and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET' | 'DELETE'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache (`~/.tenjin/session.json`); the next read or write mints a fresh one.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends. Keyed on\n // the presence of a body rather than on the method list, so a bodiless method\n // added to the union above needs no second edit here to stay bodiless.\n const digest = 'body' in req ? contentDigest(req.body) : undefined;\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n /** An OLDER CLI's file, missing a field the shape has since required. Unusable\n * and re-mintable like an absent one, so NOT the tamper signal `corrupt` is. */\n | { kind: 'outdated'; field: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\n/**\n * Fields an OLDER CLI's file can legitimately lack. An allowlist, not \"any missing\n * key\": a file with no `privateKeyJwk.d` cannot sign and is broken whoever wrote\n * it. Add a name when the schema grows a required field, never to quiet a test.\n */\nconst LATER_ADDED_FIELDS: readonly string[] = ['origin'];\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const legacy = (i: (typeof issues)[number]): boolean =>\n LATER_ADDED_FIELDS.includes(i.path.join('.')) && !hasPath(json, i.path);\n // Report the first NON-legacy issue when there is one: a file missing both\n // `origin` and its private scalar is corrupt because of the scalar, and naming\n // the benign field points the operator at the wrong thing.\n const issue = issues.find((i) => !legacy(i)) ?? issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // EVERY failure must be an allowlisted later field the file genuinely lacks.\n // One legacy omission cannot vouch for the rest of the file, and zod reports in\n // schema order, so the first issue alone would let a broken key ride in.\n const legacyOnly = issues.length > 0 && issues.every(legacy);\n if (legacyOnly && field !== undefined) return { kind: 'outdated', field };\n // Field-qualified: the message alone names none. zod never echoes the received\n // VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** Does `value` actually carry the key at `path`, whatever it holds there? */\nfunction hasPath(value: unknown, path: readonly PropertyKey[]): boolean {\n let cur: unknown = value;\n for (const key of path) {\n if (typeof cur !== 'object' || cur === null) return false;\n if (!Object.hasOwn(cur, key)) return false;\n cur = (cur as Record<PropertyKey, unknown>)[key];\n }\n return true;\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n","import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * Open a URL in the user's real default browser, best-effort. Follows the\n * passphrase.ts subprocess rules: an argv array (never a shell), a hard\n * timeout, and failure as a return value rather than a throw — callers print\n * the URL first, so a machine without an opener degrades to copy/paste.\n *\n * The opener is an absolute system path, never a bare name looked up on PATH,\n * and the BROWSER variable and other host-provided hints are dropped from the\n * child's environment. An agent host (Claude Desktop, an IDE) can put a shim on\n * PATH or set BROWSER to route the link into its own embedded view, where Apple\n * Pay and Google Pay cannot complete. On macOS the system's default https\n * handler is looked up and named explicitly with `open -b`. If the default\n * browser is itself an embedded view there is nothing more this can do, and the\n * caller's printed link and QR remain the way out.\n *\n * Windows uses rundll32's FileProtocolHandler because `start` exists only\n * inside cmd.exe, and spawning a shell around an attacker-influenced string is\n * the injection shape this module exists to avoid.\n */\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n execFileImpl?: typeof execFile;\n /** Test seam for the Linux opener search. */\n existsImpl?: (path: string) => boolean;\n /** Test seam for the macOS LaunchServices preferences location. */\n homeDir?: string;\n /** Test seam for the environment handed to the child. */\n env?: NodeJS.ProcessEnv;\n}\n\nconst OPEN_TIMEOUT_MS = 5000;\nconst MAC_OPEN = '/usr/bin/open';\nconst XDG_OPEN_CANDIDATES = [\n '/usr/bin/xdg-open',\n '/bin/xdg-open',\n '/usr/local/bin/xdg-open',\n] as const;\n/** What a bundle id may look like; keeps a hostile preference value from becoming a flag. */\nconst BUNDLE_ID = /^[A-Za-z0-9][A-Za-z0-9.-]*$/;\n\nexport function openerFor(\n platform: NodeJS.Platform,\n existsImpl: (path: string) => boolean = existsSync,\n): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: MAC_OPEN, args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n const found = XDG_OPEN_CANDIDATES.find((p) => existsImpl(p));\n return { cmd: found ?? XDG_OPEN_CANDIDATES[0], args: [] };\n}\n\n/** The child's environment without BROWSER, which xdg-open and others honor over the system default. */\nfunction openerEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const env = { ...base };\n delete env.BROWSER;\n return env;\n}\n\n/**\n * The bundle id of the default https handler, read from the user's LaunchServices\n * preferences, or undefined when none is recorded (the OS default then applies)\n * or anything about the read fails.\n */\nasync function macDefaultBrowserBundleId(\n run: typeof execFile,\n homeDir: string,\n env: NodeJS.ProcessEnv,\n): Promise<string | undefined> {\n const plist = join(\n homeDir,\n 'Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist',\n );\n const out = await new Promise<string | undefined>((resolve) => {\n run(\n '/usr/bin/plutil',\n ['-convert', 'json', '-o', '-', plist],\n { timeout: OPEN_TIMEOUT_MS, env },\n (err, stdout) => resolve(err === null ? String(stdout) : undefined),\n );\n });\n if (out === undefined) return undefined;\n try {\n const parsed = JSON.parse(out) as { LSHandlers?: unknown };\n if (!Array.isArray(parsed.LSHandlers)) return undefined;\n for (const entry of parsed.LSHandlers as Record<string, unknown>[]) {\n const scheme = entry.LSHandlerURLScheme;\n if (typeof scheme !== 'string' || scheme.toLowerCase() !== 'https') continue;\n const id = entry.LSHandlerRoleAll ?? entry.LSHandlerRoleViewer;\n if (typeof id === 'string' && BUNDLE_ID.test(id)) return id;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const platform = opts.platform ?? process.platform;\n const run = opts.execFileImpl ?? execFile;\n const env = openerEnv(opts.env ?? process.env);\n const { cmd, args } = openerFor(platform, opts.existsImpl);\n const launch = (extra: string[]): Promise<boolean> =>\n new Promise((resolve) => {\n run(\n cmd,\n [...args, ...extra, url],\n { timeout: OPEN_TIMEOUT_MS, windowsHide: true, env },\n (err) => resolve(err === null),\n );\n });\n\n if (platform === 'darwin') {\n const bundleId = await macDefaultBrowserBundleId(run, opts.homeDir ?? homedir(), env);\n if (bundleId !== undefined && (await launch(['-b', bundleId]))) return true;\n }\n return await launch([]);\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { buildSiwxHeader, SIWX_HEADER } from '../lib/siwx';\nimport { SESSION_CHAIN_ID } from '../lib/session-key';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { toMoney } from '../lib/money';\nimport { emitNotice, emitWriteNotice } from '../lib/output';\nimport { addressQrLines } from '../lib/qr';\nimport { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin wallet fund`: fund THIS wallet through Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend for a checkout\n * link for that same address (the server refuses any other address). The link is\n * either the Tenjin /fund page (US callers once headless onramp is live, with a\n * short-lived token in the URL fragment) or a Coinbase-hosted checkout. The money\n * moves entirely on Coinbase's side and the link grants no spending power over\n * the wallet. A hosted link is single-use, expires in ~5 minutes and is bound to\n * this machine's public IP at mint time, so it must be opened in a browser on this\n * machine/network.\n */\n\n/** The hosted Coinbase checkout host, one of the two hosts a returned link may use. */\nconst COINBASE_CHECKOUT_HOST = 'pay.coinbase.com';\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = PRODUCTION_ORIGIN;\n/**\n * The only hosts a returned link may point at; anything else is refused unopened.\n * The first is the host of the pinned origin (the Tenjin /fund page), so it\n * follows the origin if that is ever re-pointed.\n */\nconst ALLOWED_CHECKOUT_HOSTS: readonly string[] = [\n new URL(FUND_ORIGIN).host,\n COINBASE_CHECKOUT_HOST,\n];\n/** Matches the server's presetAmount bound (the fund link route's body schema). */\nconst MAX_PRESET_USD = 100_000;\nconst POLL_INTERVAL_MS = 5_000;\nconst POLL_TIMEOUT_MS = 600_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline won. Only `timed-out` says anything about the purchase.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to Coinbase (clamped upward to its own floor there). */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** `--no-qr`: skip the QR block a TTY otherwise gets for sending USDC from a phone. */\n qr?: boolean;\n /** Poll the balance after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n pollIntervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n const signer = await provider.getSigner();\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const baseUrl = FUND_ORIGIN;\n const rpcUrl = settings.rpcUrl.value;\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting, because\n // the envelope carrying the link is written only after runFund returns, and a\n // link that expires in ~5 minutes is worthless after a 10-minute poll.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n\n // Read the balance BEFORE minting so the poll has a baseline; an RPC flake\n // here only disables the wait, it never blocks funding.\n const startBalance = shouldWait ? await balanceOrUndefined(desc, rpcUrl) : undefined;\n\n const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: SESSION_CHAIN_ID });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n jsonBody: {\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/fund/link`, request);\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n const url = checkoutUrlFrom(res.status, res.json);\n\n // The link goes out on EVERY surface and before any waiting: it is single-use\n // with a ~5 minute expiry, and the stdout envelope that also carries it is\n // written only after this function returns. A piped or agent-driven run is\n // exactly the case that must not get the link after it has died, so these\n // three lines are write-notices (stderr, no TTY gate, no --json gate) rather\n // than human-mode notices. stdout stays exactly one JSON object.\n //\n // A Tenjin /fund link carries a token in its fragment, and it prints whole on\n // every path: a user who copies it into another browser needs the token. It is\n // not worth hiding, since it can only fund this wallet and expires in ~10 minutes.\n const willOpen = opts.open !== false && ctx.io.isTTY;\n const hosted = new URL(url).host === COINBASE_CHECKOUT_HOST;\n emitWriteNotice(ctx.io, `Checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\n hosted\n ? 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required.'\n : 'The link expires in ~10 minutes. In the US, pay with Apple Pay or Google Pay, no Coinbase account needed.',\n );\n\n let opened = false;\n // The opener is resolved by absolute path and ignores BROWSER (lib/open-url.ts), so an\n // agent host cannot route the link into its embedded view. If the user's default browser\n // is itself an embedded view there is nothing more to do here: the link and QR are printed.\n if (willOpen) {\n opened = await (opts.openUrl ?? openInBrowser)(url);\n emitNotice(\n ctx.io,\n opened ? 'Opened in your default browser.' : 'Could not open a browser; use the link above.',\n { json: ctx.flags.json },\n );\n }\n\n // Human mode only, and before the wait: the poll below also sees USDC sent\n // straight to the address, so a phone wallet is a second way to finish.\n const qrLines =\n opts.qr !== false && ctx.io.isTTY && !ctx.flags.json\n ? addressQrLines(address, ctx.io.stderr)\n : [];\n if (qrLines.length > 0) {\n ctx.io.stderr.write(\n [`Or send USDC from a phone wallet to ${address}:`, ...qrLines].join('\\n') + '\\n',\n );\n }\n\n const funded =\n shouldWait && startBalance !== undefined\n ? await pollForFunds(ctx, desc, rpcUrl, startBalance, opts)\n : undefined;\n if (funded !== undefined) {\n emitWriteNotice(ctx.io, 'USDC arrived - you can close the checkout tab.');\n }\n const pollStatus: FundPollStatus = !shouldWait\n ? 'skipped'\n : startBalance === undefined\n ? 'unavailable'\n : funded !== undefined\n ? 'arrived'\n : 'timed-out';\n\n const balanceAtomic = funded ?? startBalance;\n return {\n data: {\n address,\n checkoutUrl: url,\n opened,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n funded: funded !== undefined,\n pollStatus,\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n },\n humanLines:\n funded !== undefined\n ? [`Funded: balance is now ${toMoney(funded.toString()).usd} USDC on Base.`]\n : [\n 'Checkout link issued (printed above).',\n ...(pollStatus === 'unavailable'\n ? ['Could not read the balance to wait on it; the link is unaffected.']\n : []),\n 'Confirm arrival later with `tenjin wallet balance`.',\n ],\n };\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin wallet fund 5',\n });\n }\n return n;\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on one of the two\n * allowed hosts (the Tenjin origin or Coinbase's checkout) before anything else\n * sees it: a compromised or misconfigured server must not be able to steer the\n * user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (\n parsed !== undefined &&\n parsed.protocol === 'https:' &&\n ALLOWED_CHECKOUT_HOSTS.includes(parsed.host)\n ) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https on ${ALLOWED_CHECKOUT_HOSTS.join(' or ')}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Coinbase Onramp is not available in your region.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', 'The funding endpoint rejected the signed proof.', {\n fix: 'Check this machine’s clock, then retry.',\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'The funding endpoint is rate limited right now.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError(\n 'API_UNREACHABLE',\n 'Production has no Coinbase Onramp configured right now.',\n {\n fix: 'Retry later.',\n },\n );\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(\n desc: { address: string },\n rpcUrl: string,\n): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(desc.address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wait for the purchased USDC to land: any balance above the pre-mint baseline\n * counts (Coinbase clamps presets, so an exact-amount check would be wrong).\n * RPC flakes mid-poll are tolerated; the deadline is the only exit besides\n * arrival, and timing out is a normal outcome (the human may still be paying),\n * not an error.\n */\nasync function pollForFunds(\n ctx: CommandContext,\n desc: { address: string },\n rpcUrl: string,\n startBalance: bigint,\n opts: FundOptions,\n): Promise<bigint | undefined> {\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;\n const deadline = Date.now() + (opts.pollTimeoutMs ?? POLL_TIMEOUT_MS);\n emitNotice(ctx.io, 'Waiting for the USDC to arrive (Ctrl-C is safe; the purchase is not).', {\n json: ctx.flags.json,\n });\n while (Date.now() < deadline) {\n await sleep(interval);\n const balance = await balanceOrUndefined(desc, rpcUrl);\n if (balance !== undefined && balance > startBalance) return balance;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,kBAAiB;;;ACA1B,SAAS,YAAY,aAAa,iBAAiB;AAoDnD,IAAM,gBAAgB,iBACnB,OAAO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;AACF;AASA,eAAe,aACb,KACA,MACA,QACA,cACA,MAC6B;AAC7B,QAAM,QACJ,KAAK,UAAU,CAAC,OAAe,IAAI,QAAc,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACvF,QAAM,WAAW,KAAK,kBAAkB;AACxC,QAAM,WAAW,KAAK,IAAI,KAAK,KAAK,iBAAiB;AACrD,aAAW,IAAI,IAAI,yEAAyE;AAAA,IAC1F,MAAM,IAAI,MAAM;AAAA,EAClB,CAAC;AACD,SAAO,KAAK,IAAI,IAAI,UAAU;AAC5B,UAAM,MAAM,QAAQ;AACpB,UAAM,UAAU,MAAM,mBAAmB,MAAM,MAAM;AACrD,QAAI,YAAY,UAAa,UAAU,aAAc,QAAO;AAAA,EAC9D;AACA,SAAO;AACT;","names":["webcrypto","subtle","webcrypto"]}
@@ -0,0 +1,31 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ STDIN_TIMEOUT_MS,
4
+ runHookCommand,
5
+ runHookKind
6
+ } from "./chunk-4FYMDRD3.js";
7
+ import "./chunk-XJQ6CH7X.js";
8
+ import "./chunk-MOG7PB3A.js";
9
+ import "./chunk-LX5OT4TQ.js";
10
+ import "./chunk-VKQXVCZR.js";
11
+ import "./chunk-EWLU46J6.js";
12
+ import "./chunk-MRUPDSUM.js";
13
+ import "./chunk-2SNUOHAT.js";
14
+ import "./chunk-7QKHZQKW.js";
15
+ import "./chunk-OOSRB3OF.js";
16
+ import "./chunk-MG3G644T.js";
17
+ import "./chunk-6W5GYG3W.js";
18
+ import "./chunk-S4SAZ7OD.js";
19
+ import "./chunk-RJEPZMYY.js";
20
+ import "./chunk-2I4QTOLB.js";
21
+ import "./chunk-AMEUXNJT.js";
22
+ import "./chunk-VVAHFCX2.js";
23
+ import "./chunk-SJLTEINJ.js";
24
+ import "./chunk-LRCJ2IZ5.js";
25
+ import "./chunk-ZXTAQYNA.js";
26
+ export {
27
+ STDIN_TIMEOUT_MS,
28
+ runHookCommand,
29
+ runHookKind
30
+ };
31
+ //# sourceMappingURL=hook-command-VWJXRT7H.js.map