@keeperhub/wallet 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -113,8 +113,8 @@ function fund(walletAddress) {
113
113
 
114
114
  // src/skill-install.ts
115
115
  var import_node_child_process = require("child_process");
116
- var import_promises = require("fs/promises");
117
116
  var import_node_fs2 = require("fs");
117
+ var import_promises = require("fs/promises");
118
118
  var import_node_path2 = require("path");
119
119
  var import_node_url = require("url");
120
120
 
@@ -192,6 +192,33 @@ function readPackageVersion() {
192
192
  function buildNpxCommand(version) {
193
193
  return `npx -y -p ${PACKAGE_NAME}@${version} ${HOOK_BIN}`;
194
194
  }
195
+ function isNpxExecution() {
196
+ const execPath = process.env.npm_execpath;
197
+ if (typeof execPath !== "string" || execPath.length === 0) {
198
+ return false;
199
+ }
200
+ if (/(?:^|[\\/])npx-cli\.(?:js|cjs|mjs)$/i.test(execPath)) {
201
+ return true;
202
+ }
203
+ if (/(?:^|[\\/])npx(?:\.cmd|\.exe|\.ps1)?$/i.test(execPath)) {
204
+ return true;
205
+ }
206
+ return false;
207
+ }
208
+ var TRANSIENT_CACHE_PATTERNS = [
209
+ /[\\/]_npx[\\/]/,
210
+ /[\\/]dlx-[A-Za-z0-9]+[\\/]/,
211
+ /[\\/]xfs-[A-Za-z0-9]+[\\/]/,
212
+ /[\\/]\.bun[\\/]install[\\/]cache[\\/]/
213
+ ];
214
+ function isPathUnderTransientCache(resolvedPath) {
215
+ for (const re of TRANSIENT_CACHE_PATTERNS) {
216
+ if (re.test(resolvedPath)) {
217
+ return true;
218
+ }
219
+ }
220
+ return false;
221
+ }
195
222
  var KEEPERHUB_HOOK_MARKER = HOOK_BIN;
196
223
  function filterKeeperhubHooksFromEntry(entry) {
197
224
  if (typeof entry !== "object" || entry === null) {
@@ -218,14 +245,19 @@ function resolveHookCommand() {
218
245
  if (envOverride && envOverride.length > 0) {
219
246
  return envOverride;
220
247
  }
248
+ if (isNpxExecution()) {
249
+ return buildNpxCommand(readPackageVersion());
250
+ }
221
251
  try {
222
- (0, import_node_child_process.execFileSync)("/bin/sh", ["-c", `command -v ${HOOK_BIN}`], {
223
- stdio: "ignore"
224
- });
225
- return HOOK_COMMAND_BARE;
252
+ const resolved = (0, import_node_child_process.execFileSync)("/bin/sh", ["-c", `command -v ${HOOK_BIN}`], {
253
+ stdio: ["ignore", "pipe", "ignore"]
254
+ }).toString().trim();
255
+ if (resolved.length > 0 && !isPathUnderTransientCache(resolved)) {
256
+ return HOOK_COMMAND_BARE;
257
+ }
226
258
  } catch {
227
- return buildNpxCommand(readPackageVersion());
228
259
  }
260
+ return buildNpxCommand(readPackageVersion());
229
261
  }
230
262
  function buildKeeperhubEntry(command) {
231
263
  return {
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/balance.ts","../src/chains.ts","../src/fund.ts","../src/skill-install.ts","../src/agent-detect.ts","../src/storage.ts","../src/types.ts"],"sourcesContent":["// CLI dispatcher for `npx @keeperhub/wallet <cmd>`. Ships 4 subcommands:\n// add (provision -- NO auth), fund (pure string-build Coinbase Onramp +\n// Tempo address), balance (Base USDC + Tempo USDC.e), info (print subOrgId\n// + walletAddress from ~/.keeperhub/wallet.json).\n//\n// v0.1.4 removed the `link` subcommand. /api/agentic-wallet/link still\n// exists server-side but the UX (copy-paste session cookie) was not fit\n// for real users; the server-approval ask tier that required linking\n// also collapsed into an inline ask in this release. See KEEP-307 and\n// KEEP-308 for the long-term design decisions.\n//\n// @security The HMAC secret written to wallet.json is NEVER printed to stdout\n// or stderr. `add` prints only subOrgId + walletAddress + the config path so\n// users can inspect perms. `info` never references the secret at all. Grep\n// rule: no process.stdout/process.stderr line in this file should include\n// wallet.hmacSecret or data.hmacSecret.\n//\n// Exit codes: 0 on success, 1 on any error (WalletConfigMissingError,\n// HTTP failure, validation error). Uncaught errors are written to stderr.\n\nimport { Command } from \"commander\";\nimport { checkBalance } from \"./balance.js\";\nimport { fund } from \"./fund.js\";\nimport { installSkill } from \"./skill-install.js\";\nimport {\n getWalletConfigPath,\n readWalletConfig,\n writeWalletConfig,\n} from \"./storage.js\";\nimport { WalletConfigMissingError } from \"./types.js\";\n\nconst TRAILING_SLASH = /\\/$/;\nconst WALLET_ADDRESS_PATTERN = /^0x[a-fA-F0-9]{40}$/;\n\nfunction resolveBaseUrl(override: string | undefined): string {\n const candidate =\n override ?? process.env.KEEPERHUB_API_URL ?? \"https://app.keeperhub.com\";\n return candidate.replace(TRAILING_SLASH, \"\");\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction provisionInvalidError(\n message: string\n): Error & { code: \"PROVISION_RESPONSE_INVALID\" } {\n const err = new Error(message) as Error & {\n code: \"PROVISION_RESPONSE_INVALID\";\n };\n err.code = \"PROVISION_RESPONSE_INVALID\";\n return err;\n}\n\nfunction validateProvisionResponse(data: unknown): {\n subOrgId: string;\n walletAddress: `0x${string}`;\n hmacSecret: string;\n} {\n if (typeof data !== \"object\" || data === null) {\n throw provisionInvalidError(\"provision response is not an object\");\n }\n const { subOrgId, walletAddress, hmacSecret } = data as Record<\n string,\n unknown\n >;\n if (\n !(\n isNonEmptyString(subOrgId) &&\n isNonEmptyString(walletAddress) &&\n isNonEmptyString(hmacSecret)\n )\n ) {\n throw provisionInvalidError(\n \"provision response missing subOrgId, walletAddress, or hmacSecret\"\n );\n }\n if (!WALLET_ADDRESS_PATTERN.test(walletAddress)) {\n throw provisionInvalidError(\n `provision response walletAddress is not a valid 0x-prefixed 40-hex address: ${walletAddress}`\n );\n }\n return {\n subOrgId,\n walletAddress: walletAddress as `0x${string}`,\n hmacSecret,\n };\n}\n\nasync function cmdAdd(opts: { baseUrl?: string } = {}): Promise<void> {\n const baseUrl = resolveBaseUrl(opts.baseUrl);\n const response = await fetch(`${baseUrl}/api/agentic-wallet/provision`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: \"{}\",\n });\n if (!response.ok) {\n const text = await response.text();\n process.stderr.write(\n `[keeperhub-wallet] provision failed: HTTP ${response.status}: ${text}\\n`\n );\n process.exit(1);\n }\n const raw = (await response.json()) as unknown;\n const data = validateProvisionResponse(raw);\n await writeWalletConfig({\n subOrgId: data.subOrgId,\n walletAddress: data.walletAddress,\n hmacSecret: data.hmacSecret,\n });\n // Intentionally print only public fields. The hmacSecret is written to\n // wallet.json (chmod 0o600) but never printed -- T-34-cli-02 mitigation.\n process.stdout.write(`subOrgId: ${data.subOrgId}\\n`);\n process.stdout.write(`walletAddress: ${data.walletAddress}\\n`);\n process.stdout.write(`config written to ${getWalletConfigPath()}\\n`);\n}\n\nasync function cmdFund(): Promise<void> {\n const wallet = await readWalletConfig();\n const out = fund(wallet.walletAddress);\n process.stdout.write(`${out.coinbaseOnrampUrl}\\n`);\n process.stdout.write(`Tempo address: ${out.tempoAddress}\\n`);\n process.stdout.write(`${out.disclaimer}\\n`);\n}\n\nasync function cmdBalance(): Promise<void> {\n const wallet = await readWalletConfig();\n const snap = await checkBalance(wallet);\n process.stdout.write(`Base USDC: ${snap.base.amount}\\n`);\n process.stdout.write(`Tempo USDC.e: ${snap.tempo.amount}\\n`);\n}\n\nasync function cmdInfo(): Promise<void> {\n const wallet = await readWalletConfig();\n process.stdout.write(`subOrgId: ${wallet.subOrgId}\\n`);\n process.stdout.write(`walletAddress: ${wallet.walletAddress}\\n`);\n}\n\nexport async function runCli(argv: string[] = process.argv): Promise<void> {\n const program = new Command();\n program\n .name(\"keeperhub-wallet\")\n .description(\n \"KeeperHub agentic wallet CLI (auto-pay x402 + MPP 402 responses)\"\n )\n .version(\"0.1.3\");\n\n program\n .command(\"add\")\n .description(\"Provision a new agentic wallet (no account required)\")\n .option(\"--base-url <url>\", \"KeeperHub API base URL\")\n .action(async (opts: { baseUrl?: string }) => {\n await cmdAdd(opts);\n });\n\n program\n .command(\"fund\")\n .description(\n \"Print Coinbase Onramp URL (Base USDC) and Tempo deposit address\"\n )\n .action(async () => {\n await cmdFund();\n });\n\n program\n .command(\"balance\")\n .description(\"Print on-chain balance: Base USDC + Tempo USDC.e\")\n .action(async () => {\n await cmdBalance();\n });\n\n program\n .command(\"info\")\n .description(\"Print subOrgId and walletAddress from local config\")\n .action(async () => {\n await cmdInfo();\n });\n\n program\n .command(\"skill\")\n .description(\n \"Install the KeeperHub skill file into detected agent directories\"\n )\n .addCommand(\n new Command(\"install\")\n .description(\n \"Write skill file + register PreToolUse hook in all detected agents\"\n )\n .action(async () => {\n const result = await installSkill();\n for (const write of result.skillWrites) {\n process.stdout.write(\n `skill: ${write.agent} -> ${write.path} (${write.status})\\n`\n );\n }\n for (const reg of result.hookRegistrations) {\n if (reg.status === \"registered\") {\n process.stdout.write(\n `hook: ${reg.agent} -> PreToolUse registered\\n`\n );\n } else if (reg.status === \"notice\") {\n process.stderr.write(\n `notice: ${reg.agent} -> ${reg.message ?? \"\"}\\n`\n );\n }\n }\n if (result.skillWrites.length === 0) {\n process.stderr.write(\n \"No supported agent skill directories detected under $HOME. Create ~/.claude/, ~/.cursor/, ~/.cline/, ~/.windsurf/, or ~/.config/opencode/ and re-run.\\n\"\n );\n }\n })\n );\n\n try {\n await program.parseAsync(argv);\n } catch (err) {\n if (err instanceof WalletConfigMissingError) {\n process.stderr.write(`[keeperhub-wallet] ${err.message}\\n`);\n process.exit(1);\n }\n process.stderr.write(\n `[keeperhub-wallet] ${(err as Error).message ?? String(err)}\\n`\n );\n process.exit(1);\n }\n}\n","// checkBalance() unified view (PAY-05):\n// - Base USDC balanceOf (viem publicClient on Base)\n// - Tempo USDC.e balanceOf (viem publicClient on Tempo)\n//\n// Both legs are fetched in parallel via Promise.all. The on-chain reads\n// touch only the canonical USDC contract on their respective chains\n// (read-only ERC-20 balanceOf with no state mutation).\n//\n// The /api/agentic-wallet/credit ledger is intentionally NOT read here:\n// the server endpoint exists but no debit path is wired, so surfacing the\n// balance to users implied a capability that has not shipped. Restore the\n// leg here when KEEP-305/306 lands.\n//\n// @security balance.ts does not emit balance data to stdout/stderr via the\n// global console object or util.inspect (T-34-bal-02 mitigation). Any\n// stdout emitter added here is a privacy regression; grep-enforced in\n// acceptance criteria.\nimport {\n createPublicClient,\n erc20Abi,\n formatUnits,\n http,\n type PublicClient,\n} from \"viem\";\nimport { BASE_USDC, base, TEMPO_USDC_E, tempo } from \"./chains.js\";\nimport type { WalletConfig } from \"./types.js\";\n\n// USDC and USDC.e both use 6 decimals on Base + Tempo respectively.\nconst USDC_DECIMALS = 6;\n\nexport type BalanceSnapshot = {\n base: {\n chain: \"base\";\n token: \"USDC\";\n amount: string;\n address: `0x${string}`;\n };\n tempo: {\n chain: \"tempo\";\n token: \"USDC.e\";\n amount: string;\n address: `0x${string}`;\n };\n};\n\nexport type CheckBalanceOptions = {\n /** Injectable viem client for Base (tests mock readContract). */\n baseClient?: PublicClient;\n /** Injectable viem client for Tempo (tests mock readContract). */\n tempoClient?: PublicClient;\n};\n\n/**\n * Read the wallet's on-chain balance across Base + Tempo in parallel. Both\n * legs must resolve; any single failure rejects the Promise.\n *\n * Amounts are formatted as decimal strings (6-decimal USDC precision) so the\n * caller can render them without BigInt math.\n */\nexport async function checkBalance(\n wallet: WalletConfig,\n opts: CheckBalanceOptions = {}\n): Promise<BalanceSnapshot> {\n const baseClient =\n opts.baseClient ??\n (createPublicClient({\n chain: base,\n transport: http(),\n }) as unknown as PublicClient);\n const tempoClient =\n opts.tempoClient ??\n (createPublicClient({\n chain: tempo,\n transport: http(),\n }) as unknown as PublicClient);\n\n // Promise.all fires both reads concurrently. Total elapsed ~= max(leg)\n // rather than sum(leg); SC-3 (<2s) test asserts this.\n const [baseRaw, tempoRaw] = await Promise.all([\n baseClient.readContract({\n address: BASE_USDC,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [wallet.walletAddress],\n }) as Promise<bigint>,\n tempoClient.readContract({\n address: TEMPO_USDC_E,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [wallet.walletAddress],\n }) as Promise<bigint>,\n ]);\n\n return {\n base: {\n chain: \"base\",\n token: \"USDC\",\n amount: formatUnits(baseRaw, USDC_DECIMALS),\n address: wallet.walletAddress,\n },\n tempo: {\n chain: \"tempo\",\n token: \"USDC.e\",\n amount: formatUnits(tempoRaw, USDC_DECIMALS),\n address: wallet.walletAddress,\n },\n };\n}\n","// Sources (truth):\n// - lib/agentic-wallet/sign.ts:56 -- Base USDC at\n// 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 (chainId 8453).\n// - lib/mpp/server.ts:3 -- Tempo USDC.e at\n// 0x20c000000000000000000000b9537d11c60e8b50 (chainId 4217).\n//\n// Tempo is not in viem/chains core as of viem 2.48.1 (the version pinned in\n// this package). Define it inline via defineChain so the only dependency is\n// viem itself. TEMPO_RPC_URL overrides the default RPC for heavy readers who\n// want to point at their own node (T-34-bal-01 mitigation).\nimport { defineChain } from \"viem\";\n\nexport { base } from \"viem/chains\";\n\nexport const tempo = defineChain({\n id: 4217,\n name: \"Tempo\",\n nativeCurrency: { decimals: 18, name: \"Ether\", symbol: \"ETH\" },\n rpcUrls: {\n default: {\n http: [process.env.TEMPO_RPC_URL ?? \"https://rpc.tempo.xyz\"],\n },\n },\n blockExplorers: {\n default: { name: \"Tempo Explorer\", url: \"https://explorer.tempo.xyz\" },\n },\n});\n\n/** Circle-issued USDC on Base mainnet. */\nexport const BASE_USDC = \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\" as const;\n\n/** Bridged USDC (USDC.e) on Tempo mainnet. NOT the same contract as BASE_USDC. */\nexport const TEMPO_USDC_E =\n \"0x20c000000000000000000000b9537d11c60e8b50\" as const;\n","// Source: 34-RESEARCH Pattern 5 + Pitfall 5.\n// Coinbase deprecated the query-param pay.coinbase.com flow in favour of\n// sessionToken URLs on 2025-07-31, but the legacy endpoint still returns a\n// working Onramp page (it just may not pre-fill the asset/network/address\n// fields). We print the legacy URL for zero-dependency ergonomics and a\n// follow-up disclaimer so users know to paste manually if prefill is dropped.\n//\n// fund() is a pure string-build: no HTTP, no process spawn, no browser\n// invocation. Callers (the CLI `keeperhub-wallet fund` subcommand, the\n// `check_balance` skill in Phase 35) decide how to display the result.\n//\n// T-34-fund-01 mitigation: the host is hard-coded (pay.coinbase.com) and the\n// only user-supplied input is the wallet address, which is regex-validated\n// against the canonical 0x-prefixed 40-hex-char EVM format before any string\n// interpolation.\n\nexport type FundInstructions = {\n /** Coinbase Onramp deeplink (legacy query-param form). */\n coinbaseOnrampUrl: string;\n /** Tempo deposit address — same as the input wallet (EVM address shared). */\n tempoAddress: `0x${string}`;\n /** Plain-ASCII guidance string; no emojis (CLAUDE.md rule). */\n disclaimer: string;\n};\n\n// 0x followed by exactly 40 hex chars, case-insensitive. Kept at module scope\n// so the regex literal is compiled once (biome/ultracite useTopLevelRegex).\nconst EVM_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\n\n// Coinbase Onramp legacy deeplink. The host + path pair is the documented\n// entry point for query-param-style Onramp sessions.\nconst COINBASE_HOST = \"pay.coinbase.com\";\nconst COINBASE_PATH = \"/buy/select-asset\";\n\n/**\n * Build Coinbase Onramp URL + Tempo deposit address for the given wallet.\n *\n * No HTTP calls are performed. The caller is expected to either print the\n * resulting URL (CLI) or render it in a chat bubble (skill). The returned\n * `disclaimer` explains the Onramp deprecation + the Tempo external-transfer\n * fallback in plain ASCII so terminal clients with ASCII-only fonts render\n * identically to emoji-capable clients.\n *\n * @throws if `walletAddress` does not match /^0x[0-9a-fA-F]{40}$/.\n */\nexport function fund(walletAddress: string): FundInstructions {\n if (!EVM_ADDRESS_RE.test(walletAddress)) {\n throw new Error(`Invalid EVM wallet address: ${walletAddress}`);\n }\n\n // addresses is a JSON-encoded map {walletAddress: [\"base\"]} per Coinbase\n // Onramp docs. Encoding into URLSearchParams guarantees the colon,\n // brackets, and quotes are percent-escaped correctly.\n const params = new URLSearchParams({\n defaultNetwork: \"base\",\n defaultAsset: \"USDC\",\n addresses: JSON.stringify({ [walletAddress]: [\"base\"] }),\n presetCryptoAmount: \"5\",\n });\n\n const coinbaseOnrampUrl = `https://${COINBASE_HOST}${COINBASE_PATH}?${params.toString()}`;\n\n const disclaimer =\n \"If the Coinbase page does not pre-fill, paste your address manually. \" +\n \"For Tempo USDC.e, transfer from an exchange or another wallet to the \" +\n \"address above -- Onramp does not support Tempo directly. Coinbase \" +\n \"sessionToken URLs are the 2025+ canonical form; legacy query-param \" +\n \"URLs may drop prefill on some accounts.\";\n\n return {\n coinbaseOnrampUrl,\n tempoAddress: walletAddress as `0x${string}`,\n disclaimer,\n };\n}\n","// Idempotent skill installer for @keeperhub/wallet.\n//\n// Two public entry points:\n// - installSkill(options?) -- writes keeperhub-wallet.skill.md into every\n// detected agent's skills directory and, for Claude Code, registers a\n// PreToolUse hook pointing at `keeperhub-wallet-hook` in\n// ~/.claude/settings.json. For non-claude agents, emits a stderr notice.\n// - registerClaudeCodeHook(settingsPath, options?) -- pure settings.json\n// patcher used internally; exported so tests can drive it directly.\n//\n// Hook command resolution: the README's recommended install path is\n// `npx @keeperhub/wallet skill install`, which does not put the bin on the\n// system PATH. If we wrote a bare `keeperhub-wallet-hook` command in that\n// case, the hook would fire `command not found` on every tool call. So at\n// install time we probe PATH; if the bin resolves we keep the bare command\n// (lowest startup latency), otherwise we fall back to an `npx` invocation\n// that resolves regardless of where future shells run.\n//\n// Idempotency rule: re-running the installer MUST NOT create a duplicate\n// hook entry. We filter any existing array element whose serialised form\n// contains `keeperhub-wallet-hook` before appending a single fresh record.\n// The marker substring is present in BOTH the bare and npx forms, so the\n// de-dup survives a global-install → npx-install transition (and back).\n//\n// Preservation rule: all top-level keys in settings.json other than\n// hooks.PreToolUse MUST be byte-preserved. We only ever touch\n// hooks.PreToolUse; any foreign hooks.PostToolUse entries survive verbatim.\n\nimport { execFileSync } from \"node:child_process\";\nimport { chmod, copyFile, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { type AgentTarget, detectAgents } from \"./agent-detect.js\";\n\nconst HOOK_BIN = \"keeperhub-wallet-hook\";\nconst HOOK_COMMAND_BARE = HOOK_BIN;\nconst PACKAGE_NAME = \"@keeperhub/wallet\";\n\n/**\n * Read the installer's own version from package.json so the npx command\n * pins to it. Pinning matters because `npx -y` would otherwise pull\n * `latest` on every PreToolUse hook fire — any future compromise of the\n * `@keeperhub/wallet` scope on the npm registry would be executed on\n * every tool call by every npx-installed user. Pinning to the version\n * shipped at install time makes upgrades explicit (re-run skill install)\n * and bounds the supply-chain blast radius to \"code that was already\n * trusted enough to install\".\n *\n * Falls back to \"latest\" only if package.json cannot be located, which\n * should never happen in published builds (dist/ sits next to package.json\n * via pkg.files). The fallback exists so test runs from src/ — where the\n * resolution path is `here/../package.json` — never crash the installer.\n */\nfunction readPackageVersion(): string {\n try {\n const here = dirname(fileURLToPath(import.meta.url));\n // Module lives in dist/ at runtime and src/ during tests; in both cases\n // package.json is one level up.\n const pkgPath = join(here, \"..\", \"package.json\");\n const raw = readFileSync(pkgPath, \"utf-8\");\n const parsed = JSON.parse(raw) as { version?: string };\n if (typeof parsed.version === \"string\" && parsed.version.length > 0) {\n return parsed.version;\n }\n } catch {\n // Fall through.\n }\n return \"latest\";\n}\n\nfunction buildNpxCommand(version: string): string {\n return `npx -y -p ${PACKAGE_NAME}@${version} ${HOOK_BIN}`;\n}\n\n// Match rule for de-dup: any existing PreToolUse entry whose `command`\n// string contains this substring is considered \"ours\" and is removed\n// before append. The marker is present in BOTH the bare and pinned-npx\n// forms, so the de-dup survives a global-install <-> npx-install\n// transition (and across version bumps).\n//\n// Why match on the `command` field rather than JSON.stringify(entry):\n// the wider marker would silently delete an unrelated hook whose args\n// or matcher happen to mention the bin name (e.g. a logger). Scoping\n// to `command` is narrower and equally idempotent for our writes since\n// we always write the marker into `command`.\nconst KEEPERHUB_HOOK_MARKER = HOOK_BIN;\n\ntype PreToolUseLikeEntry = {\n hooks?: Array<{ command?: unknown }>;\n};\n\n/**\n * Drop only the `hooks[]` items that reference the keeperhub bin, leaving\n * sibling commands inside the same `PreToolUse` element intact. Returns\n * the (possibly modified) entry, or null when every `hooks[]` item was\n * keeperhub-related and the whole element should be removed.\n *\n * Why per-item: a user may merge our hook into a single `PreToolUse`\n * element alongside their own commands, e.g.:\n *\n * { matcher: \"*\", hooks: [\n * { type: \"command\", command: \"/usr/local/bin/audit-logger\" },\n * { type: \"command\", command: \"keeperhub-wallet-hook\" } ] }\n *\n * Dropping the whole element on re-install would silently delete the\n * audit-logger sibling. Dropping only matching items preserves it.\n *\n * Non-object entries and entries without a `hooks[]` array are returned\n * unchanged — we never inspect or mutate shapes we don't recognise.\n */\nfunction filterKeeperhubHooksFromEntry(entry: unknown): unknown {\n if (typeof entry !== \"object\" || entry === null) {\n return entry;\n }\n const candidate = entry as PreToolUseLikeEntry;\n if (!Array.isArray(candidate.hooks)) {\n return entry;\n }\n const survivors = candidate.hooks.filter((h) => {\n const cmd = h?.command;\n return !(typeof cmd === \"string\" && cmd.includes(KEEPERHUB_HOOK_MARKER));\n });\n if (survivors.length === candidate.hooks.length) {\n // No keeperhub hooks present in this entry — return original byte-for-byte.\n return entry;\n }\n if (survivors.length === 0) {\n // Every hook in this element was ours; drop the whole element so we\n // don't leave a `{matcher, hooks: []}` shell behind.\n return null;\n }\n return { ...candidate, hooks: survivors };\n}\n\n/**\n * Pick the hook command to write into settings.json.\n *\n * Returns the bare bin name if it resolves on PATH (global install or a\n * dev-time `npm link`), otherwise a version-pinned `npx` invocation that\n * pulls the installer's own version of `@keeperhub/wallet` on demand.\n * Override-able via the env var `KEEPERHUB_WALLET_HOOK_COMMAND` for\n * test fixtures and unusual deployments (env input is trusted — it is\n * written verbatim into settings.json and executed by the user's shell).\n */\nexport function resolveHookCommand(): string {\n const envOverride = process.env.KEEPERHUB_WALLET_HOOK_COMMAND;\n if (envOverride && envOverride.length > 0) {\n return envOverride;\n }\n try {\n // `command -v` is POSIX and avoids spawning a full shell; stdio is\n // ignored because we only care about the exit code.\n execFileSync(\"/bin/sh\", [\"-c\", `command -v ${HOOK_BIN}`], {\n stdio: \"ignore\",\n });\n return HOOK_COMMAND_BARE;\n } catch {\n return buildNpxCommand(readPackageVersion());\n }\n}\n\nexport type InstallResult = {\n skillWrites: Array<{\n agent: string;\n path: string;\n status: \"written\" | \"skipped\";\n }>;\n hookRegistrations: Array<{\n agent: string;\n status: \"registered\" | \"notice\" | \"skipped\";\n message?: string;\n }>;\n};\n\nexport type InstallOptions = {\n homeOverride?: string;\n skillSourcePath?: string;\n onNotice?: (msg: string) => void;\n /**\n * Hook command to write into settings.json (and reference in stderr\n * notices for non-Claude agents). Defaults to {@link resolveHookCommand}.\n * Override for tests, monorepo setups, or unusual deployments.\n */\n hookCommand?: string;\n};\n\nexport type RegisterClaudeCodeHookOptions = {\n /**\n * Hook command to write. Defaults to {@link resolveHookCommand}. Tests\n * pass a deterministic value to keep assertions stable across host\n * environments (CI may or may not have the bin on PATH).\n */\n hookCommand?: string;\n};\n\ntype ClaudeHookEntry = {\n matcher: string;\n hooks: Array<{ type: string; command: string }>;\n};\n\ntype ClaudeSettings = {\n hooks?: {\n PreToolUse?: unknown[];\n [k: string]: unknown;\n };\n [k: string]: unknown;\n};\n\nfunction buildKeeperhubEntry(command: string): ClaudeHookEntry {\n return {\n matcher: \"*\",\n hooks: [{ type: \"command\", command }],\n };\n}\n\nfunction resolveDefaultSkillSource(): string {\n // Resolve the module's own directory in a way that works in both ESM\n // (import.meta.url) and CJS (__dirname shim emitted by tsup). At runtime\n // the module lives inside dist/, so `../skill/` points at the sibling\n // skill/ directory shipped via pkg.files. During vitest tests the module\n // executes from src/, and `../skill/` resolves to packages/wallet/skill/.\n const here = dirname(fileURLToPath(import.meta.url));\n return join(here, \"..\", \"skill\", \"keeperhub-wallet.skill.md\");\n}\n\nfunction defaultNotice(msg: string): void {\n process.stderr.write(`${msg}\\n`);\n}\n\nexport async function registerClaudeCodeHook(\n settingsPath: string,\n options: RegisterClaudeCodeHookOptions = {}\n): Promise<void> {\n const command = options.hookCommand ?? resolveHookCommand();\n\n let raw: string | null = null;\n try {\n raw = await readFile(settingsPath, \"utf-8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw err;\n }\n }\n\n let config: ClaudeSettings = {};\n if (raw !== null) {\n try {\n config = JSON.parse(raw) as ClaudeSettings;\n } catch {\n throw new Error(\n `settings.json at ${settingsPath} is not valid JSON; aborting hook registration`\n );\n }\n }\n\n const hooks: Record<string, unknown> =\n typeof config.hooks === \"object\" && config.hooks !== null\n ? (config.hooks as Record<string, unknown>)\n : {};\n\n const existingPreToolUse = Array.isArray(hooks.PreToolUse)\n ? (hooks.PreToolUse as unknown[])\n : [];\n\n // De-dup: drop only the hooks[] items whose `command` field references\n // the keeperhub-wallet-hook bin, leaving sibling commands within the\n // same PreToolUse element untouched. Scoped to the `command` field (not\n // the full serialised entry) so an unrelated hook that mentions the bin\n // name in its matcher or args isn't silently deleted. Covers both the\n // bare-bin and version-pinned npx forms, and older versions of this\n // installer.\n const filtered: unknown[] = [];\n for (const entry of existingPreToolUse) {\n const survivor = filterKeeperhubHooksFromEntry(entry);\n if (survivor !== null) {\n filtered.push(survivor);\n }\n }\n filtered.push(buildKeeperhubEntry(command));\n\n hooks.PreToolUse = filtered;\n config.hooks = hooks as ClaudeSettings[\"hooks\"];\n\n await mkdir(dirname(settingsPath), { recursive: true, mode: 0o700 });\n const payload = `${JSON.stringify(config, null, 2)}\\n`;\n await writeFile(settingsPath, payload, { mode: 0o600 });\n // Reassert mode in case the file already existed with looser perms.\n await chmod(settingsPath, 0o600);\n}\n\nasync function writeSkillToAgent(\n agent: AgentTarget,\n skillSource: string\n): Promise<{ agent: string; path: string; status: \"written\" | \"skipped\" }> {\n await mkdir(agent.skillsDir, { recursive: true, mode: 0o755 });\n const target = join(agent.skillsDir, \"keeperhub-wallet.skill.md\");\n await copyFile(skillSource, target);\n await chmod(target, 0o644);\n return { agent: agent.agent, path: target, status: \"written\" };\n}\n\nfunction buildNoticeMessage(agent: AgentTarget, command: string): string {\n return `${agent.agent} does not support auto-registered PreToolUse hooks; run \\`${command}\\` on every tool use via ${agent.agent}'s settings file at ${agent.settingsFile}`;\n}\n\nexport async function installSkill(\n options: InstallOptions = {}\n): Promise<InstallResult> {\n const agents = detectAgents(options.homeOverride);\n const skillSource = options.skillSourcePath ?? resolveDefaultSkillSource();\n const onNotice = options.onNotice ?? defaultNotice;\n // Resolve once per install run so the bare-vs-npx decision stays\n // consistent across every detected agent. Tests pass an explicit value to\n // pin the assertion shape regardless of host PATH.\n const hookCommand = options.hookCommand ?? resolveHookCommand();\n\n const skillWrites: InstallResult[\"skillWrites\"] = [];\n const hookRegistrations: InstallResult[\"hookRegistrations\"] = [];\n\n for (const agent of agents) {\n const write = await writeSkillToAgent(agent, skillSource);\n skillWrites.push(write);\n\n if (agent.hookSupport === \"claude-code\") {\n await registerClaudeCodeHook(agent.settingsFile, { hookCommand });\n hookRegistrations.push({\n agent: agent.agent,\n status: \"registered\",\n });\n } else {\n const message = buildNoticeMessage(agent, hookCommand);\n hookRegistrations.push({\n agent: agent.agent,\n status: \"notice\",\n message,\n });\n onNotice(message);\n }\n }\n\n return { skillWrites, hookRegistrations };\n}\n","// Cross-agent skill/settings directory discovery.\n//\n// Probes canonical paths under $HOME and returns one AgentTarget record per\n// agent whose parent directory exists. The `skills/` leaf may be absent --\n// installSkill() creates it.\n//\n// NOTE: `homedir()` is called per-invocation (via `homeOverride ?? homedir()`)\n// and NEVER hoisted to a module-level constant. Tests override\n// `process.env.HOME` in `beforeEach`; hoisting would freeze the harness's\n// original HOME at import time and detection would run against the real $HOME.\n\nimport { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nexport type AgentTarget = {\n agent: \"claude-code\" | \"cursor\" | \"cline\" | \"windsurf\" | \"opencode\";\n skillsDir: string;\n settingsFile: string;\n hookSupport: \"claude-code\" | \"notice\";\n};\n\ntype AgentSpec = {\n agent: AgentTarget[\"agent\"];\n skillsRel: string[];\n settingsRel: string[];\n hookSupport: AgentTarget[\"hookSupport\"];\n};\n\n// Deterministic order: claude-code first (only agent with hook support),\n// then cursor, cline, windsurf, opencode.\nconst AGENT_SPECS: readonly AgentSpec[] = [\n {\n agent: \"claude-code\",\n skillsRel: [\".claude\", \"skills\"],\n settingsRel: [\".claude\", \"settings.json\"],\n hookSupport: \"claude-code\",\n },\n {\n agent: \"cursor\",\n skillsRel: [\".cursor\", \"skills\"],\n settingsRel: [\".cursor\", \"settings.json\"],\n hookSupport: \"notice\",\n },\n {\n agent: \"cline\",\n skillsRel: [\".cline\", \"skills\"],\n settingsRel: [\".cline\", \"settings.json\"],\n hookSupport: \"notice\",\n },\n {\n agent: \"windsurf\",\n skillsRel: [\".windsurf\", \"skills\"],\n settingsRel: [\".windsurf\", \"settings.json\"],\n hookSupport: \"notice\",\n },\n {\n agent: \"opencode\",\n skillsRel: [\".config\", \"opencode\", \"skills\"],\n settingsRel: [\".config\", \"opencode\", \"settings.json\"],\n hookSupport: \"notice\",\n },\n];\n\nexport function detectAgents(homeOverride?: string): AgentTarget[] {\n const home = homeOverride ?? homedir();\n const results: AgentTarget[] = [];\n for (const spec of AGENT_SPECS) {\n const skillsDir = join(home, ...spec.skillsRel);\n const settingsFile = join(home, ...spec.settingsRel);\n // \"Detected\" iff the parent of skills/ exists (e.g. ~/.claude/).\n // skills/ itself may be absent; installer creates it.\n if (existsSync(dirname(skillsDir))) {\n results.push({\n agent: spec.agent,\n skillsDir,\n settingsFile,\n hookSupport: spec.hookSupport,\n });\n }\n }\n return results;\n}\n","import { chmod, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { type WalletConfig, WalletConfigMissingError } from \"./types.js\";\n\n// NOTE: Every function calls `join(homedir(), \".keeperhub\", \"wallet.json\")`\n// itself. Do NOT hoist to a module-level `const WALLET_PATH` -- tests\n// override `process.env.HOME` in `beforeEach` and `homedir()` must re-read\n// that on each call. A hoisted constant would freeze the harness's original\n// HOME at import time and every test would write into the real\n// ~/.keeperhub/ directory.\n\nexport async function readWalletConfig(): Promise<WalletConfig> {\n const walletPath = join(homedir(), \".keeperhub\", \"wallet.json\");\n let raw: string;\n try {\n raw = await readFile(walletPath, \"utf-8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new WalletConfigMissingError();\n }\n throw err;\n }\n const parsed = JSON.parse(raw) as Partial<WalletConfig>;\n if (!(parsed.subOrgId && parsed.walletAddress && parsed.hmacSecret)) {\n throw new Error(`Malformed wallet.json at ${walletPath}`);\n }\n return parsed as WalletConfig;\n}\n\nexport async function writeWalletConfig(config: WalletConfig): Promise<void> {\n const walletPath = join(homedir(), \".keeperhub\", \"wallet.json\");\n await mkdir(dirname(walletPath), { recursive: true, mode: 0o700 });\n await writeFile(walletPath, JSON.stringify(config, null, 2), { mode: 0o600 });\n // Reassert mode in case the file already existed with looser perms.\n await chmod(walletPath, 0o600);\n}\n\nexport function getWalletConfigPath(): string {\n return join(homedir(), \".keeperhub\", \"wallet.json\");\n}\n","// Shared types across the package. Phase 34.\nexport type WalletConfig = {\n /** Turnkey sub-org ID returned by POST /api/agentic-wallet/provision */\n subOrgId: string;\n /** EVM-shared wallet address (same for Base chainId 8453 and Tempo chainId 4217) */\n walletAddress: `0x${string}`;\n /** 64-char lowercase hex HMAC secret, minted server-side at provision; never logged */\n hmacSecret: string;\n};\n\nexport type HmacHeaders = {\n \"X-KH-Sub-Org\": string;\n \"X-KH-Timestamp\": string;\n \"X-KH-Signature\": string;\n};\n\nexport type HookDecision = {\n decision: \"allow\" | \"deny\" | \"ask\";\n reason?: string;\n};\n\nexport class KeeperHubError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = \"KeeperHubError\";\n this.code = code;\n }\n}\n\n/** Protocol preference for a single pay() or fetch() call. \"auto\" preserves\n * the x402-first default when both challenges are offered. */\nexport type PaymentHint = \"x402\" | \"mpp\" | \"auto\";\n\nexport class WalletConfigMissingError extends Error {\n constructor() {\n super(\n \"Wallet config not found at ~/.keeperhub/wallet.json. Run `npx @keeperhub/wallet add` to provision.\"\n );\n this.name = \"WalletConfigMissingError\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBA,uBAAwB;;;ACHxB,IAAAA,eAMO;;;ACbP,kBAA4B;AAE5B,oBAAqB;AAEd,IAAM,YAAQ,yBAAY;AAAA,EAC/B,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,gBAAgB,EAAE,UAAU,IAAI,MAAM,SAAS,QAAQ,MAAM;AAAA,EAC7D,SAAS;AAAA,IACP,SAAS;AAAA,MACP,MAAM,CAAC,QAAQ,IAAI,iBAAiB,uBAAuB;AAAA,IAC7D;AAAA,EACF;AAAA,EACA,gBAAgB;AAAA,IACd,SAAS,EAAE,MAAM,kBAAkB,KAAK,6BAA6B;AAAA,EACvE;AACF,CAAC;AAGM,IAAM,YAAY;AAGlB,IAAM,eACX;;;ADLF,IAAM,gBAAgB;AA+BtB,eAAsB,aACpB,QACA,OAA4B,CAAC,GACH;AAC1B,QAAM,aACJ,KAAK,kBACJ,iCAAmB;AAAA,IAClB,OAAO;AAAA,IACP,eAAW,mBAAK;AAAA,EAClB,CAAC;AACH,QAAM,cACJ,KAAK,mBACJ,iCAAmB;AAAA,IAClB,OAAO;AAAA,IACP,eAAW,mBAAK;AAAA,EAClB,CAAC;AAIH,QAAM,CAAC,SAAS,QAAQ,IAAI,MAAM,QAAQ,IAAI;AAAA,IAC5C,WAAW,aAAa;AAAA,MACtB,SAAS;AAAA,MACT,KAAK;AAAA,MACL,cAAc;AAAA,MACd,MAAM,CAAC,OAAO,aAAa;AAAA,IAC7B,CAAC;AAAA,IACD,YAAY,aAAa;AAAA,MACvB,SAAS;AA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M,SAAS,MAAM,aAAa;AAClC,iBAAW,SAAS,OAAO,aAAa;AACtC,gBAAQ,OAAO;AAAA,UACb,UAAU,MAAM,KAAK,OAAO,MAAM,IAAI,KAAK,MAAM,MAAM;AAAA;AAAA,QACzD;AAAA,MACF;AACA,iBAAW,OAAO,OAAO,mBAAmB;AAC1C,YAAI,IAAI,WAAW,cAAc;AAC/B,kBAAQ,OAAO;AAAA,YACb,SAAS,IAAI,KAAK;AAAA;AAAA,UACpB;AAAA,QACF,WAAW,IAAI,WAAW,UAAU;AAClC,kBAAQ,OAAO;AAAA,YACb,WAAW,IAAI,KAAK,OAAO,IAAI,WAAW,EAAE;AAAA;AAAA,UAC9C;AAAA,QACF;AAAA,MACF;AACA,UAAI,OAAO,YAAY,WAAW,GAAG;AACnC,gBAAQ,OAAO;AAAA,UACb;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACL;AAEF,MAAI;AACF,UAAM,QAAQ,WAAW,IAAI;AAAA,EAC/B,SAAS,KAAK;AACZ,QAAI,eAAe,0BAA0B;AAC3C,cAAQ,OAAO,MAAM,sBAAsB,IAAI,OAAO;AAAA,CAAI;AAC1D,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,YAAQ,OAAO;AAAA,MACb,sBAAuB,IAAc,WAAW,OAAO,GAAG,CAAC;AAAA;AAAA,IAC7D;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["import_viem","import_node_fs","import_node_path","import_promises","import_node_os","import_node_path"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/balance.ts","../src/chains.ts","../src/fund.ts","../src/skill-install.ts","../src/agent-detect.ts","../src/storage.ts","../src/types.ts"],"sourcesContent":["// CLI dispatcher for `npx @keeperhub/wallet <cmd>`. Ships 4 subcommands:\n// add (provision -- NO auth), fund (pure string-build Coinbase Onramp +\n// Tempo address), balance (Base USDC + Tempo USDC.e), info (print subOrgId\n// + walletAddress from ~/.keeperhub/wallet.json).\n//\n// v0.1.4 removed the `link` subcommand. /api/agentic-wallet/link still\n// exists server-side but the UX (copy-paste session cookie) was not fit\n// for real users; the server-approval ask tier that required linking\n// also collapsed into an inline ask in this release. See KEEP-307 and\n// KEEP-308 for the long-term design decisions.\n//\n// @security The HMAC secret written to wallet.json is NEVER printed to stdout\n// or stderr. `add` prints only subOrgId + walletAddress + the config path so\n// users can inspect perms. `info` never references the secret at all. Grep\n// rule: no process.stdout/process.stderr line in this file should include\n// wallet.hmacSecret or data.hmacSecret.\n//\n// Exit codes: 0 on success, 1 on any error (WalletConfigMissingError,\n// HTTP failure, validation error). Uncaught errors are written to stderr.\n\nimport { Command } from \"commander\";\nimport { checkBalance } from \"./balance.js\";\nimport { fund } from \"./fund.js\";\nimport { installSkill } from \"./skill-install.js\";\nimport {\n getWalletConfigPath,\n readWalletConfig,\n writeWalletConfig,\n} from \"./storage.js\";\nimport { WalletConfigMissingError } from \"./types.js\";\n\nconst TRAILING_SLASH = /\\/$/;\nconst WALLET_ADDRESS_PATTERN = /^0x[a-fA-F0-9]{40}$/;\n\nfunction resolveBaseUrl(override: string | undefined): string {\n const candidate =\n override ?? process.env.KEEPERHUB_API_URL ?? \"https://app.keeperhub.com\";\n return candidate.replace(TRAILING_SLASH, \"\");\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction provisionInvalidError(\n message: string\n): Error & { code: \"PROVISION_RESPONSE_INVALID\" } {\n const err = new Error(message) as Error & {\n code: \"PROVISION_RESPONSE_INVALID\";\n };\n err.code = \"PROVISION_RESPONSE_INVALID\";\n return err;\n}\n\nfunction validateProvisionResponse(data: unknown): {\n subOrgId: string;\n walletAddress: `0x${string}`;\n hmacSecret: string;\n} {\n if (typeof data !== \"object\" || data === null) {\n throw provisionInvalidError(\"provision response is not an object\");\n }\n const { subOrgId, walletAddress, hmacSecret } = data as Record<\n string,\n unknown\n >;\n if (\n !(\n isNonEmptyString(subOrgId) &&\n isNonEmptyString(walletAddress) &&\n isNonEmptyString(hmacSecret)\n )\n ) {\n throw provisionInvalidError(\n \"provision response missing subOrgId, walletAddress, or hmacSecret\"\n );\n }\n if (!WALLET_ADDRESS_PATTERN.test(walletAddress)) {\n throw provisionInvalidError(\n `provision response walletAddress is not a valid 0x-prefixed 40-hex address: ${walletAddress}`\n );\n }\n return {\n subOrgId,\n walletAddress: walletAddress as `0x${string}`,\n hmacSecret,\n };\n}\n\nasync function cmdAdd(opts: { baseUrl?: string } = {}): Promise<void> {\n const baseUrl = resolveBaseUrl(opts.baseUrl);\n const response = await fetch(`${baseUrl}/api/agentic-wallet/provision`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: \"{}\",\n });\n if (!response.ok) {\n const text = await response.text();\n process.stderr.write(\n `[keeperhub-wallet] provision failed: HTTP ${response.status}: ${text}\\n`\n );\n process.exit(1);\n }\n const raw = (await response.json()) as unknown;\n const data = validateProvisionResponse(raw);\n await writeWalletConfig({\n subOrgId: data.subOrgId,\n walletAddress: data.walletAddress,\n hmacSecret: data.hmacSecret,\n });\n // Intentionally print only public fields. The hmacSecret is written to\n // wallet.json (chmod 0o600) but never printed -- T-34-cli-02 mitigation.\n process.stdout.write(`subOrgId: ${data.subOrgId}\\n`);\n process.stdout.write(`walletAddress: ${data.walletAddress}\\n`);\n process.stdout.write(`config written to ${getWalletConfigPath()}\\n`);\n}\n\nasync function cmdFund(): Promise<void> {\n const wallet = await readWalletConfig();\n const out = fund(wallet.walletAddress);\n process.stdout.write(`${out.coinbaseOnrampUrl}\\n`);\n process.stdout.write(`Tempo address: ${out.tempoAddress}\\n`);\n process.stdout.write(`${out.disclaimer}\\n`);\n}\n\nasync function cmdBalance(): Promise<void> {\n const wallet = await readWalletConfig();\n const snap = await checkBalance(wallet);\n process.stdout.write(`Base USDC: ${snap.base.amount}\\n`);\n process.stdout.write(`Tempo USDC.e: ${snap.tempo.amount}\\n`);\n}\n\nasync function cmdInfo(): Promise<void> {\n const wallet = await readWalletConfig();\n process.stdout.write(`subOrgId: ${wallet.subOrgId}\\n`);\n process.stdout.write(`walletAddress: ${wallet.walletAddress}\\n`);\n}\n\nexport async function runCli(argv: string[] = process.argv): Promise<void> {\n const program = new Command();\n program\n .name(\"keeperhub-wallet\")\n .description(\n \"KeeperHub agentic wallet CLI (auto-pay x402 + MPP 402 responses)\"\n )\n .version(\"0.1.3\");\n\n program\n .command(\"add\")\n .description(\"Provision a new agentic wallet (no account required)\")\n .option(\"--base-url <url>\", \"KeeperHub API base URL\")\n .action(async (opts: { baseUrl?: string }) => {\n await cmdAdd(opts);\n });\n\n program\n .command(\"fund\")\n .description(\n \"Print Coinbase Onramp URL (Base USDC) and Tempo deposit address\"\n )\n .action(async () => {\n await cmdFund();\n });\n\n program\n .command(\"balance\")\n .description(\"Print on-chain balance: Base USDC + Tempo USDC.e\")\n .action(async () => {\n await cmdBalance();\n });\n\n program\n .command(\"info\")\n .description(\"Print subOrgId and walletAddress from local config\")\n .action(async () => {\n await cmdInfo();\n });\n\n program\n .command(\"skill\")\n .description(\n \"Install the KeeperHub skill file into detected agent directories\"\n )\n .addCommand(\n new Command(\"install\")\n .description(\n \"Write skill file + register PreToolUse hook in all detected agents\"\n )\n .action(async () => {\n const result = await installSkill();\n for (const write of result.skillWrites) {\n process.stdout.write(\n `skill: ${write.agent} -> ${write.path} (${write.status})\\n`\n );\n }\n for (const reg of result.hookRegistrations) {\n if (reg.status === \"registered\") {\n process.stdout.write(\n `hook: ${reg.agent} -> PreToolUse registered\\n`\n );\n } else if (reg.status === \"notice\") {\n process.stderr.write(\n `notice: ${reg.agent} -> ${reg.message ?? \"\"}\\n`\n );\n }\n }\n if (result.skillWrites.length === 0) {\n process.stderr.write(\n \"No supported agent skill directories detected under $HOME. Create ~/.claude/, ~/.cursor/, ~/.cline/, ~/.windsurf/, or ~/.config/opencode/ and re-run.\\n\"\n );\n }\n })\n );\n\n try {\n await program.parseAsync(argv);\n } catch (err) {\n if (err instanceof WalletConfigMissingError) {\n process.stderr.write(`[keeperhub-wallet] ${err.message}\\n`);\n process.exit(1);\n }\n process.stderr.write(\n `[keeperhub-wallet] ${(err as Error).message ?? String(err)}\\n`\n );\n process.exit(1);\n }\n}\n","// checkBalance() unified view (PAY-05):\n// - Base USDC balanceOf (viem publicClient on Base)\n// - Tempo USDC.e balanceOf (viem publicClient on Tempo)\n//\n// Both legs are fetched in parallel via Promise.all. The on-chain reads\n// touch only the canonical USDC contract on their respective chains\n// (read-only ERC-20 balanceOf with no state mutation).\n//\n// The /api/agentic-wallet/credit ledger is intentionally NOT read here:\n// the server endpoint exists but no debit path is wired, so surfacing the\n// balance to users implied a capability that has not shipped. Restore the\n// leg here when KEEP-305/306 lands.\n//\n// @security balance.ts does not emit balance data to stdout/stderr via the\n// global console object or util.inspect (T-34-bal-02 mitigation). Any\n// stdout emitter added here is a privacy regression; grep-enforced in\n// acceptance criteria.\nimport {\n createPublicClient,\n erc20Abi,\n formatUnits,\n http,\n type PublicClient,\n} from \"viem\";\nimport { BASE_USDC, base, TEMPO_USDC_E, tempo } from \"./chains.js\";\nimport type { WalletConfig } from \"./types.js\";\n\n// USDC and USDC.e both use 6 decimals on Base + Tempo respectively.\nconst USDC_DECIMALS = 6;\n\nexport type BalanceSnapshot = {\n base: {\n chain: \"base\";\n token: \"USDC\";\n amount: string;\n address: `0x${string}`;\n };\n tempo: {\n chain: \"tempo\";\n token: \"USDC.e\";\n amount: string;\n address: `0x${string}`;\n };\n};\n\nexport type CheckBalanceOptions = {\n /** Injectable viem client for Base (tests mock readContract). */\n baseClient?: PublicClient;\n /** Injectable viem client for Tempo (tests mock readContract). */\n tempoClient?: PublicClient;\n};\n\n/**\n * Read the wallet's on-chain balance across Base + Tempo in parallel. Both\n * legs must resolve; any single failure rejects the Promise.\n *\n * Amounts are formatted as decimal strings (6-decimal USDC precision) so the\n * caller can render them without BigInt math.\n */\nexport async function checkBalance(\n wallet: WalletConfig,\n opts: CheckBalanceOptions = {}\n): Promise<BalanceSnapshot> {\n const baseClient =\n opts.baseClient ??\n (createPublicClient({\n chain: base,\n transport: http(),\n }) as unknown as PublicClient);\n const tempoClient =\n opts.tempoClient ??\n (createPublicClient({\n chain: tempo,\n transport: http(),\n }) as unknown as PublicClient);\n\n // Promise.all fires both reads concurrently. Total elapsed ~= max(leg)\n // rather than sum(leg); SC-3 (<2s) test asserts this.\n const [baseRaw, tempoRaw] = await Promise.all([\n baseClient.readContract({\n address: BASE_USDC,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [wallet.walletAddress],\n }) as Promise<bigint>,\n tempoClient.readContract({\n address: TEMPO_USDC_E,\n abi: erc20Abi,\n functionName: \"balanceOf\",\n args: [wallet.walletAddress],\n }) as Promise<bigint>,\n ]);\n\n return {\n base: {\n chain: \"base\",\n token: \"USDC\",\n amount: formatUnits(baseRaw, USDC_DECIMALS),\n address: wallet.walletAddress,\n },\n tempo: {\n chain: \"tempo\",\n token: \"USDC.e\",\n amount: formatUnits(tempoRaw, USDC_DECIMALS),\n address: wallet.walletAddress,\n },\n };\n}\n","// Sources (truth):\n// - lib/agentic-wallet/sign.ts:56 -- Base USDC at\n// 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 (chainId 8453).\n// - lib/mpp/server.ts:3 -- Tempo USDC.e at\n// 0x20c000000000000000000000b9537d11c60e8b50 (chainId 4217).\n//\n// Tempo is not in viem/chains core as of viem 2.48.1 (the version pinned in\n// this package). Define it inline via defineChain so the only dependency is\n// viem itself. TEMPO_RPC_URL overrides the default RPC for heavy readers who\n// want to point at their own node (T-34-bal-01 mitigation).\nimport { defineChain } from \"viem\";\n\nexport { base } from \"viem/chains\";\n\nexport const tempo = defineChain({\n id: 4217,\n name: \"Tempo\",\n nativeCurrency: { decimals: 18, name: \"Ether\", symbol: \"ETH\" },\n rpcUrls: {\n default: {\n http: [process.env.TEMPO_RPC_URL ?? \"https://rpc.tempo.xyz\"],\n },\n },\n blockExplorers: {\n default: { name: \"Tempo Explorer\", url: \"https://explorer.tempo.xyz\" },\n },\n});\n\n/** Circle-issued USDC on Base mainnet. */\nexport const BASE_USDC = \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\" as const;\n\n/** Bridged USDC (USDC.e) on Tempo mainnet. NOT the same contract as BASE_USDC. */\nexport const TEMPO_USDC_E =\n \"0x20c000000000000000000000b9537d11c60e8b50\" as const;\n","// Source: 34-RESEARCH Pattern 5 + Pitfall 5.\n// Coinbase deprecated the query-param pay.coinbase.com flow in favour of\n// sessionToken URLs on 2025-07-31, but the legacy endpoint still returns a\n// working Onramp page (it just may not pre-fill the asset/network/address\n// fields). We print the legacy URL for zero-dependency ergonomics and a\n// follow-up disclaimer so users know to paste manually if prefill is dropped.\n//\n// fund() is a pure string-build: no HTTP, no process spawn, no browser\n// invocation. Callers (the CLI `keeperhub-wallet fund` subcommand, the\n// `check_balance` skill in Phase 35) decide how to display the result.\n//\n// T-34-fund-01 mitigation: the host is hard-coded (pay.coinbase.com) and the\n// only user-supplied input is the wallet address, which is regex-validated\n// against the canonical 0x-prefixed 40-hex-char EVM format before any string\n// interpolation.\n\nexport type FundInstructions = {\n /** Coinbase Onramp deeplink (legacy query-param form). */\n coinbaseOnrampUrl: string;\n /** Tempo deposit address — same as the input wallet (EVM address shared). */\n tempoAddress: `0x${string}`;\n /** Plain-ASCII guidance string; no emojis (CLAUDE.md rule). */\n disclaimer: string;\n};\n\n// 0x followed by exactly 40 hex chars, case-insensitive. Kept at module scope\n// so the regex literal is compiled once (biome/ultracite useTopLevelRegex).\nconst EVM_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\n\n// Coinbase Onramp legacy deeplink. The host + path pair is the documented\n// entry point for query-param-style Onramp sessions.\nconst COINBASE_HOST = \"pay.coinbase.com\";\nconst COINBASE_PATH = \"/buy/select-asset\";\n\n/**\n * Build Coinbase Onramp URL + Tempo deposit address for the given wallet.\n *\n * No HTTP calls are performed. The caller is expected to either print the\n * resulting URL (CLI) or render it in a chat bubble (skill). The returned\n * `disclaimer` explains the Onramp deprecation + the Tempo external-transfer\n * fallback in plain ASCII so terminal clients with ASCII-only fonts render\n * identically to emoji-capable clients.\n *\n * @throws if `walletAddress` does not match /^0x[0-9a-fA-F]{40}$/.\n */\nexport function fund(walletAddress: string): FundInstructions {\n if (!EVM_ADDRESS_RE.test(walletAddress)) {\n throw new Error(`Invalid EVM wallet address: ${walletAddress}`);\n }\n\n // addresses is a JSON-encoded map {walletAddress: [\"base\"]} per Coinbase\n // Onramp docs. Encoding into URLSearchParams guarantees the colon,\n // brackets, and quotes are percent-escaped correctly.\n const params = new URLSearchParams({\n defaultNetwork: \"base\",\n defaultAsset: \"USDC\",\n addresses: JSON.stringify({ [walletAddress]: [\"base\"] }),\n presetCryptoAmount: \"5\",\n });\n\n const coinbaseOnrampUrl = `https://${COINBASE_HOST}${COINBASE_PATH}?${params.toString()}`;\n\n const disclaimer =\n \"If the Coinbase page does not pre-fill, paste your address manually. \" +\n \"For Tempo USDC.e, transfer from an exchange or another wallet to the \" +\n \"address above -- Onramp does not support Tempo directly. Coinbase \" +\n \"sessionToken URLs are the 2025+ canonical form; legacy query-param \" +\n \"URLs may drop prefill on some accounts.\";\n\n return {\n coinbaseOnrampUrl,\n tempoAddress: walletAddress as `0x${string}`,\n disclaimer,\n };\n}\n","// Idempotent skill installer for @keeperhub/wallet.\n//\n// Two public entry points:\n// - installSkill(options?) -- writes keeperhub-wallet.skill.md into every\n// detected agent's skills directory and, for Claude Code, registers a\n// PreToolUse hook pointing at `keeperhub-wallet-hook` in\n// ~/.claude/settings.json. For non-claude agents, emits a stderr notice.\n// - registerClaudeCodeHook(settingsPath, options?) -- pure settings.json\n// patcher used internally; exported so tests can drive it directly.\n//\n// Hook command resolution: the README's recommended install path is\n// `npx @keeperhub/wallet skill install`, which does not put the bin on the\n// system PATH. If we wrote a bare `keeperhub-wallet-hook` command in that\n// case, the hook would fire `command not found` on every tool call. So at\n// install time we probe PATH; if the bin resolves we keep the bare command\n// (lowest startup latency), otherwise we fall back to an `npx` invocation\n// that resolves regardless of where future shells run.\n//\n// Idempotency rule: re-running the installer MUST NOT create a duplicate\n// hook entry. We filter any existing array element whose serialised form\n// contains `keeperhub-wallet-hook` before appending a single fresh record.\n// The marker substring is present in BOTH the bare and npx forms, so the\n// de-dup survives a global-install → npx-install transition (and back).\n//\n// Preservation rule: all top-level keys in settings.json other than\n// hooks.PreToolUse MUST be byte-preserved. We only ever touch\n// hooks.PreToolUse; any foreign hooks.PostToolUse entries survive verbatim.\n\nimport { execFileSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { chmod, copyFile, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { type AgentTarget, detectAgents } from \"./agent-detect.js\";\n\nconst HOOK_BIN = \"keeperhub-wallet-hook\";\nconst HOOK_COMMAND_BARE = HOOK_BIN;\nconst PACKAGE_NAME = \"@keeperhub/wallet\";\n\n/**\n * Read the installer's own version from package.json so the npx command\n * pins to it. Pinning matters because `npx -y` would otherwise pull\n * `latest` on every PreToolUse hook fire — any future compromise of the\n * `@keeperhub/wallet` scope on the npm registry would be executed on\n * every tool call by every npx-installed user. Pinning to the version\n * shipped at install time makes upgrades explicit (re-run skill install)\n * and bounds the supply-chain blast radius to \"code that was already\n * trusted enough to install\".\n *\n * Falls back to \"latest\" only if package.json cannot be located, which\n * should never happen in published builds (dist/ sits next to package.json\n * via pkg.files). The fallback exists so test runs from src/ — where the\n * resolution path is `here/../package.json` — never crash the installer.\n */\nfunction readPackageVersion(): string {\n\ttry {\n\t\tconst here = dirname(fileURLToPath(import.meta.url));\n\t\t// Module lives in dist/ at runtime and src/ during tests; in both cases\n\t\t// package.json is one level up.\n\t\tconst pkgPath = join(here, \"..\", \"package.json\");\n\t\tconst raw = readFileSync(pkgPath, \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as { version?: string };\n\t\tif (typeof parsed.version === \"string\" && parsed.version.length > 0) {\n\t\t\treturn parsed.version;\n\t\t}\n\t} catch {\n\t\t// Fall through.\n\t}\n\treturn \"latest\";\n}\n\nfunction buildNpxCommand(version: string): string {\n\treturn `npx -y -p ${PACKAGE_NAME}@${version} ${HOOK_BIN}`;\n}\n\n// Detect whether the current process is being driven by `npx`. npm/npx set\n// `npm_execpath` to the path of the CLI binary that spawned the process; for\n// `npx` invocations that path ends in `npx-cli.js` (or, on Windows, an `npx`\n// shim in node_modules/.bin). We err on the side of inclusivity: any\n// recognisable npx signature flips the result.\n//\n// Why this matters for hook resolution: when the user runs\n// `npx @keeperhub/wallet skill install`, npx prepends its transient cache\n// dir (`~/.npm/_npx/<hash>/node_modules/.bin`) to PATH for the lifetime of\n// the installer. `command -v keeperhub-wallet-hook` therefore succeeds\n// inside the installer, but the cache dir disappears from PATH the moment\n// npx exits — and the hook fires from a fresh shell with no cache on PATH,\n// so the bare command would crash with `command not found` on every tool\n// call. Detecting npx and forcing the version-pinned `npx` form sidesteps\n// the whole class of \"worked at install time, broken at hook time\" bugs.\nfunction isNpxExecution(): boolean {\n\tconst execPath = process.env.npm_execpath;\n\tif (typeof execPath !== \"string\" || execPath.length === 0) {\n\t\treturn false;\n\t}\n\t// Match the canonical Node entrypoint shipped with npm/npx, plus the\n\t// POSIX/Windows shim names so this stays robust across runners.\n\tif (/(?:^|[\\\\/])npx-cli\\.(?:js|cjs|mjs)$/i.test(execPath)) {\n\t\treturn true;\n\t}\n\tif (/(?:^|[\\\\/])npx(?:\\.cmd|\\.exe|\\.ps1)?$/i.test(execPath)) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n// Recognise a path that lives inside any transient package-runner cache.\n// Each pattern below corresponds to a runner that stages the package in a\n// directory wiped after the runner exits — the same hazard as npx's _npx\n// cache. Detecting these widens the fix beyond the README's recommended\n// `npx ...` install path: pnpm/yarn/bun users who substitute their own\n// runner's `dlx` / `bunx` should not hit a \"worked at install, broken at\n// hook\" failure.\n//\n// Anchored on path SEGMENTS (separators on both sides) so a user dir that\n// merely embeds the substring (e.g. `~/projects/_npx-clone/`) never matches.\n// Patterns:\n// _npx — npm/npx cache (macOS/Linux: ~/.npm/_npx/<hash>/...,\n// Windows: %LocalAppData%/npm-cache/_npx/<hash>/...)\n// dlx-<hash> — pnpm dlx staging (~/.local/share/pnpm/store/.../tmp/dlx-*)\n// xfs-<hash> — yarn dlx (Berry) temp project ($TMPDIR/xfs-<hash>/...)\n// .bun/install/cache — bun x / bunx package cache\nconst TRANSIENT_CACHE_PATTERNS: ReadonlyArray<RegExp> = [\n\t/[\\\\/]_npx[\\\\/]/,\n\t/[\\\\/]dlx-[A-Za-z0-9]+[\\\\/]/,\n\t/[\\\\/]xfs-[A-Za-z0-9]+[\\\\/]/,\n\t/[\\\\/]\\.bun[\\\\/]install[\\\\/]cache[\\\\/]/,\n];\n\nfunction isPathUnderTransientCache(resolvedPath: string): boolean {\n\tfor (const re of TRANSIENT_CACHE_PATTERNS) {\n\t\tif (re.test(resolvedPath)) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n// Match rule for de-dup: any existing PreToolUse entry whose `command`\n// string contains this substring is considered \"ours\" and is removed\n// before append. The marker is present in BOTH the bare and pinned-npx\n// forms, so the de-dup survives a global-install <-> npx-install\n// transition (and across version bumps).\n//\n// Why match on the `command` field rather than JSON.stringify(entry):\n// the wider marker would silently delete an unrelated hook whose args\n// or matcher happen to mention the bin name (e.g. a logger). Scoping\n// to `command` is narrower and equally idempotent for our writes since\n// we always write the marker into `command`.\nconst KEEPERHUB_HOOK_MARKER = HOOK_BIN;\n\ntype PreToolUseLikeEntry = {\n\thooks?: Array<{ command?: unknown }>;\n};\n\n/**\n * Drop only the `hooks[]` items that reference the keeperhub bin, leaving\n * sibling commands inside the same `PreToolUse` element intact. Returns\n * the (possibly modified) entry, or null when every `hooks[]` item was\n * keeperhub-related and the whole element should be removed.\n *\n * Why per-item: a user may merge our hook into a single `PreToolUse`\n * element alongside their own commands, e.g.:\n *\n * { matcher: \"*\", hooks: [\n * { type: \"command\", command: \"/usr/local/bin/audit-logger\" },\n * { type: \"command\", command: \"keeperhub-wallet-hook\" } ] }\n *\n * Dropping the whole element on re-install would silently delete the\n * audit-logger sibling. Dropping only matching items preserves it.\n *\n * Non-object entries and entries without a `hooks[]` array are returned\n * unchanged — we never inspect or mutate shapes we don't recognise.\n */\nfunction filterKeeperhubHooksFromEntry(entry: unknown): unknown {\n\tif (typeof entry !== \"object\" || entry === null) {\n\t\treturn entry;\n\t}\n\tconst candidate = entry as PreToolUseLikeEntry;\n\tif (!Array.isArray(candidate.hooks)) {\n\t\treturn entry;\n\t}\n\tconst survivors = candidate.hooks.filter((h) => {\n\t\tconst cmd = h?.command;\n\t\treturn !(typeof cmd === \"string\" && cmd.includes(KEEPERHUB_HOOK_MARKER));\n\t});\n\tif (survivors.length === candidate.hooks.length) {\n\t\t// No keeperhub hooks present in this entry — return original byte-for-byte.\n\t\treturn entry;\n\t}\n\tif (survivors.length === 0) {\n\t\t// Every hook in this element was ours; drop the whole element so we\n\t\t// don't leave a `{matcher, hooks: []}` shell behind.\n\t\treturn null;\n\t}\n\treturn { ...candidate, hooks: survivors };\n}\n\n/**\n * Pick the hook command to write into settings.json.\n *\n * Returns the bare bin name if it resolves to a STABLE install on PATH\n * (global install, brew, distro pkg, dev-time `npm link`), otherwise a\n * version-pinned `npx` invocation that pulls the installer's own version\n * of `@keeperhub/wallet` on demand.\n *\n * The PATH probe alone is not enough: when the installer itself runs via\n * `npx @keeperhub/wallet skill install` (or `pnpm dlx`, `yarn dlx`, `bun x`),\n * the runner prepends its transient cache dir to PATH so `command -v`\n * succeeds — but only for this process. After the runner exits, the cache\n * dir is gone from PATH for fresh shells, and the hook fires\n * `command not found` on every tool call. To avoid that we additionally\n * (a) detect npx-driven processes via `npm_execpath` and\n * (b) reject any resolved path that lives inside a known transient\n * package-runner cache (npx `_npx`, pnpm `dlx-<hash>`, yarn `xfs-<hash>`,\n * or bun `.bun/install/cache`).\n *\n * Override-able via the env var `KEEPERHUB_WALLET_HOOK_COMMAND` for test\n * fixtures and unusual deployments (env input is trusted — it is written\n * verbatim into settings.json and executed by the user's shell).\n */\nexport function resolveHookCommand(): string {\n\tconst envOverride = process.env.KEEPERHUB_WALLET_HOOK_COMMAND;\n\tif (envOverride && envOverride.length > 0) {\n\t\treturn envOverride;\n\t}\n\n\t// Primary detection: trust npm_execpath when present. Skips the PATH probe\n\t// entirely so we don't pay the spawn cost in the common npx-install flow.\n\tif (isNpxExecution()) {\n\t\treturn buildNpxCommand(readPackageVersion());\n\t}\n\n\ttry {\n\t\t// Capture stdout so we can inspect the resolved path (not just the exit\n\t\t// code) — a path under any transient package-runner cache (npx,\n\t\t// pnpm dlx, yarn dlx, bun x) must NOT be treated as a stable install,\n\t\t// even though the probe succeeds. `command -v` is POSIX and avoids\n\t\t// spawning a full shell.\n\t\tconst resolved = execFileSync(\"/bin/sh\", [\"-c\", `command -v ${HOOK_BIN}`], {\n\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t})\n\t\t\t.toString()\n\t\t\t.trim();\n\t\tif (resolved.length > 0 && !isPathUnderTransientCache(resolved)) {\n\t\t\treturn HOOK_COMMAND_BARE;\n\t\t}\n\t} catch {\n\t\t// command -v failed: bin not on PATH at all. Fall through.\n\t}\n\n\treturn buildNpxCommand(readPackageVersion());\n}\n\nexport type InstallResult = {\n\tskillWrites: Array<{\n\t\tagent: string;\n\t\tpath: string;\n\t\tstatus: \"written\" | \"skipped\";\n\t}>;\n\thookRegistrations: Array<{\n\t\tagent: string;\n\t\tstatus: \"registered\" | \"notice\" | \"skipped\";\n\t\tmessage?: string;\n\t}>;\n};\n\nexport type InstallOptions = {\n\thomeOverride?: string;\n\tskillSourcePath?: string;\n\tonNotice?: (msg: string) => void;\n\t/**\n\t * Hook command to write into settings.json (and reference in stderr\n\t * notices for non-Claude agents). Defaults to {@link resolveHookCommand}.\n\t * Override for tests, monorepo setups, or unusual deployments.\n\t */\n\thookCommand?: string;\n};\n\nexport type RegisterClaudeCodeHookOptions = {\n\t/**\n\t * Hook command to write. Defaults to {@link resolveHookCommand}. Tests\n\t * pass a deterministic value to keep assertions stable across host\n\t * environments (CI may or may not have the bin on PATH).\n\t */\n\thookCommand?: string;\n};\n\ntype ClaudeHookEntry = {\n\tmatcher: string;\n\thooks: Array<{ type: string; command: string }>;\n};\n\ntype ClaudeSettings = {\n\thooks?: {\n\t\tPreToolUse?: unknown[];\n\t\t[k: string]: unknown;\n\t};\n\t[k: string]: unknown;\n};\n\nfunction buildKeeperhubEntry(command: string): ClaudeHookEntry {\n\treturn {\n\t\tmatcher: \"*\",\n\t\thooks: [{ type: \"command\", command }],\n\t};\n}\n\nfunction resolveDefaultSkillSource(): string {\n\t// Resolve the module's own directory in a way that works in both ESM\n\t// (import.meta.url) and CJS (__dirname shim emitted by tsup). At runtime\n\t// the module lives inside dist/, so `../skill/` points at the sibling\n\t// skill/ directory shipped via pkg.files. During vitest tests the module\n\t// executes from src/, and `../skill/` resolves to packages/wallet/skill/.\n\tconst here = dirname(fileURLToPath(import.meta.url));\n\treturn join(here, \"..\", \"skill\", \"keeperhub-wallet.skill.md\");\n}\n\nfunction defaultNotice(msg: string): void {\n\tprocess.stderr.write(`${msg}\\n`);\n}\n\nexport async function registerClaudeCodeHook(\n\tsettingsPath: string,\n\toptions: RegisterClaudeCodeHookOptions = {},\n): Promise<void> {\n\tconst command = options.hookCommand ?? resolveHookCommand();\n\n\tlet raw: string | null = null;\n\ttry {\n\t\traw = await readFile(settingsPath, \"utf-8\");\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tlet config: ClaudeSettings = {};\n\tif (raw !== null) {\n\t\ttry {\n\t\t\tconfig = JSON.parse(raw) as ClaudeSettings;\n\t\t} catch {\n\t\t\tthrow new Error(\n\t\t\t\t`settings.json at ${settingsPath} is not valid JSON; aborting hook registration`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst hooks: Record<string, unknown> =\n\t\ttypeof config.hooks === \"object\" && config.hooks !== null\n\t\t\t? (config.hooks as Record<string, unknown>)\n\t\t\t: {};\n\n\tconst existingPreToolUse = Array.isArray(hooks.PreToolUse)\n\t\t? (hooks.PreToolUse as unknown[])\n\t\t: [];\n\n\t// De-dup: drop only the hooks[] items whose `command` field references\n\t// the keeperhub-wallet-hook bin, leaving sibling commands within the\n\t// same PreToolUse element untouched. Scoped to the `command` field (not\n\t// the full serialised entry) so an unrelated hook that mentions the bin\n\t// name in its matcher or args isn't silently deleted. Covers both the\n\t// bare-bin and version-pinned npx forms, and older versions of this\n\t// installer.\n\tconst filtered: unknown[] = [];\n\tfor (const entry of existingPreToolUse) {\n\t\tconst survivor = filterKeeperhubHooksFromEntry(entry);\n\t\tif (survivor !== null) {\n\t\t\tfiltered.push(survivor);\n\t\t}\n\t}\n\tfiltered.push(buildKeeperhubEntry(command));\n\n\thooks.PreToolUse = filtered;\n\tconfig.hooks = hooks as ClaudeSettings[\"hooks\"];\n\n\tawait mkdir(dirname(settingsPath), { recursive: true, mode: 0o700 });\n\tconst payload = `${JSON.stringify(config, null, 2)}\\n`;\n\tawait writeFile(settingsPath, payload, { mode: 0o600 });\n\t// Reassert mode in case the file already existed with looser perms.\n\tawait chmod(settingsPath, 0o600);\n}\n\nasync function writeSkillToAgent(\n\tagent: AgentTarget,\n\tskillSource: string,\n): Promise<{ agent: string; path: string; status: \"written\" | \"skipped\" }> {\n\tawait mkdir(agent.skillsDir, { recursive: true, mode: 0o755 });\n\tconst target = join(agent.skillsDir, \"keeperhub-wallet.skill.md\");\n\tawait copyFile(skillSource, target);\n\tawait chmod(target, 0o644);\n\treturn { agent: agent.agent, path: target, status: \"written\" };\n}\n\nfunction buildNoticeMessage(agent: AgentTarget, command: string): string {\n\treturn `${agent.agent} does not support auto-registered PreToolUse hooks; run \\`${command}\\` on every tool use via ${agent.agent}'s settings file at ${agent.settingsFile}`;\n}\n\nexport async function installSkill(\n\toptions: InstallOptions = {},\n): Promise<InstallResult> {\n\tconst agents = detectAgents(options.homeOverride);\n\tconst skillSource = options.skillSourcePath ?? resolveDefaultSkillSource();\n\tconst onNotice = options.onNotice ?? defaultNotice;\n\t// Resolve once per install run so the bare-vs-npx decision stays\n\t// consistent across every detected agent. Tests pass an explicit value to\n\t// pin the assertion shape regardless of host PATH.\n\tconst hookCommand = options.hookCommand ?? resolveHookCommand();\n\n\tconst skillWrites: InstallResult[\"skillWrites\"] = [];\n\tconst hookRegistrations: InstallResult[\"hookRegistrations\"] = [];\n\n\tfor (const agent of agents) {\n\t\tconst write = await writeSkillToAgent(agent, skillSource);\n\t\tskillWrites.push(write);\n\n\t\tif (agent.hookSupport === \"claude-code\") {\n\t\t\tawait registerClaudeCodeHook(agent.settingsFile, { hookCommand });\n\t\t\thookRegistrations.push({\n\t\t\t\tagent: agent.agent,\n\t\t\t\tstatus: \"registered\",\n\t\t\t});\n\t\t} else {\n\t\t\tconst message = buildNoticeMessage(agent, hookCommand);\n\t\t\thookRegistrations.push({\n\t\t\t\tagent: agent.agent,\n\t\t\t\tstatus: \"notice\",\n\t\t\t\tmessage,\n\t\t\t});\n\t\t\tonNotice(message);\n\t\t}\n\t}\n\n\treturn { skillWrites, hookRegistrations };\n}\n","// Cross-agent skill/settings directory discovery.\n//\n// Probes canonical paths under $HOME and returns one AgentTarget record per\n// agent whose parent directory exists. The `skills/` leaf may be absent --\n// installSkill() creates it.\n//\n// NOTE: `homedir()` is called per-invocation (via `homeOverride ?? homedir()`)\n// and NEVER hoisted to a module-level constant. Tests override\n// `process.env.HOME` in `beforeEach`; hoisting would freeze the harness's\n// original HOME at import time and detection would run against the real $HOME.\n\nimport { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nexport type AgentTarget = {\n agent: \"claude-code\" | \"cursor\" | \"cline\" | \"windsurf\" | \"opencode\";\n skillsDir: string;\n settingsFile: string;\n hookSupport: \"claude-code\" | \"notice\";\n};\n\ntype AgentSpec = {\n agent: AgentTarget[\"agent\"];\n skillsRel: string[];\n settingsRel: string[];\n hookSupport: AgentTarget[\"hookSupport\"];\n};\n\n// Deterministic order: claude-code first (only agent with hook support),\n// then cursor, cline, windsurf, opencode.\nconst AGENT_SPECS: readonly AgentSpec[] = [\n {\n agent: \"claude-code\",\n skillsRel: [\".claude\", \"skills\"],\n settingsRel: [\".claude\", \"settings.json\"],\n hookSupport: \"claude-code\",\n },\n {\n agent: \"cursor\",\n skillsRel: [\".cursor\", \"skills\"],\n settingsRel: [\".cursor\", \"settings.json\"],\n hookSupport: \"notice\",\n },\n {\n agent: \"cline\",\n skillsRel: [\".cline\", \"skills\"],\n settingsRel: [\".cline\", \"settings.json\"],\n hookSupport: \"notice\",\n },\n {\n agent: \"windsurf\",\n skillsRel: [\".windsurf\", \"skills\"],\n settingsRel: [\".windsurf\", \"settings.json\"],\n hookSupport: \"notice\",\n },\n {\n agent: \"opencode\",\n skillsRel: [\".config\", \"opencode\", \"skills\"],\n settingsRel: [\".config\", \"opencode\", \"settings.json\"],\n hookSupport: \"notice\",\n },\n];\n\nexport function detectAgents(homeOverride?: string): AgentTarget[] {\n const home = homeOverride ?? homedir();\n const results: AgentTarget[] = [];\n for (const spec of AGENT_SPECS) {\n const skillsDir = join(home, ...spec.skillsRel);\n const settingsFile = join(home, ...spec.settingsRel);\n // \"Detected\" iff the parent of skills/ exists (e.g. ~/.claude/).\n // skills/ itself may be absent; installer creates it.\n if (existsSync(dirname(skillsDir))) {\n results.push({\n agent: spec.agent,\n skillsDir,\n settingsFile,\n hookSupport: spec.hookSupport,\n });\n }\n }\n return results;\n}\n","import { chmod, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { type WalletConfig, WalletConfigMissingError } from \"./types.js\";\n\n// NOTE: Every function calls `join(homedir(), \".keeperhub\", \"wallet.json\")`\n// itself. Do NOT hoist to a module-level `const WALLET_PATH` -- tests\n// override `process.env.HOME` in `beforeEach` and `homedir()` must re-read\n// that on each call. A hoisted constant would freeze the harness's original\n// HOME at import time and every test would write into the real\n// ~/.keeperhub/ directory.\n\nexport async function readWalletConfig(): Promise<WalletConfig> {\n const walletPath = join(homedir(), \".keeperhub\", \"wallet.json\");\n let raw: string;\n try {\n raw = await readFile(walletPath, \"utf-8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new WalletConfigMissingError();\n }\n throw err;\n }\n const parsed = JSON.parse(raw) as Partial<WalletConfig>;\n if (!(parsed.subOrgId && parsed.walletAddress && parsed.hmacSecret)) {\n throw new Error(`Malformed wallet.json at ${walletPath}`);\n }\n return parsed as WalletConfig;\n}\n\nexport async function writeWalletConfig(config: WalletConfig): Promise<void> {\n const walletPath = join(homedir(), \".keeperhub\", \"wallet.json\");\n await mkdir(dirname(walletPath), { recursive: true, mode: 0o700 });\n await writeFile(walletPath, JSON.stringify(config, null, 2), { mode: 0o600 });\n // Reassert mode in case the file already existed with looser perms.\n await chmod(walletPath, 0o600);\n}\n\nexport function getWalletConfigPath(): string {\n return join(homedir(), \".keeperhub\", \"wallet.json\");\n}\n","// Shared types across the package. Phase 34.\nexport type WalletConfig = {\n /** Turnkey sub-org ID returned by POST /api/agentic-wallet/provision */\n subOrgId: string;\n /** EVM-shared wallet address (same for Base chainId 8453 and Tempo chainId 4217) */\n walletAddress: `0x${string}`;\n /** 64-char lowercase hex HMAC secret, minted server-side at provision; never logged */\n hmacSecret: string;\n};\n\nexport type HmacHeaders = {\n \"X-KH-Sub-Org\": string;\n \"X-KH-Timestamp\": string;\n \"X-KH-Signature\": string;\n};\n\nexport type HookDecision = {\n decision: \"allow\" | \"deny\" | \"ask\";\n reason?: string;\n};\n\nexport class KeeperHubError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = \"KeeperHubError\";\n this.code = code;\n }\n}\n\n/** Protocol preference for a single pay() or fetch() call. \"auto\" preserves\n * the x402-first default when both challenges are offered. */\nexport type PaymentHint = \"x402\" | \"mpp\" | \"auto\";\n\nexport class WalletConfigMissingError extends Error {\n constructor() {\n super(\n \"Wallet config not found at ~/.keeperhub/wallet.json. Run `npx @keeperhub/wallet add` to provision.\"\n );\n this.name = \"WalletConfigMissingError\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBA,uBAAwB;;;ACHxB,IAAAA,eAMO;;;ACbP,kBAA4B;AAE5B,oBAAqB;AAEd,IAAM,YAAQ,yBAAY;AAAA,EAC/B,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,gBAAgB,EAAE,UAAU,IAAI,MAAM,SAAS,QAAQ,MAAM;AAAA,EAC7D,SAAS;AAAA,IACP,SAAS;AAAA,MACP,MAAM,CAAC,QAAQ,IAAI,iBAAiB,uBAAuB;AAAA,IAC7D;AAAA,EACF;AAAA,EACA,gBAAgB;AAAA,IACd,SAAS,EAAE,MAAM,kBAAkB,KAAK,6BAA6B;AAAA,EACvE;AACF,CAAC;AAGM,IAAM,YAAY;AAGlB,IAAM,eACX;;;ADLF,IAAM,gBAAgB;AA+BtB,eAAsB,aACpB,QACA,OAA4B,CAAC,GACH;AAC1B,QAAM,aACJ,KAAK,kBACJ,iCAAmB;AAAA,IAClB,OAAO;AAAA,IACP,eAAW,mBAAK;AAAA,EAClB,CAAC;AACH,QAAM,cACJ,KAAK,mBACJ,iCAAmB;AAAA,IAClB,OAAO;AAAA,IACP,eAAW,mBAAK;AAAA,EAClB,CAAC;AAIH,QAAM,CAAC,SAAS,QAAQ,IAAI,MAAM,QAAQ,IAAI;AAAA,IAC5C,WAAW,aAAa;AAAA,MACtB,SAAS;AAAA,MACT,KAAK;AAAA,MACL,cAAc;AAAA,MACd,MAAM,CAAC,OAAO,aAAa;AAAA,IAC7B,CAAC;AAAA,IACD,YAAY,aAAa;AAAA,MACvB,SAAS;AAAA,MACT,KAAK;AAAA,MACL,cAAc;AAAA,M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,QAAQ,WAAW,IAAI;AAAA,EAC/B,SAAS,KAAK;AACZ,QAAI,eAAe,0BAA0B;AAC3C,cAAQ,OAAO,MAAM,sBAAsB,IAAI,OAAO;AAAA,CAAI;AAC1D,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,YAAQ,OAAO;AAAA,MACb,sBAAuB,IAAc,WAAW,OAAO,GAAG,CAAC;AAAA;AAAA,IAC7D;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["import_viem","import_node_fs","import_node_path","import_promises","import_node_os","import_node_path"]}
package/dist/cli.js CHANGED
@@ -94,8 +94,8 @@ function fund(walletAddress) {
94
94
 
95
95
  // src/skill-install.ts
96
96
  import { execFileSync } from "child_process";
97
- import { chmod, copyFile, mkdir, readFile, writeFile } from "fs/promises";
98
97
  import { readFileSync } from "fs";
98
+ import { chmod, copyFile, mkdir, readFile, writeFile } from "fs/promises";
99
99
  import { dirname as dirname2, join as join2 } from "path";
100
100
  import { fileURLToPath } from "url";
101
101
 
@@ -173,6 +173,33 @@ function readPackageVersion() {
173
173
  function buildNpxCommand(version) {
174
174
  return `npx -y -p ${PACKAGE_NAME}@${version} ${HOOK_BIN}`;
175
175
  }
176
+ function isNpxExecution() {
177
+ const execPath = process.env.npm_execpath;
178
+ if (typeof execPath !== "string" || execPath.length === 0) {
179
+ return false;
180
+ }
181
+ if (/(?:^|[\\/])npx-cli\.(?:js|cjs|mjs)$/i.test(execPath)) {
182
+ return true;
183
+ }
184
+ if (/(?:^|[\\/])npx(?:\.cmd|\.exe|\.ps1)?$/i.test(execPath)) {
185
+ return true;
186
+ }
187
+ return false;
188
+ }
189
+ var TRANSIENT_CACHE_PATTERNS = [
190
+ /[\\/]_npx[\\/]/,
191
+ /[\\/]dlx-[A-Za-z0-9]+[\\/]/,
192
+ /[\\/]xfs-[A-Za-z0-9]+[\\/]/,
193
+ /[\\/]\.bun[\\/]install[\\/]cache[\\/]/
194
+ ];
195
+ function isPathUnderTransientCache(resolvedPath) {
196
+ for (const re of TRANSIENT_CACHE_PATTERNS) {
197
+ if (re.test(resolvedPath)) {
198
+ return true;
199
+ }
200
+ }
201
+ return false;
202
+ }
176
203
  var KEEPERHUB_HOOK_MARKER = HOOK_BIN;
177
204
  function filterKeeperhubHooksFromEntry(entry) {
178
205
  if (typeof entry !== "object" || entry === null) {
@@ -199,14 +226,19 @@ function resolveHookCommand() {
199
226
  if (envOverride && envOverride.length > 0) {
200
227
  return envOverride;
201
228
  }
229
+ if (isNpxExecution()) {
230
+ return buildNpxCommand(readPackageVersion());
231
+ }
202
232
  try {
203
- execFileSync("/bin/sh", ["-c", `command -v ${HOOK_BIN}`], {
204
- stdio: "ignore"
205
- });
206
- return HOOK_COMMAND_BARE;
233
+ const resolved = execFileSync("/bin/sh", ["-c", `command -v ${HOOK_BIN}`], {
234
+ stdio: ["ignore", "pipe", "ignore"]
235
+ }).toString().trim();
236
+ if (resolved.length > 0 && !isPathUnderTransientCache(resolved)) {
237
+ return HOOK_COMMAND_BARE;
238
+ }
207
239
  } catch {
208
- return buildNpxCommand(readPackageVersion());
209
240
  }
241
+ return buildNpxCommand(readPackageVersion());
210
242
  }
211
243
  function buildKeeperhubEntry(command) {
212
244
  return {