tenjin-cli 0.1.0-alpha.28 → 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.
- package/README.md +13 -10
- package/dist/{chunk-ZG6ZZLO7.js → chunk-25GGN553.js} +9 -11
- package/dist/{chunk-ZG6ZZLO7.js.map → chunk-25GGN553.js.map} +1 -1
- package/dist/{chunk-B2L53TMK.js → chunk-2SNUOHAT.js} +28 -23
- package/dist/chunk-2SNUOHAT.js.map +1 -0
- package/dist/{chunk-UEOWNDQG.js → chunk-3FY5HG7R.js} +82 -13
- package/dist/chunk-3FY5HG7R.js.map +1 -0
- package/dist/{chunk-DJYAPACT.js → chunk-4FYMDRD3.js} +32 -24
- package/dist/chunk-4FYMDRD3.js.map +1 -0
- package/dist/{chunk-ZP7AHN7Z.js → chunk-AMEUXNJT.js} +3 -5
- package/dist/{chunk-ZP7AHN7Z.js.map → chunk-AMEUXNJT.js.map} +1 -1
- package/dist/chunk-EWLU46J6.js +100 -0
- package/dist/chunk-EWLU46J6.js.map +1 -0
- package/dist/{chunk-RLPLYUME.js → chunk-LRCJ2IZ5.js} +3 -3
- package/dist/{chunk-RLPLYUME.js.map → chunk-LRCJ2IZ5.js.map} +1 -1
- package/dist/{chunk-YFJJYHVG.js → chunk-LX5OT4TQ.js} +3 -3
- package/dist/{chunk-YFJJYHVG.js.map → chunk-LX5OT4TQ.js.map} +1 -1
- package/dist/{chunk-ZO3X5NPG.js → chunk-MG3G644T.js} +4 -4
- package/dist/{chunk-6KA4HFX5.js → chunk-MOG7PB3A.js} +3 -3
- package/dist/{chunk-DYSDQE7S.js → chunk-MRUPDSUM.js} +14 -93
- package/dist/chunk-MRUPDSUM.js.map +1 -0
- package/dist/{chunk-KAMRYUK2.js → chunk-OOSRB3OF.js} +2 -2
- package/dist/{chunk-PZ5N6BAL.js → chunk-ORWL5BSN.js} +5 -4
- package/dist/chunk-ORWL5BSN.js.map +1 -0
- package/dist/chunk-P4LVLFO4.js +29 -0
- package/dist/chunk-P4LVLFO4.js.map +1 -0
- package/dist/{chunk-ZP5PV3JB.js → chunk-QTGUDCIR.js} +5 -5
- package/dist/{chunk-FQ6DHINU.js → chunk-R4AO7GC2.js} +437 -78
- package/dist/chunk-R4AO7GC2.js.map +1 -0
- package/dist/{chunk-UOW5JXYY.js → chunk-RJEPZMYY.js} +10 -4
- package/dist/chunk-RJEPZMYY.js.map +1 -0
- package/dist/{chunk-VSUHGRVB.js → chunk-SBL4THYT.js} +712 -93
- package/dist/chunk-SBL4THYT.js.map +1 -0
- package/dist/{chunk-BRHREK7E.js → chunk-SFEQGENI.js} +2 -2
- package/dist/{chunk-K6AXXYCG.js → chunk-SJLTEINJ.js} +10 -2
- package/dist/{chunk-K6AXXYCG.js.map → chunk-SJLTEINJ.js.map} +1 -1
- package/dist/{chunk-XVTD7UWR.js → chunk-TROZ6HL4.js} +2 -2
- package/dist/{chunk-3QJREVMX.js → chunk-USOLCBKC.js} +5 -5
- package/dist/{chunk-W6JX4LYF.js → chunk-VKQXVCZR.js} +46 -5
- package/dist/chunk-VKQXVCZR.js.map +1 -0
- package/dist/{chunk-QTND6XWJ.js → chunk-VVAHFCX2.js} +51 -3
- package/dist/chunk-VVAHFCX2.js.map +1 -0
- package/dist/{chunk-7H3RN4WJ.js → chunk-WM7TJEBP.js} +5 -5
- package/dist/{chunk-MNTQMZJB.js → chunk-XDYKZRLN.js} +22 -13
- package/dist/chunk-XDYKZRLN.js.map +1 -0
- package/dist/{chunk-A5H3E5QA.js → chunk-XJQ6CH7X.js} +3 -2
- package/dist/{chunk-7R37M6WV.js → chunk-ZQNGTLOC.js} +5 -5
- package/dist/{cli-234DNHN6.js → cli-JPTDHGRX.js} +38 -33
- package/dist/{cli-234DNHN6.js.map → cli-JPTDHGRX.js.map} +1 -1
- package/dist/{config-IY2OJCAK.js → config-YYKDH2TH.js} +11 -11
- package/dist/{doctor-2UZZF44A.js → doctor-SSTXGCHX.js} +60 -56
- package/dist/doctor-SSTXGCHX.js.map +1 -0
- package/dist/{fund-RZ2QFULK.js → fund-QWVWRVDK.js} +14 -16
- package/dist/{fund-RZ2QFULK.js.map → fund-QWVWRVDK.js.map} +1 -1
- package/dist/hook-command-VWJXRT7H.js +31 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
- package/dist/hosts/claude/tenjin/.mcp.json +2 -1
- package/dist/hosts/claude/tenjin/hooks/hooks.json +18 -3
- package/dist/index.js +6 -6
- package/dist/{install-O5FJ5EP3.js → install-2GXXD4DK.js} +19 -16
- package/dist/{install-identity-QM44IQ6Z.js → install-identity-FK3YF227.js} +7 -8
- package/dist/{install-wallet-Z52EDLPB.js → install-wallet-TC22U52X.js} +17 -12
- package/dist/{install-wallet-Z52EDLPB.js.map → install-wallet-TC22U52X.js.map} +1 -1
- package/dist/{mcp-33HAADDF.js → mcp-42H2F4NY.js} +2091 -348
- package/dist/mcp-42H2F4NY.js.map +1 -0
- package/dist/{package-RT24HTTP.js → package-6DJA3Y2O.js} +2 -2
- package/dist/{paths-MUXHUOCM.js → paths-POPTXJO6.js} +6 -2
- package/dist/{pay-IR2V76FX.js → pay-LSDJBIAZ.js} +18 -15
- package/dist/payments-SPECLBRQ.js +105 -0
- package/dist/payments-SPECLBRQ.js.map +1 -0
- package/dist/{send-PI4NUA7I.js → send-MHAOLPK3.js} +12 -14
- package/dist/{send-PI4NUA7I.js.map → send-MHAOLPK3.js.map} +1 -1
- package/dist/status-O2RWLPS5.js +114 -0
- package/dist/status-O2RWLPS5.js.map +1 -0
- package/dist/{status-line-2G5JPQAE.js → status-line-45TVCRM3.js} +7 -8
- package/dist/{status-line-2G5JPQAE.js.map → status-line-45TVCRM3.js.map} +1 -1
- package/dist/{uninstall-THKUH5ZT.js → uninstall-VOK2Z5M4.js} +27 -17
- package/dist/uninstall-VOK2Z5M4.js.map +1 -0
- package/dist/update-FGP3HNLD.js +33 -0
- package/dist/{wallet-53EFH4M5.js → wallet-DA7OFNEW.js} +17 -12
- package/docs/agent-permissions.md +11 -8
- package/docs/safety-model.md +3 -1
- package/package.json +2 -2
- package/dist/chunk-AO54FM4H.js +0 -563
- package/dist/chunk-AO54FM4H.js.map +0 -1
- package/dist/chunk-B2L53TMK.js.map +0 -1
- package/dist/chunk-DJYAPACT.js.map +0 -1
- package/dist/chunk-DYSDQE7S.js.map +0 -1
- package/dist/chunk-FQ6DHINU.js.map +0 -1
- package/dist/chunk-FZTSGQVK.js +0 -52
- package/dist/chunk-FZTSGQVK.js.map +0 -1
- package/dist/chunk-MNTQMZJB.js.map +0 -1
- package/dist/chunk-PZ5N6BAL.js.map +0 -1
- package/dist/chunk-QTND6XWJ.js.map +0 -1
- package/dist/chunk-UEOWNDQG.js.map +0 -1
- package/dist/chunk-UOW5JXYY.js.map +0 -1
- package/dist/chunk-VSUHGRVB.js.map +0 -1
- package/dist/chunk-W6JX4LYF.js.map +0 -1
- package/dist/doctor-2UZZF44A.js.map +0 -1
- package/dist/hook-command-PZHKS7ES.js +0 -31
- package/dist/mcp-33HAADDF.js.map +0 -1
- package/dist/payments-GFV4HU5R.js +0 -47
- package/dist/payments-GFV4HU5R.js.map +0 -1
- package/dist/status-ZUHTJK46.js +0 -71
- package/dist/status-ZUHTJK46.js.map +0 -1
- package/dist/uninstall-THKUH5ZT.js.map +0 -1
- package/dist/update-NPZDP24E.js +0 -18
- /package/dist/{chunk-ZO3X5NPG.js.map → chunk-MG3G644T.js.map} +0 -0
- /package/dist/{chunk-6KA4HFX5.js.map → chunk-MOG7PB3A.js.map} +0 -0
- /package/dist/{chunk-KAMRYUK2.js.map → chunk-OOSRB3OF.js.map} +0 -0
- /package/dist/{chunk-ZP5PV3JB.js.map → chunk-QTGUDCIR.js.map} +0 -0
- /package/dist/{chunk-BRHREK7E.js.map → chunk-SFEQGENI.js.map} +0 -0
- /package/dist/{chunk-XVTD7UWR.js.map → chunk-TROZ6HL4.js.map} +0 -0
- /package/dist/{chunk-3QJREVMX.js.map → chunk-USOLCBKC.js.map} +0 -0
- /package/dist/{chunk-7H3RN4WJ.js.map → chunk-WM7TJEBP.js.map} +0 -0
- /package/dist/{chunk-A5H3E5QA.js.map → chunk-XJQ6CH7X.js.map} +0 -0
- /package/dist/{chunk-7R37M6WV.js.map → chunk-ZQNGTLOC.js.map} +0 -0
- /package/dist/{config-IY2OJCAK.js.map → config-YYKDH2TH.js.map} +0 -0
- /package/dist/{hook-command-PZHKS7ES.js.map → hook-command-VWJXRT7H.js.map} +0 -0
- /package/dist/{install-O5FJ5EP3.js.map → install-2GXXD4DK.js.map} +0 -0
- /package/dist/{install-identity-QM44IQ6Z.js.map → install-identity-FK3YF227.js.map} +0 -0
- /package/dist/{package-RT24HTTP.js.map → package-6DJA3Y2O.js.map} +0 -0
- /package/dist/{paths-MUXHUOCM.js.map → paths-POPTXJO6.js.map} +0 -0
- /package/dist/{pay-IR2V76FX.js.map → pay-LSDJBIAZ.js.map} +0 -0
- /package/dist/{update-NPZDP24E.js.map → update-FGP3HNLD.js.map} +0 -0
- /package/dist/{wallet-53EFH4M5.js.map → wallet-DA7OFNEW.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/paid.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { appendFile, mkdir, open, readFile, rm, type FileHandle } from 'node:fs/promises';\nimport { request as httpsRequest } from 'node:https';\nimport type { LookupFunction } from 'node:net';\nimport { dirname, join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { resolvePublicDestination, type DestinationOptions } from '../lib/destination';\nimport { hasCode } from '../lib/errno';\nimport { withFileLock } from '../lib/lock';\nimport { downloadsDir, paidLedgerPath } from '../lib/paths';\nimport { mask } from '../lib/redact';\nimport { USDC_ADDRESS } from '../lib/usdc-balance';\nimport { releaseUnchargedExposure } from '../lib/wallet/spend';\n\n/**\n * WHAT A PAID ROUTER CALL BOUGHT, KEPT ON THIS MACHINE. One JSON line per paid\n * call in `~/.tenjin/paid/ledger.jsonl`: who was paid, for what, how much, the\n * settlement it carried and the files it saved. It is the user's own record\n * and the receipt `tenjin payments reconcile` resolves an unknown settlement\n * against. Nothing here can fail a lookup: every write swallows its own error.\n */\n\nexport type Settlement = 'settled' | 'unknown' | 'not_charged';\n\n/** The EIP-3009 authorization that was signed, enough to ask the token later\n * whether it was used. */\nexport interface SignedAuthorization {\n from: string;\n nonce: string;\n /** Unix seconds; after it the authorization can no longer be used. */\n validBefore: string;\n}\n\nexport interface PaidRecord {\n version: 1;\n ts: string;\n capabilityId: string;\n provider: string;\n url: string;\n /** The input or query sent, masked and cut to {@link MAX_SENT_CHARS}. */\n sent: string;\n amountAtomic: string;\n txHash?: string;\n settlement: Settlement;\n savedFiles: string[];\n authorization?: SignedAuthorization;\n /** When reconcile last asked the chain about it, so a slow or rate-limited\n * RPC is not asked about the same record on every lookup. */\n lastCheckedAt?: string;\n}\n\nexport const MAX_SENT_CHARS = 4_096;\n\n/**\n * A JSON value with every object key and string leaf masked on its own. The\n * mask anchors on word boundaries, which a serialized string hides: after an\n * escaped `\\n` a key reads as `nsk-ant-…`, one word, and passes.\n */\nexport function maskDeep(value: unknown): unknown {\n if (typeof value === 'string') return mask(value);\n if (Array.isArray(value)) return value.map(maskDeep);\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n mask(key),\n maskDeep(entry),\n ]),\n );\n }\n return value;\n}\n\n/** The input or query as it is recorded: secrets masked, then cut. */\nexport function recordedSent(sent: string): string {\n return mask(sent).slice(0, MAX_SENT_CHARS);\n}\n\nexport async function appendPaidRecord(dataDir: string, record: PaidRecord): Promise<void> {\n try {\n const path = paidLedgerPath(dataDir);\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n // Under the lock reconcile rewrites with, so an append is never lost to it.\n await withFileLock(`${path}.lock`, () =>\n appendFile(path, `${JSON.stringify(record)}\\n`, { mode: 0o600 }),\n );\n } catch {\n // The record is the user's convenience; the lookup already happened.\n }\n}\n\n/** `authorizationState(address,bytes32)`: the first four bytes of its keccak-256. */\nconst AUTHORIZATION_STATE_SELECTOR = '0xe94a0102';\nconst WORD_RE = /^0x[0-9a-fA-F]{64}$/;\n/** How many unknown settlements one pass asks the chain about. */\nexport const MAX_RECONCILE_CHECKS = 3;\n/** How long a record the chain could not answer for waits before it is asked\n * about again by the lookup-time pass. */\nexport const RECHECK_MS = 10 * 60_000;\nconst RECONCILE_TIMEOUT_MS = 1_500;\n\n/**\n * Whether USDC on Base has used this authorization: true once a facilitator\n * settled it, false while it has not. Null when the RPC could not say.\n */\nexport async function authorizationUsed(\n authorization: SignedAuthorization,\n rpcUrl: string,\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number; blockTag?: string } = {},\n): Promise<boolean | null> {\n const result = await rpcCall(\n rpcUrl,\n 'eth_call',\n [\n {\n to: USDC_ADDRESS,\n data: `${AUTHORIZATION_STATE_SELECTOR}${authorization.from.slice(2).toLowerCase().padStart(64, '0')}${authorization.nonce.slice(2).toLowerCase()}`,\n },\n opts.blockTag ?? 'latest',\n ],\n opts,\n );\n if (typeof result !== 'string' || !WORD_RE.test(result)) return null;\n return BigInt(result) !== 0n;\n}\n\n/**\n * The chain's own clock: the latest block's number and timestamp (seconds).\n * Expiry is decided against it, not this machine's clock, and the state is\n * read at that same block: a node that lags, or a clock running ahead, then\n * agrees with itself. Null when the RPC could not say.\n */\nexport async function latestBlock(\n rpcUrl: string,\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number } = {},\n): Promise<{ tag: string; timestamp: number } | null> {\n const result = await rpcCall(rpcUrl, 'eth_getBlockByNumber', ['latest', false], opts);\n if (result === null || typeof result !== 'object') return null;\n const { number, timestamp } = result as { number?: unknown; timestamp?: unknown };\n if (typeof number !== 'string' || !/^0x[0-9a-fA-F]+$/.test(number)) return null;\n if (typeof timestamp !== 'string' || !/^0x[0-9a-fA-F]+$/.test(timestamp)) return null;\n return { tag: number, timestamp: Number(BigInt(timestamp)) };\n}\n\nasync function rpcCall(\n rpcUrl: string,\n method: string,\n params: unknown[],\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number },\n): Promise<unknown> {\n try {\n const res = await (opts.fetchImpl ?? fetch)(rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),\n signal: AbortSignal.timeout(opts.timeoutMs ?? RECONCILE_TIMEOUT_MS),\n });\n if (!res.ok) return null;\n return ((await res.json()) as { result?: unknown } | null)?.result ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface ReconcileOutcome {\n /** Records asked about in this pass. */\n checked: number;\n /** The authorization was used: the amount was charged. */\n settled: number;\n /** It expired unused: nothing was charged. */\n notCharged: number;\n /** Still unknown: not yet expired, no authorization on record, or the RPC\n * could not answer. */\n unknown: number;\n /** What the not-charged payments gave back to today's automatic budget. */\n releasedAtomic: string;\n}\n\n/**\n * RESOLVE \"SETTLEMENT UNKNOWN\" FROM THE CHAIN. A paid call whose seller never\n * confirmed settlement leaves a record marked `unknown`. Once the chain's\n * latest block is past its authorization's `validBefore`, the token's own\n * `authorizationState(from, nonce)` read AT THAT BLOCK is final: used means\n * charged, unused means it can never be charged, since no later block can\n * carry it. This machine's clock only decides whether the chain is worth\n * asking. At most `max` records are asked about per pass, and\n * a record the RPC cannot answer for stays unknown, stamped `lastCheckedAt`,\n * and is not asked about again for `recheckMs`.\n *\n * The chain is asked outside the lock; the file is re-read and rewritten under\n * it, so an append made meanwhile is kept.\n */\nexport async function reconcilePayments(\n dataDir: string,\n opts: {\n rpcUrl: string;\n fetchImpl?: typeof fetch;\n now?: () => number;\n max?: number;\n timeoutMs?: number;\n /** Defaults to {@link RECHECK_MS}; the command passes 0. */\n recheckMs?: number;\n },\n): Promise<ReconcileOutcome> {\n const path = paidLedgerPath(dataDir);\n const now = (opts.now ?? Date.now)();\n const records = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n const open = records.filter(\n (entry): entry is { line: string; record: PaidRecord } =>\n entry.record !== null && entry.record.settlement === 'unknown',\n );\n const recheckMs = opts.recheckMs ?? RECHECK_MS;\n const due = open.filter(\n ({ record }) =>\n record.authorization !== undefined &&\n Number(record.authorization.validBefore) * 1_000 < now &&\n (record.lastCheckedAt === undefined || now - Date.parse(record.lastCheckedAt) >= recheckMs),\n );\n const answers = new Map<string, Settlement>();\n const asked = new Set<string>();\n let checked = 0;\n const rpc = {\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n };\n const block = due.length > 0 ? await latestBlock(opts.rpcUrl, rpc) : null;\n for (const { record } of due.slice(0, opts.max ?? MAX_RECONCILE_CHECKS)) {\n // Not past validBefore on the chain yet: not asked, and not stamped.\n if (block !== null && Number(record.authorization!.validBefore) >= block.timestamp) continue;\n checked += 1;\n asked.add(record.authorization!.nonce);\n if (block === null) continue;\n const used = await authorizationUsed(record.authorization!, opts.rpcUrl, {\n ...rpc,\n blockTag: block.tag,\n });\n if (used !== null) answers.set(record.authorization!.nonce, used ? 'settled' : 'not_charged');\n }\n // NOT CHARGED GIVES THE DAILY BUDGET BACK FIRST: exactly that payment's\n // exposure, by its nonce, while it is still inside the window that counted\n // it. Only then is the record marked; a release that could not be written\n // leaves it unknown, and the next pass asks again. A second release of the\n // same nonce finds nothing, so a retry never gives back twice.\n let releasedAtomic = 0n;\n for (const [nonce, answer] of [...answers]) {\n if (answer !== 'not_charged') continue;\n const released = await releaseUnchargedExposure(dataDir, nonce, {\n ...(opts.now !== undefined ? { now: opts.now } : {}),\n });\n if (released === null) answers.delete(nonce);\n else releasedAtomic += released;\n }\n if (asked.size > 0) {\n await withFileLock(`${path}.lock`, async () => {\n const current = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n const lines = current.map(({ line, record }) => {\n const nonce =\n record?.settlement === 'unknown' && record.authorization !== undefined\n ? record.authorization.nonce\n : undefined;\n if (nonce === undefined || !asked.has(nonce)) return line;\n const answer = answers.get(nonce);\n const stamp = new Date(now).toISOString();\n return JSON.stringify(\n answer === undefined\n ? { ...record, lastCheckedAt: stamp }\n : { ...record, settlement: answer, lastCheckedAt: stamp, reconciledAt: stamp },\n );\n });\n await writeFileAtomic(path, lines.map((line) => `${line}\\n`).join(''), { mode: 0o600 });\n });\n }\n const settled = [...answers.values()].filter((value) => value === 'settled').length;\n return {\n checked,\n settled,\n notCharged: answers.size - settled,\n unknown: open.length - answers.size,\n releasedAtomic: releasedAtomic.toString(),\n };\n}\n\n/** Every line, and the record it holds when it is one; other lines ride along. */\nfunction parseLedger(raw: string): { line: string; record: PaidRecord | null }[] {\n return raw\n .split('\\n')\n .filter((line) => line.trim().length > 0)\n .map((line) => {\n try {\n const value = JSON.parse(line) as PaidRecord;\n return { line, record: value !== null && value.version === 1 ? value : null };\n } catch {\n return { line, record: null };\n }\n });\n}\n\n/** The media a paid result links to, by the extension its path ends in. */\nconst MEDIA_EXTENSIONS = new Set([\n 'png',\n 'jpg',\n 'jpeg',\n 'webp',\n 'gif',\n 'svg',\n 'mp3',\n 'wav',\n 'm4a',\n 'ogg',\n 'mp4',\n 'webm',\n 'mov',\n]);\nexport const MAX_MEDIA_FILES = 5;\nexport const MAX_MEDIA_BYTES = 200 * 1024 * 1024;\nexport const MEDIA_TIMEOUT_MS = 60_000;\nconst MAX_REDIRECTS = 3;\nconst URL_RE = /https:\\/\\/[^\\s\"'<>\\\\]+/g;\n\n/** Every https URL in the result whose path ends in a media extension, in\n * order and without repeats, at most {@link MAX_MEDIA_FILES}. */\nexport function mediaUrlsIn(result: string, limit = MAX_MEDIA_FILES): string[] {\n const found: string[] = [];\n for (const match of result.matchAll(URL_RE)) {\n if (found.length >= limit) break;\n let url: URL;\n try {\n url = new URL(match[0]);\n } catch {\n continue;\n }\n const ext = url.pathname.split('.').pop()?.toLowerCase() ?? '';\n if (!url.pathname.includes('.') || !MEDIA_EXTENSIONS.has(ext)) continue;\n if (!found.includes(url.toString())) found.push(url.toString());\n }\n return found;\n}\n\n/** One GET the media download makes, connected to the address it validated. */\nexport interface PinnedTarget {\n url: URL;\n /** The address `resolvePublicDestination` checked; the socket goes here. */\n address: string;\n family: 4 | 6;\n}\n\nexport interface MediaResponse {\n status: number;\n location?: string;\n contentLength?: number;\n body: AsyncIterable<Uint8Array>;\n /** Drop the connection without reading the rest. */\n discard: () => void;\n}\n\nexport type MediaTransport = (target: PinnedTarget, signal: AbortSignal) => Promise<MediaResponse>;\n\nexport interface MediaDeps {\n /** Test seam; production connects with {@link pinnedGet}. */\n transport?: MediaTransport;\n destination?: DestinationOptions;\n now?: () => number;\n timeoutMs?: number;\n maxBytes?: number;\n}\n\n/**\n * CONNECT TO THE ADDRESS THAT WAS CHECKED. `fetch` resolves the name again on\n * its own, so a host answering publicly to the check and privately a moment\n * later (DNS rebinding) would get the request. `node:https` with a `lookup`\n * that hands back the one validated address closes that: the socket goes to\n * it, and TLS still verifies the certificate against the URL's own host name.\n */\nexport const pinnedGet: MediaTransport = (target, signal) =>\n new Promise((resolve, reject) => {\n const req = httpsRequest(\n target.url,\n {\n method: 'GET',\n signal,\n lookup: pinnedLookup(target),\n },\n (res) => {\n const length = Number(res.headers['content-length']);\n const location = res.headers.location;\n resolve({\n status: res.statusCode ?? 0,\n ...(typeof location === 'string' ? { location } : {}),\n ...(Number.isFinite(length) ? { contentLength: length } : {}),\n body: res,\n discard: () => res.destroy(),\n });\n },\n );\n req.on('error', reject);\n req.end();\n });\n\n/** A `lookup` that answers every name with the one validated address. */\nexport function pinnedLookup(target: Pick<PinnedTarget, 'address' | 'family'>): LookupFunction {\n return ((_host: string, options: { all?: boolean }, callback: LookupCallback) => {\n if (options.all === true) {\n callback(null, [{ address: target.address, family: target.family }]);\n } else {\n callback(null, target.address, target.family);\n }\n }) as unknown as LookupFunction;\n}\n\ntype LookupCallback = (\n err: Error | null,\n address: string | { address: string; family: number }[],\n family?: number,\n) => void;\n\n/**\n * Download each URL into the downloads dir, one at a time, each under its own\n * size cap and deadline, every hop of a redirect validated and connected to\n * the address it validated. Returns the paths that were written; a URL that\n * fails is skipped and never fails the call.\n */\nexport async function saveMedia(\n dataDir: string,\n stem: string,\n urls: string[],\n deps: MediaDeps = {},\n): Promise<string[]> {\n const saved: string[] = [];\n for (const [index, url] of urls.entries()) {\n const path = await saveOne(dataDir, `${stem}-${index + 1}`, url, deps);\n if (path !== null) saved.push(path);\n }\n return saved;\n}\n\nasync function saveOne(\n dataDir: string,\n stem: string,\n raw: string,\n deps: MediaDeps,\n): Promise<string | null> {\n const transport = deps.transport ?? pinnedGet;\n const maxBytes = deps.maxBytes ?? MAX_MEDIA_BYTES;\n const signal = AbortSignal.timeout(deps.timeoutMs ?? MEDIA_TIMEOUT_MS);\n let target = raw;\n let path: string | null = null;\n try {\n let res: MediaResponse | null = null;\n for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {\n const pinned = await resolvePublicDestination(target, deps.destination ?? {});\n res = await transport(pinned, signal);\n if (res.status < 300 || res.status >= 400 || res.location === undefined) break;\n res.discard();\n target = new URL(res.location, target).toString();\n res = null;\n }\n if (res === null || res.status < 200 || res.status >= 300) {\n res?.discard();\n return null;\n }\n if ((res.contentLength ?? 0) > maxBytes) {\n res.discard();\n return null;\n }\n const ext = new URL(target).pathname.split('.').pop()?.toLowerCase() ?? 'bin';\n const file = await createUniqueFile(\n downloadsDir(dataDir),\n `${stem}-${(deps.now ?? Date.now)()}`,\n MEDIA_EXTENSIONS.has(ext) ? ext : 'bin',\n );\n path = file.path;\n let size = 0;\n try {\n for await (const chunk of res.body) {\n size += chunk.byteLength;\n if (size > maxBytes) {\n res.discard();\n throw new Error('media over the size cap');\n }\n await writeAll(file.handle, chunk);\n }\n } finally {\n await file.handle.close();\n }\n return path;\n } catch {\n if (path !== null) await rm(path, { force: true }).catch(() => undefined);\n return null;\n }\n}\n\n/**\n * EVERY BYTE, OR A THROW. `FileHandle.write` may write fewer bytes than it was\n * handed and says so only in `bytesWritten`; a caller that ignores it saves a\n * file with a hole in it. A write that makes no progress is an error.\n */\nexport async function writeAll(\n handle: Pick<FileHandle, 'write'>,\n bytes: Uint8Array,\n): Promise<void> {\n let offset = 0;\n while (offset < bytes.byteLength) {\n const { bytesWritten } = await handle.write(bytes, offset, bytes.byteLength - offset);\n if (bytesWritten <= 0) throw new Error('the file write made no progress');\n offset += bytesWritten;\n }\n}\n\n/**\n * A NEW FILE, NEVER ANOTHER CALL'S. The name is the stem plus a random suffix,\n * created with an exclusive flag, so two lookups finishing in the same\n * millisecond each get their own file; a clash is retried with a new suffix.\n */\nexport async function createUniqueFile(\n directory: string,\n stem: string,\n ext: string,\n): Promise<{ path: string; handle: FileHandle }> {\n await mkdir(directory, { recursive: true });\n const safe = stem.replace(/[^A-Za-z0-9_-]+/g, '-').slice(0, 100) || 'lookup';\n for (let attempt = 0; ; attempt += 1) {\n const path = join(directory, `${safe}-${randomBytes(4).toString('hex')}.${ext}`);\n try {\n return { path, handle: await open(path, 'wx', 0o600) };\n } catch (err) {\n if (attempt >= 4 || !hasCode(err, 'EEXIST')) throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,mBAAmB;AAC5B,SAAS,YAAY,OAAO,MAAM,UAAU,UAA2B;AACvE,SAAS,WAAW,oBAAoB;AAExC,SAAS,SAAS,YAAY;AA+CvB,IAAM,iBAAiB;AAOvB,SAAS,SAAS,OAAyB;AAChD,MAAI,OAAO,UAAU,SAAU,QAAO,KAAK,KAAK;AAChD,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,QAAQ;AACnD,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO,OAAO;AAAA,MACZ,OAAO,QAAQ,KAAgC,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM;AAAA,QACrE,KAAK,GAAG;AAAA,QACR,SAAS,KA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W,GAAG;AACpC,UAAM,OAAO,KAAK,WAAW,GAAG,IAAI,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,IAAI,GAAG,EAAE;AAC/E,QAAI;AACF,aAAO,EAAE,MAAM,QAAQ,MAAM,KAAK,MAAM,MAAM,GAAK,EAAE;AAAA,IACvD,SAAS,KAAK;AACZ,UAAI,WAAW,KAAK,CAAC,QAAQ,KAAK,QAAQ,EAAG,OAAM;AAAA,IACrD;AAAA,EACF;AACF;","names":["open"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/client-meta.ts","../src/lib/http.ts"],"sourcesContent":["import pkg from '../../package.json';\nimport { PRODUCTION_ORIGIN } from './production-origin';\n\n/**\n * The RFC 9110 product token naming this CLI. It leads every User-Agent the\n * shared transport sends, because the server's `parseUserAgentProduct()` (tenjin\n * PR #544) attributes on the FIRST product only and the CLI is the user agent\n * that constructed and sent the request.\n */\nexport const TENJIN_PRODUCT = `tenjin-cli/${pkg.version}`;\n\n/** The product NAME alone, which is what identifies a copy of us in a handoff. */\nexport const TENJIN_PRODUCT_NAME = 'tenjin-cli';\n\n/**\n * The product the WebSearch hook leads with, so a ridealong query is separable\n * from a deliberate `tenjin search`. Leading is the mechanism: the server\n * attributes on the FIRST User-Agent product, landing here in `client_name`.\n *\n * The separation is the deliverable, not any one consumer: whatever judges hook\n * demand needs these populations distinguishable at ingest (tenjin#704,\n * tenjin-agent#179). A rename breaks no filter today, it merges them again. */\nexport const WEBSEARCH_HOOK_PRODUCT_NAME = 'tenjin-websearch-hook';\nexport const WEBSEARCH_HOOK_PRODUCT = `${WEBSEARCH_HOOK_PRODUCT_NAME}/${pkg.version}`;\n\n/** Every identity of ours a handoff may carry, which composition drops rather\n * than duplicate, whichever product is leading. */\nexport const OWN_PRODUCT_NAMES = [TENJIN_PRODUCT_NAME, WEBSEARCH_HOOK_PRODUCT_NAME];\n\n/**\n * The identifying comment. It rides LAST so a caller's products keep the order\n * they were handed off in, and so stripping it is enough to recover the caller's\n * sequence from an already-composed field (see `composeUserAgent`).\n */\nexport const TENJIN_COMMENT = `(+${PRODUCTION_ORIGIN})`;\n\n/**\n * The CLI's identity on every HTTP request, sent as the standard `User-Agent`\n * header from the shared transport (`http.ts`). `X-Tenjin-Client` is retired and\n * this CLI sends it nowhere.\n */\nexport const TENJIN_USER_AGENT = `${TENJIN_PRODUCT} ${TENJIN_COMMENT}`;\n\n/** The same field for the WebSearch hook, which identifies as its own product. */\nexport const WEBSEARCH_HOOK_USER_AGENT = `${WEBSEARCH_HOOK_PRODUCT} ${TENJIN_COMMENT}`;\n\n/** The handoff seam for an agent that launches the CLI as a subprocess. */\nexport const CALLER_USER_AGENT_ENV = 'TENJIN_CALLER_USER_AGENT';\n\n/** The server's bound: a longer field is discarded whole, never truncated. */\nexport const USER_AGENT_MAX_LENGTH = 512;\n\n/**\n * One RFC 9110 product: a token, optionally `/token`. The handoff accepts a\n * sequence of these and nothing else (no comments, no free text), which is what\n * structurally keeps a user, wallet, session, hostname, or machine identifier\n * out of the field rather than a blocklist that has to guess at one.\n */\nexport const PRODUCT_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+(?:\\/[!#$%&'*+.^_`|~0-9A-Za-z-]+)?$/;\n\n/** Printable ASCII, the only range the server parses; also excludes CR/LF/tab. */\nexport const PRINTABLE_ASCII_RE = /^[\\x20-\\x7e]*$/;\n\nexport interface ComposeUserAgentInput {\n /** A caller's product sequence, passed programmatically; wins over the env. */\n caller?: string | undefined;\n /** Environment seam; defaults to `process.env`. */\n env?: NodeJS.ProcessEnv;\n /** The product to lead with; the WebSearch hook passes its own. */\n product?: string;\n}\n\n/**\n * Compose the field the transport sends: the Tenjin product, then the caller's\n * products in their original order, then the Tenjin comment. The handoff is\n * SELF-REPORTED TELEMETRY and never trusted policy input; nothing here or on the\n * server may read it to decide entitlement, spend, or trust.\n *\n * Idempotent by construction: the caller value is decomposed into tokens, our own\n * product and comment are dropped from it, and the field is rebuilt from\n * `TENJIN_PRODUCT`, so re-composing an already-composed field (a retry, a nested\n * helper, an agent re-exporting the env it received) yields the same string\n * rather than a second `tenjin-cli` token. Caller products survive byte for byte.\n *\n * Rejection is total, never partial: a non-printable, non-product, or overlong\n * handoff is OMITTED and the Tenjin identity travels alone, because truncating a\n * product token would mint a different, false identity.\n */\nexport function composeUserAgent(input: ComposeUserAgentInput = {}): string {\n const product = input.product ?? TENJIN_PRODUCT;\n const alone = `${product} ${TENJIN_COMMENT}`;\n const raw = input.caller ?? (input.env ?? process.env)[CALLER_USER_AGENT_ENV];\n const products = callerProducts(raw);\n if (products.length === 0) return alone;\n const composed = `${product} ${products.join(' ')} ${TENJIN_COMMENT}`;\n return composed.length <= USER_AGENT_MAX_LENGTH ? composed : alone;\n}\n\n/** The caller's products, or none at all when any part of the handoff is unusable. */\nfunction callerProducts(raw: string | undefined): string[] {\n if (raw === undefined || !PRINTABLE_ASCII_RE.test(raw)) return [];\n // Printable ASCII leaves the space as the only whitespace, so it is the only\n // separator a product sequence can have.\n const tokens = raw.split(' ').filter((token) => token.length > 0 && !isOwnIdentity(token));\n return tokens.every((token) => PRODUCT_RE.test(token)) ? tokens : [];\n}\n\n/**\n * Our own identity inside a caller value, matched case-insensitively: a product\n * token is case-sensitive to the server, but a copy of ours in any casing is\n * still a duplicate identity, and dropping it is what makes composition total.\n */\nfunction isOwnIdentity(token: string): boolean {\n const lower = token.toLowerCase();\n // Both sides are lowered: comparing a lowered token against a constant that is\n // merely all-lowercase TODAY would break silently the day either gains a\n // capital, and it fails safe (the stale copy stops matching, then fails\n // PRODUCT_RE, and the whole handoff drops), so nothing would notice.\n if (lower === TENJIN_COMMENT.toLowerCase()) return true;\n return OWN_PRODUCT_NAMES.some((name) => {\n const own = name.toLowerCase();\n return lower === own || lower.startsWith(`${own}/`);\n });\n}\n","import { CliError } from './errors';\nimport { composeUserAgent } from './client-meta';\n\n/**\n * The single JSON client the whole CLI grows on: `doctor` uses it in B1, `search`\n * reuses it in B2. It never throws on a transport/protocol failure — it returns a\n * discriminated result so callers decide how each failure class maps to a check\n * or an error. `fetchImpl` is injectable so tests never touch the network.\n */\nexport interface FetchJsonOptions {\n /** Abort the request after this many milliseconds. */\n timeoutMs: number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** Optional request headers, merged onto the User-Agent this module always sends. */\n headers?: Record<string, string>;\n /** The team shelf's bypass secret and its origin; see {@link ShelfBypass}. */\n bypass?: ShelfBypass;\n /**\n * INTERNAL. A caller's own product sequence, composed BEHIND the CLI's\n * identity (see `composeUserAgent`). The package ships a `bin` and no\n * `exports` map, so this is not a supported seam for code outside this repo:\n * the documented handoff is the `TENJIN_CALLER_USER_AGENT` environment\n * variable, which is what a subprocess launcher sets and what this falls back\n * to. Kept as an option so an in-repo caller can pass a value the environment\n * does not carry.\n */\n callerUserAgent?: string;\n}\n\n/**\n * The team shelf's Vercel \"Protection Bypass for Automation\" header.\n *\n * A door key for a protected preview deployment, not a credential of anyone's:\n * it gets a request past Deployment Protection and authenticates nobody. It is\n * NOT in {@link CREDENTIAL_HEADERS}, whose members are wallet-signed material a\n * redirect target could REPLAY — this one cannot be replayed into a signature.\n * It is still a secret, and DISCLOSING it is the whole harm: whoever holds it\n * walks into the team shelf. So it pins redirects exactly as a signed header\n * does (see {@link carriesBypassKey}), and where it may go is decided here and\n * nowhere else.\n */\nexport const SHELF_BYPASS_HEADER = 'x-vercel-protection-bypass';\n\n/**\n * A bypass secret and the origin it belongs to.\n *\n * THE ORIGIN IS PART OF THE VALUE, and that is the whole design. The CLI talks\n * to two shelves in team mode — the team's own deployment and the public\n * marketplace — and a caller that decides \"this request is to the team shelf, so\n * attach the key\" is a caller that eventually gets it wrong once. So callers\n * pass the pair and this transport does the compare: the header is attached from\n * the REQUEST URL, so a request to any other host cannot carry it, whatever the\n * call site believed.\n */\nexport interface ShelfBypass {\n /** `URL.origin` of the shelf the secret opens (the configured `baseUrl`). */\n origin: string;\n secret: string;\n}\n\n/** The bypass header for `url`, or nothing. Exported for the hook-script mirror\n * test, which runs the generated copy of this rule against this one. */\nexport function shelfBypassHeaders(\n url: string,\n bypass: ShelfBypass | undefined,\n): Record<string, string> {\n if (bypass === undefined || bypass.secret.length === 0) return {};\n let origin: string;\n try {\n origin = new URL(url).origin;\n } catch {\n return {};\n }\n if (origin !== bypass.origin) return {};\n return { [SHELF_BYPASS_HEADER]: bypass.secret };\n}\n\n/**\n * Whether the request being assembled actually carries the door key.\n *\n * A request that carries it MUST NOT follow a redirect. `fetch`'s default\n * `redirect: 'follow'` re-sends request headers verbatim to the new host (Node\n * strips only `Authorization`), so a single 3xx anywhere on the shelf origin —\n * the Vercel Authentication interstitial a rotated bypass secret gets, a domain\n * alias, a CDN rule — would hand the team shelf's key to whatever `Location`\n * names. Nothing else is needed to walk in afterwards, so the key never leaves\n * the origin it was paired with, not even one hop.\n *\n * Read off the BUILT headers rather than off `opts.bypass`, for the same reason\n * {@link CREDENTIAL_HEADERS} is matched by name: attaching the secret is what\n * arms the protection, so an off-origin request (which gets no header) keeps\n * ordinary transport and a call site cannot forget to ask for the pin.\n */\nfunction carriesBypassKey(headers: Record<string, string>): boolean {\n return Object.keys(headers).some((name) => name.toLowerCase() === SHELF_BYPASS_HEADER);\n}\n\n/** The anonymous install id: a random UUID minted once per data dir. */\nexport const INSTALL_ID_HEADER = 'tenjin-install-id';\n\n/**\n * Who is using the router, for Tenjin's own request telemetry: an anonymous\n * install id, random and tied to nothing but the data dir.\n *\n * Same shape as {@link ShelfBypass}, for the same reason: the transport decides\n * where it goes, from the REQUEST URL, so a call site cannot send it to a\n * provider by believing it is talking to Tenjin. `pay` runs over this transport\n * to third-party sellers, and none of them gets the header.\n *\n * Process-wide rather than a per-call option because it is not a per-call\n * decision: every request to Tenjin carries it, and threading it through forty\n * call sites is forty chances to forget one. Set only by the two process entries\n * (the CLI's `index.ts` and the daemon), so an in-process test that never sets\n * it sends exactly what it always did.\n *\n * Redirects are left to the request's usual transport: an unpinned request\n * follows them as `fetch` does, headers and all. Tenjin's origins redirect only\n * to Tenjin's own hosts, and the id is not a credential, so it is not worth the\n * redirect pin the bypass key and signed headers get.\n */\nexport interface TenjinIdentity {\n /** The origins that are Tenjin's own for this process. */\n origins: () => Promise<readonly string[]>;\n /** The install id; absent when it could not be read or created. */\n installId: () => Promise<string | undefined>;\n}\n\nlet tenjinIdentity: TenjinIdentity | undefined;\n\nexport function setTenjinIdentity(identity: TenjinIdentity | undefined): void {\n tenjinIdentity = identity;\n}\n\n/**\n * The telemetry headers for `url`, or nothing. NEVER THROWS: a data dir that\n * cannot be read costs the request its telemetry and nothing else.\n */\nexport async function tenjinIdentityHeaders(url: string): Promise<Record<string, string>> {\n const identity = tenjinIdentity;\n if (identity === undefined) return {};\n try {\n if (!(await identity.origins()).includes(new URL(url).origin)) return {};\n const id = await identity.installId();\n return id !== undefined ? { [INSTALL_ID_HEADER]: id } : {};\n } catch {\n return {};\n }\n}\n\n/**\n * The one place the identity is written for anything that can import it; both\n * transports funnel their Headers through it, so a third entry point on this\n * side cannot ship without it. `.set` on a Headers\n * object is what makes this total: a caller header spelled `User-Agent` in any\n * case lands in the same slot and is overwritten, never duplicated, so a\n * call-specific header cannot erase the composed field or add a second one.\n */\nfunction applyUserAgent(headers: Headers, callerUserAgent?: string): Headers {\n headers.set('user-agent', composeUserAgent({ caller: callerUserAgent }));\n return headers;\n}\n\n/** The same write for `fetchJson`'s plain-object headers; Headers.entries() is lowercase-keyed. */\nfunction withUserAgent(\n callerHeaders?: Record<string, string>,\n callerUserAgent?: string,\n): Record<string, string> {\n return Object.fromEntries(\n applyUserAgent(new Headers(callerHeaders ?? {}), callerUserAgent).entries(),\n );\n}\n\n/** A successful 2xx whose body parsed as JSON. */\nexport interface FetchJsonSuccess {\n ok: true;\n status: number;\n json: unknown;\n /** The server's `x-request-id`, when it sent one — useful in error reports. */\n requestId?: string;\n}\n\n/**\n * A failed request, tagged by class so the caller maps it deliberately:\n * `network`/`timeout` (never reached the server or no answer), `http` (a non-2xx\n * status), `invalid-json` (2xx but the body was not JSON).\n */\nexport interface FetchJsonFailure {\n ok: false;\n kind: 'network' | 'timeout' | 'http' | 'invalid-json' | 'blocked-redirect' | 'oversized-header';\n status?: number;\n requestId?: string;\n message: string;\n /**\n * On `invalid-json`, and on `http` when the status is 401/403: the response\n * looks like an access-protection or sign-in page rather than an API answer.\n * See {@link accessGateSignals} for what \"looks like\" means. Callers use it to\n * point at the missing credential instead of at the base URL, which is the one\n * setting that was already correct (#218).\n */\n gateSuspected?: boolean;\n /**\n * Present (true) only where the response left the host that was asked for:\n * `gateSuspected`'s STRONGER signal (the final URL's host differs), or, on\n * `blocked-redirect`, a `Location` that resolves to another host. An HTML\n * content-type alone proves a page came back, not who sent it, and a 3xx\n * alone proves only that the URL moved; leaving the host is what lets a\n * caller name access protection outright.\n */\n gateOffOrigin?: boolean;\n /**\n * On `network`: the layer the error chain names, when it names one. The\n * origin never answered, so a caller that blames it (or its base URL) gives\n * the wrong fix. See {@link transportFailure}.\n */\n transport?: TransportFailure;\n}\n\n/** Which layer refused a request that never reached the origin. */\nexport interface TransportFailure {\n layer: 'proxy' | 'dns' | 'tls' | 'connect';\n /** The socket's own error code, for every layer but `proxy`. */\n code?: string;\n /** What the proxy answered to `CONNECT`, for `proxy` only. */\n proxyStatus?: number;\n}\n\n/**\n * Does this response read as a protection page rather than as an API answer?\n *\n * Two independent signals, reported separately because they prove different\n * amounts (the caller's wording must not outrun the evidence):\n *\n * - an HTML content-type, because a Vercel Deployment Protection interstitial\n * and every sign-in wall answer with a page;\n * - a final URL whose host is not the one asked for, because a gate that\n * redirects to sign in lands the probe on another host and `fetch` follows it\n * silently on the unpinned requests this function serves.\n *\n * Decided HERE because this transport is the only place holding the `Response`;\n * a caller re-deriving it from the failure message would be guessing. An\n * unreadable final URL is NOT suspicion: `res.url` is empty on a synthesized\n * Response, so only a host that reads AND differs counts.\n */\nfunction accessGateSignals(\n requestedUrl: string,\n res: Response,\n): { gateSuspected: boolean; gateOffOrigin?: true } {\n const html = /^\\s*text\\/html\\b/i.test(res.headers.get('content-type') ?? '');\n let offOrigin = false;\n if (res.url.length > 0) {\n try {\n offOrigin = new URL(requestedUrl).host !== new URL(res.url).host;\n } catch {\n offOrigin = false;\n }\n }\n return {\n gateSuspected: html || offOrigin,\n ...(offOrigin ? { gateOffOrigin: true as const } : {}),\n };\n}\n\n/**\n * Does an unfollowed 3xx point off the host that was asked for?\n *\n * The pinned branch never follows, so `res.url` is still the requested URL and\n * `Location` is the only evidence about where the hop went. That distinction\n * carries the whole verdict downstream: a gate's sign-in interstitial lands on\n * another host, while an `http://` base URL that 301s to https, or a host\n * normalising to its canonical name, does not, and reading either as a refused\n * credential blames the wrong setting. A relative target resolves against the\n * request, so it is same-host by construction; a missing or unparseable one is\n * NOT an off-host claim.\n */\nfunction redirectLeavesHost(requestedUrl: string, location: string | null): boolean {\n if (location === null || location.length === 0) return false;\n try {\n return new URL(requestedUrl).host !== new URL(location, requestedUrl).host;\n } catch {\n return false;\n }\n}\n\n/**\n * Header names that carry wallet-signed material.\n *\n * A request bearing any of these must NEVER follow a redirect. `resource-ref`\n * pins the invariant — \"nothing signed may leave for a host the user did not\n * configure\" — but `assertOnBaseOrigin` only checks the URL the caller asked\n * for, and `fetch`'s default `redirect: 'follow'` re-sends request headers\n * verbatim to the new host (Node strips only `Authorization`). A 3xx anywhere on\n * the configured origin would therefore hand a signature BOUND TO THE REAL\n * DOMAIN to whoever `Location` points at, replayable against it for the\n * signature's lifetime.\n *\n * Detected by header NAME rather than by a caller-supplied \"this is signed\" flag\n * so the protection cannot be forgotten at a call site: attaching the credential\n * is what arms it. Matched case-insensitively. Kept as literals so the base\n * transport keeps its single dependency; `http.test.ts` pins them against the\n * real constants in `lib/siwx` and the x402 payment headers.\n *\n * All three wallet-signed families this CLI sends are here: the SIWX auth\n * header, the x402 payment header (`payment-signature` for x402 v2, plus\n * `x-payment`, the v1 spelling `@x402/core` can emit, as drift insurance even\n * though `read-client` pins v2), and `tenjin-session-delegation` — a REUSABLE\n * session-lifetime SIWX signature `session-key` attaches to every session-signed\n * write, which makes it the most replayable credential of the set. The RFC 9421\n * `Signature`/`Signature-Input` pair riding alongside it is deliberately absent:\n * it covers method, URL, and body digest, so it is not usefully replayable at\n * another host.\n */\nconst CREDENTIAL_HEADERS = new Set([\n 'sign-in-with-x',\n 'payment-signature',\n 'x-payment',\n 'tenjin-session-delegation',\n]);\n\nfunction carriesSignedMaterial(headers: Record<string, string>): boolean {\n return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));\n}\n\nexport type FetchJsonResult = FetchJsonSuccess | FetchJsonFailure;\n\nexport async function fetchJson(url: string, opts: FetchJsonOptions): Promise<FetchJsonResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n // The timer stays armed until the body is fully consumed (cleared in the outer\n // finally), so a server that sends headers then stalls the body still trips the\n // deadline instead of hanging forever on res.json().\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n let res: Response;\n // `new Headers` throws on a malformed caller header, so building them stays\n // inside the catch that turns any pre-flight refusal into the same\n // discriminated network failure a dead socket gets.\n let pinned = false;\n try {\n const headers = withUserAgent(\n { ...opts.headers, ...shelfBypassHeaders(url, opts.bypass) },\n opts.callerUserAgent,\n );\n // fetchJson sends no signed material — doctor's probes and the contract\n // checks are anonymous — so the door key is the one thing here worth\n // pinning, and it pins the same way it does in httpRequest.\n pinned = carriesBypassKey(headers);\n res = await doFetch(url, {\n signal: controller.signal,\n headers: { ...headers, ...(await tenjinIdentityHeaders(url)) },\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\n // A timeout is a network failure the AbortController induced; distinguish it\n // from an organic one so the caller can say \"timed out\" rather than a raw\n // AbortError message.\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n // Fail CLOSED, ahead of the ordinary non-2xx branch, so an unfollowed 3xx is\n // never reported as a plain HTTP status a caller might retry by hand.\n if (pinned && res.status >= 300 && res.status < 400) {\n return {\n ok: false,\n kind: 'blocked-redirect',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n // Where it pointed, not that it pointed: only a hop that leaves the host\n // asked for is evidence about the key. Same-host 3xx happens to a base\n // URL that needs fixing, with a perfectly good key.\n ...(redirectLeavesHost(url, res.headers.get('location'))\n ? { gateOffOrigin: true as const }\n : {}),\n message:\n `Request to ${url} was redirected (${res.status}) while carrying the team shelf's ` +\n 'bypass key; refusing to follow it, because the key opens only the configured origin.',\n };\n }\n\n if (!res.ok) {\n return {\n ok: false,\n kind: 'http',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n // 401/403 is one of the three shapes deployment protection answers with\n // (200 HTML and a 30x interstitial are the others), so the gate signals\n // ride here too. Other statuses stay unmarked: a 404 or 500 HTML page is\n // an ordinary broken deployment, not a credential problem.\n ...(res.status === 401 || res.status === 403 ? accessGateSignals(url, res) : {}),\n message: `Request to ${url} failed with status ${res.status}`,\n };\n }\n\n let json: unknown;\n try {\n json = await res.json();\n } catch (err) {\n // The body read can fail three ways. A timeout wins first: the abort fires\n // synchronously with `timedOut`, so any abort-induced rejection here is our\n // deadline. Otherwise a SyntaxError is a genuine parse failure (invalid\n // JSON); anything else is a transport failure mid-body (network).\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (err instanceof SyntaxError) {\n return {\n ok: false,\n kind: 'invalid-json',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n ...accessGateSignals(url, res),\n message: `Response from ${url} was not valid JSON`,\n };\n }\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n\n return {\n ok: true,\n status: res.status,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction timeoutFailure(url: string, timeoutMs: number): FetchJsonFailure {\n return {\n ok: false,\n kind: 'timeout',\n message: `Request to ${url} timed out after ${timeoutMs}ms`,\n };\n}\n\n/**\n * A full HTTP round trip that surfaces the STATUS, headers, and best-effort JSON\n * body for ANY status. Unlike fetchJson (2xx-only), the B2 read/pay flow needs\n * the body on a 402 (the leak-safe preview) and a 409 (the owned-re-pay gate),\n * and search/outcome need a 4xx validation envelope. A transport/timeout failure\n * still returns the discriminated FetchJsonFailure so callers map it uniformly.\n */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'DELETE';\n timeoutMs: number;\n headers?: Record<string, string>;\n /** The team shelf's bypass secret and its origin; see {@link ShelfBypass}. */\n bypass?: ShelfBypass;\n /** INTERNAL; see `FetchJsonOptions.callerUserAgent`. */\n callerUserAgent?: string;\n /** A JSON body (POST); serialized with a content-type header set automatically. */\n jsonBody?: unknown;\n /**\n * A body the CALLER already encoded, sent byte for byte with no content-type\n * of this transport's choosing: the router's provider leg is handed a request\n * the server built, and re-encoding it would make the bytes signed for and\n * the bytes sent two different things. The caller's own `headers` carry the\n * content type. Ignored when `jsonBody` is set.\n */\n rawBody?: string;\n fetchImpl?: typeof fetch;\n /**\n * A caller's own abort, combined with (never replacing) `timeoutMs`. The loop's\n * legs pass the fire's signal here so a harness that closed its socket stops the\n * request in flight; a caller with no such signal is unchanged.\n */\n signal?: AbortSignal;\n /**\n * Refuse redirects even when the request carries no signed header. For a\n * caller whose response becomes a durable local artifact (`fetchRead`: the\n * 200 is written to the library as an entitlement record under the\n * server-chosen id/slug), following a cross-origin redirect would let\n * another host's bytes be recorded as if the configured origin served them.\n * Off by default so search/outcome/publish/doctor keep normal transport.\n */\n blockRedirects?: boolean;\n /**\n * Keep a binary body as bytes. A sound, an image or any other non-text\n * payload decoded as text is corrupted, so with this set a response whose\n * content type is not text ({@link isBinaryContentType}) comes back with\n * `bytes` and an empty `text`. The router's provider leg sets it; every other\n * caller reads text as before.\n */\n binaryBody?: boolean;\n /** The cap on such a body; over it the response is a failure, never a\n * buffer that grows without bound. Defaults to {@link MAX_BINARY_BODY_BYTES}. */\n maxBinaryBytes?: number;\n /**\n * Send no install id, and mint none. For a request that checks the network\n * rather than uses Tenjin (the reachability probe), so it never counts as an\n * install in request telemetry.\n */\n anonymous?: boolean;\n}\n\n/** The same cap the router's linked-media download uses. */\nexport const MAX_BINARY_BODY_BYTES = 200 * 1024 * 1024;\n\n/**\n * The body's bytes, read chunk by chunk and abandoned the moment they pass\n * `max`; null over the cap. A declared length over it is refused unread.\n */\nasync function readCapped(res: Response, max: number): Promise<Uint8Array | null> {\n const declared = Number(res.headers.get('content-length') ?? '0');\n if (Number.isFinite(declared) && declared > max) {\n await res.body?.cancel().catch(() => undefined);\n return null;\n }\n if (res.body === null) return new Uint8Array();\n const reader = res.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > max) {\n await reader.cancel().catch(() => undefined);\n return null;\n }\n chunks.push(value);\n }\n return new Uint8Array(Buffer.concat(chunks));\n}\n\n/**\n * A content type whose body is not text: anything that is not `text/*` and\n * not a JSON, XML, JavaScript, YAML or form type. An absent header is text, as\n * it always was here.\n */\nexport function isBinaryContentType(contentType: string | undefined): boolean {\n const type = (contentType ?? '').split(';')[0]!.trim().toLowerCase();\n if (type.length === 0) return false;\n if (type.startsWith('text/')) return false;\n return !/(?:json|xml|javascript|ecmascript|yaml|x-www-form-urlencoded)/.test(type);\n}\n\nexport interface HttpResponse {\n ok: true;\n status: number;\n /** Case-insensitive header lookup over the response. */\n header(name: string): string | undefined;\n /** Parsed JSON body, or undefined when the body was empty or not JSON. */\n json: unknown;\n /** The raw body text; what a non-JSON endpoint actually said (`pay` delivers it). */\n text: string;\n /** The body's bytes, only for a binary body read with `binaryBody`; `text`\n * is then empty. */\n bytes?: Uint8Array;\n requestId?: string;\n}\n\nexport type HttpResult = HttpResponse | FetchJsonFailure;\n\n/** The wire form of one request: what to send, and whether it may follow a redirect. */\ninterface PreparedRequest {\n ok: true;\n headers: Record<string, string>;\n body: string | undefined;\n signed: boolean;\n bypassed: boolean;\n pinned: boolean;\n}\n\n/**\n * Assemble the request and DERIVE its redirect decision from the headers that\n * were actually built, in one place and one pass. The redirect flags are\n * returned rather than assigned, so they have no value until the headers do:\n * there is no state in which `pinned` is readable but not yet computed, which\n * is what would let a signed request follow a 3xx to another host. Anything\n * that refuses here (`new Headers` throws on a malformed caller header) becomes\n * the same discriminated failure a dead socket does, because this transport\n * documents a returned failure for every refusal, not an exception.\n */\nfunction prepareRequest(url: string, opts: HttpRequestOptions): PreparedRequest | FetchJsonFailure {\n try {\n let body: string | undefined;\n // The bypass rides in with the caller's headers rather than being set after\n // them, so a caller cannot spell it a second way and win the slot.\n const merged = new Headers({ ...opts.headers, ...shelfBypassHeaders(url, opts.bypass) });\n if (opts.jsonBody !== undefined) {\n body = JSON.stringify(opts.jsonBody);\n merged.set('content-type', 'application/json');\n } else if (opts.rawBody !== undefined) {\n body = opts.rawBody;\n }\n const wantsAccept = opts.method === 'POST' || opts.method === 'PUT' || body !== undefined;\n if (wantsAccept && !merged.has('accept')) merged.set('accept', 'application/json');\n // An `accept`/`content-type` set here wins the slot regardless of how a\n // caller cased its own copy.\n const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());\n\n // Signed requests opt out of redirect following entirely; see CREDENTIAL_HEADERS.\n // So does a request carrying the team shelf's bypass key: it cannot be\n // replayed, but a 3xx would DISCLOSE it, and that is the whole harm (see\n // carriesBypassKey). A caller can also pin an unsigned, keyless request\n // (blockRedirects) when the response it gets back becomes a durable local record.\n const signed = carriesSignedMaterial(headers);\n const bypassed = carriesBypassKey(headers);\n return {\n ok: true,\n headers,\n body,\n signed,\n bypassed,\n pinned: signed || bypassed || opts.blockRedirects === true,\n };\n } catch (err) {\n return {\n ok: false,\n kind: 'network',\n message: `Request to ${url} failed: ${errorMessage(err)}`,\n };\n }\n}\n\nexport async function httpRequest(url: string, opts: HttpRequestOptions): Promise<HttpResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n // The caller's abort is combined with the timeout rather than chosen between:\n // whichever fires first ends the request, and `timedOut` still says which.\n const signal =\n opts.signal === undefined\n ? controller.signal\n : AbortSignal.any([controller.signal, opts.signal]);\n\n try {\n const prepared = prepareRequest(url, opts);\n if (!prepared.ok) return prepared;\n const { headers, body, signed, bypassed, pinned } = prepared;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method: opts.method ?? 'GET',\n headers:\n opts.anonymous === true ? headers : { ...headers, ...(await tenjinIdentityHeaders(url)) },\n body,\n signal,\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (isHeaderOverflow(err)) return oversizedHeaderFailure(url);\n const transport = transportFailure(err);\n return {\n ok: false,\n kind: 'network',\n message: `Request to ${url} failed: ${errorMessage(err)}`,\n ...(transport !== undefined ? { transport } : {}),\n };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n // Fail CLOSED on a redirect the request was not allowed to follow. This\n // returns a failure rather than the 3xx response so no caller can mistake an\n // unfollowed redirect for a normal status and retry it by hand.\n if (pinned && res.status >= 300 && res.status < 400) {\n return {\n ok: false,\n kind: 'blocked-redirect',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: signed\n ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; ` +\n 'refusing to follow it, because the signature is bound to the configured origin.'\n : bypassed\n ? `Request to ${url} was redirected (${res.status}) while carrying the team shelf's ` +\n 'bypass key; refusing to follow it, because the key opens only the configured origin.'\n : `Request to ${url} was redirected (${res.status}); ` +\n 'refusing to follow it, because the response must come from the configured origin.',\n };\n }\n // Read the raw text once; parse best-effort. A non-JSON body (empty 202, an\n // HTML error page) yields `undefined` rather than a thrown parse, because a\n // 402/409 caller keys off the STATUS and only some statuses carry JSON.\n let text: string;\n let bytes: Uint8Array | undefined;\n try {\n if (opts.binaryBody === true && isBinaryContentType(res.headers.get('content-type') ?? '')) {\n const read = await readCapped(res, opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES);\n if (read === null) {\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} returned a file over the ${Math.round((opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES) / 1_048_576)} MB cap; it was not kept.`,\n };\n }\n bytes = read;\n text = '';\n } else {\n text = await res.text();\n }\n } catch (err) {\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n let json: unknown;\n if (text.length > 0) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n return {\n ok: true,\n status: res.status,\n header: (name) => res.headers.get(name) ?? undefined,\n json,\n text,\n ...(bytes !== undefined ? { bytes } : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport interface FailureToCliErrorOptions {\n fix?: string;\n details?: unknown;\n}\n\n/**\n * Normalize a fetch failure into the CLI error contract: network/timeout are a\n * NETWORK_ERROR, an `http` status (server reachable but errored — commonly 5xx)\n * is API_UNREACHABLE, and a 2xx that failed to parse when JSON was required is a\n * CONTRACT_MISMATCH. Callers that need a check-specific code (doctor) build their\n * own CliError; this is the default B2's passthrough leans on.\n */\nexport function fetchFailureToCliError(\n failure: FetchJsonFailure,\n opts: FailureToCliErrorOptions = {},\n): CliError {\n const code =\n failure.kind === 'network' || failure.kind === 'timeout'\n ? 'NETWORK_ERROR'\n : failure.kind === 'invalid-json'\n ? 'CONTRACT_MISMATCH'\n : failure.kind === 'oversized-header'\n ? 'CHALLENGE_TOO_LARGE'\n : 'API_UNREACHABLE';\n // The one failure with a remedy nobody can apply from inside the process, so\n // it names the operator's knob rather than suggesting a retry.\n // The knob, with no claim about payment: a caller that knows its leg passes\n // its own `fix` and says what happened to the money there.\n const fix =\n opts.fix ??\n (failure.kind === 'oversized-header'\n ? 'Raising `--max-http-header-size` on the node process that runs this CLI would let the header be read; that is an operator decision, not a default this build changes.'\n : undefined);\n return new CliError(code, failure.message, {\n ...(fix !== undefined ? { fix } : {}),\n ...(opts.details !== undefined ? { details: opts.details } : {}),\n });\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Does this transport failure mean the response HEADERS were too big for this\n * process to read?\n *\n * Node caps them at 16 KiB unless `--max-http-header-size` says otherwise, and\n * an x402 challenge is a header: a seller that embeds its whole output schema\n * in one can exceed the cap on its own (AnyAPI's is 52 KB, measured\n * 2026-09-22). undici then aborts the request and the generic path reported\n * `fetch failed` with no status and nothing naming the cause, which reads as\n * \"the endpoint is down\" for a seller that is answering perfectly.\n *\n * The message is undici's, matched on its stable text and on the code it\n * attaches; the CAUSE is the one that carries either, so both are checked.\n */\nfunction isHeaderOverflow(err: unknown): boolean {\n const seen = [err, (err as { cause?: unknown } | null)?.cause];\n return seen.some((candidate) => {\n if (candidate === null || typeof candidate !== 'object') return false;\n const code = (candidate as { code?: unknown }).code;\n if (code === 'UND_ERR_HEADERS_OVERFLOW' || code === 'HPE_HEADER_OVERFLOW') return true;\n const message = (candidate as { message?: unknown }).message;\n return typeof message === 'string' && /headers overflow|header overflow/i.test(message);\n });\n}\n\nconst DNS_CODES = new Set(['ENOTFOUND', 'EAI_AGAIN', 'EAI_FAIL', 'EAI_NODATA', 'EAI_NONAME']);\nconst CONNECT_CODES = new Set([\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'ETIMEDOUT',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_SOCKET',\n]);\nconst TLS_CODE = /^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_|SELF_SIGNED_|DEPTH_ZERO_)/;\n/** undici's text when a proxy answers `CONNECT` with anything but 200. */\nconst PROXY_REFUSAL = /Proxy response \\((\\d{3})\\)/;\n\n/**\n * The layer a `fetch failed` came from, read down the `cause` chain. fetch\n * wraps the real error twice: a proxy refusing the tunnel is\n * `TypeError: fetch failed`, then `Request was cancelled.`, then undici's\n * `UND_ERR_ABORTED` with the proxy's status in its message (Node 24.18,\n * measured 2026-10-05). Undefined when no link names a layer.\n */\nexport function transportFailure(err: unknown): TransportFailure | undefined {\n let link: unknown = err;\n for (let depth = 0; depth < 5 && link !== null && typeof link === 'object'; depth += 1) {\n const { code, message, cause } = link as { code?: unknown; message?: unknown; cause?: unknown };\n const proxy = typeof message === 'string' ? PROXY_REFUSAL.exec(message) : null;\n if (proxy !== null) return { layer: 'proxy', proxyStatus: Number(proxy[1]) };\n if (typeof code === 'string') {\n if (DNS_CODES.has(code)) return { layer: 'dns', code };\n if (TLS_CODE.test(code)) return { layer: 'tls', code };\n if (CONNECT_CODES.has(code)) return { layer: 'connect', code };\n }\n link = cause;\n }\n return undefined;\n}\n\n/**\n * The named refusal for that case. NOT a `network` failure: nothing is wrong\n * with the connection, and a caller that retries gets the same 52 KB again.\n *\n * SAYS NOTHING ABOUT PAYMENT. This transport serves the unpaid probe and the\n * paid retry alike and cannot tell them apart, so a message asserting either\n * way is wrong on one of them: it read as \"nothing was sent\" on a leg where a\n * signed authorization had already left. The leg adds that sentence, because\n * the leg is what knows; see `runPay`.\n */\nfunction oversizedHeaderFailure(url: string): FetchJsonFailure {\n let origin = url;\n try {\n origin = new URL(url).origin;\n } catch {\n // Keep the raw string; this is a diagnostic, not a destination.\n }\n return {\n ok: false,\n kind: 'oversized-header',\n message:\n `${origin} answered with a response header block larger than this process will read. ` +\n 'An x402 challenge travels in a header, and a seller that embeds its whole output ' +\n 'schema in one can exceed the limit, so the response could not be read.',\n };\n}\n"],"mappings":";;;;;;;;;;AASO,IAAM,iBAAiB,cAAc,gBAAI,OAAO;AAGhD,IAAM,sBAAsB;AAU5B,IAAM,8BAA8B;AACpC,IAAM,yBAAyB,GAAG,2BAA2B,IAAI,gBAAI,OAAO;AAI5E,IAAM,oBAAoB,CAAC,qBAAqB,2BAA2B;AAO3E,IAAM,iBAAiB,KAAK,iBAAiB;AAO7C,IAAM,oBAAoB,GAAG,cAAc,IAAI,cAAc;AAG7D,IAAM,4BAA4B,GAAG,sBAAsB,IAAI,cAAc;AAG7E,IAAM,wBAAwB;AAG9B,IAAM,wBAAwB;AAQ9B,IAAM,aAAa;AAGnB,IAAM,qBAAqB;AA2B3B,SAAS,iBAAiB,QAA+B,CAAC,GAAW;AAC1E,QAAM,UAAU,MAAM,WAAW;AACjC,QAAM,QAAQ,GAAG,OAAO,IAAI,cAAc;AAC1C,QAAM,MAAM,MAAM,WAAW,MAAM,OAAO,QAAQ,KAAK,qBAAqB;AAC5E,QAAM,WAAW,eAAe,GAAG;AACnC,MAAI,SAAS,WAAW,EAAG,QAAO;AAClC,QAAM,WAAW,GAAG,OAAO,IAAI,SAAS,KAAK,GAAG,CAAC,IAAI,cAAc;AACnE,SAAO,SAAS,UAAU,wBAAwB,WAAW;AAC/D;AAGA,SAAS,eAAe,KAAmC;AACzD,MAAI,QAAQ,UAAa,CAAC,mBAAmB,KAAK,GAAG,EAAG,QAAO,CAAC;AAGhE,QAAM,SAAS,IAAI,MAAM,GAAG,EAAE,OAAO,CAAC,UAAU,MAAM,SAAS,KAAK,CAAC,cAAc,KAAK,CAAC;AACzF,SAAO,OAAO,MAAM,CAAC,UAAU,WAAW,KAAK,KAAK,CAAC,IAAI,SAAS,CAAC;AACrE;AAOA,SAAS,cAAc,OAAwB;AAC7C,QAAM,QAAQ,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AAE;AAC3E,QAAI,OAAO,SAAS,UAAU;AAC5B,UAAI,UAAU,IAAI,IAAI,EAAG,QAAO,EAAE,OAAO,OAAO,KAAK;AACrD,UAAI,SAAS,KAAK,IAAI,EAAG,QAAO,EAAE,OAAO,OAAO,KAAK;AACrD,UAAI,cAAc,IAAI,IAAI,EAAG,QAAO,EAAE,OAAO,WAAW,KAAK;AAAA,IAC/D;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAYA,SAAS,uBAAuB,KAA+B;AAC7D,MAAI,SAAS;AACb,MAAI;AACF,aAAS,IAAI,IAAI,GAAG,EAAE;AAAA,EACxB,QAAQ;AAAA,EAER;AACA,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SACE,GAAG,MAAM;AAAA,EAGb;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/install.ts","../src/lib/skill-placement.ts","../src/router/claude-cli.ts","../src/router/legacy-install.ts","../src/router/status-line-wiring.ts","../src/router/plugin-registration.ts","../src/router/plugin-files.ts","../src/router/plugin-folder.ts","../src/router/reachability.ts"],"sourcesContent":["import { readFile, realpath } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\nimport pkg from '../../package.json';\nimport { persistRouterDefaults, ROUTER_DEFAULTS, type RouterLimits } from '../commands/config';\nimport { askText, selectOne } from '../lib/clack';\nimport { CliError } from '../lib/errors';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { paint } from '../lib/output';\nimport { resolveContextSettings } from '../lib/settings';\nimport type { SpendPolicy } from '../lib/policy';\nimport { removeRetiredSkills } from '../lib/skill-placement';\nimport { loadRawConfig, type PartialConfig } from '../lib/config';\nimport type { WalletDeps, WalletOutcome } from '../commands/install-wallet';\nimport type { CommandContext, CommandResult } from '../context';\nimport { readAliveStamp } from './alive';\nimport {\n findClaudeBinary,\n readClaudeCode,\n userMcpFile,\n userSettingsPath,\n type ClaudeBinary,\n type ClaudeCodeState,\n} from './claude-cli';\nimport {\n inspectLegacyInstall,\n projectMcpFile,\n removeLegacyInstall,\n type LegacyInstall,\n type LegacyRemoval,\n} from './legacy-install';\nimport { PLUGIN_ID } from './names';\nimport { CLAUDE_CODE_FLOOR } from './claude-cli';\nimport {\n folderState,\n readPluginListing,\n registerPlugin,\n type PluginRegistration,\n type PluginScope,\n} from './plugin-registration';\nimport { probeRouter, type RouterCheck } from './reachability';\nimport { readMcpServers, type InstalledAt, type ListMcpProcesses } from './mcp-processes';\nimport {\n FEE_APPROVAL,\n limitsUsd,\n OWN_LIMITS_COMMANDS,\n ROUTING_FEE_TERMS,\n shownLimits,\n spendQuestion,\n} from './spend-question';\n\n/**\n * `tenjin install` for the router product: the wallet, the spend limits, and\n * the Claude Code plugin `tenjin`, registered with no step left to the person.\n *\n * WHAT IT WRITES. The wallet and the spend defaults under the data dir, as\n * before. The plugin is registered through Claude Code's own `claude plugin`\n * commands from this package's `dist/hosts/claude` folder (see\n * `plugin-registration.ts`), or written as a folder under the config dir's\n * `skills/` where no `claude` binary can be run. The plugin carries the seven\n * routing legs, the `router` MCP server, and the hooks that allow the request\n * tool and deny the legs' own tool to the model, so this command writes\n * nothing into `settings.json` or `~/.claude.json` itself.\n *\n * NO STEP IS LEFT TO THE PERSON. An agent runs this in the person's session:\n * the spend question comes back for the agent to ask there, the `claude`\n * binary is found through `CLAUDE_CODE_EXECPATH` where PATH lacks it, a failed\n * plugin command falls back to the folder, and the one step after it is\n * typing `/reload-plugins` in the same session, or starting the next one.\n *\n * THE SETTINGS INSTALL OF EARLIER RELEASES is left working until the plugin\n * has proven to load on this machine (see {@link migrateSettingsInstall}).\n */\n\nexport { AFTER_CALL_TIMEOUT_SECONDS, ROUTE_HOOK_TIMEOUT_SECONDS } from './plugin-files';\n\nexport const DISCLOSURE: readonly string[] = [\n \"What leaves this machine: the bounded text of each prompt, each native search query or URL (and, when one came back short, its status, size or error), each task handed to a subagent, and each question your assistant asks you with your answers, sent to Tenjin for the free routing gate, beside this session's id. When the gate offers free library docs for a search, that search query also goes to Tenjin's docs lookup, which asks Context7.\",\n 'What is kept when a lookup is paid: the capability chosen, a hash of the contract, a hash of the arguments, and your wallet address. No prompt text, no arguments, no hint text.',\n 'What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere.',\n];\n\n/** What the person does after a successful install, in the session they are in. */\nexport const RELOAD_STEP =\n 'type /reload-plugins in this Claude Code session, or start a new session, so Tenjin loads';\n/**\n * The same step while a settings install is still here: only a new session.\n * `/reload-plugins` would load the plugin beside the pre-upgrade `x402` server\n * that session is still running, and every event would route twice.\n */\nexport const NEW_SESSION_STEP = 'start a new Claude Code session so Tenjin loads';\n\n/** The step that loads the plugin, given whether a settings install is still here. */\nexport function loadStep(settingsInstallPresent: boolean): string {\n return settingsInstallPresent ? NEW_SESSION_STEP : RELOAD_STEP;\n}\n\nexport interface RouterInstallArgs {\n /**\n * Register the plugin for this project only (Claude Code's `local` scope,\n * `.claude/settings.local.json`), or write its folder under the project's\n * `.claude/skills/`.\n */\n project?: boolean;\n /**\n * Bring what this machine ALREADY has up to the running build: the plugin,\n * or a settings install the plugin then replaces, with no config write. A\n * refusal when nothing of ours is here. `tenjin update` spawns exactly this\n * after it swaps the binary, so the flag's name and meaning are a\n * compatibility contract.\n */\n refresh?: boolean;\n /**\n * Accept the limits the question shows instead of asking: the selector's\n * \"Use these limits\", for an agent running the user's yes.\n */\n yes?: boolean;\n /** Create no wallet, for CI and scripted machines. */\n noWallet?: boolean;\n}\n\nexport interface RouterInstallDeps extends WalletDeps {\n /** This user's running `tenjin mcp` processes; tests inject them. */\n listMcpProcesses?: ListMcpProcesses;\n /** When this build was installed; tests inject it. */\n installedAt?: InstalledAt;\n homeDir?: string;\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** Finds the `claude` binary; tests inject one, production reads PATH and `CLAUDE_CODE_EXECPATH`. */\n findClaude?: (env: NodeJS.ProcessEnv) => ClaudeBinary | null;\n /** The marketplace folder; production reads this package's `dist/hosts/claude`. */\n hostsDir?: string | null;\n /** Whether a person can answer the spend-limit question (a TTY on stdout and\n * stdin, no `--json`); injected in tests. */\n isInteractive?: boolean;\n /** The spend-limit selector; defaults to the clack list. */\n promptLimits?: (message: string) => Promise<LimitsChoice | null>;\n /** One amount question; defaults to the clack text input. */\n promptAmount?: (message: string, placeholder: string) => Promise<string | null>;\n /** The router reachability probe's transport; tests inject it. */\n fetchImpl?: typeof fetch;\n}\n\nexport type LimitsChoice = 'approve' | 'own';\n\n/** Where a settings install of this scope kept its entries and its server. */\nexport interface SettingsInstallPaths {\n settingsPath: string;\n mcpFile: string;\n mcpScope: 'user' | 'project';\n}\n\nexport function settingsInstallPaths(\n project: boolean,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): SettingsInstallPaths {\n return project\n ? {\n settingsPath: join(cwd, '.claude', 'settings.json'),\n mcpFile: projectMcpFile(cwd),\n mcpScope: 'project',\n }\n : {\n settingsPath: userSettingsPath(env, home),\n mcpFile: userMcpFile(env, home),\n mcpScope: 'user',\n };\n}\n\n/** The settings install's state, as install, update, doctor and uninstall report it. */\nexport interface Migration {\n /**\n * `none` (no settings install here), `pending` (left in place until the\n * plugin proves it loads), `done` (removed by this run), or `blocked` (the\n * settings file could not be read).\n */\n state: 'none' | 'pending' | 'done' | 'blocked';\n settingsPath: string;\n /** Why it is still pending or blocked. */\n reason?: string;\n removed?: LegacyRemoval;\n}\n\n/**\n * THE GUARDED MIGRATION. A working settings install is removed only once the\n * plugin has proven to load on this machine: Claude Code at or above the floor\n * and listing the plugin enabled (when a binary can be asked), and the\n * plugin's `alive` leg having stamped the machine from a real session. Until\n * then both stay, and the `alive` marker keeps the old legs silent in any\n * session the plugin serves. Only `install` and `update` migrate; doctor\n * reports.\n */\nexport async function pluginProof(\n claude: ClaudeCodeState,\n dataDir: string,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): Promise<{ proven: true } | { proven: false; reason: string }> {\n if (claude.binary !== null && !claude.meetsFloor) {\n return {\n proven: false,\n reason: `Claude Code ${claude.version ?? '(unknown)'} is older than the plugin needs`,\n };\n }\n if (claude.binary !== null) {\n const listing = await readPluginListing(claude.binary, env, cwd);\n if (!listing.enabled) {\n return { proven: false, reason: 'Claude Code does not list the plugin as enabled yet' };\n }\n }\n if ((await readAliveStamp(dataDir)) === null) {\n return {\n proven: false,\n reason: 'the plugin has not loaded in a Claude Code session on this machine yet',\n };\n }\n return { proven: true };\n}\n\nexport async function migrateSettingsInstall(\n legacy: LegacyInstall,\n claude: ClaudeCodeState,\n opts: { dataDir: string; env: NodeJS.ProcessEnv; cwd: string; mcpScope: 'user' | 'project' },\n): Promise<Migration> {\n if (!legacy.present) return { state: 'none', settingsPath: legacy.settingsPath };\n const proof = await pluginProof(claude, opts.dataDir, opts.env, opts.cwd);\n if (!proof.proven) {\n return { state: 'pending', settingsPath: legacy.settingsPath, reason: proof.reason };\n }\n const removed = await removeLegacyInstall(legacy, {\n binary: claude.binary,\n env: opts.env,\n cwd: opts.cwd,\n mcpScope: opts.mcpScope,\n });\n return { state: 'done', settingsPath: legacy.settingsPath, removed };\n}\n\n/**\n * `tenjin update` runs the refresh from home, where nothing proves scope. A\n * project install is taken when this directory, not being home, holds one:\n * the plugin enabled in its `settings.local.json`, its plugin folder, or a\n * settings install's entries.\n */\nasync function inferRefreshProject(\n cwd: string,\n home: string,\n env: NodeJS.ProcessEnv,\n): Promise<boolean> {\n const [cwdPath, homePath] = await Promise.all([\n realpath(cwd).catch(() => cwd),\n realpath(home).catch(() => home),\n ]);\n if (cwdPath === homePath) return false;\n const local = await readFile(join(cwd, '.claude', 'settings.local.json'), 'utf8')\n .then((raw) => JSON.parse(raw) as { enabledPlugins?: Record<string, unknown> })\n .catch(() => null);\n if (local?.enabledPlugins?.[PLUGIN_ID] === true) return true;\n if ((await folderState('local', env, home, cwd)).state === 'ours') return true;\n const paths = settingsInstallPaths(true, env, home, cwd);\n return (await inspectLegacyInstall(paths.settingsPath, paths.mcpFile)).events.length > 0;\n}\n\n/** Is any install of ours here for a refresh to bring up to date? */\nasync function somethingToRefresh(\n claude: ClaudeCodeState,\n scope: PluginScope,\n legacy: LegacyInstall,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<boolean> {\n if (legacy.present) return true;\n if ((await folderState(scope, env, home, cwd)).state === 'ours') return true;\n if (claude.binary !== null) {\n const listing = await readPluginListing(claude.binary, env, cwd);\n if (listing.id === PLUGIN_ID) return true;\n }\n return false;\n}\n\nexport async function runRouterInstall(\n args: RouterInstallArgs,\n ctx: CommandContext,\n deps: RouterInstallDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n if (!isAbsolute(home)) {\n throw new CliError('INTERNAL', 'The home directory is not an absolute path.', {\n fix: 'Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`.',\n });\n }\n const config = await loadRawConfig(ctx.dataDir); // Validate before any install writes; retired keys remain readable.\n const cwd = deps.cwd ?? process.cwd();\n // An explicit --project wins, including for a project rooted at home.\n const project =\n args.project ?? (args.refresh === true && (await inferRefreshProject(cwd, home, env)));\n const scope: PluginScope = project ? 'local' : 'user';\n const claude = await readClaudeCode(env, cwd, deps.findClaude ?? findClaudeBinary);\n const paths = settingsInstallPaths(project, env, home, cwd);\n const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);\n\n if (args.refresh === true && !(await somethingToRefresh(claude, scope, legacy, env, home, cwd))) {\n throw new CliError(\n 'REFUSED',\n `Nothing to refresh: neither the ${PLUGIN_ID} plugin nor a settings install of Tenjin is registered here.`,\n { fix: 'Run `tenjin install` to set this machine up.' },\n );\n }\n // The shelf install's gate: a refresh, `--json`, or a run with no terminal on\n // either side asks nothing. An agent's install is that run: its shell has no\n // terminal. Install then writes no spend limit at all, the same state a\n // person cancelling at the selector leaves, and its output hands the question\n // to whoever ran it (see {@link spendApproval}). Until someone answers, the\n // bare CLI's zero holds and doctor reports the question as pending.\n const humanOutput = ctx.flags.json === true ? false : (deps.isInteractive ?? ctx.io.isTTY);\n const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n // `--yes` is the selector's \"Use these limits\", answered ahead: the same\n // install, run again by an agent for the user's yes.\n const limits =\n args.refresh === true\n ? undefined\n : args.yes === true\n ? shownLimits(config)\n : canPrompt\n ? await approveLimits(config, deps)\n : {};\n const spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true, limits);\n const removedKeysLines =\n spend.removed.length > 0\n ? [\n `Removed retired settings: ${spend.removed.join(', ')}. Automatic router limits remain in effect; manual pay always requires consent.`,\n ]\n : [];\n const removedSkills = await removeRetiredSkills(home, project ? cwd : undefined);\n // BELOW THE FLOOR, A WORKING SETTINGS INSTALL WINS. The plugin's routing\n // legs need Claude Code 2.1.287, but its `alive` leg is a command that runs\n // on any version and would silence the settings install in every session,\n // leaving the machine unrouted. So nothing is registered until `claude\n // update`, and the settings install keeps routing.\n const plugin: PluginRegistration =\n !claude.meetsFloor && legacy.present\n ? deferredRegistration(scope, claude)\n : await registerPlugin({\n binary: claude.binary,\n scope,\n version: pkg.version,\n env,\n home,\n cwd,\n ...(deps.hostsDir !== undefined ? { hostsDir: deps.hostsDir } : {}),\n });\n const migration =\n legacy.unreadable !== undefined && !legacy.present\n ? { state: 'blocked' as const, settingsPath: paths.settingsPath, reason: legacy.unreadable }\n : await migrateSettingsInstall(legacy, claude, {\n dataDir: ctx.dataDir,\n env,\n cwd,\n mcpScope: paths.mcpScope,\n });\n // A `tenjin mcp` that started before this install runs the old build until\n // its session reloads it. Named, never killed.\n const pending = settingsInstallStays(migration);\n const servers = await readMcpServers(deps, { settingsInstallPending: pending });\n const serverLines =\n servers.stale > 0\n ? [paint(ctx.io, 'yellow', `! ${servers.check.detail}. ${servers.check.fix ?? ''}`.trim())]\n : [];\n const claudeCode = claudeCodeData(claude);\n const notices = refreshNotices(plugin, claude, migration);\n if (args.refresh === true) {\n // A refresh that could not register the plugin is not a converged install,\n // unless the settings install it would replace still routes here.\n if (plugin.state === 'failed' && migration.state !== 'pending') {\n throw new CliError(\n 'REFUSED',\n `The ${PLUGIN_ID} plugin could not be registered: ${plugin.reason ?? 'unknown reason'}.`,\n { fix: registrationFix(plugin), details: { plugin, claudeCode, migration } },\n );\n }\n return {\n data: {\n plugin,\n claudeCode,\n migration,\n notices,\n refresh: true,\n spend,\n removedSkills,\n scope,\n mcpServer: servers.check,\n },\n humanLines: [\n ...refreshLines(ctx, plugin, claude, migration),\n ...removedKeysLines,\n ...serverLines,\n ],\n };\n }\n // The shelf install's wallet step, unchanged except that it never asks: a\n // lookup cannot be paid without a wallet, so install makes one. A failure is\n // reported, never fatal; everything above is useful without it.\n const { resolveWallet } = await import('../commands/install-wallet');\n const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? 'flag' : undefined, false);\n // Read back AFTER the write: a machine that already carried its own caps\n // keeps them, and a readout quoting the defaults would describe limits this\n // run did not set.\n const effective = await resolveContextSettings(ctx);\n const approval =\n !canPrompt && args.yes !== true && !spend.kept.includes('maxAutoSpend')\n ? spendApproval(config, args)\n : undefined;\n // A warning, never a failure: everything above is written and correct, and\n // the network this machine is on now may not be the one it uses later.\n const router = await probeRouter(effective.baseUrl, {\n timeoutMs: ctx.flags.timeout,\n env,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n const data = {\n plugin,\n claudeCode,\n migration,\n next: nextStep(plugin, claude, wallet, migration),\n spend: {\n ...spend,\n effective: effectiveLimits(effective.policy),\n ...(approval !== undefined ? { approval } : {}),\n },\n wallet,\n router: {\n status: router.status === 'ok' ? 'ok' : 'warn',\n detail: router.detail,\n ...(router.fix !== undefined ? { fix: router.fix } : {}),\n },\n disclosure: DISCLOSURE,\n removedSkills,\n mcpServer: servers.check,\n };\n return {\n data,\n humanLines: [\n ...lines(ctx, {\n plugin,\n claude,\n migration,\n wallet,\n policy: effective.policy,\n ...(approval !== undefined ? { approval } : {}),\n router,\n }),\n ...removedKeysLines,\n ...serverLines,\n ],\n };\n}\n\nfunction claudeCodeData(claude: ClaudeCodeState): Record<string, unknown> {\n return {\n binary: claude.binary?.path ?? null,\n source: claude.binary?.source ?? null,\n version: claude.version,\n meetsFloor: claude.meetsFloor,\n ...(claude.fix !== undefined ? { fix: claude.fix } : {}),\n };\n}\n\n/**\n * The fix for a registration that did not happen, worded as a step the agent\n * can take in the session: never a command for the person to run elsewhere.\n */\nfunction registrationFix(plugin: PluginRegistration): string {\n if (plugin.id !== null && plugin.method === 'none') {\n return `${plugin.id} keeps serving this machine at the version Claude Code has; run \\`tenjin install\\` again to retry.`;\n }\n if (\n plugin.path !== undefined &&\n plugin.reason?.includes('not a folder this CLI wrote') === true\n ) {\n return `Move ${plugin.path} aside, then run \\`tenjin install\\` again.`;\n }\n return 'Run `tenjin doctor` to see the cause, then run `tenjin install` again.';\n}\n\n/** The one step after the install, for the agent to relay in the session. */\nfunction nextStep(\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n wallet: WalletOutcome,\n migration: Migration,\n): string {\n if (plugin.state === 'failed') return registrationFix(plugin);\n const steps: string[] = [];\n if (wallet.status === 'created') steps.push('fund the wallet with `tenjin wallet fund`');\n if (plugin.state === 'deferred') {\n steps.unshift('run `claude update`');\n steps.push(\n 'run `tenjin install` again; until then the earlier Tenjin setup keeps routing as before',\n );\n return steps.join(', then ');\n }\n if (!claude.meetsFloor) steps.unshift('run `claude update`');\n steps.push(loadStep(settingsInstallStays(migration)));\n return steps.join(', then ');\n}\n\n/** Is a settings install still on this machine after this run? */\nfunction settingsInstallStays(migration: Migration): boolean {\n return migration.state === 'pending' || migration.state === 'blocked';\n}\n\nfunction deferredRegistration(scope: PluginScope, claude: ClaudeCodeState): PluginRegistration {\n return {\n method: 'none',\n id: null,\n scope,\n state: 'deferred',\n version: pkg.version,\n steps: [],\n reason: `Claude Code ${claude.version ?? ''} is older than ${CLAUDE_CODE_FLOOR}, which the plugin needs, so it was not registered and the earlier settings setup keeps routing`,\n };\n}\n\n/** The status line a migration took out, in words, or nothing. */\nfunction statusLineNotice(migration: Migration): string | null {\n const status = migration.removed?.statusLine;\n if (status === 'removed') {\n return 'Removed the Tenjin status line (`tenjin status-line`) with the earlier settings setup; the plugin sets none. To keep it, set `tenjin status-line` as your Claude Code status line command.';\n }\n if (status === 'restored') {\n return 'Took the Tenjin footer out of your status line and put your own command back; the plugin sets none.';\n }\n return null;\n}\n\n/**\n * WHAT `tenjin update` PRINTS FROM THIS REFRESH. Update captures this run's\n * output and shows only its failures, so anything a person must know about a\n * refresh that succeeded rides here, as sentences the parent prints verbatim.\n */\nfunction refreshNotices(\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n migration: Migration,\n): string[] {\n const out: string[] = [];\n if (plugin.state === 'deferred') {\n out.push(\n `Claude Code ${claude.version ?? ''} is older than ${CLAUDE_CODE_FLOOR}, so the Tenjin plugin was not registered and the earlier settings setup keeps routing. Run \\`claude update\\`, then \\`tenjin install\\`.`,\n );\n } else if (plugin.state !== 'failed' && settingsInstallStays(migration)) {\n out.push(\n 'Start a new Claude Code session so the Tenjin plugin loads; the earlier settings setup is removed by the next `tenjin update` or `tenjin install` after that.',\n );\n }\n const status = statusLineNotice(migration);\n if (status !== null) out.push(status);\n return out;\n}\n\n/** What turns automatic payment on after an install that left it at zero. */\nconst AUTO_SPEND_FIX = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;\nconst DECLINED =\n 'the router then pays for nothing on its own, and the question stays open until the user answers it';\n\n/** The spend question an install that could not ask hands to its caller. */\nexport interface SpendApproval {\n /** For the agent to put to the user as written: the limits and the routing fee. */\n question: string;\n /** The limits the question shows, in USD, as the selector shows them. */\n limits: { maxAutoSpend: string; sessionBudget: string };\n /** The routing fee's terms, which a yes also approves. */\n routingFee: string;\n /** What the agent does with each answer. */\n next: string;\n /** The one command for a yes: this install again with `--yes`, as the selector's \"Use these limits\". */\n approve: string;\n /** The commands for limits of the user's own. */\n own: string;\n}\n\n/**\n * An agent runs install with `--json` or in a shell with no terminal, so the\n * CLI cannot ask. The agent can: this is what the selector would have shown\n * (the limits and the routing fee) and what to run for each answer, the same\n * shape as the `request` tool's `needs_input` step. A script or CI ignores\n * it, and the zero holds.\n */\nfunction spendApproval(config: PartialConfig, args: RouterInstallArgs): SpendApproval {\n const limits = shownLimits(config);\n const approve = yesCommand(args);\n return {\n question: spendQuestion(limits),\n limits: limitsUsd(limits),\n routingFee: ROUTING_FEE_TERMS,\n next: `In this session, show the user these limits and ask this question before you change any limit. If they say yes, run the same install again with --yes: \\`${approve}\\`. If they give other amounts, run ${OWN_LIMITS_COMMANDS}. If they say no, run nothing: ${DECLINED}.`,\n approve,\n own: OWN_LIMITS_COMMANDS.replaceAll('`', ''),\n };\n}\n\n/** The install this run was, with `--yes`: what an agent runs for the user's yes. */\nfunction yesCommand(args: RouterInstallArgs): string {\n return [\n 'tenjin install',\n ...(args.project === true ? ['--project'] : []),\n ...(args.noWallet === true ? ['--no-wallet'] : []),\n '--yes',\n ].join(' ');\n}\n\n/**\n * The one question install asks, before anything is written: approve the\n * automatic spend limits or set your own. Only a key the file does not already\n * name is asked for, because the write fills absent keys and keeps the rest.\n * The question names the routing fee and its deposits too, and either answer\n * approves it. Cancelling at any step writes nothing.\n */\nasync function approveLimits(\n config: PartialConfig,\n deps: RouterInstallDeps,\n): Promise<RouterLimits | undefined> {\n const shown = shownLimits(config);\n const askCall = config.maxAutoSpend === undefined;\n const askDay = config.sessionBudget === undefined;\n if (!askCall && !askDay) return undefined;\n const daily =\n shown.sessionBudget === 'none'\n ? 'no daily limit'\n : `$${toMoney(shown.sessionBudget).usd} a day`;\n const fee = `\\n${ROUTING_FEE_TERMS}\\n${FEE_APPROVAL}`;\n const choice = await (deps.promptLimits ?? promptLimits)(\n `The router pays for tool calls without asking, up to:\\n $${toMoney(shown.maxAutoSpend).usd} a call, ${daily}${fee}`,\n );\n if (choice === null) throw installCancelled();\n if (choice === 'approve') return shown;\n const ask = deps.promptAmount ?? promptAmount;\n return {\n maxAutoSpend: askCall\n ? await askLimit(ask, 'Most the router may pay for one call, in USD', '0.25', false)\n : shown.maxAutoSpend,\n sessionBudget: askDay\n ? await askLimit(ask, 'Most it may pay in a day, in USD, or none', '5', true)\n : shown.sessionBudget,\n };\n}\n\n/** Asks until the answer is a positive amount (or `none` for the daily limit). */\nasync function askLimit(\n ask: NonNullable<RouterInstallDeps['promptAmount']>,\n question: string,\n placeholder: string,\n allowNone: boolean,\n): Promise<string> {\n let message = question;\n for (;;) {\n const answer = await ask(message, placeholder);\n if (answer === null) throw installCancelled();\n const parsed = parseLimit(answer, allowNone);\n if (!('refusal' in parsed)) return parsed.value;\n message = `${parsed.refusal} ${question}`;\n }\n}\n\n/** Zero is refused: a zero per-call limit means the router can never pay, and\n * `router.enabled false` is how to turn it off. */\nfunction parseLimit(answer: string, allowNone: boolean): { value: string } | { refusal: string } {\n const trimmed = answer.trim();\n if (allowNone && trimmed === 'none') return { value: 'none' };\n let atomic: string;\n try {\n atomic = parseUsdToAtomic(trimmed);\n } catch (err) {\n if (err instanceof CliError) return { refusal: `${err.message}.` };\n throw err;\n }\n if (atomic === '0') return { refusal: 'The limit must be more than zero.' };\n return { value: atomic };\n}\n\nfunction installCancelled(): CliError {\n return new CliError('REFUSED', 'Install cancelled before anything was written.', {\n fix: 'Re-run `tenjin install` and choose the spend limits.',\n });\n}\n\nfunction promptLimits(message: string): Promise<LimitsChoice | null> {\n return selectOne<LimitsChoice>({\n message,\n choices: [\n { value: 'approve', label: 'Use these limits' },\n { value: 'own', label: 'Choose my own' },\n ],\n initialValue: 'approve',\n });\n}\n\nfunction promptAmount(message: string, placeholder: string): Promise<string | null> {\n return askText({ message, placeholder });\n}\n\ninterface EffectiveLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\nfunction effectiveLimits(policy: SpendPolicy): EffectiveLimits {\n return {\n maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,\n sessionBudget:\n policy.sessionBudgetAtomic === null\n ? 'no daily ceiling'\n : toMoney(policy.sessionBudgetAtomic.toString()).usd,\n };\n}\n\nfunction walletLines(ctx: CommandContext, ok: string, w: WalletOutcome): string[] {\n if (w.status === 'created') return [`${ok} Wallet created: ${w.address}`];\n if (w.status === 'existing') return [`${ok} Wallet: ${w.address}`];\n if (w.reason === 'flag') return [' No wallet yet. Create one with: tenjin wallet create'];\n return [\n paint(ctx.io, 'yellow', `! No wallet was created. ${w.warning ?? ''}`.trimEnd()),\n ` ${w.fix ?? 'Create one with: tenjin wallet create'}`,\n ];\n}\n\n/** The plugin line: what Claude Code will list, or why nothing is registered. */\nfunction pluginLines(ctx: CommandContext, plugin: PluginRegistration): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (plugin.state === 'deferred') return [warn(`${plugin.reason ?? ''}`)];\n if (plugin.state === 'failed') {\n return [warn(`The Tenjin plugin was not registered: ${plugin.reason ?? 'unknown reason'}`)];\n }\n if (plugin.method === 'skills-dir') {\n return [\n ` Plugin ${plugin.id ?? ''} written to ${plugin.path ?? ''} (${plugin.fallbackReason ?? ''})`,\n ];\n }\n return [];\n}\n\n/** The settings install's line, when there is one. */\nfunction migrationLines(ctx: CommandContext, migration: Migration): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (migration.state === 'pending') {\n return [\n ` The settings install in ${migration.settingsPath} stays until the plugin has loaded (${migration.reason ?? ''}); \\`tenjin update\\` or \\`tenjin install\\` removes it then.`,\n ];\n }\n if (migration.state === 'blocked') {\n return [warn(`${migration.settingsPath} could not be read: ${migration.reason ?? ''}`)];\n }\n if (migration.state === 'done') {\n const removed = migration.removed;\n const status = statusLineNotice(migration);\n return [\n ` Removed the earlier settings setup from ${migration.settingsPath}: the plugin carries its hooks, permissions and server`,\n ...(status !== null ? [` ${status}`] : []),\n ...(removed?.warnings ?? []).map((w) => warn(w)),\n ];\n }\n return [];\n}\n\nfunction claudeLines(ctx: CommandContext, claude: ClaudeCodeState): string[] {\n if (claude.meetsFloor) return [];\n return [\n paint(\n ctx.io,\n 'yellow',\n `! Claude Code ${claude.version ?? ''} is older than the plugin needs. ${claude.fix ?? ''}`.trim(),\n ),\n ];\n}\n\n/**\n * A few lines a first-time user can read at a glance: it worked, here is your\n * wallet, here is the one thing to do next. Paths, steps and data-handling\n * detail stay in `--json` and the docs; the terminal only grows a line when\n * something needs the user.\n */\nfunction lines(\n ctx: CommandContext,\n s: {\n plugin: PluginRegistration;\n claude: ClaudeCodeState;\n migration: Migration;\n wallet: WalletOutcome;\n policy: SpendPolicy;\n approval?: SpendApproval;\n router: RouterCheck;\n },\n): string[] {\n const ok = paint(ctx.io, 'green', '✓');\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const limits = effectiveLimits(s.policy);\n const daily =\n s.policy.sessionBudgetAtomic === null ? 'no daily limit' : `$${limits.sessionBudget} a day`;\n const spend =\n s.approval !== undefined\n ? [\n warn('Automatic payments are off until the user approves a spend limit'),\n ` Ask the user in this session: ${s.approval.question}`,\n ` Yes: ${s.approval.approve}`,\n ` Other amounts: ${s.approval.own}`,\n ` No: run nothing, ${DECLINED.replaceAll('`', '')}`,\n ]\n : s.policy.maxAutoSpendAtomic === 0n\n ? [\n warn('Automatic payments are off: every paid lookup needs your approval'),\n ` To let the router pay without asking, run: ${AUTO_SPEND_FIX}`,\n ]\n : [` Automatic router: up to $${limits.maxAutoSpend} per call; daily limit ${daily}`];\n const router =\n s.router.status === 'ok'\n ? []\n : [\n warn(`The router did not answer: ${s.router.detail}`),\n ...(s.router.fix !== undefined ? [` ${s.router.fix}`] : []),\n ];\n return [\n s.plugin.state === 'failed'\n ? warn('Tenjin could not finish setting up Claude Code')\n : s.plugin.state === 'deferred'\n ? warn('Tenjin keeps its earlier Claude Code setup until Claude Code is updated')\n : `${ok} Tenjin is set up for Claude Code (plugin ${s.plugin.id ?? PLUGIN_ID})`,\n ...walletLines(ctx, ok, s.wallet),\n ...spend,\n ...pluginLines(ctx, s.plugin),\n ...claudeLines(ctx, s.claude),\n ...migrationLines(ctx, s.migration),\n ...router,\n '',\n `Next: ${nextStep(s.plugin, s.claude, s.wallet, s.migration)}`,\n ];\n}\n\n/** \"Up to date\" only when nothing below it needs the user. */\nfunction refreshLines(\n ctx: CommandContext,\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n migration: Migration,\n): string[] {\n const issues = [\n ...pluginLines(ctx, plugin),\n ...claudeLines(ctx, claude),\n ...migrationLines(ctx, migration),\n ];\n const head =\n plugin.state === 'failed'\n ? paint(ctx.io, 'yellow', '! Tenjin is updated, but its plugin was not registered')\n : plugin.state === 'deferred'\n ? paint(ctx.io, 'yellow', '! Tenjin is updated; its plugin waits for a newer Claude Code')\n : `${paint(ctx.io, 'green', '✓')} Tenjin is up to date (plugin ${plugin.id ?? PLUGIN_ID})`;\n return [head, ...issues];\n}\n","import { lstatSync } from 'node:fs';\nimport { readdir, rm, rmdir } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport {\n CLI_SKILL_NAMES,\n readSkillFile,\n skillFrontmatterName,\n skillsDirsFor,\n} from './skill-wiring';\nimport { RETIRED_SKILL_NAMES, SHIPPED_SKILL_FILES } from './skills-source';\nimport { hasCode } from './errno';\n\nfunction isRealDirectory(path: string): boolean {\n try {\n return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n } catch (err) {\n // Linux reports ENOTDIR when an ancestor is a regular file. Nothing can\n // be installed below it, just as with an absent path. Do not follow symlinks.\n if (hasCode(err, 'ENOENT') || hasCode(err, 'ENOTDIR')) return false;\n throw err;\n }\n}\n\n/**\n * Remove only the files our named skill shipped (SKILL.md last, as the ownership\n * proof), then any directory they leave empty; preserve foreign skills and\n * adjacent user files.\n */\nexport async function removeOwnedSkill(\n name: string,\n skillsDir: string,\n): Promise<{ changed: boolean }> {\n if (!isRealDirectory(skillsDir)) {\n return { changed: false };\n }\n const skillDir = join(skillsDir, name);\n if (!isRealDirectory(skillDir)) {\n return { changed: false };\n }\n const path = join(skillDir, 'SKILL.md');\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return { changed: false };\n if (read.kind !== 'ok' || skillFrontmatterName(read.bytes.toString('utf8')) !== name) {\n return { changed: false }; // not ours to delete for sitting at our path\n }\n const shipped = (SHIPPED_SKILL_FILES as Record<string, readonly string[]>)[name] ?? [];\n const subdirs = new Set<string>();\n for (const rel of shipped) {\n if (rel === 'SKILL.md') continue;\n const file = join(skillDir, rel);\n // A symlinked `references/` would route the delete outside the skill.\n if (!isRealDirectory(dirname(file))) continue;\n subdirs.add(dirname(file));\n if (lstatSync(file, { throwIfNoEntry: false })?.isFile() === true) await rm(file);\n }\n await rm(path, { force: true });\n for (const dir of [...subdirs, skillDir].sort((a, b) => b.length - a.length)) {\n const rest = await readdir(dir).catch(() => null);\n if (rest !== null && rest.length === 0) await rmdir(dir).catch(() => undefined);\n }\n return { changed: true };\n}\n\n/**\n * Refresh retires obsolete skills without needing their old packaged source:\n * the retired names, and the shelf's CLI skills, whose `tenjin search` and\n * `tenjin publish` commands the router CLI does not ship.\n */\nexport async function removeRetiredSkills(home: string, project?: string): Promise<string[]> {\n const removed: string[] = [];\n const dirs = [...skillsDirsFor(home), ...(project ? skillsDirsFor(project) : [])];\n for (const dir of new Set(dirs)) {\n for (const name of [...RETIRED_SKILL_NAMES, ...CLI_SKILL_NAMES]) {\n if ((await removeOwnedSkill(name, dir)).changed) removed.push(join(dir, name));\n }\n }\n return removed;\n}\n","import { execFile } from 'node:child_process';\nimport { statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { delimiter, isAbsolute, join } from 'node:path';\n\n/**\n * CLAUDE CODE'S OWN COMMANDS, AND WHERE ITS CONFIG LIVES. Install, update,\n * uninstall and doctor register and read the plugin through `claude plugin`\n * and `claude mcp` rather than editing Claude Code's files, so every write is\n * Claude Code's and lands where it would put it. This module finds the binary,\n * runs it without a shell, and reads its `--json` answers. It never throws on a\n * failed command: each caller decides what a failure means.\n */\n\n/** The oldest Claude Code the plugin is built for: `mcp_tool` legs on a plugin server. */\nexport const CLAUDE_CODE_FLOOR = '2.1.287';\n\n/**\n * Claude Code's config directory: `CLAUDE_CONFIG_DIR` when set, else\n * `~/.claude`. Every path this CLI reads or writes for Claude Code goes through\n * here, so the plugin, the migration and doctor see the config the `claude`\n * commands they run see.\n */\nexport function claudeConfigDir(env: NodeJS.ProcessEnv, home: string = homedir()): string {\n const dir = env.CLAUDE_CONFIG_DIR;\n return dir !== undefined && dir.length > 0 ? dir : join(home, '.claude');\n}\n\n/** The user settings file, under {@link claudeConfigDir}. */\nexport function userSettingsPath(env: NodeJS.ProcessEnv, home: string = homedir()): string {\n return join(claudeConfigDir(env, home), 'settings.json');\n}\n\n/**\n * Where `claude mcp add -s user` writes: `.claude.json` inside\n * `CLAUDE_CONFIG_DIR` when it is set, else `~/.claude.json` beside `~/.claude`.\n */\nexport function userMcpFile(env: NodeJS.ProcessEnv, home: string = homedir()): string {\n const dir = env.CLAUDE_CONFIG_DIR;\n return dir !== undefined && dir.length > 0\n ? join(dir, '.claude.json')\n : join(home, '.claude.json');\n}\n\nexport interface ClaudeBinary {\n /** The absolute path this run executes. */\n path: string;\n /** `path` when found on PATH, `execpath` when it came from `CLAUDE_CODE_EXECPATH`. */\n source: 'path' | 'execpath';\n}\n\nfunction isFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * THE BINARY, WITHOUT ASKING ANYONE TO INSTALL IT: `claude` on PATH first,\n * then `CLAUDE_CODE_EXECPATH`, which Claude Code exports to the commands its\n * Bash tool runs (so an agent's install finds it even where PATH does not, as\n * in Claude Desktop). Null when neither exists; the caller then writes the\n * plugin folder, which needs no binary.\n */\nexport function findClaudeBinary(env: NodeJS.ProcessEnv): ClaudeBinary | null {\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of (env.PATH ?? '').split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n const candidate = join(part, `claude${ext}`);\n if (isFile(candidate)) return { path: candidate, source: 'path' };\n }\n }\n const exec = env.CLAUDE_CODE_EXECPATH;\n if (exec !== undefined && isAbsolute(exec) && isFile(exec)) {\n return { path: exec, source: 'execpath' };\n }\n return null;\n}\n\nexport interface ClaudeRun {\n /** The exit code, or null when the binary could not be started or was killed. */\n code: number | null;\n stdout: string;\n stderr: string;\n}\n\nexport interface ClaudeRunOptions {\n env: NodeJS.ProcessEnv;\n cwd: string;\n timeoutMs?: number;\n}\n\n/** One `claude` command, no shell. Never rejects. */\nexport function runClaude(\n bin: ClaudeBinary,\n args: string[],\n opts: ClaudeRunOptions,\n): Promise<ClaudeRun> {\n return new Promise((resolve) => {\n execFile(\n bin.path,\n args,\n {\n env: opts.env,\n cwd: opts.cwd,\n timeout: opts.timeoutMs ?? 30_000,\n maxBuffer: 4 * 1024 * 1024,\n windowsHide: true,\n },\n (err, stdout, stderr) => {\n const code =\n err === null\n ? 0\n : typeof (err as { code?: unknown }).code === 'number'\n ? (err as { code: number }).code\n : null;\n resolve({ code, stdout: String(stdout), stderr: String(stderr) });\n },\n );\n });\n}\n\n/**\n * The one result line a `--json` plugin command prints: the last stdout line\n * that parses as an object. Failures also print a human line on stderr, which\n * is ignored here.\n */\nexport function jsonResult(stdout: string): Record<string, unknown> | null {\n const lines = stdout.split('\\n').map((l) => l.trim());\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n const line = lines[i]!;\n if (!line.startsWith('{')) continue;\n try {\n const parsed = JSON.parse(line) as unknown;\n if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n\n/** A `--json` list (`plugin list`, `marketplace list`), or null when it is not one. */\nexport function jsonList(stdout: string): Record<string, unknown>[] | null {\n const start = stdout.indexOf('[');\n if (start === -1) return null;\n try {\n const parsed = JSON.parse(stdout.slice(start)) as unknown;\n return Array.isArray(parsed)\n ? parsed.filter(\n (row): row is Record<string, unknown> =>\n row !== null && typeof row === 'object' && !Array.isArray(row),\n )\n : null;\n } catch {\n return null;\n }\n}\n\n/** `2.1.296 (Claude Code)` to `2.1.296`. */\nexport function parseClaudeVersion(text: string): string | null {\n return /(\\d+)\\.(\\d+)\\.(\\d+)/.exec(text)?.[0] ?? null;\n}\n\n/** Is `version` at or above {@link CLAUDE_CODE_FLOOR}? */\nexport function meetsFloor(version: string, floor: string = CLAUDE_CODE_FLOOR): boolean {\n const a = version.split('.').map(Number);\n const b = floor.split('.').map(Number);\n for (let i = 0; i < 3; i += 1) {\n const x = a[i] ?? 0;\n const y = b[i] ?? 0;\n if (x !== y) return x > y;\n }\n return true;\n}\n\nexport interface ClaudeCodeState {\n binary: ClaudeBinary | null;\n /** The version `claude --version` printed, or null when it could not be read. */\n version: string | null;\n /** False only for a version read and found below the floor. */\n meetsFloor: boolean;\n /** What to do about it, worded for the session the agent runs in. */\n fix?: string;\n}\n\n/**\n * THE FLOOR'S FIX IS ONE THE AGENT RUNS: `claude update` updates the binary in\n * place, and a new session picks it up. Nobody is sent out of the session to\n * do it.\n */\nexport const CLAUDE_UPDATE_FIX =\n 'Run `claude update` in this session, then start a new Claude Code session so the newer version loads.';\n\n/** The binary and its version, read once per command. */\nexport async function readClaudeCode(\n env: NodeJS.ProcessEnv,\n cwd: string,\n find: (env: NodeJS.ProcessEnv) => ClaudeBinary | null = findClaudeBinary,\n): Promise<ClaudeCodeState> {\n const binary = find(env);\n if (binary === null) return { binary, version: null, meetsFloor: true };\n const run = await runClaude(binary, ['--version'], { env, cwd, timeoutMs: 15_000 });\n const version = run.code === 0 ? parseClaudeVersion(run.stdout) : null;\n const ok = version === null || meetsFloor(version);\n return {\n binary,\n version,\n meetsFloor: ok,\n ...(ok ? {} : { fix: CLAUDE_UPDATE_FIX }),\n };\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { inspectHooksFile } from '../lib/harness-hooks';\nimport { runClaude, type ClaudeBinary } from './claude-cli';\nimport { LEGACY_HOOK_TOOL, LEGACY_MCP_SERVER_NAME, LEGACY_REQUEST_TOOL } from './names';\nimport { classifyStatusLine, decomposeCommand, type StatusLineState } from './status-line-wiring';\n\n/**\n * THE SETTINGS-BASED INSTALL, READ AND REMOVED. Releases up to alpha.26 wrote\n * seven hook entries, an allow and a deny rule and a status line into\n * settings.json, and registered an `x402` MCP server with `claude mcp add`.\n * The plugin replaces all of it. `install` and `update` remove it only once the\n * plugin has proven to load on this machine, `uninstall` removes it outright,\n * and doctor only reads it.\n *\n * EXACT SHAPES ONLY. A hook handler is Tenjin's when it is an `mcp_tool` call\n * to the `x402` server's `hook` tool, or a command that is exactly\n * `tenjin hook <leg>` (optionally with a path). Any other command that merely\n * contains `tenjin hook` is the user's, kept and reported. Removal is handler\n * by handler, so a group holding a foreign handler beside ours keeps it. The\n * rules are touched only when the `x402` server is Tenjin's or gone, and a\n * status line only in a file that still held Tenjin's hooks, and only in the\n * exact shapes Tenjin wrote. A file is written only when something was removed\n * from it, and no key is ever added to it.\n *\n * SHIM: this module goes on or after 2026-12-01, the first release cut 30 or\n * more days after the plugin PR 2 ships, and doctor keeps naming an\n * unmigrated machine after that.\n */\n\nconst LEGACY_COMMAND_RE = /^(\\S*\\/)?tenjin hook [a-z]+$/;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** One handler, in an exact shape a settings install wrote. */\nexport function ownsLegacyHandler(handler: unknown): boolean {\n if (!isPlainObject(handler)) return false;\n if (handler.type === 'mcp_tool') {\n return handler.server === LEGACY_MCP_SERVER_NAME && handler.tool === 'hook';\n }\n const command = handler.command;\n return typeof command === 'string' && LEGACY_COMMAND_RE.test(command.trim());\n}\n\n/** A handler that mentions `tenjin hook` without being one of ours: reported, never removed. */\nfunction lookalike(handler: unknown): string | null {\n if (!isPlainObject(handler) || ownsLegacyHandler(handler)) return null;\n const command = handler.command;\n return typeof command === 'string' && command.includes('tenjin hook') ? command : null;\n}\n\nexport type McpEntryState = 'ok' | 'absent' | 'wrong-command' | 'unreadable';\n\n/**\n * What an entry named `x402` actually launches. The name proves nothing: a\n * stale entry pointing at another binary would read as a working request tool.\n */\nexport function classifyMcpEntry(entry: unknown): McpEntryState {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return 'absent';\n const { command, args } = entry as { command?: unknown; args?: unknown };\n if (typeof command !== 'string' || command.length === 0) return 'wrong-command';\n // The basename, so `/opt/homebrew/bin/tenjin` and a bare `tenjin` both pass.\n const binary = command.split(/[\\\\/]/).pop();\n const runsRouter =\n binary === 'tenjin' && Array.isArray(args) && args.length === 1 && args[0] === 'mcp';\n return runsRouter ? 'ok' : 'wrong-command';\n}\n\n/**\n * The `x402` entry in one registration file: `~/.claude.json` (or the one in\n * `CLAUDE_CONFIG_DIR`) for user scope, `<project>/.mcp.json` for project scope.\n * Only \"it is not there\" is an absence: a file that exists and cannot be read\n * or parsed says nothing about what is registered in it.\n */\nexport async function readLegacyMcpEntry(path: string): Promise<McpEntryState> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n return code === 'ENOENT' || code === 'ENOTDIR' ? 'absent' : 'unreadable';\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return 'unreadable';\n }\n const servers = (parsed as { mcpServers?: unknown } | null)?.mcpServers;\n if (servers === undefined) return 'absent';\n if (!isPlainObject(servers)) return 'unreadable';\n const entry = servers[LEGACY_MCP_SERVER_NAME];\n return entry === undefined ? 'absent' : classifyMcpEntry(entry);\n}\n\nexport interface LegacyInstall {\n settingsPath: string;\n /** The registration file the `x402` entry would be in. */\n mcpFile: string;\n /** Anything of the settings install left on this machine. */\n present: boolean;\n /** The events holding a handler of ours. */\n events: string[];\n allowRule: boolean;\n denyRule: boolean;\n statusLine: StatusLineState;\n mcp: McpEntryState;\n /** Commands that mention `tenjin hook` but are not ours, left in place. */\n lookalikes: string[];\n /** Set when the settings file could not be read; nothing is then known or removed. */\n unreadable?: string;\n}\n\n/** What the settings install left in one scope. Reads only. */\nexport async function inspectLegacyInstall(\n settingsPath: string,\n mcpFile: string,\n): Promise<LegacyInstall> {\n const mcp = await readLegacyMcpEntry(mcpFile);\n const base = {\n settingsPath,\n mcpFile,\n events: [] as string[],\n allowRule: false,\n denyRule: false,\n statusLine: 'absent' as StatusLineState,\n mcp,\n lookalikes: [] as string[],\n };\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { ...base, present: mcp === 'ok', unreadable: found.refusal.message };\n }\n const events = Object.entries(found.hooks)\n .filter(([, list]) => list.some((entry) => handlersOf(entry).some(ownsLegacyHandler)))\n .map(([event]) => event);\n const lookalikes = Object.values(found.hooks).flatMap((list) =>\n list.flatMap((entry) =>\n handlersOf(entry)\n .map(lookalike)\n .filter((c) => c !== null),\n ),\n );\n const rulesOurs = mcp === 'ok' || (mcp === 'absent' && events.length > 0);\n const allowRule = rulesOurs && listOf(found.settings, 'allow').includes(LEGACY_REQUEST_TOOL);\n const denyRule = rulesOurs && listOf(found.settings, 'deny').includes(LEGACY_HOOK_TOOL);\n const statusLine = events.length > 0 ? classifyStatusLine(found.settings.statusLine) : 'absent';\n const statusOurs = statusLine === 'ours' || statusLine === 'composed';\n return {\n ...base,\n present: events.length > 0 || allowRule || denyRule || statusOurs || mcp === 'ok',\n events,\n allowRule,\n denyRule,\n statusLine,\n lookalikes,\n };\n}\n\nfunction handlersOf(entry: unknown): unknown[] {\n return isPlainObject(entry) && Array.isArray(entry.hooks) ? entry.hooks : [];\n}\n\nfunction listOf(settings: Record<string, unknown>, key: 'allow' | 'deny'): unknown[] {\n const permissions = settings.permissions;\n if (!isPlainObject(permissions)) return [];\n const list = permissions[key];\n return Array.isArray(list) ? list : [];\n}\n\nexport interface LegacyRemoval {\n /** The events a handler of ours was taken out of. */\n events: string[];\n allowRule: boolean;\n denyRule: boolean;\n /** `removed` (ours alone), `restored` (the user's own command put back), or untouched. */\n statusLine: 'removed' | 'restored' | 'kept';\n /** The `x402` registration: removed, not there, or kept with the reason. */\n mcp: 'removed' | 'absent' | 'kept';\n wroteSettings: boolean;\n warnings: string[];\n}\n\nexport interface RemoveLegacyOptions {\n binary: ClaudeBinary | null;\n env: NodeJS.ProcessEnv;\n cwd: string;\n /** The `claude mcp` scope the `x402` entry was registered at. */\n mcpScope: 'user' | 'project';\n}\n\n/** Take out what {@link inspectLegacyInstall} found, under the exact-shape rules above. */\nexport async function removeLegacyInstall(\n found: LegacyInstall,\n opts: RemoveLegacyOptions,\n): Promise<LegacyRemoval> {\n const out: LegacyRemoval = {\n events: [],\n allowRule: false,\n denyRule: false,\n statusLine: 'kept',\n mcp: found.mcp === 'absent' ? 'absent' : 'kept',\n wroteSettings: false,\n warnings: [],\n };\n if (found.unreadable === undefined) await removeFromSettings(found, out);\n else out.warnings.push(found.unreadable);\n if (found.mcp === 'ok') await removeMcpEntry(opts, out);\n else if (found.mcp === 'wrong-command') {\n out.warnings.push(\n `an MCP server named ${LEGACY_MCP_SERVER_NAME} launches something else, so it is not Tenjin's and was left in place`,\n );\n } else if (found.mcp === 'unreadable') {\n out.warnings.push(`${found.mcpFile} could not be read, so nothing was removed from it`);\n }\n return out;\n}\n\nasync function removeFromSettings(found: LegacyInstall, out: LegacyRemoval): Promise<void> {\n const read = await inspectHooksFile(found.settingsPath);\n if ('refusal' in read) {\n out.warnings.push(read.refusal.message);\n return;\n }\n if (read.raw === null) return;\n const next: Record<string, unknown> = { ...read.settings };\n if (isPlainObject(read.settings.hooks)) {\n const hooks: Record<string, unknown> = {};\n for (const [event, list] of Object.entries(read.hooks)) {\n const kept: unknown[] = [];\n for (const entry of list) {\n const handlers = handlersOf(entry);\n const left = handlers.filter((h) => !ownsLegacyHandler(h));\n if (left.length === handlers.length) kept.push(entry);\n else if (left.length > 0) kept.push({ ...(entry as Record<string, unknown>), hooks: left });\n }\n if (kept.length !== list.length || kept.some((e, i) => e !== list[i])) out.events.push(event);\n // An event WE emptied loses its key; one that was already empty stays.\n if (kept.length > 0 || list.length === 0) hooks[event] = kept;\n }\n next.hooks = hooks;\n }\n if ((found.allowRule || found.denyRule) && isPlainObject(read.settings.permissions)) {\n const permissions = { ...read.settings.permissions };\n if (found.allowRule && Array.isArray(permissions.allow)) {\n permissions.allow = permissions.allow.filter((r) => r !== LEGACY_REQUEST_TOOL);\n out.allowRule = true;\n }\n if (found.denyRule && Array.isArray(permissions.deny)) {\n permissions.deny = permissions.deny.filter((r) => r !== LEGACY_HOOK_TOOL);\n out.denyRule = true;\n }\n next.permissions = permissions;\n }\n if (found.statusLine === 'ours') {\n delete next.statusLine;\n out.statusLine = 'removed';\n } else if (found.statusLine === 'composed' && isPlainObject(read.settings.statusLine)) {\n const command = read.settings.statusLine.command;\n const original = typeof command === 'string' ? decomposeCommand(command) : null;\n if (original !== null) {\n next.statusLine = { ...read.settings.statusLine, command: original };\n out.statusLine = 'restored';\n }\n }\n // Only a removal writes: a file holding nothing of ours keeps its bytes,\n // whatever its formatting.\n const removed =\n out.events.length > 0 || out.allowRule || out.denyRule || out.statusLine !== 'kept';\n if (!removed) return;\n const body = `${JSON.stringify(next, null, 2)}\\n`;\n const mode = await stat(read.path)\n .then((s) => ({ mode: s.mode & 0o777 }))\n .catch(() => ({}));\n // Compared again just before the rename: a concurrent edit is refused, not lost.\n if ((await readFile(read.path, 'utf8').catch(() => null)) !== read.raw) {\n out.warnings.push(`${read.path} changed while it was read, so it was left as it is`);\n Object.assign(out, { events: [], allowRule: false, denyRule: false, statusLine: 'kept' });\n return;\n }\n try {\n await writeFileAtomic(read.path, body, mode);\n out.wroteSettings = true;\n } catch (err) {\n out.warnings.push(err instanceof Error ? err.message : String(err));\n Object.assign(out, { events: [], allowRule: false, denyRule: false, statusLine: 'kept' });\n }\n}\n\n/**\n * THE `x402` REGISTRATION GOES THROUGH CLAUDE'S OWN COMMAND, and only after\n * this CLI's own read of that file found it launching `tenjin mcp`: a server\n * the read did not find is never removed by name, because another tool may\n * own one called `x402`. With no binary it is left and reported; the plugin's\n * server is namespaced and does not collide with it.\n */\nasync function removeMcpEntry(opts: RemoveLegacyOptions, out: LegacyRemoval): Promise<void> {\n if (opts.binary === null) {\n out.warnings.push(\n `the ${LEGACY_MCP_SERVER_NAME} MCP registration stays until a run with the claude binary removes it`,\n );\n return;\n }\n const run = await runClaude(\n opts.binary,\n ['mcp', 'remove', LEGACY_MCP_SERVER_NAME, '-s', opts.mcpScope],\n { env: opts.env, cwd: opts.cwd },\n );\n if (run.code === 0) out.mcp = 'removed';\n else {\n out.warnings.push(\n `claude mcp remove ${LEGACY_MCP_SERVER_NAME} did not succeed: ${(run.stderr || run.stdout).trim().slice(0, 200) || 'no output'}`,\n );\n }\n}\n\n/** The project-scope registration file. */\nexport function projectMcpFile(cwd: string): string {\n return join(cwd, '.mcp.json');\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { CliError } from '../lib/errors';\nimport { inspectHooksFile } from '../lib/harness-hooks';\n\n/**\n * The `statusLine` key in Claude Code's settings file. `install` no longer\n * sets it (a plugin cannot), so the router reads this module only to recognise\n * and take back a status line an earlier release wrote (`legacy-install.ts`).\n * The writer below stays for the shelf code that still imports it.\n *\n * The one setting the live footer needs, and the one piece of harness\n * configuration a person is most likely to have already set for themselves.\n *\n * SO IT IS NEVER REPLACED. An existing status line that is not ours is left\n * exactly as it is, and `install` prints the composition line instead;\n * `--status-line compose` writes that line only because it was asked for by\n * name. Writing over it and saying so in the output destroys a configuration\n * this CLI did not create.\n *\n * OWNERSHIP IS ONE MARKER, the command naming `tenjin status-line`, used by\n * `install`, `install --refresh`, `uninstall` and `doctor` alike, so the four\n * can never disagree about which status line is Tenjin's.\n */\n\n/** The command `install` registers, in the shape the hook entries use: a plain\n * command line on PATH, with no path into this build's dist directory. */\nexport const STATUS_LINE_COMMAND = 'tenjin status-line';\n/** Claude Code re-runs the command on this interval, in seconds. */\nexport const STATUS_LINE_REFRESH_SECONDS = 1;\n/** The marker that makes a status line ours, composed or not. */\nconst OUR_MARKER = STATUS_LINE_COMMAND;\n\n/** What the user asked for, when they asked. Absent means the default path. */\nexport type StatusLineMode = 'own' | 'compose' | 'skip';\n\nconst MODES: readonly StatusLineMode[] = ['own', 'compose', 'skip'];\n\n/** `--status-line <mode>`, refused rather than guessed at. */\nexport function statusLineMode(value: string): StatusLineMode {\n const mode = MODES.find((known) => known === value);\n if (mode === undefined) {\n throw new CliError('USAGE', `--status-line takes ${MODES.join(', ')}, not \"${value}\".`, {\n fix: 'Run `tenjin install --status-line own`.',\n });\n }\n return mode;\n}\n\n/**\n * What is in the file: ours alone, ours appended to someone else's, someone\n * else's alone, or nothing.\n */\nexport type StatusLineState = 'ours' | 'composed' | 'foreign' | 'absent';\n\nexport interface StatusLineResult {\n path: string;\n state: StatusLineState;\n /** True when this run changed the file. */\n wrote: boolean;\n /** The command now registered, when one of ours is. */\n command?: string;\n /** The exact command to set by hand, printed when a foreign line is kept. */\n compose?: string;\n /** Why nothing was written, for a file this run would not touch. */\n warning?: string;\n}\n\nexport function classifyStatusLine(value: unknown): StatusLineState {\n if (value === null || value === undefined) return 'absent';\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n // A status line whose command this build cannot read is still the user's.\n if (typeof command !== 'string' || command.trim().length === 0) return 'foreign';\n if (command.trim() === OUR_MARKER) return 'ours';\n return command.includes(OUR_MARKER) ? 'composed' : 'foreign';\n}\n\nfunction ours(): Record<string, unknown> {\n return {\n type: 'command',\n command: STATUS_LINE_COMMAND,\n refreshInterval: STATUS_LINE_REFRESH_SECONDS,\n };\n}\n\nconst shQuote = (value: string): string => `'${value.replaceAll(\"'\", String.raw`'\\''`)}'`;\nconst shUnquote = (value: string): string => value.replaceAll(String.raw`'\\''`, \"'\");\n\n/** The inner script, with the user's own command as the one hole in it. */\nfunction composedScript(existing: string): string {\n return [\n 'event=$(cat)',\n `yours=$(printf %s \"$event\" | ${existing})`,\n `tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND})`,\n 'printf %s \"$yours${tenjin:+ · $tenjin}\"',\n ].join('; ');\n}\n\n/**\n * The command a composition was built from, or null when this is not a\n * composition this build wrote. It is the exact inverse of\n * {@link composeCommand}: a hand-edited line matches nothing and is kept whole,\n * because guessing at someone's shell is how an uninstall breaks a prompt.\n */\nexport function decomposeCommand(command: string): string | null {\n const trimmed = command.trim();\n if (!trimmed.startsWith(\"sh -c '\") || !trimmed.endsWith(\"'\")) return null;\n const script = shUnquote(trimmed.slice(\"sh -c '\".length, -1));\n const prefix = 'event=$(cat); yours=$(printf %s \"$event\" | ';\n if (!script.startsWith(prefix)) return null;\n const rest = script.slice(prefix.length);\n const suffix = `); tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND}); printf %s \"$yours\\${tenjin:+ · $tenjin}\"`;\n if (!rest.endsWith(suffix)) return null;\n const existing = rest.slice(0, -suffix.length);\n return existing.length > 0 && composedScript(existing) === script ? existing : null;\n}\n\n/**\n * The user's status line with ours appended after a separator, on one line.\n *\n * The harness writes its event on stdin ONCE, so a composition cannot simply\n * run two commands in sequence: the event is captured first and replayed into\n * each. Ours contributes nothing when this session has no activity, and the\n * separator goes with it, so a quiet session looks exactly as it did before.\n */\nexport function composeCommand(existing: string): string {\n return `sh -c ${shQuote(composedScript(existing))}`;\n}\n\n/** The command a status-line setting runs, in either shape it can take. */\nfunction commandOf(value: unknown): string | undefined {\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n return typeof command === 'string' && command.trim().length > 0 ? command.trim() : undefined;\n}\n\n/** What a foreign status line's owner is told to set, verbatim. */\nfunction composeFor(value: unknown): string | undefined {\n const command = commandOf(value);\n return command === undefined ? undefined : composeCommand(command);\n}\n\nexport interface EnsureStatusLineOpts {\n mode?: StatusLineMode;\n /**\n * `install --refresh` and the refresh `tenjin update` spawns: converge a\n * status line of ours that is already registered, and ADD NOTHING. A machine\n * whose owner removed ours, or never had it, keeps that answer across every\n * upgrade without a second place to record it.\n */\n refreshOnly?: boolean;\n}\n\nexport async function ensureStatusLine(\n settingsPath: string,\n opts: EnsureStatusLineOpts = {},\n): Promise<StatusLineResult> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', wrote: false, warning: found.refusal.reason };\n }\n const { path, settings } = found;\n const current = settings.statusLine;\n const state = classifyStatusLine(current);\n if (opts.mode === 'skip') {\n return { path, state, wrote: false, ...(state === 'foreign' ? kept(current) : {}) };\n }\n if (opts.mode === 'compose') {\n const composed = composeFor(current);\n if (composed === undefined) return writeStatusLine(found, ours(), 'ours');\n // THEIR OBJECT, with the command swapped. Rebuilding it from ours would\n // drop whatever else they had set on it, such as their own padding.\n const base =\n typeof current === 'object' && current !== null && !Array.isArray(current)\n ? (current as Record<string, unknown>)\n : ours();\n return state === 'composed'\n ? { path, state, wrote: false, command: composed }\n : writeStatusLine(found, { ...base, command: composed }, 'composed');\n }\n if (state === 'foreign') {\n // NOT REPLACED, AND NOT WRITTEN AROUND. The user keeps what they set, and\n // gets the one command that adds ours to it.\n return { path, state, wrote: false, ...kept(current) };\n }\n if (state === 'composed') return { path, state, wrote: false };\n if (state === 'absent' && opts.refreshOnly === true) {\n return { path, state, wrote: false };\n }\n return writeStatusLine(found, ours(), 'ours');\n}\n\n/** `uninstall`: take out a status line of OURS, and only if it is ours alone. */\nexport async function removeStatusLine(settingsPath: string): Promise<StatusLineResult> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', wrote: false, warning: found.refusal.reason };\n }\n const { path, settings } = found;\n const current = settings.statusLine;\n const state = classifyStatusLine(current);\n if (state === 'ours') return writeStatusLine(found, undefined, 'absent');\n // A COMPOSED LINE IS MOSTLY THE USER'S TEXT, so it is not deleted: the half\n // this build wrote is unwound and their own command is put back exactly as it\n // was. A composition that was hand-edited since inverts to nothing and is\n // left whole, because guessing at someone's shell is the worse failure.\n if (state === 'composed') {\n const command = commandOf(current);\n const original = command === undefined ? null : decomposeCommand(command);\n if (original === null) return { path, state, wrote: false };\n const kept = { ...(current as Record<string, unknown>), command: original };\n return writeStatusLine(found, kept, 'foreign');\n }\n return { path, state, wrote: false };\n}\n\n/** What `doctor` reports, without writing anything. */\nexport async function inspectStatusLine(\n settingsPath: string,\n): Promise<{ path: string; state: StatusLineState; warning?: string }> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', warning: found.refusal.reason };\n }\n return { path: found.path, state: classifyStatusLine(found.settings.statusLine) };\n}\n\nfunction kept(current: unknown): { compose?: string } {\n const compose = composeFor(current);\n return compose === undefined ? {} : { compose };\n}\n\ntype Inspection = { path: string; raw: string | null; settings: Record<string, unknown> };\n\n/**\n * One key, written through the same read-compare-write the hooks writer uses:\n * every other key is copied through in its original order, the bytes are\n * re-read before the rename so a concurrent edit is refused rather than lost,\n * and the file keeps its mode.\n */\nasync function writeStatusLine(\n found: Inspection,\n value: Record<string, unknown> | undefined,\n state: StatusLineState,\n): Promise<StatusLineResult> {\n const { path, raw, settings } = found;\n const next: Record<string, unknown> = { ...settings };\n if (value === undefined) delete next.statusLine;\n else next.statusLine = value;\n const body = `${JSON.stringify(next, null, 2)}\\n`;\n const result: StatusLineResult = {\n path,\n state,\n wrote: false,\n ...(typeof value?.command === 'string' ? { command: value.command } : {}),\n };\n if (body === raw) return result;\n const mode = await stat(path)\n .then((s) => ({ mode: s.mode & 0o777 }))\n .catch(() => ({}));\n if (raw !== null && (await readFile(path, 'utf8').catch(() => null)) !== raw) {\n return {\n ...result,\n state: classifyStatusLine(settings.statusLine),\n warning: 'changed-since-read',\n };\n }\n try {\n await writeFileAtomic(path, body, mode);\n } catch (err) {\n return {\n ...result,\n state: classifyStatusLine(settings.statusLine),\n warning: err instanceof Error ? err.message : String(err),\n };\n }\n return { ...result, wrote: true };\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { versionFreeEntry } from '../commands/update';\nimport {\n claudeConfigDir,\n jsonList,\n jsonResult,\n runClaude,\n type ClaudeBinary,\n type ClaudeRun,\n} from './claude-cli';\nimport { MARKETPLACE_NAME, PLUGIN_ID, PLUGIN_NAME, SKILLS_DIR_PLUGIN_ID } from './names';\nimport { PLUGIN_DIR, renderPluginFiles } from './plugin-files';\nimport {\n inspectPluginFolder,\n pluginFolderPath,\n removePluginFolder,\n writePluginFolder,\n type FolderRemoval,\n} from './plugin-folder';\n\n/**\n * REGISTERING THE PLUGIN, WITH NO STEP LEFT TO THE PERSON. With a `claude`\n * binary (on PATH, or the one Claude Code names in `CLAUDE_CODE_EXECPATH`):\n *\n * claude plugin marketplace add <package>/dist/hosts/claude --json\n * claude plugin install tenjin@tenjin --scope <scope> --json\n * claude plugin update tenjin@tenjin --scope <scope> --json (only when the version moved)\n *\n * The marketplace is a `directory` source read in place from the installed\n * package, so there is no git or network step and the plugin is the CLI's own\n * build. Each command is non-interactive, idempotent and answers one JSON line\n * (lab, Claude Code 2.1.296): a second `add` of the same folder is a no-op, an\n * `add` of a moved folder repoints the marketplace, and `install` of an\n * installed plugin reports both versions. No binary, or a command that fails:\n * the plugin is written as a folder under the config dir's `skills/`, which\n * Claude Code loads with no command at all.\n */\n\nexport type PluginScope = 'user' | 'local';\n\nexport interface RegistrationStep {\n command: string;\n ok: boolean;\n detail?: string;\n}\n\nexport interface PluginRegistration {\n /** `plugin` through Claude's commands, `skills-dir` as a folder, `none` when neither worked. */\n method: 'plugin' | 'skills-dir' | 'none';\n /** The id Claude Code lists it under. */\n id: string | null;\n scope: PluginScope;\n /**\n * `installed` (new), `updated` (the version moved), `current` (already this\n * build), `written` (the folder), `deferred` (left for a newer Claude Code,\n * with a settings install still routing), or `failed` (nothing registered).\n */\n state: 'installed' | 'updated' | 'current' | 'written' | 'deferred' | 'failed';\n /** The marketplace folder or the plugin folder. */\n path?: string;\n version: string;\n steps: RegistrationStep[];\n /** Why the folder was written instead of running the commands. */\n fallbackReason?: string;\n /** Why nothing was registered. */\n reason?: string;\n /** A folder an earlier fallback wrote, removed because the commands now registered the plugin. */\n supersededFolder?: FolderRemoval;\n}\n\nexport interface RegisterOptions {\n binary: ClaudeBinary | null;\n scope: PluginScope;\n /** The CLI version the plugin files carry. */\n version: string;\n env: NodeJS.ProcessEnv;\n home: string;\n cwd: string;\n /** The marketplace folder; defaults to this package's `dist/hosts/claude`. */\n hostsDir?: string | null;\n}\n\n/** Where the folder fallback lives for this scope. */\nexport function folderFor(scope: PluginScope, env: NodeJS.ProcessEnv, home: string, cwd: string) {\n return pluginFolderPath(scope === 'local' ? join(cwd, '.claude') : claudeConfigDir(env, home));\n}\n\nexport async function registerPlugin(opts: RegisterOptions): Promise<PluginRegistration> {\n const folder = folderFor(opts.scope, opts.env, opts.home, opts.cwd);\n const steps: RegistrationStep[] = [];\n let fallbackReason: string;\n if (opts.binary !== null) {\n const hosts = opts.hostsDir === undefined ? await packageHostsDir() : opts.hostsDir;\n if (hosts === null) {\n fallbackReason = 'this build carries no plugin marketplace folder (dist/hosts/claude)';\n } else {\n const done = await viaPluginCommands(opts.binary, hosts, opts, steps);\n if (done.ok) {\n // A folder an earlier fallback wrote would load as a second copy.\n const superseded = await removePluginFolder(folder);\n return {\n method: 'plugin',\n id: PLUGIN_ID,\n scope: opts.scope,\n state: done.state,\n path: hosts,\n version: opts.version,\n steps,\n ...(superseded.removed ? { supersededFolder: superseded } : {}),\n };\n }\n fallbackReason = done.reason;\n }\n // NO SECOND COPY. A plugin Claude Code already has (an earlier install\n // whose update just failed, or a `tenjin` from another marketplace) would\n // load beside the folder, and every event would run both sets of legs and\n // pay twice. It is left as it is, and the run reports the failure.\n const existing = await existingCopy(opts.binary, opts.env, opts.home, opts.cwd);\n if (existing !== null) {\n return {\n method: 'none',\n id: existing,\n scope: opts.scope,\n state: 'failed',\n version: opts.version,\n steps,\n reason: `${fallbackReason}; ${existing} is already in Claude Code and was left as it is, so no second copy was written`,\n };\n }\n } else {\n fallbackReason = 'no claude binary on PATH or in CLAUDE_CODE_EXECPATH';\n // A plugin Claude's commands registered earlier must not get a second copy.\n if (await installedThroughCommands(opts.env, opts.home)) {\n return {\n method: 'plugin',\n id: PLUGIN_ID,\n scope: opts.scope,\n state: 'current',\n version: opts.version,\n steps,\n fallbackReason: `${fallbackReason}; ${PLUGIN_ID} is already registered, so it was left as it is`,\n };\n }\n }\n const written = await writePluginFolder(folder, renderPluginFiles(opts.version));\n if (written.state === 'written') {\n return {\n method: 'skills-dir',\n id: SKILLS_DIR_PLUGIN_ID,\n scope: opts.scope,\n state: 'written',\n path: folder,\n version: opts.version,\n steps,\n fallbackReason,\n };\n }\n return {\n method: 'none',\n id: null,\n scope: opts.scope,\n state: 'failed',\n path: folder,\n version: opts.version,\n steps,\n fallbackReason,\n reason: written.reason ?? 'the plugin folder could not be written',\n };\n}\n\ntype CommandsOutcome =\n { ok: true; state: 'installed' | 'updated' | 'current' } | { ok: false; reason: string };\n\nasync function viaPluginCommands(\n binary: ClaudeBinary,\n hosts: string,\n opts: RegisterOptions,\n steps: RegistrationStep[],\n): Promise<CommandsOutcome> {\n const run = (args: string[]) => runClaude(binary, args, { env: opts.env, cwd: opts.cwd });\n const scopeArgs = ['--scope', opts.scope];\n // The marketplace is declared at user scope by default, the form every\n // release since 2.1.287 takes; only a project install names its scope.\n const marketplaceScope = opts.scope === 'user' ? [] : scopeArgs;\n\n // A marketplace called `tenjin` that is not this package's is somebody\n // else's, and `add` would repoint it: it is left alone. So is every\n // marketplace when the list cannot be read, because an unread list cannot\n // prove there is no such marketplace to repoint.\n const known = await run(['plugin', 'marketplace', 'list', '--json']);\n const listed = known.code === 0 ? jsonList(known.stdout) : null;\n steps.push({\n command: 'claude plugin marketplace list --json',\n ok: listed !== null,\n ...(listed === null ? { detail: commandDetail(known) } : {}),\n });\n if (listed === null) {\n return {\n ok: false,\n reason: `claude plugin marketplace list could not be read (${commandDetail(known)}), so no marketplace was added or repointed`,\n };\n }\n const existing = listed.find((m) => m.name === MARKETPLACE_NAME);\n if (existing !== undefined && !(await ownMarketplace(existing))) {\n return {\n ok: false,\n reason: `a marketplace named ${MARKETPLACE_NAME} that this CLI did not add is already configured, so it was left as it is`,\n };\n }\n\n const add = await step(\n steps,\n ['plugin', 'marketplace', 'add', hosts, '--json', ...marketplaceScope],\n run,\n );\n if (!add.ok) return { ok: false, reason: `claude plugin marketplace add failed: ${add.detail}` };\n const install = await step(steps, ['plugin', 'install', PLUGIN_ID, ...scopeArgs, '--json'], run);\n if (!install.ok) return { ok: false, reason: `claude plugin install failed: ${install.detail}` };\n const installed = install.result?.installedVersion;\n const available = install.result?.availableVersion;\n if (typeof installed !== 'string' || typeof available !== 'string') {\n return { ok: true, state: 'installed' };\n }\n if (installed === available) return { ok: true, state: 'current' };\n const update = await step(steps, ['plugin', 'update', PLUGIN_ID, ...scopeArgs, '--json'], run);\n if (!update.ok) return { ok: false, reason: `claude plugin update failed: ${update.detail}` };\n return { ok: true, state: 'updated' };\n}\n\nasync function step(\n steps: RegistrationStep[],\n args: string[],\n run: (args: string[]) => Promise<ClaudeRun>,\n): Promise<{ ok: boolean; detail: string; result: Record<string, unknown> | null }> {\n const out = await run(args);\n const result = jsonResult(out.stdout);\n const ok =\n out.code === 0 && (result === null || result.outcome === undefined || result.outcome === 'ok');\n const detail = commandDetail(out, result);\n steps.push({ command: `claude ${args.join(' ')}`, ok, ...(ok ? {} : { detail }) });\n return { ok, detail, result };\n}\n\n/** What a failed command said: its JSON message, else its output, else how it ended. */\nfunction commandDetail(out: ClaudeRun, result: Record<string, unknown> | null = null): string {\n if (typeof result?.message === 'string') return result.message;\n const text = (out.stderr || out.stdout).trim().slice(0, 300);\n if (text.length > 0) return text;\n return out.code === null ? 'the command could not be run' : `exit ${out.code}`;\n}\n\n/**\n * Is this marketplace one `install` added? A directory source whose plugin\n * folder carries the `tenjin-cli` marker in its manifest, or, when that folder\n * is gone (a package manager removed the old version's directory), one whose\n * path is a `tenjin-cli` package's `dist/hosts/claude`.\n */\nexport async function ownMarketplace(row: Record<string, unknown>): Promise<boolean> {\n const path = typeof row.path === 'string' ? row.path : undefined;\n if (row.source !== 'directory' || path === undefined) return false;\n if ((await stat(path).catch(() => null)) === null) {\n return /tenjin-cli[\\\\/]dist[\\\\/]hosts[\\\\/]claude$/.test(path);\n }\n return (await inspectPluginFolder(join(path, PLUGIN_DIR))) === 'ours';\n}\n\n/**\n * A `tenjin` plugin Claude Code already holds that a folder would duplicate:\n * any enabled `tenjin@<marketplace>`. The folder's own `tenjin@skills-dir` is\n * not a duplicate, since writing the folder updates it in place. When the list\n * cannot be read, Claude Code's own record of installed plugins answers.\n */\nasync function existingCopy(\n binary: ClaudeBinary,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<string | null> {\n const out = await runClaude(binary, ['plugin', 'list', '--json'], { env, cwd });\n const listed = out.code === 0 ? jsonList(out.stdout) : null;\n if (listed === null) return (await installedThroughCommands(env, home)) ? PLUGIN_ID : null;\n const row = listed.find(\n (p) =>\n typeof p.id === 'string' &&\n p.id.startsWith(`${PLUGIN_NAME}@`) &&\n p.id !== SKILLS_DIR_PLUGIN_ID &&\n p.enabled === true,\n );\n return typeof row?.id === 'string' ? row.id : null;\n}\n\n/** Claude Code's own record of installed plugins, read when no binary can be asked. */\nasync function installedThroughCommands(env: NodeJS.ProcessEnv, home: string): Promise<boolean> {\n try {\n const raw = await readFile(\n join(claudeConfigDir(env, home), 'plugins', 'installed_plugins.json'),\n 'utf8',\n );\n const plugins = (JSON.parse(raw) as { plugins?: unknown }).plugins;\n return plugins !== null && typeof plugins === 'object' && PLUGIN_ID in plugins;\n } catch {\n return false;\n }\n}\n\n/**\n * THIS PACKAGE'S MARKETPLACE FOLDER, `dist/hosts/claude`, beside the bundle\n * that is running. Under pnpm the running path pins a version\n * (`.pnpm/tenjin-cli@<v>/...`), and a marketplace registered there would point\n * at a directory the next upgrade deletes, so the version-free path beside the\n * store is used when it exists, as `tenjin update` does for its re-exec.\n */\nexport async function packageHostsDir(\n moduleDir: string = dirname(fileURLToPath(import.meta.url)),\n): Promise<string | null> {\n const catalog = join(moduleDir, 'hosts', 'claude', '.claude-plugin', 'marketplace.json');\n const stable = versionFreeEntry(catalog) ?? catalog;\n if ((await stat(stable).catch(() => null))?.isFile() !== true) return null;\n return dirname(dirname(stable));\n}\n\n/** Doctor's and the migration's read: is the plugin installed and enabled? */\nexport interface PluginListing {\n /** The row for `tenjin@tenjin` or `tenjin@skills-dir`, when Claude Code lists one. */\n id: string | null;\n enabled: boolean;\n version: string | null;\n /** False when the list itself could not be read. */\n read: boolean;\n}\n\nexport async function readPluginListing(\n binary: ClaudeBinary,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): Promise<PluginListing> {\n const out = await runClaude(binary, ['plugin', 'list', '--json'], { env, cwd });\n const rows = out.code === 0 ? jsonList(out.stdout) : null;\n if (rows === null) return { id: null, enabled: false, version: null, read: false };\n const row =\n rows.find((r) => r.id === PLUGIN_ID && r.enabled === true) ??\n rows.find((r) => r.id === SKILLS_DIR_PLUGIN_ID && r.enabled === true) ??\n rows.find((r) => r.id === PLUGIN_ID || r.id === SKILLS_DIR_PLUGIN_ID);\n if (row === undefined) return { id: null, enabled: false, version: null, read: true };\n return {\n id: String(row.id),\n enabled: row.enabled === true,\n version: typeof row.version === 'string' ? row.version : null,\n read: true,\n };\n}\n\n/** Is a folder of ours there for this scope? */\nexport async function folderState(\n scope: PluginScope,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<{ path: string; state: 'absent' | 'ours' | 'foreign' }> {\n const path = folderFor(scope, env, home, cwd);\n return { path, state: await inspectPluginFolder(path) };\n}\n","import { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { HOOK_TOOL, hookToolInput, type HookKind } from './hook-tool';\nimport {\n MARKETPLACE_NAME,\n MCP_SERVER_NAME,\n PLUGIN_HOOK_TOOL,\n PLUGIN_NAME,\n PLUGIN_SERVER,\n REQUEST_TOOL,\n} from './names';\n\n/**\n * THE CLAUDE CODE PLUGIN, AS FILES. `tenjin install` registers it with Claude\n * Code's own `claude plugin` commands from the package's `dist/hosts/claude`\n * folder, which the build renders from this module, and writes the same plugin\n * folder under the config dir's `skills/` when there is no `claude` binary to\n * run. The checked-in `hosts/claude/` templates are pinned to this render by a\n * test, so the two cannot drift.\n *\n * NOTHING HERE IMPORTS MORE THAN THE NAMES AND THE PRODUCTION ORIGIN:\n * `tsup.config.ts` loads this module to render the shipped files, and its\n * import graph is the build's.\n */\n\n/**\n * The harness's kill budget for each routing leg: a stuck server never holds a\n * prompt longer than this. Every wait inside the leg is cut from it: the gate's\n * 3.5 s, which holds the paid path's 402, the reads before a deposit and the\n * paid request, with 500 ms left for the transcript read and the reply\n * (`wire.test.ts` pins the sum). A whole leg whose call carried a deposit took\n * 2.8 to 3.3 s on Base Sepolia, so it fits; a slower one (a wallet unlock, a\n * slow settlement) loses only that prompt's hint, and the SDK recovers the\n * channel on the next call.\n */\nexport const ROUTE_HOOK_TIMEOUT_SECONDS = 5;\n/**\n * The after-call entries' kill budget, longer than the rest for the one wait\n * a leg makes: a search the pre-call leg is fetching free docs for waits up to\n * `AUGMENT_WAIT_MS` (9 s) for them, and when none came back and the search was\n * short, the gate's 3.5 s follow, with startup to spare (`wire.test.ts` pins\n * the sum). Every other after-call event returns as fast as before, so the\n * number is a ceiling, not a cost.\n */\nexport const AFTER_CALL_TIMEOUT_SECONDS = 15;\n/** The `alive` leg and the two permission answers do no network work. */\nexport const LOCAL_HOOK_TIMEOUT_SECONDS = 5;\n\n/** The subagent tool, under its current name and its older one. */\nexport const DELEGATION_MATCHER = 'Agent|Task';\n/** The native tools both native arms watch. */\nexport const NATIVE_MATCHER = 'WebSearch|WebFetch';\n/** The host's question to the user, watched before it is asked and after. */\nexport const ASK_MATCHER = 'AskUserQuestion';\n\n/**\n * The `alive` leg: the plugin's `SessionStart` entry, so it runs before any\n * other event of a session. It marks the session as one the plugin serves, so\n * a settings-install leg in the same session stays silent, and stamps the\n * machine as one the plugin has loaded on, which the migration waits for. A\n * command, not an `mcp_tool` call: a session's MCP servers may still be\n * connecting when `SessionStart` fires, and a command needs nothing running.\n */\nexport const ALIVE_COMMAND = 'tenjin hook alive';\n\n/** A PreToolUse answer, as a hook command's stdout carries it. */\nfunction permissionAnswer(decision: 'allow' | 'deny', reason: string): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: 'PreToolUse',\n permissionDecision: decision,\n permissionDecisionReason: reason,\n },\n });\n}\n\n/**\n * THE HOOK LEGS' TOOL IS DENIED TO THE MODEL. Its event fields are plain\n * arguments, so the model calling it could forge a routing leg. This blocking\n * hook replaces the settings install's `permissions.deny` rule: a plugin cannot\n * carry permission rules, and a blocking hook takes precedence over allow rules\n * in every mode, bypass included, while Claude Code's own `mcp_tool` hook calls\n * still run (lab, Claude Code 2.1.296). The tool stays in the model's list. The\n * tool's transcript check (`admitHookEvent`) stays for a machine with hooks off.\n *\n * Static text, so no process starts: a fixed answer needs no CLI.\n */\nexport const DENY_HOOK_COMMAND = `echo '${permissionAnswer(\n 'deny',\n `Only the Tenjin hooks call this tool. To make a lookup, call ${REQUEST_TOOL}.`,\n)}'`;\n\n/**\n * THE REQUEST TOOL IS ALLOWED BY THE PLUGIN ITSELF, replacing the settings\n * install's `permissions.allow` rule, so an install needs no rule the user\n * adds. A hook's allow never overrides the user's own `deny` or `ask` rule for\n * the tool. The tool still pays only within the local spend policy, and an\n * amount over it returns `needs_approval` with nothing paid.\n */\nexport const ALLOW_HOOK_COMMAND = `echo '${permissionAnswer('allow', 'Tenjin lookup')}'`;\n\n/** One routing leg: Claude Code calls the plugin server's `hook` tool. */\nfunction leg(kind: HookKind, timeout = ROUTE_HOOK_TIMEOUT_SECONDS): unknown[] {\n return [\n {\n type: 'mcp_tool',\n server: PLUGIN_SERVER,\n tool: HOOK_TOOL,\n input: hookToolInput(kind),\n timeout,\n },\n ];\n}\n\nfunction command(text: string): unknown[] {\n return [{ type: 'command', command: text, timeout: LOCAL_HOOK_TIMEOUT_SECONDS }];\n}\n\n/**\n * The seven routing legs. The native tools are routed twice over one lookup:\n * BEFORE the call, with a line pointing to a paid lookup when one fits; and\n * AFTER it, only when it came back short and nothing was said before, or to\n * add the free docs the pre-call arm fetched to a search's results. A failed\n * call fires PostToolUseFailure rather than PostToolUse, so the second takes\n * both. The host's question to the user is routed the same two ways: before it\n * is asked, when a service could stand in for what it asks for, and after,\n * with the user's answers read as their own words.\n */\nexport function routerHookPlan(): { event: string; matcher?: string; hooks: unknown[] }[] {\n const afterCall = () => leg('shortfall', AFTER_CALL_TIMEOUT_SECONDS);\n return [\n { event: 'UserPromptSubmit', hooks: leg('prompt') },\n { event: 'PreToolUse', matcher: NATIVE_MATCHER, hooks: leg('native') },\n { event: 'PreToolUse', matcher: DELEGATION_MATCHER, hooks: leg('agent') },\n { event: 'PostToolUse', matcher: NATIVE_MATCHER, hooks: afterCall() },\n { event: 'PostToolUseFailure', matcher: NATIVE_MATCHER, hooks: afterCall() },\n { event: 'PreToolUse', matcher: ASK_MATCHER, hooks: leg('ask') },\n { event: 'PostToolUse', matcher: ASK_MATCHER, hooks: leg('answer') },\n ];\n}\n\n/** `hooks/hooks.json`: the `alive` leg, the seven routing legs and the two permission answers. */\nexport function renderPluginHooks(): { hooks: Record<string, unknown[]> } {\n const plan = [\n { event: 'SessionStart', hooks: command(ALIVE_COMMAND) },\n ...routerHookPlan(),\n { event: 'PreToolUse', matcher: PLUGIN_HOOK_TOOL, hooks: command(DENY_HOOK_COMMAND) },\n { event: 'PreToolUse', matcher: REQUEST_TOOL, hooks: command(ALLOW_HOOK_COMMAND) },\n ];\n const hooks: Record<string, unknown[]> = {};\n for (const { event, hooks: handlers, ...rest } of plan) {\n (hooks[event] ??= []).push({ ...rest, hooks: handlers });\n }\n return { hooks };\n}\n\n/**\n * `.mcp.json`: the server Claude Code starts for the plugin, the CLI on PATH.\n *\n * `--plugin` KEEPS IT FROM BEING SUPPRESSED. Claude Code drops a plugin's MCP\n * server whose command and arguments match a server the user configured, and\n * a settings install's `x402` entry runs `tenjin mcp`; with the same command\n * the plugin's `router` server would not start while the two coexist, its legs\n * would fail, and the old ones stay silent (checked on Claude Code 2.1.296).\n */\nexport const PLUGIN_MCP_ARGS = ['mcp', '--plugin'] as const;\n\nexport function renderPluginMcp(): { mcpServers: Record<string, unknown> } {\n return { mcpServers: { [MCP_SERVER_NAME]: { command: 'tenjin', args: [...PLUGIN_MCP_ARGS] } } };\n}\n\n/** The key whose presence marks a plugin manifest as one this CLI wrote. */\nexport const OWNER_MARKER = 'tenjin-cli';\n/** The marker's value in the checked-in templates, which carry no version. */\nconst UNBUILT = 'source';\n\nconst DESCRIPTION =\n 'Tenjin picks the right tool when your agent needs one, and one wallet on this machine pays for every call.';\n\n/**\n * `.claude-plugin/plugin.json`. The version is the CLI's, stamped at build time,\n * so Claude Code's plugin list names the build that runs; the checked-in\n * template carries none. `metadata[tenjin-cli]` is the ownership marker the\n * folder fallback, `update` and `uninstall` check before they touch a folder.\n */\nexport function renderPluginManifest(version?: string): Record<string, unknown> {\n return {\n name: PLUGIN_NAME,\n ...(version !== undefined ? { version } : {}),\n description: DESCRIPTION,\n author: { name: 'Tenjin', url: PRODUCTION_ORIGIN },\n homepage: `${PRODUCTION_ORIGIN}/agents`,\n repository: 'https://github.com/BackTrackCo/tenjin-agent',\n metadata: { [OWNER_MARKER]: version ?? UNBUILT },\n };\n}\n\n/** The plugin's folder inside the marketplace folder. */\nexport const PLUGIN_DIR = PLUGIN_NAME;\n\n/** `.claude-plugin/marketplace.json`: one plugin, read in place from the package. */\nexport function renderMarketplace(version?: string): Record<string, unknown> {\n return {\n name: MARKETPLACE_NAME,\n owner: { name: 'Tenjin', url: PRODUCTION_ORIGIN },\n description: \"Tenjin's tool router for Claude Code, installed by `tenjin install`.\",\n ...(version !== undefined ? { metadata: { version } } : {}),\n plugins: [\n {\n name: PLUGIN_NAME,\n source: `./${PLUGIN_DIR}`,\n description: DESCRIPTION,\n ...(version !== undefined ? { version } : {}),\n },\n ],\n };\n}\n\n/**\n * EVERY FILE THE PLUGIN FOLDER HOLDS, relative to the plugin's root, and the\n * only paths install, update and uninstall ever write or unlink in a folder.\n * The manifest is last: a crash mid-write never leaves a manifest pointing at\n * parts that are not there yet.\n */\nexport const PLUGIN_FILES = [\n '.mcp.json',\n 'hooks/hooks.json',\n '.claude-plugin/plugin.json',\n] as const;\n\nconst json = (value: unknown): string => `${JSON.stringify(value, null, 2)}\\n`;\n\n/** The plugin folder's files, by {@link PLUGIN_FILES} path. */\nexport function renderPluginFiles(version?: string): Record<string, string> {\n return {\n '.mcp.json': json(renderPluginMcp()),\n 'hooks/hooks.json': json(renderPluginHooks()),\n '.claude-plugin/plugin.json': json(renderPluginManifest(version)),\n };\n}\n\n/** The marketplace folder's files: its catalog and the plugin under {@link PLUGIN_DIR}. */\nexport function renderHostFiles(version?: string): Record<string, string> {\n const plugin = Object.entries(renderPluginFiles(version)).map(\n ([path, body]) => [`${PLUGIN_DIR}/${path}`, body] as const,\n );\n return {\n '.claude-plugin/marketplace.json': json(renderMarketplace(version)),\n ...Object.fromEntries(plugin),\n };\n}\n","import { lstat, readdir, readFile, rm, rmdir } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { PLUGIN_NAME } from './names';\nimport { OWNER_MARKER, PLUGIN_FILES } from './plugin-files';\n\n/**\n * THE FOLDER FALLBACK: the plugin as a folder under a config dir's `skills/`,\n * which Claude Code loads in place as `tenjin@skills-dir` with no `claude`\n * command at all (lab, 2026-10-09: the manifest's name wins over the folder's).\n * `install` writes it only where it cannot run `claude plugin`.\n *\n * OWNERSHIP RULES. Only `tenjin-router/` is ever touched, never `skills/tenjin`,\n * where tenjin.sh tells readers to drop its hosted skill. The folder is ours\n * only when it is a real directory (never followed through a link) whose\n * manifest names `tenjin` and carries the `tenjin-cli` marker. Inside it, only\n * the paths in {@link PLUGIN_FILES} are written or unlinked, so a user's own\n * `skills/` or `commands/` there survive every update and uninstall.\n */\n\nexport const FOLDER_NAME = 'tenjin-router';\n\n/** `<base>/skills/tenjin-router`, for a config dir or a project's `.claude`. */\nexport function pluginFolderPath(base: string): string {\n return join(base, 'skills', FOLDER_NAME);\n}\n\nexport type FolderState = 'absent' | 'ours' | 'foreign';\n\nexport async function inspectPluginFolder(dir: string): Promise<FolderState> {\n const entry = await lstat(dir).catch(() => null);\n if (entry === null) return 'absent';\n if (!entry.isDirectory() || entry.isSymbolicLink()) return 'foreign';\n try {\n const manifest = JSON.parse(\n await readFile(join(dir, '.claude-plugin', 'plugin.json'), 'utf8'),\n ) as { name?: unknown; metadata?: Record<string, unknown> };\n const marked =\n manifest.metadata !== null &&\n typeof manifest.metadata === 'object' &&\n OWNER_MARKER in manifest.metadata;\n return manifest.name === PLUGIN_NAME && marked ? 'ours' : 'foreign';\n } catch {\n return 'foreign';\n }\n}\n\nexport interface FolderWrite {\n path: string;\n state: 'written' | 'refused';\n reason?: string;\n}\n\n/**\n * Write the listed files, each atomically (a temp file in its own directory,\n * renamed over the file), the manifest last. A folder that exists and is not\n * ours is refused and reported, never overwritten.\n */\nexport async function writePluginFolder(\n dir: string,\n files: Record<string, string>,\n): Promise<FolderWrite> {\n const state = await inspectPluginFolder(dir);\n if (state === 'foreign') {\n return {\n path: dir,\n state: 'refused',\n reason: `${dir} exists and is not a folder this CLI wrote, so it was left as it is`,\n };\n }\n try {\n for (const path of PLUGIN_FILES) {\n const body = files[path];\n if (body === undefined) continue;\n await writeFileAtomic(join(dir, path), body);\n }\n } catch (err) {\n return {\n path: dir,\n state: 'refused',\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n return { path: dir, state: 'written' };\n}\n\nexport interface FolderRemoval {\n path: string;\n /** False when there was no folder of ours to remove. */\n removed: boolean;\n /** What is left in the folder that is not ours, relative to it. */\n left: string[];\n reason?: string;\n}\n\n/**\n * Unlink the listed files, remove the subfolders they leave empty, deepest\n * first, and the folder itself only when it is then empty. Never recursive.\n */\nexport async function removePluginFolder(dir: string): Promise<FolderRemoval> {\n const state = await inspectPluginFolder(dir);\n if (state === 'absent') return { path: dir, removed: false, left: [] };\n if (state === 'foreign') {\n return {\n path: dir,\n removed: false,\n left: [],\n reason: `${dir} is not a folder this CLI wrote, so nothing in it was removed`,\n };\n }\n for (const path of PLUGIN_FILES) await rm(join(dir, path), { force: true });\n const subdirs = [...new Set(PLUGIN_FILES.map((p) => dirname(p)).filter((d) => d !== '.'))].sort(\n (a, b) => b.split('/').length - a.split('/').length,\n );\n for (const sub of subdirs) await rmdir(join(dir, sub)).catch(() => undefined);\n const left = await listFiles(dir);\n if (left.length === 0) await rmdir(dir).catch(() => undefined);\n return { path: dir, removed: true, left };\n}\n\nasync function listFiles(dir: string): Promise<string[]> {\n const out: string[] = [];\n const walk = async (current: string): Promise<void> => {\n for (const entry of await readdir(current, { withFileTypes: true }).catch(() => [])) {\n const path = join(current, entry.name);\n if (entry.isDirectory()) await walk(path);\n else out.push(relative(dir, path).split(sep).join('/'));\n }\n };\n await walk(dir);\n return out.sort();\n}\n","import { envProxySupported, proxyVariable } from '../lib/env-proxy';\nimport { httpRequest, type HttpResponse } from '../lib/http';\nimport { isSameDeployment, PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { ROUTER_PATH } from './decision';\n\nexport interface RouterCheck {\n name: string;\n status: 'ok' | 'warn' | 'fail';\n required: boolean;\n detail: string;\n fix?: string;\n}\n\n/**\n * One cheap request to the free decision route with an empty body. It checks\n * the route is reachable and enabled, not that it routes: a 400 is the route\n * refusing that body, and a 404 is the route switched off. Nothing is signed\n * and no Jev request is spent. `doctor` fails on it; `install` only warns.\n *\n * A refusal is blamed on the layer that sent it. A proxy, firewall or VPN that\n * blocks the host is not the origin asking for credentials, and on the\n * production base URL the fix is never \"set the base URL\", because that is the\n * one setting that is already right.\n */\nexport async function probeRouter(\n baseUrl: string,\n opts: {\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n env?: NodeJS.ProcessEnv;\n /** Test seam; production asks this Node whether it can use the proxy. */\n proxySupported?: boolean;\n },\n): Promise<RouterCheck> {\n const fail = (detail: string, fix: string): RouterCheck => ({\n name: 'router',\n status: 'fail',\n required: true,\n detail,\n fix,\n });\n // `TENJIN_BASE_URL` and `--base-url` reach here unvalidated. A throw would\n // fail an install that has already written everything else.\n let url: string;\n try {\n url = new URL(ROUTER_PATH, baseUrl).toString();\n } catch {\n return fail(\n `the base URL ${JSON.stringify(baseUrl)} is not a URL`,\n `Check TENJIN_BASE_URL, or set it with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n const host = new URL(url).host;\n const probe = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n blockRedirects: true,\n // A reachability check, not use: it must not count this machine as an install.\n anonymous: true,\n jsonBody: {},\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n });\n const production = isSameDeployment(new URL(url).origin, PRODUCTION_ORIGIN);\n const checkBase = production\n ? 'Try again later.'\n : 'Check that the configured base URL names the Tenjin router (`tenjin config get baseUrl`), then try again later.';\n const env = opts.env ?? process.env;\n const network = networkFix(host, env, production, opts.proxySupported ?? envProxySupported());\n const credentials = proxyCredentialsFix(env);\n // Off production, a host that does not resolve or answer is most likely a\n // typo or a dev server that is not running, not a blocked network.\n const unreached = production ? network : checkBase;\n if (!probe.ok) {\n const t = probe.transport;\n if (t?.layer === 'proxy' && t.proxyStatus === 407) {\n return fail(\n `a proxy between this machine and ${host} asked for its own credentials (407)`,\n credentials,\n );\n }\n if (t?.layer === 'proxy') {\n return fail(\n `a proxy refused the connection to ${host} (${t.proxyStatus}), so the router never answered`,\n unreached,\n );\n }\n if (t?.layer === 'dns') {\n return fail(`${host} did not resolve (${t.code}), so the router was not reached`, unreached);\n }\n if (t?.layer === 'tls') {\n return fail(\n `the TLS connection to ${host} failed (${t.code}). A proxy that inspects TLS causes this`,\n `If this network inspects TLS, set NODE_EXTRA_CA_CERTS to its CA certificate. ${unreached}`,\n );\n }\n if (t?.layer === 'connect') {\n return fail(`could not connect to ${host} (${t.code})`, unreached);\n }\n return fail(`the router at ${url} is unreachable or erroring (${probe.message})`, unreached);\n }\n // 429 is the route's own rate limit: proof the router is there.\n if (probe.status === 200 || probe.status === 400 || probe.status === 429) {\n return { name: 'router', status: 'ok', required: true, detail: `${url} is live` };\n }\n if (probe.status === 404) {\n return fail(`the router is not enabled at ${url}`, checkBase);\n }\n if (probe.status === 407) {\n return fail(\n `a proxy between this machine and ${host} asked for its own credentials (407)`,\n credentials,\n );\n }\n if (probe.status === 401 || probe.status === 403) {\n if (!fromDeployment(probe)) {\n return fail(\n `${host} answered ${probe.status} without the headers a Tenjin deployment sends, so a proxy, firewall or VPN on the way most likely refused the request`,\n network,\n );\n }\n if (production) {\n return fail(`${url} refused this machine (${probe.status})`, checkBase);\n }\n return fail(\n `${url} is not a Tenjin router (it asked for credentials)`,\n `Set the router URL with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n if (probe.status >= 500) {\n return fail(`the router at ${url} is unreachable or erroring (${probe.status})`, checkBase);\n }\n return fail(\n `${url} answered ${probe.status}, which a Tenjin router does not`,\n 'Check that the configured base URL names a Tenjin deployment (`tenjin config get baseUrl`).',\n );\n}\n\n/**\n * Did the origin send this, rather than something in front of it? Every Vercel\n * response carries `x-vercel-id` (its own access protection included), and\n * every Tenjin API route adds `x-request-id`. A block page from a proxy,\n * firewall or VPN carries neither.\n */\nfunction fromDeployment(probe: HttpResponse): boolean {\n return probe.header('x-vercel-id') !== undefined || probe.header('x-request-id') !== undefined;\n}\n\nfunction networkFix(\n host: string,\n env: NodeJS.ProcessEnv,\n production: boolean,\n proxySupported: boolean,\n): string {\n const proxy = proxyVariable(env);\n const config = production ? \" Tenjin's own config is correct and needs no change.\" : '';\n if (proxy !== undefined && !proxySupported) {\n return `This shell sets ${proxy}, but Node ${process.versions.node} cannot send Tenjin's requests through it. Upgrade to Node 24.14 or newer, or run from a network that reaches ${host} directly.${config}`;\n }\n const via = proxy !== undefined ? ` (this shell sets ${proxy})` : '';\n return `Allow ${host} through your proxy, firewall or VPN${via}, or run from a network that reaches it.${config}`;\n}\n\nfunction proxyCredentialsFix(env: NodeJS.ProcessEnv): string {\n const proxy = proxyVariable(env) ?? 'HTTPS_PROXY';\n return `Put the proxy's credentials in ${proxy} (\\`http://user:password@proxy:port\\`), then try again.`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAAA,WAAU,gBAAgB;AACnC,SAAS,WAAAC,gBAAe;AACxB,SAAS,cAAAC,aAAY,QAAAC,aAAY;;;ACFjC,SAAS,iBAAiB;AAC1B,SAAS,SAAS,IAAI,aAAa;AACnC,SAAS,SAAS,YAAY;AAU9B,SAAS,gBAAgB,MAAuB;AAC9C,MAAI;AACF,WAAO,UAAU,MAAM,EAAE,gBAAgB,MAAM,CAAC,GAAG,YAAY,MAAM;AAAA,EACvE,SAAS,KAAK;AAGZ,QAAI,QAAQ,KAAK,QAAQ,KAAK,QAAQ,KAAK,SAAS,EAAG,QAAO;AAC9D,UAAM;AAAA,EACR;AACF;AAOA,eAAsB,iBACpB,MACA,WAC+B;AAC/B,MAAI,CAAC,gBAAgB,SAAS,GAAG;AAC/B,WAAO,EAAE,SAAS,MAAM;AAAA,EAC1B;AACA,QAAM,WAAW,KAAK,WAAW,IAAI;AACrC,MAAI,CAAC,gBAAgB,QAAQ,GAAG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AAM,EAAE;AAAA,IACpD,GAAI,EAAE,OAAO,QAAQ,SAAY,CAAC,KAAK,EAAE,OAAO,GAAG,EAAE,IAAI,CAAC;AAAA,EAC5D;AACN,SAAO;AAAA,IACL,EAAE,OAAO,UAAU,WACf,KAAK,gDAAgD,IACrD,EAAE,OAAO,UAAU,aACjB,KAAK,yEAAyE,IAC9E,GAAG,EAAE,6CAA6C,EAAE,OAAO,MAAM,SAAS;AAAA,IAChF,GAAG,YAAY,KAAK,IAAI,EAAE,MAAM;AAAA,IAChC,GAAG;AAAA,IACH,GAAG,YAAY,KAAK,EAAE,MAAM;AAAA,IAC5B,GAAG,YAAY,KAAK,EAAE,MAAM;AAAA,IAC5B,GAAG,eAAe,KAAK,EAAE,SAAS;AAAA,IAClC,GAAG;AAAA,IACH;AAAA,IACA,SAAS,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC;AAAA,EAC9D;AACF;AAGA,SAAS,aACP,KACA,QACA,QACA,WACU;AACV,QAAM,SAAS;AAAA,IACb,GAAG,YAAY,KAAK,MAAM;AAAA,IAC1B,GAAG,YAAY,KAAK,MAAM;AAAA,IAC1B,GAAG,eAAe,KAAK,SAAS;AAAA,EAClC;AACA,QAAM,OACJ,OAAO,UAAU,WACb,MAAM,IAAI,IAAI,UAAU,wDAAwD,IAChF,OAAO,UAAU,aACf,MAAM,IAAI,IAAI,UAAU,+DAA+D,IACvF,GAAG,MAAM,IAAI,IAAI,SAAS,QAAG,CAAC,iCAAiC,OAAO,MAAM,SAAS;AAC7F,SAAO,CAAC,MAAM,GAAG,MAAM;AACzB;","names":["readFile","homedir","isAbsolute","join","join","lines","join","command","command","command","join","readFile","stat","dirname","join","readdir","readFile","rm","rmdir","dirname","join","join","readFile","rm","dirname","rmdir","readdir","join","stat","readFile","dirname","join","readFile","homedir","isAbsolute"]}
|