tenjin-cli 0.1.0-alpha.14 → 0.1.0-alpha.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/README.md +18 -3
  2. package/dist/{buy-2JBYPHAI.js → buy-VIRNSYGN.js} +24 -23
  3. package/dist/{chunk-QWBUKIP2.js → chunk-2MYQN7HM.js} +66 -27
  4. package/dist/chunk-2MYQN7HM.js.map +1 -0
  5. package/dist/{chunk-DAZAXFSF.js → chunk-2RF2GIJQ.js} +57 -226
  6. package/dist/chunk-2RF2GIJQ.js.map +1 -0
  7. package/dist/{chunk-VEAERJVJ.js → chunk-3GL2Z5QK.js} +23 -9
  8. package/dist/chunk-3GL2Z5QK.js.map +1 -0
  9. package/dist/{chunk-IUQZ4Z7M.js → chunk-4CQIDQOT.js} +6 -1
  10. package/dist/chunk-4CQIDQOT.js.map +1 -0
  11. package/dist/{chunk-IXZJ3JOO.js → chunk-4KG27W2S.js} +10 -10
  12. package/dist/chunk-4KG27W2S.js.map +1 -0
  13. package/dist/{chunk-54AJIO3E.js → chunk-5QQTYWEU.js} +4 -3
  14. package/dist/chunk-5QQTYWEU.js.map +1 -0
  15. package/dist/chunk-65DTCCJ7.js +21 -0
  16. package/dist/chunk-65DTCCJ7.js.map +1 -0
  17. package/dist/{chunk-7NADDA2V.js → chunk-A5DKHMUN.js} +20 -8
  18. package/dist/chunk-A5DKHMUN.js.map +1 -0
  19. package/dist/{chunk-WYLMJQVH.js → chunk-B63XPWQ4.js} +24 -18
  20. package/dist/chunk-B63XPWQ4.js.map +1 -0
  21. package/dist/{chunk-L6G35FU5.js → chunk-CAR6FHK6.js} +5 -5
  22. package/dist/{chunk-7GJQ5RGA.js → chunk-CPCX67TI.js} +20 -22
  23. package/dist/{chunk-7GJQ5RGA.js.map → chunk-CPCX67TI.js.map} +1 -1
  24. package/dist/{chunk-XVPQGCH4.js → chunk-CQBVCYI2.js} +36 -50
  25. package/dist/chunk-CQBVCYI2.js.map +1 -0
  26. package/dist/chunk-DBU5CXBV.js +4731 -0
  27. package/dist/chunk-DBU5CXBV.js.map +1 -0
  28. package/dist/chunk-DHJD77OW.js +81 -0
  29. package/dist/chunk-DHJD77OW.js.map +1 -0
  30. package/dist/{chunk-XGZ5EVMB.js → chunk-EDZSNPE5.js} +2 -2
  31. package/dist/{chunk-736DW4V3.js → chunk-EFWZPUTC.js} +2 -2
  32. package/dist/chunk-EPFL6CTE.js +448 -0
  33. package/dist/chunk-EPFL6CTE.js.map +1 -0
  34. package/dist/{chunk-3P3ES4XU.js → chunk-GHLVXVZD.js} +3 -5
  35. package/dist/{chunk-3P3ES4XU.js.map → chunk-GHLVXVZD.js.map} +1 -1
  36. package/dist/{chunk-4UHNXY6B.js → chunk-H3SOOJ2I.js} +88 -294
  37. package/dist/chunk-H3SOOJ2I.js.map +1 -0
  38. package/dist/{chunk-MJSXP4LW.js → chunk-HPJGOLTN.js} +6 -8
  39. package/dist/{chunk-MJSXP4LW.js.map → chunk-HPJGOLTN.js.map} +1 -1
  40. package/dist/{chunk-J6FUAIRR.js → chunk-HRGBS2PA.js} +4 -6
  41. package/dist/{chunk-J6FUAIRR.js.map → chunk-HRGBS2PA.js.map} +1 -1
  42. package/dist/{chunk-FDUD3W5V.js → chunk-ITUXPJIS.js} +55 -58
  43. package/dist/chunk-ITUXPJIS.js.map +1 -0
  44. package/dist/{chunk-ETKZWJ4B.js → chunk-JBIKAAT3.js} +2 -2
  45. package/dist/{chunk-ETKZWJ4B.js.map → chunk-JBIKAAT3.js.map} +1 -1
  46. package/dist/{chunk-3ZW7HPY5.js → chunk-KAJZHIQ4.js} +13 -10
  47. package/dist/chunk-KAJZHIQ4.js.map +1 -0
  48. package/dist/{chunk-OWVVI4VQ.js → chunk-KINZ23CV.js} +107 -4535
  49. package/dist/chunk-KINZ23CV.js.map +1 -0
  50. package/dist/{chunk-PCX2JQ2J.js → chunk-LRYV3SK7.js} +9 -7
  51. package/dist/{chunk-PCX2JQ2J.js.map → chunk-LRYV3SK7.js.map} +1 -1
  52. package/dist/{chunk-ACBEHJAH.js → chunk-NIKXHWOL.js} +11 -13
  53. package/dist/{chunk-ACBEHJAH.js.map → chunk-NIKXHWOL.js.map} +1 -1
  54. package/dist/chunk-OKDRDT74.js +209 -0
  55. package/dist/chunk-OKDRDT74.js.map +1 -0
  56. package/dist/chunk-OKYSNAS3.js +2144 -0
  57. package/dist/chunk-OKYSNAS3.js.map +1 -0
  58. package/dist/{chunk-B676GPS2.js → chunk-OLWTRUTS.js} +7 -3
  59. package/dist/{chunk-B676GPS2.js.map → chunk-OLWTRUTS.js.map} +1 -1
  60. package/dist/{chunk-WU5CZPLD.js → chunk-QQ6ELLSA.js} +6 -8
  61. package/dist/{chunk-WU5CZPLD.js.map → chunk-QQ6ELLSA.js.map} +1 -1
  62. package/dist/{chunk-NAAMHWSI.js → chunk-QZ6ROAJU.js} +5 -4
  63. package/dist/chunk-QZ6ROAJU.js.map +1 -0
  64. package/dist/{chunk-GEHL43VE.js → chunk-R7RSCBI7.js} +130 -47
  65. package/dist/chunk-R7RSCBI7.js.map +1 -0
  66. package/dist/{chunk-LSWP7MU2.js → chunk-U6VPKMGC.js} +127 -27
  67. package/dist/chunk-U6VPKMGC.js.map +1 -0
  68. package/dist/{chunk-W4VW5XYB.js → chunk-US456VUI.js} +6 -6
  69. package/dist/{chunk-O75FOHXS.js → chunk-V44J2MXV.js} +64 -36
  70. package/dist/chunk-V44J2MXV.js.map +1 -0
  71. package/dist/{chunk-4Y53PDH6.js → chunk-VJQKL3YH.js} +10 -7
  72. package/dist/{chunk-4Y53PDH6.js.map → chunk-VJQKL3YH.js.map} +1 -1
  73. package/dist/{chunk-VRPLZERE.js → chunk-VJSQSLBM.js} +47 -26
  74. package/dist/chunk-VJSQSLBM.js.map +1 -0
  75. package/dist/{chunk-PKW3H26Z.js → chunk-VYOJOX4Z.js} +9 -7
  76. package/dist/chunk-VYOJOX4Z.js.map +1 -0
  77. package/dist/chunk-WY2K35OL.js +269 -0
  78. package/dist/chunk-WY2K35OL.js.map +1 -0
  79. package/dist/{chunk-PAOVPSP6.js → chunk-ZFJJ3EXC.js} +53 -5
  80. package/dist/chunk-ZFJJ3EXC.js.map +1 -0
  81. package/dist/{cli-U2BEUA55.js → cli-KKRKBU5T.js} +71 -40
  82. package/dist/{cli-U2BEUA55.js.map → cli-KKRKBU5T.js.map} +1 -1
  83. package/dist/config-JMRUNYE6.js +37 -0
  84. package/dist/discover-B5HF6SHM.js +102 -0
  85. package/dist/discover-B5HF6SHM.js.map +1 -0
  86. package/dist/doctor-ZBG7X66D.js +32 -0
  87. package/dist/edit-PZJIILQE.js +40 -0
  88. package/dist/{fund-Y5IAHZ5D.js → fund-EUDH5KPA.js} +19 -19
  89. package/dist/index.js +1 -1
  90. package/dist/{inspect-NFQ6SQQQ.js → inspect-QC6WEQPN.js} +20 -20
  91. package/dist/{install-DXX7PVUP.js → install-GNK2W3PI.js} +196 -78
  92. package/dist/install-GNK2W3PI.js.map +1 -0
  93. package/dist/outcome-KSGWZHUS.js +24 -0
  94. package/dist/pay-BC4UICPA.js +361 -0
  95. package/dist/pay-BC4UICPA.js.map +1 -0
  96. package/dist/publish-LXWFDIKF.js +42 -0
  97. package/dist/{read-W7QVRBVD.js → read-JMNUQ56P.js} +21 -21
  98. package/dist/{run-CJWPGMIQ.js → run-XYTQ5TWQ.js} +52 -45
  99. package/dist/{run-CJWPGMIQ.js.map → run-XYTQ5TWQ.js.map} +1 -1
  100. package/dist/search-TSQAB45E.js +25 -0
  101. package/dist/{send-C5EOKXOU.js → send-G746D7PQ.js} +14 -15
  102. package/dist/{send-C5EOKXOU.js.map → send-G746D7PQ.js.map} +1 -1
  103. package/dist/{session-OBCUUIFX.js → session-JBKWMJ24.js} +17 -17
  104. package/dist/{skill-heal-D6EPLPS6.js → skill-heal-WKD67SLJ.js} +17 -9
  105. package/dist/skill-heal-WKD67SLJ.js.map +1 -0
  106. package/dist/skill-placement-RIU4AMC2.js +20 -0
  107. package/dist/{uninstall-OWJNJ5LI.js → uninstall-5E263VTS.js} +12 -12
  108. package/dist/uninstall-5E263VTS.js.map +1 -0
  109. package/dist/{update-24Y2CQTT.js → update-R76LHOZW.js} +7 -8
  110. package/dist/{update-24Y2CQTT.js.map → update-R76LHOZW.js.map} +1 -1
  111. package/dist/{wallet-SLRIYJ2U.js → wallet-TQ7D5EQ7.js} +7 -8
  112. package/dist/{wallet-OFXDIIGP.js → wallet-ZAVXWLWP.js} +11 -12
  113. package/dist/wallet-ZAVXWLWP.js.map +1 -0
  114. package/docs/agent-permissions.md +17 -2
  115. package/docs/command-reference.md +84 -42
  116. package/docs/safety-model.md +9 -0
  117. package/package.json +1 -1
  118. package/skills/tenjin/SKILL.md +38 -29
  119. package/skills/tenjin-pay/SKILL.md +76 -0
  120. package/skills/tenjin-publish/SKILL.md +10 -7
  121. package/skills/tenjin-search/SKILL.md +18 -13
  122. package/skills/tenjin-search/references/permissions.md +9 -3
  123. package/dist/chunk-3ZW7HPY5.js.map +0 -1
  124. package/dist/chunk-4UHNXY6B.js.map +0 -1
  125. package/dist/chunk-54AJIO3E.js.map +0 -1
  126. package/dist/chunk-7NADDA2V.js.map +0 -1
  127. package/dist/chunk-DAZAXFSF.js.map +0 -1
  128. package/dist/chunk-DTCXO7HS.js +0 -791
  129. package/dist/chunk-DTCXO7HS.js.map +0 -1
  130. package/dist/chunk-FDUD3W5V.js.map +0 -1
  131. package/dist/chunk-GEHL43VE.js.map +0 -1
  132. package/dist/chunk-IU2HVT3Y.js +0 -313
  133. package/dist/chunk-IU2HVT3Y.js.map +0 -1
  134. package/dist/chunk-IUQZ4Z7M.js.map +0 -1
  135. package/dist/chunk-IXZJ3JOO.js.map +0 -1
  136. package/dist/chunk-LSWP7MU2.js.map +0 -1
  137. package/dist/chunk-NAAMHWSI.js.map +0 -1
  138. package/dist/chunk-O75FOHXS.js.map +0 -1
  139. package/dist/chunk-OWVVI4VQ.js.map +0 -1
  140. package/dist/chunk-PAOVPSP6.js.map +0 -1
  141. package/dist/chunk-PKW3H26Z.js.map +0 -1
  142. package/dist/chunk-PQZVDCCA.js +0 -125
  143. package/dist/chunk-PQZVDCCA.js.map +0 -1
  144. package/dist/chunk-QWBUKIP2.js.map +0 -1
  145. package/dist/chunk-VEAERJVJ.js.map +0 -1
  146. package/dist/chunk-VRPLZERE.js.map +0 -1
  147. package/dist/chunk-WYLMJQVH.js.map +0 -1
  148. package/dist/chunk-XVPQGCH4.js.map +0 -1
  149. package/dist/chunk-ZQIQ55KK.js +0 -51
  150. package/dist/chunk-ZQIQ55KK.js.map +0 -1
  151. package/dist/config-CNUIX23Q.js +0 -32
  152. package/dist/doctor-QJJXRWTO.js +0 -31
  153. package/dist/edit-HJ44P44P.js +0 -40
  154. package/dist/install-DXX7PVUP.js.map +0 -1
  155. package/dist/outcome-ANV4QIED.js +0 -24
  156. package/dist/publish-PCBTCXCZ.js +0 -42
  157. package/dist/search-JGAVKTYJ.js +0 -25
  158. package/dist/skill-heal-D6EPLPS6.js.map +0 -1
  159. package/dist/uninstall-OWJNJ5LI.js.map +0 -1
  160. /package/dist/{buy-2JBYPHAI.js.map → buy-VIRNSYGN.js.map} +0 -0
  161. /package/dist/{chunk-L6G35FU5.js.map → chunk-CAR6FHK6.js.map} +0 -0
  162. /package/dist/{chunk-XGZ5EVMB.js.map → chunk-EDZSNPE5.js.map} +0 -0
  163. /package/dist/{chunk-736DW4V3.js.map → chunk-EFWZPUTC.js.map} +0 -0
  164. /package/dist/{chunk-W4VW5XYB.js.map → chunk-US456VUI.js.map} +0 -0
  165. /package/dist/{config-CNUIX23Q.js.map → config-JMRUNYE6.js.map} +0 -0
  166. /package/dist/{doctor-QJJXRWTO.js.map → doctor-ZBG7X66D.js.map} +0 -0
  167. /package/dist/{edit-HJ44P44P.js.map → edit-PZJIILQE.js.map} +0 -0
  168. /package/dist/{fund-Y5IAHZ5D.js.map → fund-EUDH5KPA.js.map} +0 -0
  169. /package/dist/{inspect-NFQ6SQQQ.js.map → inspect-QC6WEQPN.js.map} +0 -0
  170. /package/dist/{outcome-ANV4QIED.js.map → outcome-KSGWZHUS.js.map} +0 -0
  171. /package/dist/{publish-PCBTCXCZ.js.map → publish-LXWFDIKF.js.map} +0 -0
  172. /package/dist/{read-W7QVRBVD.js.map → read-JMNUQ56P.js.map} +0 -0
  173. /package/dist/{search-JGAVKTYJ.js.map → search-TSQAB45E.js.map} +0 -0
  174. /package/dist/{session-OBCUUIFX.js.map → session-JBKWMJ24.js.map} +0 -0
  175. /package/dist/{wallet-OFXDIIGP.js.map → skill-placement-RIU4AMC2.js.map} +0 -0
  176. /package/dist/{wallet-SLRIYJ2U.js.map → wallet-TQ7D5EQ7.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/open-url.ts","../src/commands/fund.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\n\n/**\n * Open a URL in the platform's default browser, best-effort. Follows the\n * passphrase.ts subprocess rules: an argv array (never a shell), a hard\n * timeout, and failure as a return value rather than a throw — callers print\n * the URL first, so a machine without an opener degrades to copy/paste.\n * Windows uses rundll32's FileProtocolHandler because `start` exists only\n * inside cmd.exe, and spawning a shell around an attacker-influenced string is\n * the injection shape this module exists to avoid.\n */\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n execFileImpl?: typeof execFile;\n}\n\nconst OPEN_TIMEOUT_MS = 5000;\n\nexport function openerFor(platform: NodeJS.Platform): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: 'open', args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n return { cmd: 'xdg-open', args: [] };\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const { cmd, args } = openerFor(opts.platform ?? process.platform);\n const run = opts.execFileImpl ?? execFile;\n return await new Promise((resolve) => {\n run(cmd, [...args, url], { timeout: OPEN_TIMEOUT_MS, windowsHide: true }, (err) =>\n resolve(err === null),\n );\n });\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { buildSiwxHeader, SIWX_HEADER } from '../lib/siwx';\nimport { SESSION_CHAIN_ID } from '../lib/session-key';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { toMoney } from '../lib/money';\nimport { emitNotice, emitWriteNotice } from '../lib/output';\nimport { openInBrowser } from '../lib/open-url';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin fund`: card-fund THIS wallet via Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend to mint a\n * Coinbase-hosted checkout URL for that same address (the server refuses any\n * other address, per Coinbase's onboarding-verified auth model). The money\n * moves entirely on Coinbase's side; the minted session grants no spending\n * power over the wallet. Two Coinbase properties shape the UX here: the URL is\n * single-use and expires in ~5 minutes (mint fresh per run, open immediately,\n * never persist), and it is bound to this machine's public IP at mint time, so\n * it must be opened in a browser on this machine/network.\n */\n\n/** The only host a minted checkout URL may point at; anything else is refused unopened. */\nconst CHECKOUT_HOST = 'pay.coinbase.com';\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = 'https://tenjin.blog';\n/** Matches the server's presetAmount bound (app/api/cdp/session bodySchema). */\nconst MAX_PRESET_USD = 100_000;\nconst POLL_INTERVAL_MS = 5_000;\nconst POLL_TIMEOUT_MS = 600_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline won. Only `timed-out` says anything about the purchase.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to Coinbase (clamped upward to its own floor there). */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** Poll the balance after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n pollIntervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n const signer = await provider.getSigner();\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const baseUrl = FUND_ORIGIN;\n const rpcUrl = settings.rpcUrl.value;\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting, because\n // the envelope carrying the link is written only after runFund returns, and a\n // link that expires in ~5 minutes is worthless after a 10-minute poll.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n\n // Read the balance BEFORE minting so the poll has a baseline; an RPC flake\n // here only disables the wait, it never blocks funding.\n const startBalance = shouldWait ? await balanceOrUndefined(desc, rpcUrl) : undefined;\n\n const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: SESSION_CHAIN_ID });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n jsonBody: {\n mode: 'onramp',\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/cdp/session`, request);\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n const url = checkoutUrlFrom(res.status, res.json);\n\n // The link goes out on EVERY surface and before any waiting: it is single-use\n // with a ~5 minute expiry, and the stdout envelope that also carries it is\n // written only after this function returns. A piped or agent-driven run is\n // exactly the case that must not get the link after it has died, so these\n // three lines are write-notices (stderr, no TTY gate, no --json gate) rather\n // than human-mode notices. stdout stays exactly one JSON object.\n emitWriteNotice(ctx.io, `Coinbase Onramp checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\n 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required.',\n );\n\n let opened = false;\n if (opts.open !== false && ctx.io.isTTY) {\n opened = await (opts.openUrl ?? openInBrowser)(url);\n emitNotice(\n ctx.io,\n opened ? 'Opened in your default browser.' : 'Could not open a browser; use the link above.',\n { json: ctx.flags.json },\n );\n }\n\n const funded =\n shouldWait && startBalance !== undefined\n ? await pollForFunds(ctx, desc, rpcUrl, startBalance, opts)\n : undefined;\n if (funded !== undefined) {\n emitWriteNotice(ctx.io, 'USDC arrived - you can close the checkout tab.');\n }\n const pollStatus: FundPollStatus = !shouldWait\n ? 'skipped'\n : startBalance === undefined\n ? 'unavailable'\n : funded !== undefined\n ? 'arrived'\n : 'timed-out';\n\n const balanceAtomic = funded ?? startBalance;\n return {\n data: {\n address,\n checkoutUrl: url,\n opened,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n funded: funded !== undefined,\n pollStatus,\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n },\n humanLines:\n funded !== undefined\n ? [`Funded: balance is now ${toMoney(funded.toString()).usd} USDC on Base.`]\n : [\n 'Checkout link issued (printed above).',\n ...(pollStatus === 'unavailable'\n ? ['Could not read the balance to wait on it; the link is unaffected.']\n : []),\n 'Confirm arrival later with `tenjin wallet balance`.',\n ],\n };\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin fund 5',\n });\n }\n return n;\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on Coinbase's\n * checkout host before anything else sees it: a compromised or misconfigured\n * server must not be able to steer the user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (parsed !== undefined && parsed.protocol === 'https:' && parsed.host === CHECKOUT_HOST) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https://${CHECKOUT_HOST}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Coinbase Onramp is not available in your region.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', 'The funding endpoint rejected the signed proof.', {\n fix: 'Check this machine’s clock, then retry.',\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'The funding endpoint is rate limited right now.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError(\n 'API_UNREACHABLE',\n 'Production has no Coinbase Onramp configured right now.',\n {\n fix: 'Retry later.',\n },\n );\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(\n desc: { address: string },\n rpcUrl: string,\n): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(desc.address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wait for the purchased USDC to land: any balance above the pre-mint baseline\n * counts (Coinbase clamps presets, so an exact-amount check would be wrong).\n * RPC flakes mid-poll are tolerated; the deadline is the only exit besides\n * arrival, and timing out is a normal outcome (the human may still be paying),\n * not an error.\n */\nasync function pollForFunds(\n ctx: CommandContext,\n desc: { address: string },\n rpcUrl: string,\n startBalance: bigint,\n opts: FundOptions,\n): Promise<bigint | undefined> {\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;\n const deadline = Date.now() + (opts.pollTimeoutMs ?? POLL_TIMEOUT_MS);\n emitNotice(ctx.io, 'Waiting for the USDC to arrive (Ctrl-C is safe; the purchase is not).', {\n json: ctx.flags.json,\n });\n while (Date.now() < deadline) {\n await sleep(interval);\n const balance = await balanceOrUndefined(desc, rpcUrl);\n if (balance !== undefined && balance > startBalance) return balance;\n }\n return undefined;\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,KAAK,UAAU,CAAC,OAAe,IAAI,QAAc,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACvF,QAAM,WAAW,KAAK,kBAAkB;AACxC,QAAM,WAAW,KAAK,IAAI,KAAK,KAAK,iBAAiB;AACrD,aAAW,IAAI,IAAI,yEAAyE;AAAA,IAC1F,MAAM,IAAI,MAAM;AAAA,EAClB,CAAC;AACD,SAAO,KAAK,IAAI,IAAI,UAAU;AAC5B,UAAM,MAAM,QAAQ;AACpB,UAAM,UAAU,MAAM,mBAAmB,MAAM,MAAM;AACrD,QAAI,YAAY,UAAa,UAAU,aAAc,QAAO;AAAA,EAC9D;AACA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/config.ts","../src/lib/clack.ts","../src/lib/harness-hooks.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { styleText } from 'node:util';\nimport { CliError } from '../lib/errors';\nimport { confirmChoice } from '../lib/clack';\nimport {\n inspectFreeVerbRules,\n MODE_GATED_RULES,\n retractModeGatedRules,\n wireFreeVerbAllowlist,\n type PermissionsResult,\n} from '../lib/harness-permissions';\nimport { modeGatedPointer } from '../lib/permissions';\nimport { stopHookIsCurrent } from '../lib/harness-hooks';\nimport {\n CONFIG_KEYS,\n HOOKS_CONFIG_KEYS,\n PUBLISH_CONFIG_KEYS,\n PublishModeSchema,\n RawConfigSchema,\n SEND_MAX_UNSET,\n UPDATE_CONFIG_KEYS,\n loadRawConfig,\n parseSearchHookModeFlag,\n parseStopNagFlag,\n parseUpdateModeFlag,\n resolveSettings,\n} from '../lib/config';\nimport type {\n EffectiveSettings,\n HooksConfigKey,\n PartialConfig,\n Provenance,\n PublishConfigKey,\n PublishMode,\n ScalarConfigKey,\n SearchHookMode,\n UpdateConfigKey,\n} from '../lib/config';\nimport {\n detectHarnesses,\n harnessInPlay,\n harnessTargetDir,\n onPath,\n type HarnessTarget,\n} from '../lib/skill-wiring';\nimport { loadProjectConfig } from '../lib/settings';\nimport { configPath } from '../lib/paths';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport type { Money } from '../schemas';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * How one config key is presented in `data`. `value` is the machine form: dual\n * Money for the spend keys, the stored string for `confirm`/URLs, the string[]\n * for the allowlist. `threshold` rides along only for `confirm: above:<atomic>`\n * so an agent reads the dollar amount without re-parsing the string.\n */\ninterface RenderedValue {\n value: Money | string | string[] | boolean;\n threshold?: Money;\n}\ninterface RenderedSetting extends RenderedValue {\n source: Provenance;\n}\n\n/**\n * Seams for the one `config set` path that touches a file outside the data dir.\n * Tests inject all of them; nothing here is reachable from a flag.\n */\nexport interface ConfigSetDeps {\n /** Home whose `.claude/settings.json` is synced; defaults to os.homedir(). */\n homeDir?: string;\n /** Overrides TTY detection, exactly as install's own seam does. */\n isInteractive?: boolean;\n /** The yes/no for a loosening write; defaults to the clack confirm (default yes). */\n confirmRule?: (label: string) => Promise<boolean>;\n /** Whether this machine's harness is Claude Code (the only settings file we write).\n * Absent, it is DETECTED the way install and doctor detect it. */\n harnessIsClaude?: boolean;\n /** The retraction-only pass `review` runs; defaults to the real writer. */\n retractModeGated?: (home: string) => Promise<PermissionsResult>;\n /** Whether the installed Stop hook matches this build; defaults to reading it. */\n stopHookIsCurrent?: (dataDir: string) => Promise<boolean>;\n /** PATH probe for harness detection; defaults to probing `env.PATH`. */\n which?: (bin: string) => boolean;\n /** Environment for that probe; defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n inspectAllowlist?: typeof inspectFreeVerbRules;\n wireAllowlist?: (home: string, mode: PublishMode) => Promise<PermissionsResult>;\n}\n\nconst CONFIRM_ABOVE = 'above:';\nconst KEY_WIDTH = Math.max(\n ...[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...UPDATE_CONFIG_KEYS].map(\n (key) => key.length,\n ),\n);\n\n/**\n * A one-line human description per key, appended (dim) to the bare `config`\n * listing only. Machine `data` is unchanged; these are humanLines decoration.\n */\nconst KEY_DESCRIPTIONS: Record<string, string> = {\n maxAutoSpend: 'auto-approve a read up to this amount',\n sessionBudget: 'cap on total auto-spend per session',\n confirm: 'when to ask before paying',\n sendMaxAmount:\n 'hard cap per tenjin send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes',\n allowlistCreators: 'only auto-pay these creators (empty = any)',\n baseUrl: 'Tenjin API base URL',\n rpcUrl: 'Base RPC endpoint for balance reads',\n evalCohort: 'opt in to the search evaluation cohort',\n 'publish.mode': 'review=always ask, auto=ask on findings, full-auto=only hard blocks stop it',\n 'publish.defaultPrice': 'price used when none is given',\n 'hooks.searchMode':\n 'harness WebSearch hook: auto=ask Tenjin first, remind=static reminder, off=inert',\n 'hooks.stopNag':\n 'end-of-turn reminder about searches nothing answered yet: on=both arms, deliberate-only=drop the batched web-search arm, off=neither',\n 'update.mode':\n 'nudge=report a newer version (stderr line, JSON envelope, hook output), off=neither report nor ask npm',\n};\n\nfunction isPublishKey(key: string): key is PublishConfigKey {\n return (PUBLISH_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHooksKey(key: string): key is HooksConfigKey {\n return (HOOKS_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isUpdateKey(key: string): key is UpdateConfigKey {\n return (UPDATE_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/**\n * Show every effective key with its value and provenance. `data` is keyed by\n * config key; provenance comes from resolveSettings over the *raw* file (not the\n * defaults-merged config), so a key the user never set reads `default`, not\n * `file`.\n */\nexport async function runConfigList(ctx: CommandContext): Promise<CommandResult> {\n const settings = await resolveFromContext(ctx);\n const data: Record<string, RenderedSetting> = {};\n const humanLines: string[] = [];\n for (const key of CONFIG_KEYS) {\n const entry = renderSetting(key, settings[key].value, settings[key].source);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of PUBLISH_CONFIG_KEYS) {\n const entry = renderPublishSetting(key, settings);\n data[key] = entry;\n humanLines.push(describedLine(key, entry, downgradeNote(key, settings)));\n }\n for (const key of HOOKS_CONFIG_KEYS) {\n const entry = renderHooksSetting(key, settings);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of UPDATE_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.updateMode.value,\n source: settings.updateMode.source,\n };\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n return { data, humanLines };\n}\n\n/** Same per-key shape as list, for one key. Unknown key is a USAGE failure. */\nexport async function runConfigGet(\n { key }: { key: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) {\n const settings = await resolveFromContext(ctx);\n const entry = renderPublishSetting(key, settings);\n return {\n data: { key, ...entry },\n humanLines: [withNote(formatLine(key, entry), downgradeNote(key, settings))],\n };\n }\n if (isHooksKey(key)) {\n const entry = renderHooksSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isUpdateKey(key)) {\n const { updateMode } = await resolveFromContext(ctx);\n const entry: RenderedSetting = { value: updateMode.value, source: updateMode.source };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n const configKey = assertKey(key);\n const settings = await resolveFromContext(ctx);\n const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * Parse the value for this key, then persist it merged into the existing raw\n * file — never materializing defaults for keys the user did not set, so\n * provenance stays truthful. The written key now reads `file`.\n */\nexport async function runConfigSet(\n { key, value }: { key: string; value: string },\n ctx: CommandContext,\n deps: ConfigSetDeps = {},\n): Promise<CommandResult> {\n if (isPublishKey(key)) return setPublishKey(key, value, ctx, deps);\n if (isHooksKey(key)) return setHooksKey(key, value, ctx, deps);\n if (isUpdateKey(key)) return setUpdateKey(key, value, ctx);\n const configKey = assertKey(key);\n const stored = parseValue(configKey, value);\n await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));\n const entry = renderSetting(configKey, stored, 'file');\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * `config set publish.mode|publish.defaultPrice`. mode validates to the enum;\n * defaultPrice parses decimal USD at the edge into atomic (matching the spend\n * keys). The subkey is merged into the nested publish block, so a sibling subkey\n * (or an unknown one a newer CLI wrote) is preserved.\n */\nasync function setPublishKey(\n key: PublishConfigKey,\n value: string,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<CommandResult> {\n const entry: RenderedSetting =\n key === 'publish.mode'\n ? { value: parsePublishMode(value), source: 'file' }\n : { value: toMoney(parseUsdToAtomic(value)), source: 'file' };\n const subkey = key === 'publish.mode' ? 'mode' : 'defaultPrice';\n const stored = key === 'publish.mode' ? (entry.value as string) : (entry.value as Money).atomic;\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, [subkey]: stored },\n }));\n const humanLines = [formatLine(key, entry)];\n if (key !== 'publish.mode') return { data: { key, ...entry }, humanLines };\n\n // The mode decides whether a publish asks; the harness rule decides whether the\n // harness asks ANYWAY. Settling one and leaving the other to the next `tenjin\n // install` is the seam that made publish.mode look broken (tenjin-agent #161),\n // so the two move together from here too.\n const allowlist = await syncPublishRule(entry.value as PublishMode, ctx, deps);\n return {\n data: { key, ...entry, allowlist },\n humanLines: [...humanLines, ...allowlistLines(allowlist)],\n };\n}\n\n/**\n * What `config set publish.mode` did about the harness rule the mode carries.\n * `skipped` names why nothing was written; `pointer` is the line to show when it\n * is the operator's move.\n */\ninterface AllowlistSync {\n added: string[];\n removed: string[];\n skipped?: 'not-claude' | 'no-tty' | 'declined' | 'unwritable';\n pointer?: string;\n}\n\n/** Names what the write actually carries: on a machine that never ran `install`,\n * the free tier is pending too, and a question naming two lines while eleven\n * land is asking about something else. */\nfunction publishRuleQuestion(mode: PublishMode, pending: readonly string[]): string {\n const gated = new Set<string>(MODE_GATED_RULES);\n const others = pending.filter((rule) => !gated.has(rule)).length;\n const also =\n others > 0 ? ` Also adds the ${others} free-verb rule(s) \\`tenjin install\\` writes.` : '';\n return (\n `publish.mode ${mode} is unattended only if your harness allowlist carries ` +\n `${MODE_GATED_RULES.join(' and ')}. Add them to ~/.claude/settings.json now?${also}`\n );\n}\n\n/**\n * Keep the harness allowlist in step with the mode just written.\n *\n * ASYMMETRIC ON PURPOSE, and the asymmetry is the consent rule:\n * - Loosening (auto/full-auto) ADDS a grant, so it needs a human in the loop.\n * No TTY, `--json`, or a declined prompt all leave the file alone and return\n * the pointer instead; nothing here writes on silence.\n * - Tightening (review) only ever REMOVES a rule this CLI wrote under a setting\n * the operator has just changed, so it runs unconditionally — the same reason\n * install sweeps a retired rule without asking. Leaving it behind would keep\n * publishing pre-cleared after the operator said \"ask me first\", which is the\n * failure that matters.\n */\nasync function syncPublishRule(\n mode: PublishMode,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<AllowlistSync> {\n const home = deps.homeDir ?? homedir();\n const nothing: AllowlistSync = { added: [], removed: [] };\n\n const write = async (): Promise<AllowlistSync> => {\n const result = await (deps.wireAllowlist ?? wireFreeVerbAllowlist)(home, mode);\n if (result.skipped !== undefined) {\n return {\n added: [],\n removed: [],\n skipped: 'unwritable',\n ...(result.fix !== undefined ? { pointer: result.fix } : {}),\n };\n }\n return { added: result.added, removed: result.removed };\n };\n\n // Only Claude Code has a settings file of this shape; guessing at another\n // harness's config is the uninvited write lib/harness-permissions.ts avoids.\n // DETECTED, never assumed: a codex-only machine has a ~/.claude/settings.json\n // that nothing reads, so prompting about it is noise and writing to it is an\n // uninvited edit — and the retraction would sweep a file we never owned.\n const isClaude = deps.harnessIsClaude ?? (await claudeInPlay(home, ctx, deps));\n if (!isClaude) {\n // No settings file of ours to be missing anything, so the pointer would be\n // advice about a machine this is not.\n return { ...nothing, skipped: 'not-claude' };\n }\n\n const probe = await (deps.inspectAllowlist ?? inspectFreeVerbRules)(home, mode);\n const gated = new Set<string>(MODE_GATED_RULES);\n const missing = (probe.pending ?? []).filter((r) => gated.has(r));\n // Only ever names rules this machine does not have. A pointer built from the\n // mode alone told a fully-wired operator to go add what they already had.\n const pointer = modeGatedPointer(mode, missing) ?? undefined;\n\n // Tightening runs with no question and with no precondition, through a pass\n // that can only ever REMOVE. Riding the additive writer made this decline\n // whenever the free tier was not byte-exact — silently, and in the tightening\n // direction, on the undo the operator just typed.\n if (mode === 'review') {\n const retracted = await (deps.retractModeGated ?? retractModeGatedRules)(home);\n if (retracted.skipped !== undefined) {\n return {\n ...nothing,\n skipped: 'unwritable',\n ...(retracted.fix !== undefined ? { pointer: retracted.fix } : {}),\n };\n }\n return { added: [], removed: retracted.removed };\n }\n\n // SATISFIED BEFORE TTY, and the order is the point: a fully-wired machine has\n // nothing to ask about and nothing to write, so a `--json` or headless run\n // there is a no-op rather than a `no-tty` skip carrying a pointer at rules it\n // already has.\n if (probe.satisfied !== undefined) return nothing;\n\n const canPrompt =\n ctx.flags.json === true ? false : (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n if (!canPrompt) return { ...nothing, skipped: 'no-tty', ...(pointer ? { pointer } : {}) };\n\n const confirm = deps.confirmRule ?? ((label: string) => confirmChoice(label, true));\n if (!(await confirm(publishRuleQuestion(mode, probe.pending ?? [])))) {\n return { ...nothing, skipped: 'declined', ...(pointer ? { pointer } : {}) };\n }\n return write();\n}\n\n/** Claude Code's business? The union install and doctor target with: detected on\n * PATH or by its home directory, or named by a past `--harness`, which outranks\n * the probes. */\nasync function claudeInPlay(\n home: string,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<boolean> {\n const env = deps.env ?? process.env;\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n const requested = await loadRawConfig(ctx.dataDir)\n .then((c) => c.install?.harness ?? [])\n .catch(() => [] as HarnessTarget[]);\n return harnessInPlay(\n home,\n harnessTargetDir(home, 'claude'),\n detectHarnesses(home, which),\n requested,\n );\n}\n\n/** The human rendering of {@link syncPublishRule}, or nothing when it was a no-op. */\nfunction allowlistLines(sync: AllowlistSync): string[] {\n const lines: string[] = [];\n if (sync.added.length > 0) {\n lines.push(`Added ${sync.added.length} harness rule(s) to your allowlist.`);\n }\n if (sync.removed.length > 0) {\n lines.push(`Removed ${sync.removed.join(', ')} from your allowlist.`);\n }\n if (sync.pointer !== undefined) lines.push(sync.pointer);\n return lines;\n}\n\n/**\n * `config set hooks.searchMode`. Merged into the nested hooks block through the\n * same locked read-modify-write every other set uses, so a subkey a newer CLI\n * wrote survives. The installed script reads this file on every run, so a value\n * that script UNDERSTANDS takes effect immediately with no re-install — which is\n * every value it shipped knowing about, and not `deliberate-only` on a script\n * written before that existed. That one case is reported, once, below.\n */\nasync function setHooksKey(\n key: HooksConfigKey,\n value: string,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<CommandResult> {\n const subkey = key === 'hooks.searchMode' ? 'searchMode' : 'stopNag';\n const parsed =\n key === 'hooks.searchMode' ? parseSearchHookModeFlag(value, key) : parseStopNagFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, [subkey]: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n // ONE honest line, not a nag loop: the value is stored either way, and the\n // operator is told the running script predates it rather than left believing a\n // setting took that did not.\n const current = await (deps.stopHookIsCurrent ?? stopHookIsCurrent)(ctx.dataDir);\n const stale =\n parsed === 'deliberate-only' && !current\n ? `The installed Stop hook predates ${JSON.stringify(parsed)} and will keep treating it as \"on\". Run \\`tenjin install\\` to update it.`\n : undefined;\n return {\n data: { key, ...entry, ...(stale !== undefined ? { hookScriptStale: true } : {}) },\n humanLines: [formatLine(key, entry), ...(stale !== undefined ? [stale] : [])],\n };\n}\n\n/**\n * `config set update.mode`. Same locked merge-write as every other set, so the\n * next command reports (or stops reporting) under the new mode immediately,\n * with nothing to re-install and no process to restart.\n */\nasync function setUpdateKey(\n key: UpdateConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseUpdateModeFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n update: { ...existing.update, mode: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\nfunction parsePublishMode(value: string): string {\n const parsed = PublishModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid publish mode: ${JSON.stringify(value)}`, {\n fix: 'Use \"review\", \"auto\", or \"full-auto\".',\n });\n}\n\n/**\n * Persist just `publish.mode` into the global config through the same locked\n * merge-write every `config set` uses (never a raw overwrite), so a sibling\n * subkey or an unknown block a newer CLI wrote is preserved. Used by `install`'s\n * setup prompt; the mode is a validated PublishMode.\n */\nexport async function persistPublishMode(dir: string, mode: PublishMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, mode },\n }));\n}\n\n/**\n * Persist `hooks.searchMode` through the same locked merge-write, for `install`'s\n * hook decision. The mode is already a validated SearchHookMode.\n */\nexport async function persistSearchHookMode(dir: string, mode: SearchHookMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, searchMode: mode },\n }));\n}\n\n/**\n * Record the explicit `--harness` set `install` was given, through the same locked\n * merge-write. It REPLACES the previous record rather than unioning with it: the last\n * explicit request is the current intent, and re-running install with the right flag\n * is then the way out of a mistaken one. Detected harnesses are never recorded — they\n * are re-probed on every `doctor` — so this file holds only what detection cannot see.\n */\nexport async function persistInstallHarness(\n dir: string,\n harness: readonly HarnessTarget[],\n): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, harness: [...harness] },\n }));\n}\n\nasync function resolveFromContext(ctx: CommandContext): Promise<EffectiveSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n // Feed the per-project `.tenjin.json` layer so the publish keys read out what a\n // real `publish` would resolve (project/env included), not a global-only guess.\n const project = await loadProjectConfig(process.cwd());\n return resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n project: project?.layer,\n });\n}\n\nfunction assertKey(key: string): ScalarConfigKey {\n if ((CONFIG_KEYS as string[]).includes(key)) return key as ScalarConfigKey;\n throw new CliError('USAGE', `Unknown config key: ${JSON.stringify(key)}`, {\n fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS].join(', ')}.`,\n });\n}\n\nfunction renderSetting(\n key: ScalarConfigKey,\n stored: string | string[] | boolean,\n source: Provenance,\n): RenderedSetting {\n return { ...renderValue(key, stored), source };\n}\n\n/**\n * The list/get shape for a publish key, read from the resolved effective\n * settings, which now include the per-project `.tenjin.json` layer (see\n * resolveFromContext) so the source reflects what a publish would actually use.\n */\nfunction renderPublishSetting(key: PublishConfigKey, settings: EffectiveSettings): RenderedSetting {\n if (key === 'publish.mode') {\n return { value: settings.publishMode.value, source: settings.publishMode.source };\n }\n return {\n value: toMoney(settings.publishDefaultPrice.value),\n source: settings.publishDefaultPrice.source,\n };\n}\n\n/** The list/get shape for a hooks key: a plain enum string either way. */\nfunction renderHooksSetting(key: HooksConfigKey, settings: EffectiveSettings): RenderedSetting {\n const resolved = key === 'hooks.searchMode' ? settings.hooksSearchMode : settings.hooksStopNag;\n return { value: resolved.value, source: resolved.source };\n}\n\nfunction renderValue(key: ScalarConfigKey, stored: string | string[] | boolean): RenderedValue {\n if (Array.isArray(stored) || typeof stored === 'boolean') return { value: stored };\n if (key === 'maxAutoSpend' || key === 'sessionBudget') return { value: toMoney(stored) };\n if (key === 'sendMaxAmount') {\n // 'unset' is the resolved sentinel for an absent key (send refuses), never\n // a stored value; 'none' is the explicit uncapped opt-in.\n return { value: stored === 'none' || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };\n }\n if (key === 'confirm' && stored.startsWith(CONFIRM_ABOVE)) {\n return { value: stored, threshold: toMoney(stored.slice(CONFIRM_ABOVE.length)) };\n }\n return { value: stored };\n}\n\n/** Per-key edge parsing. Returns the persisted form; throws USAGE on bad input. */\nfunction parseValue(key: ScalarConfigKey, value: string): string | string[] | boolean {\n switch (key) {\n case 'maxAutoSpend':\n case 'sessionBudget':\n return parseUsdToAtomic(value); // throws USAGE on a bad amount\n case 'sendMaxAmount':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'confirm':\n return parseConfirm(value);\n case 'allowlistCreators':\n return parseAllowlist(value);\n case 'baseUrl':\n case 'rpcUrl':\n return parseHttpUrl(value);\n case 'evalCohort':\n return parseBoolean(value);\n }\n}\n\nfunction parseBoolean(value: string): boolean {\n if (value === 'true') return true;\n if (value === 'false') return false;\n throw new CliError('USAGE', `Invalid boolean value: ${JSON.stringify(value)}`, {\n fix: 'Use \"true\" or \"false\".',\n });\n}\n\nfunction parseConfirm(value: string): string {\n if (value === 'always') return 'always';\n if (value.startsWith(CONFIRM_ABOVE)) {\n return `${CONFIRM_ABOVE}${parseUsdToAtomic(value.slice(CONFIRM_ABOVE.length))}`;\n }\n throw new CliError('USAGE', `Invalid confirm value: ${JSON.stringify(value)}`, {\n fix: 'Use \"always\" or \"above:<usd>\", e.g. above:0.25.',\n });\n}\n\nfunction parseAllowlist(value: string): string[] {\n // \"\" clears to []; comma-split, trim, drop empties. Reject an entry with\n // internal whitespace — a creator handle/address is a single token.\n const entries = value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n for (const entry of entries) {\n if (/\\s/.test(entry)) {\n throw new CliError('USAGE', `Invalid creator entry: ${JSON.stringify(entry)}`, {\n fix: 'Creator entries cannot contain spaces; separate multiple with commas.',\n });\n }\n }\n return entries;\n}\n\nfunction parseHttpUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new CliError('USAGE', `Invalid URL: ${JSON.stringify(value)}`, {\n fix: 'Pass an absolute http(s) URL like https://tenjin.blog.',\n });\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new CliError('USAGE', `URL must be http or https: ${JSON.stringify(value)}`, {\n fix: 'Pass an absolute http(s) URL like https://tenjin.blog.',\n });\n }\n return value;\n}\n\n/**\n * Apply `merge` to the raw file and write it back atomically. Uses the partial\n * schema and writeFileAtomic (not writeConfig, which would materialize every\n * default into the file and corrupt provenance). loadRawConfig surfaces a\n * corrupt existing file as CONFIG_INVALID, which propagates.\n *\n * The whole read-merge-write runs under a cross-process file lock: without it two\n * concurrent `config set` on different keys race on the read, and the last writer\n * drops the other's update (worst case, a zeroed maxAutoSpend resurrected). The\n * data dir is ensured first so the lock's mkdir has a parent on a fresh install.\n */\nasync function persist(\n dir: string,\n merge: (existing: PartialConfig) => PartialConfig,\n): Promise<void> {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = `${configPath(dir)}.lock`;\n try {\n await withFileLock(lockPath, async () => {\n const existing = await loadRawConfig(dir);\n const merged = merge(existing);\n const validated = RawConfigSchema.parse(merged);\n await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o644,\n dirMode: 0o700,\n });\n });\n } catch (err) {\n // A lock timeout is not the user's malformed input; surface it as INTERNAL with\n // the one manual step (there is no auto-steal), keeping the JSON error contract.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nfunction formatLine(key: string, entry: RenderedSetting): string {\n const label = key.padEnd(KEY_WIDTH);\n return ` ${label} ${displayValue(entry)} ${styleText('dim', `(${entry.source})`)}`;\n}\n\n/** The list variant: the value line, a dim description, and an optional dim note. */\nfunction describedLine(key: string, entry: RenderedSetting, note?: string): string {\n const description = KEY_DESCRIPTIONS[key];\n let line = formatLine(key, entry);\n if (description !== undefined) line += ` ${styleText('dim', `- ${description}`)}`;\n return withNote(line, note);\n}\n\n/** Append a dim parenthetical note (e.g. the full-auto downgrade) when present. */\nfunction withNote(line: string, note?: string): string {\n return note !== undefined ? `${line} ${styleText('dim', `(${note})`)}` : line;\n}\n\n/**\n * The `publish.mode` line gains a downgrade note when the effective mode came from\n * a committed `.tenjin.json` asking for `full-auto` (the loosening gate demoted it\n * to `auto`). Human-only; the machine `data` shape is unchanged.\n */\nfunction downgradeNote(key: PublishConfigKey, settings: EffectiveSettings): string | undefined {\n if (key !== 'publish.mode' || settings.publishMode.downgradedWarning === undefined) {\n return undefined;\n }\n return 'downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)';\n}\n\nfunction displayValue(entry: RenderedSetting): string {\n const { value } = entry;\n if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '(empty)';\n if (typeof value === 'boolean') return value ? 'true' : 'false'; // evalCohort\n if (typeof value === 'object') return `${value.usd} USD`; // Money (spend keys)\n if (entry.threshold !== undefined) return `above ${entry.threshold.usd} USD`; // confirm\n return value; // 'always', baseUrl, rpcUrl\n}\n","import type { Readable, Writable } from 'node:stream';\n\n/**\n * The pretty-prompt renderer behind the install walkthrough's seams.\n *\n * @clack/prompts is a devDependency BUNDLED by tsup (published `dependencies`\n * stays `{}`), and every entry point here is behind a dynamic `import()` so it\n * lands in its own split chunk: a `search` or `doctor` run never parses it.\n *\n * Nothing in this module is reachable from a machine run. Commands call it only\n * on the real interactive path (a TTY on both stdout and stdin, no `--json`),\n * and always through an injectable seam, so unit tests supply answers directly\n * and never touch clack or a terminal.\n *\n * Prompts render on STDERR, like every other prompt in this CLI: stdout carries\n * the human walkthrough (or a single JSON envelope) and must not be interleaved\n * with prompt chrome.\n */\n\n/** Cancel (ctrl-C, escape) is not an answer. Callers map `null` to their own default. */\nexport type Cancelled = null;\n\nexport interface SelectChoice<T extends string> {\n value: T;\n label: string;\n /** The one line of consequence shown beside the label. */\n hint?: string;\n}\n\n/** Streams a prompt reads and draws on. Injected by tests; defaults to the real ones. */\ninterface PromptStreams {\n input?: Readable;\n output?: Writable;\n}\n\n/** DECTCUM show-cursor. Written on the EOF path in case the prompt did not get to. */\nconst SHOW_CURSOR = '\\x1b[?25h';\n\n/**\n * Settle a prompt when its input goes away instead of hanging forever.\n *\n * Ctrl-D at a clack prompt leaves its promise unsettled: no resolve, no reject,\n * no cancel symbol. The process then dies on an unsettled top-level await with\n * exit 13, nothing printed, and the cursor still hidden. The readline seam this\n * replaced handled it on purpose (\"ctrl-D mid-prompt reads as the default\"), and\n * that behavior has to survive the renderer swap.\n *\n * \"Input goes away\" is two different events, and only covering one of them was\n * the original bug:\n *\n * - The STREAM ends. A pipe closes, a harness detaches, stdin was already at\n * EOF. Caught via `end` / `close`.\n * - The ctrl-D BYTE (0x04) arrives with the stream still open. This is what a\n * real terminal sends, and it is the common case. A prompt puts stdin in raw\n * mode, where 0x04 is ordinary data rather than EOF, so no stream event ever\n * fires; clack has no binding for it and simply keeps waiting. Caught via the\n * `keypress` decoder readline installs, which is a read-only view of the same\n * bytes: listening there takes nothing away from the prompt, where a `data`\n * listener would risk flipping the stream to flowing before clack reads it.\n *\n * Two mechanisms settle it, because one of them is advisory. The AbortSignal is\n * clack's own teardown: it flips the prompt to `cancel`, which restores the\n * cursor and raw mode and resolves with the cancel symbol. The race is the\n * guarantee, for a prompt that is not yet listening or never settles anyway; on\n * that path we restore the cursor ourselves, since no prompt did.\n */\nfunction withInputEnd<T>(\n streams: Required<PromptStreams>,\n onEnd: T,\n run: (signal: AbortSignal) => Promise<T>,\n): Promise<T> {\n const controller = new AbortController();\n let settleEnd: (() => void) | undefined;\n const ended = new Promise<T>((resolve) => {\n settleEnd = () => {\n streams.output.write(SHOW_CURSOR);\n resolve(onEnd);\n };\n });\n\n const end = (): void => {\n controller.abort();\n settleEnd?.();\n };\n const onKeypress = (_text: string | undefined, key?: { name?: string; ctrl?: boolean }): void => {\n if (key?.ctrl === true && key.name === 'd') end();\n };\n\n streams.input.on('keypress', onKeypress);\n // A stream that finished before we got here never emits `end` again, so ask.\n if (streams.input.readableEnded) {\n queueMicrotask(end);\n } else {\n streams.input.once('end', end);\n streams.input.once('close', end);\n }\n\n return Promise.race([run(controller.signal), ended]).finally(() => {\n streams.input.off('keypress', onKeypress);\n streams.input.off('end', end);\n streams.input.off('close', end);\n });\n}\n\nfunction resolveStreams(streams: PromptStreams): Required<PromptStreams> {\n return { input: streams.input ?? process.stdin, output: streams.output ?? process.stderr };\n}\n\n/**\n * A single-choice list. Returns the chosen value, or `null` when the operator\n * cancelled or the input ended, both of which callers treat as \"leave everything\n * as it was\".\n */\nexport async function selectOne<T extends string>(opts: {\n message: string;\n choices: readonly SelectChoice<T>[];\n initialValue: T;\n streams?: PromptStreams;\n}): Promise<T | Cancelled> {\n const { select, isCancel } = await import('@clack/prompts');\n const streams = resolveStreams(opts.streams ?? {});\n return withInputEnd<T | Cancelled>(streams, null, async (signal) => {\n // Instantiated at `string`, not at `T`: clack's `Option<Value>` is a conditional\n // type that a generic `T extends string` cannot resolve. The values come from\n // this call's own choices, so narrowing the answer back is sound.\n const answer = await select<string>({\n message: opts.message,\n options: opts.choices.map((c) => ({\n value: c.value as string,\n label: c.label,\n ...(c.hint !== undefined ? { hint: c.hint } : {}),\n })),\n initialValue: opts.initialValue,\n input: streams.input,\n output: streams.output,\n signal,\n });\n return isCancel(answer) ? null : (answer as T);\n });\n}\n\n/** A yes/no confirm. Cancelling, or an input that ends, reads as no. */\nexport async function confirmChoice(\n message: string,\n initialValue = true,\n streams: PromptStreams = {},\n): Promise<boolean> {\n const { confirm, isCancel } = await import('@clack/prompts');\n const resolved = resolveStreams(streams);\n return withInputEnd<boolean>(resolved, false, async (signal) => {\n const answer = await confirm({\n message,\n initialValue,\n input: resolved.input,\n output: resolved.output,\n signal,\n });\n return isCancel(answer) ? false : answer;\n });\n}\n\n/** Open the walkthrough's prompt sequence with a title bar. */\nexport async function intro(message: string): Promise<void> {\n const clack = await import('@clack/prompts');\n clack.intro(message, { output: process.stderr });\n}\n\n/** Close it, so the last prompt is not left dangling above plain stdout lines. */\nexport async function outro(message: string): Promise<void> {\n const clack = await import('@clack/prompts');\n clack.outro(message, { output: process.stderr });\n}\n","import { lstat, readFile, realpath } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from './atomic-json';\nimport { claudeSettingsPath } from './harness-permissions';\nimport { hooksDir } from './paths';\nimport {\n STOP_HOOK_FILE,\n WEBSEARCH_HOOK_FILE,\n stopHookScript,\n websearchHookScript,\n} from './hook-scripts';\nimport type { SearchHookMode } from './config';\n\n/**\n * The second place the CLI writes into a harness's own settings file, and it\n * carries the same invariants as lib/harness-permissions.ts for the same reasons:\n * additive only, never clobbers a file it cannot understand, and refuses rather\n * than overwriting a change that landed mid-run. Read that module's header first;\n * what follows is only what is different here.\n *\n * WHAT A HOOK ENTRY IS. Unlike a permission rule, a hook entry names an\n * executable. Two properties keep that honest:\n *\n * - The command can only ever be `node <path under the Tenjin data dir>`. There\n * is no argument, no config key, and no call path that lets a caller point a\n * hook at some other program, and the scripts themselves are generated from\n * constants in lib/hook-scripts.ts rather than from anything on the wire.\n * - Neither hook can block, deny, or modify a tool call. The WebSearch hook emits\n * `additionalContext` and never `permissionDecision`, so a WebSearch always\n * proceeds; the Stop hook only ever adds a line at the end of a turn.\n *\n * OWNERSHIP IS BY PATH. An entry is ours when its command mentions one of our two\n * script filenames. That is what makes a re-install idempotent, lets a drifted\n * command (an older install's path, a moved data dir) be rewritten in place\n * instead of duplicated, and keeps every entry someone else wrote untouched.\n */\n\n/** The hook events this module writes, in the order they are reported. */\nexport const HOOK_EVENTS = ['PreToolUse', 'Stop'] as const;\nexport type HookEvent = (typeof HOOK_EVENTS)[number];\n\n/** The tool the WebSearch hook fires on. Never `WebFetch`, never a wildcard. */\nexport const WEBSEARCH_MATCHER = 'WebSearch';\n\n/**\n * Seconds the harness allows each hook before killing it, and the HARD bound on\n * how long either can delay anything. The scripts' own watchdogs (2s and 1.5s)\n * are the design budget and cover the ordinary case, but they are event-loop\n * timers: a synchronous read that blocks outlasts them. This kill does not, so it\n * is the number to quote when the question is \"what is the worst case\".\n */\nconst HOOK_TIMEOUT_SECONDS = 5;\n\nexport type HooksSkipReason =\n | 'harness-not-claude'\n | 'mode-off'\n | 'declined'\n | 'dry-run'\n | 'unresolvable'\n | 'unreadable'\n | 'unparsable'\n | 'unexpected-shape'\n | 'changed-since-read';\n\nexport interface HooksResult {\n /** The harness this outcome is about; only `claude` has a settings file we write. */\n harness: string;\n /** The settings file, absent when the harness has no such file. */\n path?: string;\n /** Where the hook scripts live (or would). */\n scriptsDir: string;\n /** The behavior the installed scripts will follow (config `hooks.searchMode`). */\n mode: SearchHookMode;\n /** Events whose entry this run appended. */\n added: HookEvent[];\n /** Events whose entry was already there, byte-identical. */\n alreadyPresent: HookEvent[];\n /** Events whose existing entry pointed somewhere else and was rewritten in place. */\n updated: HookEvent[];\n /** Script files this run wrote or refreshed. */\n scripts: string[];\n skipped?: HooksSkipReason;\n /** Human-readable detail for a skip that is a problem rather than a choice. */\n warning?: string;\n /** The exact command that changes this outcome, mirroring the CliError contract. */\n fix?: string;\n}\n\n/** The undo, stated the same way everywhere it is shown. */\nexport function hooksUndo(settingsPath: string, scriptsDir: string): string {\n return `Undo anytime: \\`tenjin config set hooks.searchMode off\\` disarms them, or delete the tenjin hook entries from ${settingsPath} and the scripts in ${scriptsDir}.`;\n}\n\nfunction skip(\n reason: HooksSkipReason,\n args: {\n harness: string;\n path?: string;\n scriptsDir: string;\n mode: SearchHookMode;\n warning?: string;\n fix?: string;\n },\n): HooksResult {\n return {\n harness: args.harness,\n ...(args.path !== undefined ? { path: args.path } : {}),\n scriptsDir: args.scriptsDir,\n mode: args.mode,\n added: [],\n alreadyPresent: [],\n updated: [],\n scripts: [],\n skipped: reason,\n ...(args.warning !== undefined ? { warning: args.warning } : {}),\n ...(args.fix !== undefined ? { fix: args.fix } : {}),\n };\n}\n\n/** A decision NOT to wire, shaped like a write outcome so the caller has one type. */\nexport function hooksSkipped(\n harness: string,\n homeDir: string,\n dataDir: string,\n mode: SearchHookMode,\n reason: HooksSkipReason,\n): HooksResult {\n return skip(reason, {\n harness,\n ...(harness === 'claude' ? { path: claudeSettingsPath(homeDir) } : {}),\n scriptsDir: hooksDir(dataDir),\n mode,\n fix: fixFor(reason),\n });\n}\n\n/**\n * The command that turns a skip into a write. Every skipped state names one, so a\n * machine consumer reading the envelope never has to work out the remedy from\n * prose, which is the same contract a CliError's `fix` carries.\n */\nfunction fixFor(reason: HooksSkipReason): string {\n switch (reason) {\n case 'harness-not-claude':\n return 'Hooks are wired for Claude Code only. Re-run `tenjin install --harness claude` on a machine with Claude Code.';\n case 'mode-off':\n return 'Enable them with `tenjin config set hooks.searchMode auto`, then re-run `tenjin install`.';\n case 'declined':\n case 'dry-run':\n return 'Wire them with `tenjin install --search-hooks auto`.';\n case 'changed-since-read':\n return 'Another process changed the file mid-run; re-run `tenjin install`.';\n default:\n return 'Fix the reported file, then re-run `tenjin install --search-hooks auto`.';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Quote a path for the shell the harness runs a `command` hook through. POSIX\n * shells take single quotes (with the standard `'\\''` escape for an embedded\n * one); cmd.exe does not understand them at all and takes double quotes. Getting\n * this wrong on a home directory with a space silently installs a hook that can\n * never run, so it is a real branch rather than an assumption about paths.\n */\nexport function quoteForShell(path: string, platform: string = process.platform): string {\n if (platform === 'win32') return `\"${path}\"`;\n return `'${path.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nfunction commandFor(scriptPath: string, platform?: string): string {\n return `node ${quoteForShell(scriptPath, platform)}`;\n}\n\n/** One hook handler, exactly as it is written into settings.json. */\nfunction handlerFor(scriptPath: string, platform?: string): Record<string, unknown> {\n return {\n type: 'command',\n command: commandFor(scriptPath, platform),\n timeout: HOOK_TIMEOUT_SECONDS,\n };\n}\n\n/** Is this settings.json entry one of ours? Keyed on the script FILENAME, so a\n * data dir that moved is recognized as our entry and rewritten, not duplicated. */\nfunction ownsEntry(entry: unknown, scriptFile: string): boolean {\n if (!isPlainObject(entry)) return false;\n const handlers = entry.hooks;\n if (!Array.isArray(handlers)) return false;\n return handlers.some(\n (h) => isPlainObject(h) && typeof h.command === 'string' && h.command.includes(scriptFile),\n );\n}\n\ninterface HookSpec {\n event: HookEvent;\n scriptFile: string;\n script: string;\n /** Absent for Stop, which the harness fires on every occurrence with no matcher. */\n matcher?: string;\n}\n\nfunction specs(dataDir: string): HookSpec[] {\n return [\n {\n event: 'PreToolUse',\n scriptFile: WEBSEARCH_HOOK_FILE,\n script: websearchHookScript(dataDir),\n matcher: WEBSEARCH_MATCHER,\n },\n { event: 'Stop', scriptFile: STOP_HOOK_FILE, script: stopHookScript(dataDir) },\n ];\n}\n\n/**\n * Does the Stop hook ON DISK match what this build would write?\n *\n * `hooks.stopNag` is read by the installed script at run time, so a `config set`\n * takes effect immediately — but only for values that script UNDERSTANDS. A\n * script written before `deliberate-only` existed maps every non-`off` value to\n * `on`, so the set succeeds, `config get` reports it effective from `file`, and\n * the batch keeps firing. Never throws: a machine with no hook installed is not\n * drifted, it is unhooked, and neither is this function's caller's problem to\n * fail on.\n */\nexport async function stopHookIsCurrent(dataDir: string): Promise<boolean> {\n const spec = specs(dataDir).find((h) => h.scriptFile === STOP_HOOK_FILE);\n if (spec === undefined) return true;\n const path = join(hooksDir(dataDir), STOP_HOOK_FILE);\n const onDisk = await readFile(path, 'utf8').catch(() => null);\n // Absent means nothing is running that could be stale.\n return onDisk === null || onDisk === spec.script;\n}\n\nexport interface WireHooksOptions {\n homeDir: string;\n dataDir: string;\n mode: SearchHookMode;\n /** Shell-quoting target; injected so both branches are testable on one machine. */\n platform?: string;\n}\n\n/**\n * Write the hook scripts and merge their entries into ~/.claude/settings.json.\n *\n * The SCRIPTS are written whatever the mode, including `off`: the mode is read by\n * the script at run time, so an operator who later flips `hooks.searchMode` back\n * to `auto` gets working hooks without re-installing. Only `mode: 'off'` is\n * refused at the caller (see `hooksSkipped`), which leaves settings.json alone\n * entirely.\n *\n * Idempotent: a second run rewrites no script whose bytes match, appends no entry\n * that is already there, and does not touch settings.json at all when nothing\n * changed.\n */\nexport async function wireSearchHooks(opts: WireHooksOptions): Promise<HooksResult> {\n const { homeDir, dataDir, mode, platform } = opts;\n const scriptsDir = hooksDir(dataDir);\n const plan = specs(dataDir);\n\n const found = await inspectSettings(homeDir, scriptsDir, mode);\n if ('result' in found) return found.result;\n const { path, raw, settings, hooks } = found;\n\n const added: HookEvent[] = [];\n const alreadyPresent: HookEvent[] = [];\n const updated: HookEvent[] = [];\n const nextHooks: Record<string, unknown> = { ...hooks };\n\n for (const spec of plan) {\n const existing = hooks[spec.event];\n if (existing !== undefined && !Array.isArray(existing)) {\n return refuse(\n path,\n scriptsDir,\n mode,\n 'unexpected-shape',\n `${path} has a \"hooks.${spec.event}\" key that is not an array; it was left exactly as it is.`,\n );\n }\n const list: unknown[] = existing ?? [];\n const desired = {\n ...(spec.matcher !== undefined ? { matcher: spec.matcher } : {}),\n hooks: [handlerFor(join(scriptsDir, spec.scriptFile), platform)],\n };\n const idx = list.findIndex((e) => ownsEntry(e, spec.scriptFile));\n if (idx === -1) {\n nextHooks[spec.event] = [...list, desired];\n added.push(spec.event);\n continue;\n }\n if (JSON.stringify(list[idx]) === JSON.stringify(desired)) {\n alreadyPresent.push(spec.event);\n continue;\n }\n // Ours, but stale: an older install's path, or a data dir that moved. Rewritten\n // IN PLACE so the entry keeps its position among whatever else is registered.\n nextHooks[spec.event] = list.map((e, i) => (i === idx ? desired : e));\n updated.push(spec.event);\n }\n\n // Nothing to register: no guard is involved, so the scripts are simply brought\n // up to date. This is the path a re-run takes after an upgrade changed a body.\n if (added.length === 0 && updated.length === 0) {\n const scripts = await writeScripts(plan, scriptsDir);\n return { harness: 'claude', path, scriptsDir, mode, added, alreadyPresent, updated, scripts };\n }\n\n const next = { ...settings, hooks: nextHooks };\n // TWO compares, and both are load-bearing.\n //\n // The FIRST is cheap and early: it refuses before a single byte is written, so\n // the ordinary contended case costs nothing and leaves nothing half-done.\n const changed = async (): Promise<boolean> =>\n (await readFile(path, 'utf8').catch(() => null)) !== raw;\n if (await changed()) return refuseChanged(path, scriptsDir, mode, []);\n\n // Past the first guard, and still before the entry that points at them, so a\n // harness never reads an entry naming a file that is not on disk yet.\n const scripts = await writeScripts(plan, scriptsDir);\n\n // The SECOND compare sits ADJACENT to the commit, because the writes above are\n // two read/write/rename sequences wide and this is a whole-file replacement\n // built from a snapshot taken before them. Claude Code writing settings.json\n // during that window passed the first compare and would be erased here. The\n // refusal reports the scripts that WERE refreshed, so the result describes what\n // actually happened rather than claiming nothing was touched: the bodies are\n // versioned and idempotent, so a refreshed script with no new entry is inert\n // and the re-run the fix names simply registers it.\n if (await changed()) return refuseChanged(path, scriptsDir, mode, scripts);\n await writeFileAtomic(path, `${JSON.stringify(next, null, 2)}\\n`);\n return { harness: 'claude', path, scriptsDir, mode, added, alreadyPresent, updated, scripts };\n}\n\n/**\n * The `changed-since-read` refusal, carrying whatever scripts the run had already\n * refreshed. Nothing about settings.json is written on this path.\n */\nfunction refuseChanged(\n path: string,\n scriptsDir: string,\n mode: SearchHookMode,\n scripts: string[],\n): HooksResult {\n return {\n ...refuse(\n path,\n scriptsDir,\n mode,\n 'changed-since-read',\n `${path} changed while it was being updated, so no hooks were registered. Re-run \\`tenjin install\\`.`,\n ),\n scripts,\n };\n}\n\n/** Bring each script up to date, returning the ones this run actually wrote. A\n * body that already matches is left alone, so a re-run rewrites nothing. */\nasync function writeScripts(plan: HookSpec[], scriptsDir: string): Promise<string[]> {\n const written: string[] = [];\n for (const spec of plan) {\n const target = join(scriptsDir, spec.scriptFile);\n const onDisk = await readFile(target, 'utf8').catch(() => null);\n if (onDisk === spec.script) continue;\n await writeFileAtomic(target, spec.script, { mode: 0o755, dirMode: 0o700 });\n written.push(target);\n }\n return written;\n}\n\nfunction refuse(\n path: string,\n scriptsDir: string,\n mode: SearchHookMode,\n reason: HooksSkipReason,\n warning: string,\n): HooksResult {\n return skip(reason, { harness: 'claude', path, scriptsDir, mode, warning, fix: fixFor(reason) });\n}\n\ninterface SettingsInspection {\n path: string;\n /** The exact bytes read, so the commit can prove nothing changed underneath it. */\n raw: string | null;\n settings: Record<string, unknown>;\n hooks: Record<string, unknown>;\n}\n\n/**\n * Resolve and read the settings file. Every refusal lives here, so the shape\n * checks and the write agree by construction. Symlinks are resolved before the\n * write for the same reason lib/harness-permissions.ts resolves them: committing\n * with a rename over a dotfiles-managed link would sever it.\n */\nasync function inspectSettings(\n homeDir: string,\n scriptsDir: string,\n mode: SearchHookMode,\n): Promise<SettingsInspection | { result: HooksResult }> {\n const declaredPath = claudeSettingsPath(homeDir);\n const entry = await lstat(declaredPath).catch(() => null);\n\n let path = declaredPath;\n if (entry !== null) {\n try {\n path = await realpath(declaredPath);\n } catch (err) {\n return {\n result: refuse(\n declaredPath,\n scriptsDir,\n mode,\n 'unresolvable',\n `${declaredPath} could not be resolved (${(err as Error).message}); it was left exactly as it is.`,\n ),\n };\n }\n }\n\n let settings: Record<string, unknown> = {};\n let raw: string | null = null;\n if (entry !== null) {\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n return {\n result: refuse(\n path,\n scriptsDir,\n mode,\n 'unreadable',\n `${path} could not be read (${(err as Error).message}); no hooks were registered.`,\n ),\n };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n return {\n result: refuse(\n path,\n scriptsDir,\n mode,\n 'unparsable',\n `${path} is not valid JSON (${(err as Error).message}); it was left exactly as it is.`,\n ),\n };\n }\n if (!isPlainObject(parsed)) {\n return {\n result: refuse(\n path,\n scriptsDir,\n mode,\n 'unexpected-shape',\n `${path} is not a JSON object; it was left exactly as it is.`,\n ),\n };\n }\n settings = parsed;\n }\n\n const hooksValue = settings.hooks;\n if (hooksValue !== undefined && !isPlainObject(hooksValue)) {\n return {\n result: refuse(\n path,\n scriptsDir,\n mode,\n 'unexpected-shape',\n `${path} has a \"hooks\" key that is not an object; it was left exactly as it is.`,\n ),\n };\n }\n return { path, raw, settings, hooks: hooksValue ?? {} };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,iBAAiB;;;ACkC1B,IAAM,cAAc;AA8BpB,SAAS,aACP,SACA,OACA,KACY;AACZ,QAAM,aAAa,IAAI,gBAAgB;AACvC,MAAI;AACJ,QAAM,QAAQ,IAAI,QAAW,CAAC,YAAY;AACxC,gBAAY,MAAM;AAChB,cAAQ,OAAO,MAAM,WAAW;AAChC,cAAQ,KAAK;AAAA,IACf;AAAA,EACF,CAAC;AAED,QAAM,MAAM,MAAY;AACtB,eAAW,MAAM;AACjB,gBAAY;AAAA,EACd;AACA,QAAM,aAAa,CAAC,OAA2B,QAAkD;AAC/F,QAAI,KAAK,SAAS,QAAQ,IAAI,SAAS,IAAK,KAAI;AAAA,EAClD;AAEA,UAAQ,MAAM,GAAG,YAAY,UAAU;AAEvC,MAAI,QAAQ,MAAM,eAAe;AAC/B,mBAAe,GAAG;AAAA,EACpB,OAAO;AACL,YAAQ,MAAM,KAAK,OAAO,GAAG;AAC7B,YAAQ,MAAM,KAAK,SAAS,GAAG;AAAA,EACjC;AAEA,SAAO,QAAQ,KAAK,CAAC,IAAI,WAAW,MAAM,GAAG,KAAK,CAAC,EAAE,QAAQ,MAAM;AACjE,YAAQ,MAAM,IAAI,YAAY,UAAU;AACxC,YAAQ,MAAM,IAAI,OAAO,GAAG;AAC5B,YAAQ,MAAM,IAAI,SAAS,GAAG;AAAA,EAChC,CAAC;AACH;AAEA,SAAS,eAAe,SAAiD;AACvE,SAAO,EAAE,OAAO,QAAQ,SAAS,QAAQ,OAAO,QAAQ,QAAQ,UAAU,QAAQ,OAAO;AAC3F;AAOA,eAAsB,UAA4B,MAKvB;AACzB,QAAM,EAAE,QAA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AAK,KAAK,aAAa,KAAK,CAAC,KAAK,UAAU,OAAO,IAAI,MAAM,MAAM,GAAG,CAAC;AACrF;AAGA,SAAS,cAAc,KAAa,OAAwB,MAAuB;AACjF,QAAM,cAAc,iBAAiB,GAAG;AACxC,MAAI,OAAO,WAAW,KAAK,KAAK;AAChC,MAAI,gBAAgB,OAAW,SAAQ,KAAK,UAAU,OAAO,KAAK,WAAW,EAAE,CAAC;AAChF,SAAO,SAAS,MAAM,IAAI;AAC5B;AAGA,SAAS,SAAS,MAAc,MAAuB;AACrD,SAAO,SAAS,SAAY,GAAG,IAAI,KAAK,UAAU,OAAO,IAAI,IAAI,GAAG,CAAC,KAAK;AAC5E;AAOA,SAAS,cAAc,KAAuB,UAAiD;AAC7F,MAAI,QAAQ,kBAAkB,SAAS,YAAY,sBAAsB,QAAW;AAClF,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAAgC;AACpD,QAAM,EAAE,MAAM,IAAI;AAClB,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,SAAS,IAAI,MAAM,KAAK,IAAI,IAAI;AACvE,MAAI,OAAO,UAAU,UAAW,QAAO,QAAQ,SAAS;AACxD,MAAI,OAAO,UAAU,SAAU,QAAO,GAAG,MAAM,GAAG;AAClD,MAAI,MAAM,cAAc,OAAW,QAAO,SAAS,MAAM,UAAU,GAAG;AACtE,SAAO;AACT;","names":["scripts","settings","entry"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/http.ts"],"sourcesContent":["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 /**\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 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. The generated hook scripts are the one request\n * path that cannot reach here, and they carry their own mirrored composer\n * (`lib/hook-scripts.ts`) rather than an exemption. `.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';\n status?: number;\n requestId?: string;\n message: string;\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 try {\n res = await doFetch(url, {\n signal: controller.signal,\n headers: withUserAgent(opts.headers, opts.callerUserAgent),\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 if (!res.ok) {\n return {\n ok: false,\n kind: 'http',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\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 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';\n timeoutMs: number;\n headers?: Record<string, string>;\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 fetchImpl?: typeof fetch;\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\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 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 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 const merged = new Headers(opts.headers ?? {});\n if (opts.jsonBody !== undefined) {\n body = JSON.stringify(opts.jsonBody);\n merged.set('content-type', 'application/json');\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 // A caller can also pin an unsigned request (blockRedirects) when the\n // response it gets back becomes a durable local record.\n const signed = carriesSignedMaterial(headers);\n return { ok: true, headers, body, signed, pinned: signed || opts.blockRedirects === true };\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\n try {\n const prepared = prepareRequest(url, opts);\n if (!prepared.ok) return prepared;\n const { headers, body, signed, pinned } = prepared;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method: opts.method ?? 'GET',\n headers,\n body,\n signal: controller.signal,\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\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 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 : `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 try {\n text = await res.text();\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 ...(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 : 'API_UNREACHABLE';\n return new CliError(code, failure.message, {\n ...(opts.fix !== undefined ? { fix: opts.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"],"mappings":";;;;;;;;;AAsCA,SAAS,eAAe,SAAkB,iBAAmC;AAC3E,UAAQ,IAAI,cAAc,iBAAiB,EAAE,QAAQ,gBAAgB,CAAC,CAAC;AACvE,SAAO;AACT;AAGA,SAAS,cACP,eACA,iBACwB;AACxB,SAAO,OAAO;AAAA,IACZ,eAAe,IAAI,QAAQ,iBAAiB,CAAC,CAAC,G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QAAI;AACJ,QAAI;AACF,aAAO,MAAM,IAAI,KAAK;AAAA,IACxB,SAAS,KAAK;AACZ,UAAI,SAAU,QAAO,eAAe,KAAK,KAAK,SAAS;AACvD,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,MAAM;AAAA,QACN,QAAQ,IAAI;AAAA,QACZ,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC;AAAA,QAC/C,SAAS,cAAc,GAAG,4CAA4C,aAAa,GAAG,CAAC;AAAA,MACzF;AAAA,IACF;AACA,QAAI;AACJ,QAAI,KAAK,SAAS,GAAG;AACnB,UAAI;AACF,eAAO,KAAK,MAAM,IAAI;AAAA,MACxB,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,IAAI;AAAA,MACZ,QAAQ,CAAC,SAAS,IAAI,QAAQ,IAAI,IAAI,KAAK;AAAA,MAC3C;AAAA,MACA,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC;AAAA,IACjD;AAAA,EACF,UAAE;AACA,iBAAa,KAAK;AAAA,EACpB;AACF;AAcO,SAAS,uBACd,SACA,OAAiC,CAAC,GACxB;AACV,QAAM,OACJ,QAAQ,SAAS,aAAa,QAAQ,SAAS,YAC3C,kBACA,QAAQ,SAAS,iBACf,sBACA;AACR,SAAO,IAAI,SAAS,MAAM,QAAQ,SAAS;AAAA,IACzC,GAAI,KAAK,QAAQ,SAAY,EAAE,KAAK,KAAK,IAAI,IAAI,CAAC;AAAA,IAClD,GAAI,KAAK,YAAY,SAAY,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;AAAA,EAChE,CAAC;AACH;AAEA,SAAS,aAAa,KAAsB;AAC1C,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/search-store.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { writeFileAtomic } from './atomic-json';\nimport { withFileLock } from './lock';\n\n/**\n * A small local ledger of recent searches so `outcome --last` can target the most\n * recent one and `buy <resourceId>` can resolve the payable read URL a candidate\n * carried (the read route is keyed by handle/slug, not id, so an id alone can't\n * build the URL). Bounded and best-effort: a corrupt file reads as empty rather\n * than blocking a command. NOT an entitlement record, that is the library receipt.\n */\n\nconst MAX_ENTRIES = 50;\n\nconst StoredCandidateSchema = z.object({\n resourceId: z.string(),\n url: z.string(),\n title: z.string(),\n price: z.string(),\n});\nexport type StoredCandidate = z.infer<typeof StoredCandidateSchema>;\n\n/**\n * What closed an open loop. The Stop hook stays quiet once any of these is\n * recorded: `outcome` (the loop was reported) or `publish` (the answer went back\n * to the marketplace).\n *\n * `candidate` is RETAINED but never written. It is what the removed candidate\n * pen recorded, and an older `searches.json` still carries it; dropping the\n * member would make those entries fail to parse and read as an empty store,\n * which would resurrect loops their owner already closed.\n */\nexport const SearchResolutionSchema = z.enum(['outcome', 'publish', 'candidate']);\nexport type SearchResolution = z.infer<typeof SearchResolutionSchema>;\n\n/**\n * Who ran the search. `cli` is a deliberate `tenjin search`: the agent decided\n * the question was worth looking up, so an unanswered one is a strong signal.\n * `websearch-hook` is the PreToolUse hook riding along with a WebSearch the agent\n * was going to run anyway, which is a much weaker signal, because nobody judged\n * the question suitable for the marketplace before it was sent.\n *\n * The distinction exists because the Stop hook must not treat them alike: an\n * unanswered deliberate search deserves being named on its own, while a batch of\n * hook searches deserves one line the agent can dismiss at a glance. Keeping both\n * in ONE store is what makes the hook's misses reachable by explicit\n * `outcome --search-id`, `buy <resourceId>`, and the open-loop reminder at all\n * (`--last` deliberately skips hook entries; see {@link latestSearch}).\n *\n * OPTIONAL, and absent means `cli`: a store written by an earlier version has no\n * source field, and those entries were all explicit searches.\n */\nexport const SearchSourceSchema = z.enum(['cli', 'websearch-hook']);\nexport type SearchSource = z.infer<typeof SearchSourceSchema>;\n\nconst StoredSearchSchema = z.object({\n searchId: z.string(),\n at: z.string(),\n question: z.string(),\n decision: z.string(),\n candidates: z.array(StoredCandidateSchema),\n /** Absent until something closes the loop; see {@link markSearchResolved}. */\n resolved: z.object({ by: SearchResolutionSchema, at: z.string() }).optional(),\n /** Absent on entries written before sources existed; see {@link SearchSourceSchema}. */\n source: SearchSourceSchema.optional(),\n /**\n * The harness session this search was run in, when anything could attribute it.\n * This ledger is MACHINE-GLOBAL, so without it the Stop hook nags whichever\n * session happens to stop next about open loops belonging to a sibling session,\n * which that session cannot act on. The hook scopes on this when both the entry\n * and the turn-end payload name a session, and stays global otherwise, so an\n * unstamped entry is still raised everywhere rather than nowhere.\n *\n * OPTIONAL: the WebSearch hook is handed one by the harness (`session_id` on\n * its stdin payload), and a deliberate `tenjin search` reads the same value\n * from CLAUDE_CODE_SESSION_ID (or an operator's TENJIN_SESSION_ID). Absent on\n * entries written before this field existed, and on any harness that exports\n * neither.\n */\n sessionId: z.string().optional(),\n // How many of the search's browse pointers cost money, and NOT the pointers\n // themselves: keeping them out of the store is what makes `buy <resourceId>`\n // unable to reach one (see the browse comment in agent-api.ts), and a count\n // cannot undo that. It exists so `outcome` can tell \"this search offered\n // nothing to buy\" from \"this search offered a payable browse tail\", which the\n // candidates array alone cannot say. Counts only PAID pointers because a\n // zero-priced piece is delivered by `read` with no purchase to decline.\n // Optional because entries written before this field existed have no answer,\n // and `undefined` must read as unknown rather than as zero.\n paidBrowseCount: z.number().int().nonnegative().optional(),\n});\nexport type StoredSearch = z.infer<typeof StoredSearchSchema>;\n\nconst StoreSchema = z.object({\n schemaVersion: z.literal(1),\n searches: z.array(StoredSearchSchema),\n});\n\n/**\n * The store and its lock. Both paths are EXPORTED because the installed hook\n * scripts write this same file from outside the CLI process: they cannot import\n * this module, so they reimplement the lock protocol against this exact path.\n * Two writers of one file must at least agree on where the mutex lives, and a\n * test pins the script's protocol against this one.\n */\nexport function searchStorePath(dataDir: string): string {\n return join(dataDir, 'searches.json');\n}\n\nexport function searchStoreLockPath(dataDir: string): string {\n return `${searchStorePath(dataDir)}.lock`;\n}\n\nfunction storePath(dataDir: string): string {\n return searchStorePath(dataDir);\n}\n\nexport async function loadSearches(dataDir: string): Promise<StoredSearch[]> {\n let raw: string;\n try {\n raw = await readFile(storePath(dataDir), 'utf8');\n } catch {\n return [];\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return [];\n }\n const parsed = StoreSchema.safeParse(json);\n return parsed.success ? parsed.data.searches : [];\n}\n\n/** Prepend a search (newest first), cap to MAX_ENTRIES, persist under a lock so\n * concurrent searches don't drop each other's entry. */\nexport async function recordSearch(dataDir: string, entry: StoredSearch): Promise<void> {\n await mkdir(dataDir, { recursive: true, mode: 0o700 });\n const lockPath = `${storePath(dataDir)}.lock`;\n await withFileLock(lockPath, async () => {\n const existing = await loadSearches(dataDir);\n const searches = [entry, ...existing.filter((l) => l.searchId !== entry.searchId)].slice(\n 0,\n MAX_ENTRIES,\n );\n await writeFileAtomic(\n storePath(dataDir),\n `${JSON.stringify({ schemaVersion: 1, searches }, null, 2)}\\n`,\n { mode: 0o644, dirMode: 0o700 },\n );\n });\n}\n\n/**\n * What a {@link markSearchResolved} call actually did. Returned rather than\n * swallowed because a caller may REPORT the close to its own user, and \"I tried\"\n * is not \"it happened\": a lock timeout or an unwritable store still leaves the\n * loop open and the reminder due, so a receipt claiming otherwise would be a\n * confident lie. `already-resolved` is a success for anyone asking about the\n * LOOP (something closed it), and a no-op for anyone asking about this call.\n * `relinked` is the one that CHANGED a resolution that was already there.\n */\nexport type ResolutionOutcome =\n 'resolved' | 'relinked' | 'already-resolved' | 'not-found' | 'failed';\n\nexport interface MarkResolvedOptions {\n /**\n * Overwrite a resolution recorded by something else, rather than leaving the\n * first closer in place. Only `publish` passes it, and the reason is the loop\n * this whole ledger exists for: an agent mid-research closes a MISS as\n * `regenerated` because the answer is not written yet, finishes it minutes\n * later, and then has no way to say the piece it just published is what\n * answered that question (tenjin-agent #161). A close is a report of intent at\n * a moment; a publish is the answer arriving, and the answer wins.\n */\n relink?: boolean;\n}\n\n/**\n * Record that something closed the loop on `searchId`, so the Stop hook stops\n * raising it. Best-effort and it NEVER throws: an unknown id (the search aged\n * past MAX_ENTRIES, or came from another machine) writes nothing, and a failure\n * to persist costs one stale nag rather than the command the caller actually\n * ran. The FIRST resolution wins unless the caller asks to {@link\n * MarkResolvedOptions.relink}, so an ordinary `outcome` after a publish still\n * does not rewrite who closed it.\n */\nexport async function markSearchResolved(\n dataDir: string,\n searchId: string,\n by: SearchResolution,\n at: string = new Date().toISOString(),\n options: MarkResolvedOptions = {},\n): Promise<ResolutionOutcome> {\n try {\n const lockPath = `${storePath(dataDir)}.lock`;\n let outcome: ResolutionOutcome = 'not-found';\n await withFileLock(lockPath, async () => {\n const existing = await loadSearches(dataDir);\n const target = existing.find((s) => s.searchId === searchId);\n if (target === undefined) return;\n if (target.resolved !== undefined) {\n // Nothing to relink when the recorded closer is already this one: the\n // loop is where it should be, and rewriting the timestamp would report\n // a change nobody made.\n if (options.relink !== true || target.resolved.by === by) {\n outcome = 'already-resolved';\n return;\n }\n outcome = 'relinked';\n }\n const searches = existing.map((s) =>\n s.searchId === searchId ? { ...s, resolved: { by, at } } : s,\n );\n await writeFileAtomic(\n storePath(dataDir),\n `${JSON.stringify({ schemaVersion: 1, searches }, null, 2)}\\n`,\n { mode: 0o644, dirMode: 0o700 },\n );\n // 'relinked' was decided above and survives the write; anything else that\n // reached here closed a loop nothing had closed.\n if (outcome !== 'relinked') outcome = 'resolved';\n });\n return outcome;\n } catch {\n // Bookkeeping for a hook nudge. It must never fail the verb that ran — but\n // the caller is told, so nothing reports a close that did not happen.\n return 'failed';\n }\n}\n\n/**\n * The most recent DELIBERATE search: `--last` means \"the search I just ran\", and\n * in auto mode the WebSearch hook prepends a ridealong entry on every web search,\n * so an unfiltered head would routinely re-target `outcome --last` at a query the\n * agent never chose to make (found in dogfooding). Hook entries stay reachable by\n * explicit `--search-id`, which is what the Stop hook's reminder names.\n */\nexport async function latestSearch(dataDir: string): Promise<StoredSearch | null> {\n const searches = await loadSearches(dataDir);\n return searches.find((s) => s.source !== 'websearch-hook') ?? null;\n}\n\n/** The stored candidate for a resourceId across recent searches (newest first). */\nexport async function findStoredCandidate(\n dataDir: string,\n resourceId: string,\n): Promise<StoredCandidate | null> {\n for (const search of await loadSearches(dataDir)) {\n const hit = search.candidates.find((c) => c.resourceId === resourceId);\n if (hit) return hit;\n }\n return null;\n}\n\n/** The most recent searchId that surfaced this resource (by id or url), for\n * purchase attribution (`X-Tenjin-Search-Id`). Null when no local search did. */\nexport async function findSearchForResource(\n dataDir: string,\n match: { resourceId?: string; url?: string },\n): Promise<string | null> {\n for (const search of await loadSearches(dataDir)) {\n const hit = search.candidates.some(\n (c) =>\n (match.resourceId !== undefined && c.resourceId === match.resourceId) ||\n (match.url !== undefined && c.url === match.url),\n );\n if (hit) return search.searchId;\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,OAAO,gBAAgB;AAChC,SAAS,YAAY;AAarB,IAAM,cAAc;AAEpB,IAAM,wBAAwB,iBAAE,OAAO;AAAA,EACrC,YAAY,iBAAE,OAAO;AAAA,EACrB,KAAK,iBAAE,OAAO;AAAA,EACd,OAAO,iBAAE,OAAO;AAAA,EAChB,OAAO,iBAAE,OAAO;AAClB,CAAC;AAaM,IAAM,yBAAyB,iBAAE,KAAK,CAAC,WAAW,WAAW,WAAW,CAAC;AAoBzE,IAAM,qBAAqB,iBAAE,KAAK,CAAC,OAAO,gBAAgB,CAAC;AAGlE,IAAM,qBAAqB,iBAAE,OAAO;AAAA,EAClC,UAAU,iBAAE,OAAO;AAAA,EACnB,IAAI,iBAAE,OAAO;AAAA,EACb,UAAU,iBAAE,OAAO;AAAA,EACnB,UAAU,iBAAE,OAAO;AAAA,EACnB,YAAY,iBAAE,MAAM,qBAAqB;AAAA;AAAA,EAEzC,UAAU,iBAAE,OAAO,EAAE,IAAI,wBAAwB,IAAI,iBAAE,O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