tenjin-cli 0.1.0-alpha.32 → 0.1.0-alpha.33

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 (165) hide show
  1. package/README.md +42 -23
  2. package/dist/{_esm-RLLC72MS.js → _esm-BIN7VY2L.js} +2 -2
  3. package/dist/{alive-MROUMFH3.js → alive-GSOWKUOY.js} +4 -4
  4. package/dist/{auto-update-OPWMRZLS.js → auto-update-Y24UL56V.js} +5 -3
  5. package/dist/{chunk-2GNOFONN.js → chunk-2M2VPI2E.js} +2 -2
  6. package/dist/chunk-2M2VPI2E.js.map +1 -0
  7. package/dist/{chunk-VUGQTZ2L.js → chunk-2RWB7RKE.js} +89 -33
  8. package/dist/chunk-2RWB7RKE.js.map +1 -0
  9. package/dist/{chunk-OTWLERSW.js → chunk-36RVGZNY.js} +2 -2
  10. package/dist/{chunk-B7EM4GGF.js → chunk-3GNJXKIT.js} +2 -2
  11. package/dist/{chunk-DRDUIZIA.js → chunk-4K7TQHNP.js} +4 -4
  12. package/dist/{chunk-SYOS5CAC.js → chunk-4YOZGGTZ.js} +73 -2
  13. package/dist/chunk-4YOZGGTZ.js.map +1 -0
  14. package/dist/{chunk-AD226HDR.js → chunk-A5GKIG5O.js} +5 -5
  15. package/dist/{chunk-JEVQ5LKO.js → chunk-AGMVASXZ.js} +3 -3
  16. package/dist/{chunk-ADV4LDTB.js → chunk-BF4XHEQK.js} +12 -2
  17. package/dist/chunk-BF4XHEQK.js.map +1 -0
  18. package/dist/{chunk-IDTRSAHE.js → chunk-C2Q76BVM.js} +48 -49
  19. package/dist/chunk-C2Q76BVM.js.map +1 -0
  20. package/dist/{chunk-VJUVFZ2D.js → chunk-FVIGCDSV.js} +1 -1
  21. package/dist/chunk-FVIGCDSV.js.map +1 -0
  22. package/dist/{chunk-QF3LSMGS.js → chunk-GTTUCOPD.js} +2 -2
  23. package/dist/{chunk-3DIL66VX.js → chunk-HGGWCP7W.js} +2 -2
  24. package/dist/{chunk-D5TOQSO4.js → chunk-HMWYAUA6.js} +10 -6
  25. package/dist/{chunk-D5TOQSO4.js.map → chunk-HMWYAUA6.js.map} +1 -1
  26. package/dist/{chunk-445VQTVM.js → chunk-IE7P2BZE.js} +2 -2
  27. package/dist/{chunk-VOZA6O7K.js → chunk-ILNIZ5I2.js} +190 -96
  28. package/dist/chunk-ILNIZ5I2.js.map +1 -0
  29. package/dist/{chunk-TF5HCP33.js → chunk-INTFHMU4.js} +4 -4
  30. package/dist/{chunk-HREHWL32.js → chunk-J57UC3DD.js} +2 -2
  31. package/dist/{chunk-AV5NZMYO.js → chunk-KM7RY2ZS.js} +2 -2
  32. package/dist/{chunk-TAW4UFFF.js → chunk-L6JEXB3E.js} +132 -132
  33. package/dist/chunk-L6JEXB3E.js.map +1 -0
  34. package/dist/{chunk-E7LGOMH6.js → chunk-LRW6S53P.js} +4 -3
  35. package/dist/chunk-LRW6S53P.js.map +1 -0
  36. package/dist/{chunk-PKHI276N.js → chunk-LXAYUOXI.js} +18 -9
  37. package/dist/chunk-LXAYUOXI.js.map +1 -0
  38. package/dist/{chunk-WOM257PW.js → chunk-NDGZDTSJ.js} +3 -3
  39. package/dist/{chunk-SFASB5FL.js → chunk-P3LFTKE7.js} +3 -14
  40. package/dist/chunk-P3LFTKE7.js.map +1 -0
  41. package/dist/{chunk-YUY4SAGM.js → chunk-RVPYTUP4.js} +5 -5
  42. package/dist/chunk-RVPYTUP4.js.map +1 -0
  43. package/dist/{chunk-GAKUQHKA.js → chunk-TC2WZLSC.js} +3 -3
  44. package/dist/{chunk-D3ZURCG7.js → chunk-TKPF35W6.js} +2 -2
  45. package/dist/{chunk-I5TDIUKM.js → chunk-U3IKUGRP.js} +23 -5
  46. package/dist/chunk-U3IKUGRP.js.map +1 -0
  47. package/dist/{chunk-BI673VEJ.js → chunk-UXZONNEQ.js} +3 -3
  48. package/dist/{chunk-PJNENX2A.js → chunk-WFSPCCVW.js} +2 -2
  49. package/dist/{chunk-PJNENX2A.js.map → chunk-WFSPCCVW.js.map} +1 -1
  50. package/dist/{chunk-DW4YTVR3.js → chunk-WXA2BWTE.js} +6 -2
  51. package/dist/chunk-WXA2BWTE.js.map +1 -0
  52. package/dist/{chunk-JRZBBPO6.js → chunk-ZDZERB6L.js} +56 -228
  53. package/dist/chunk-ZDZERB6L.js.map +1 -0
  54. package/dist/{chunk-G75OPGAK.js → chunk-ZNNXRNFD.js} +5 -3
  55. package/dist/chunk-ZNNXRNFD.js.map +1 -0
  56. package/dist/{chunk-CISYM4EO.js → chunk-ZURZHELF.js} +2 -2
  57. package/dist/{cli-FB4LOA5A.js → cli-E36SPKBW.js} +44 -44
  58. package/dist/{cli-FB4LOA5A.js.map → cli-E36SPKBW.js.map} +1 -1
  59. package/dist/{codex-event-TYVES3UX.js → codex-event-ZO2GEFE6.js} +2 -2
  60. package/dist/{codex-host-WW4H2SKT.js → codex-host-KECJVTA2.js} +3 -3
  61. package/dist/{codex-install-2C623HPW.js → codex-install-HQZDGFXW.js} +90 -47
  62. package/dist/codex-install-HQZDGFXW.js.map +1 -0
  63. package/dist/{config-HOVJFEKD.js → config-HY2E4GGW.js} +8 -8
  64. package/dist/{doctor-NKU4V5OV.js → doctor-I6XQEKWD.js} +42 -31
  65. package/dist/doctor-I6XQEKWD.js.map +1 -0
  66. package/dist/{fund-WEBHTZGN.js → fund-2QRO7OJL.js} +16 -11
  67. package/dist/{fund-WEBHTZGN.js.map → fund-2QRO7OJL.js.map} +1 -1
  68. package/dist/{hook-command-ZA2PNKS6.js → hook-command-2UBCSZG6.js} +12 -13
  69. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  70. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  71. package/dist/hosts/claude/tenjin/hooks/register.tsx +51 -11
  72. package/dist/hosts/claude/tenjin/types/index.d.ts +2 -1
  73. package/dist/{hosts-AV5MHBAU.js → hosts-DVQJ32QC.js} +2 -2
  74. package/dist/index.js +16 -15
  75. package/dist/index.js.map +1 -1
  76. package/dist/{install-PT4EZS4R.js → install-ILUX5C4A.js} +24 -17
  77. package/dist/{install-identity-5A4OE6YC.js → install-identity-TZKGY6LQ.js} +7 -7
  78. package/dist/{install-wallet-SAAPKB73.js → install-wallet-5M4OTYLX.js} +13 -13
  79. package/dist/isows-native-Q2UDIVPT.js +9 -0
  80. package/dist/isows-native-Q2UDIVPT.js.map +1 -0
  81. package/dist/{mcp-HAWKCTPQ.js → mcp-LE4DUS22.js} +23 -24
  82. package/dist/{mcp-HAWKCTPQ.js.map → mcp-LE4DUS22.js.map} +1 -1
  83. package/dist/{package-SR2WB6MK.js → package-IJFGMWEV.js} +2 -2
  84. package/dist/{pay-OXC3WKYV.js → pay-WCG3IH4R.js} +13 -13
  85. package/dist/{payments-3KHMP2MG.js → payments-HFPPWHTV.js} +6 -6
  86. package/dist/{plugin-registration-N3GRIZVM.js → plugin-registration-PZFI5GZW.js} +18 -17
  87. package/dist/{runtime-UVNUA3AS.js → runtime-UZOKSUZX.js} +145 -27
  88. package/dist/runtime-UZOKSUZX.js.map +1 -0
  89. package/dist/{runtime-fetch-EKFRNR6Z.js → runtime-fetch-ZSSSK72Y.js} +5 -2
  90. package/dist/{runtime-layout-BDWZG2TQ.js → runtime-layout-WIDILZ6K.js} +2 -2
  91. package/dist/{send-HMKJLT34.js → send-GCVEAQKL.js} +8 -8
  92. package/dist/{status-RWXIIWYS.js → status-HCVAOCN7.js} +10 -10
  93. package/dist/{status-line-77XYZP7E.js → status-line-OPCXDHL2.js} +6 -6
  94. package/dist/{uninstall-D5G67UJH.js → uninstall-BAWRBXXQ.js} +19 -18
  95. package/dist/{uninstall-D5G67UJH.js.map → uninstall-BAWRBXXQ.js.map} +1 -1
  96. package/dist/{update-LRNOEGSB.js → update-CACXLQLR.js} +20 -17
  97. package/dist/{usdc-D6X7EIQ2.js → usdc-VG4CIOUK.js} +4 -4
  98. package/dist/{viemAdapter-By13KInL-RL742ETX.js → viemAdapter-By13KInL-DOFTEIJV.js} +2 -2
  99. package/dist/{wallet-XFYC27BR.js → wallet-QL4UUXEZ.js} +11 -11
  100. package/docs/agent-permissions.md +16 -12
  101. package/docs/troubleshooting.md +5 -5
  102. package/package.json +4 -4
  103. package/scripts/installers/install.ps1 +67 -0
  104. package/scripts/installers/install.sh +68 -0
  105. package/dist/_esm-C5CRWCYU.js +0 -3737
  106. package/dist/_esm-C5CRWCYU.js.map +0 -1
  107. package/dist/chunk-2GNOFONN.js.map +0 -1
  108. package/dist/chunk-ADV4LDTB.js.map +0 -1
  109. package/dist/chunk-DW4YTVR3.js.map +0 -1
  110. package/dist/chunk-E7LGOMH6.js.map +0 -1
  111. package/dist/chunk-G75OPGAK.js.map +0 -1
  112. package/dist/chunk-I5TDIUKM.js.map +0 -1
  113. package/dist/chunk-IDTRSAHE.js.map +0 -1
  114. package/dist/chunk-JRZBBPO6.js.map +0 -1
  115. package/dist/chunk-PKHI276N.js.map +0 -1
  116. package/dist/chunk-SFASB5FL.js.map +0 -1
  117. package/dist/chunk-SYOS5CAC.js.map +0 -1
  118. package/dist/chunk-TAW4UFFF.js.map +0 -1
  119. package/dist/chunk-VJUVFZ2D.js.map +0 -1
  120. package/dist/chunk-VOZA6O7K.js.map +0 -1
  121. package/dist/chunk-VUGQTZ2L.js.map +0 -1
  122. package/dist/chunk-YUY4SAGM.js.map +0 -1
  123. package/dist/codex-install-2C623HPW.js.map +0 -1
  124. package/dist/doctor-NKU4V5OV.js.map +0 -1
  125. package/dist/runtime-UVNUA3AS.js.map +0 -1
  126. /package/dist/{_esm-RLLC72MS.js.map → _esm-BIN7VY2L.js.map} +0 -0
  127. /package/dist/{alive-MROUMFH3.js.map → alive-GSOWKUOY.js.map} +0 -0
  128. /package/dist/{auto-update-OPWMRZLS.js.map → auto-update-Y24UL56V.js.map} +0 -0
  129. /package/dist/{chunk-OTWLERSW.js.map → chunk-36RVGZNY.js.map} +0 -0
  130. /package/dist/{chunk-B7EM4GGF.js.map → chunk-3GNJXKIT.js.map} +0 -0
  131. /package/dist/{chunk-DRDUIZIA.js.map → chunk-4K7TQHNP.js.map} +0 -0
  132. /package/dist/{chunk-AD226HDR.js.map → chunk-A5GKIG5O.js.map} +0 -0
  133. /package/dist/{chunk-JEVQ5LKO.js.map → chunk-AGMVASXZ.js.map} +0 -0
  134. /package/dist/{chunk-QF3LSMGS.js.map → chunk-GTTUCOPD.js.map} +0 -0
  135. /package/dist/{chunk-3DIL66VX.js.map → chunk-HGGWCP7W.js.map} +0 -0
  136. /package/dist/{chunk-445VQTVM.js.map → chunk-IE7P2BZE.js.map} +0 -0
  137. /package/dist/{chunk-TF5HCP33.js.map → chunk-INTFHMU4.js.map} +0 -0
  138. /package/dist/{chunk-HREHWL32.js.map → chunk-J57UC3DD.js.map} +0 -0
  139. /package/dist/{chunk-AV5NZMYO.js.map → chunk-KM7RY2ZS.js.map} +0 -0
  140. /package/dist/{chunk-WOM257PW.js.map → chunk-NDGZDTSJ.js.map} +0 -0
  141. /package/dist/{chunk-GAKUQHKA.js.map → chunk-TC2WZLSC.js.map} +0 -0
  142. /package/dist/{chunk-D3ZURCG7.js.map → chunk-TKPF35W6.js.map} +0 -0
  143. /package/dist/{chunk-BI673VEJ.js.map → chunk-UXZONNEQ.js.map} +0 -0
  144. /package/dist/{chunk-CISYM4EO.js.map → chunk-ZURZHELF.js.map} +0 -0
  145. /package/dist/{codex-event-TYVES3UX.js.map → codex-event-ZO2GEFE6.js.map} +0 -0
  146. /package/dist/{codex-host-WW4H2SKT.js.map → codex-host-KECJVTA2.js.map} +0 -0
  147. /package/dist/{config-HOVJFEKD.js.map → config-HY2E4GGW.js.map} +0 -0
  148. /package/dist/{hook-command-ZA2PNKS6.js.map → hook-command-2UBCSZG6.js.map} +0 -0
  149. /package/dist/{hosts-AV5MHBAU.js.map → hosts-DVQJ32QC.js.map} +0 -0
  150. /package/dist/{install-PT4EZS4R.js.map → install-ILUX5C4A.js.map} +0 -0
  151. /package/dist/{install-identity-5A4OE6YC.js.map → install-identity-TZKGY6LQ.js.map} +0 -0
  152. /package/dist/{install-wallet-SAAPKB73.js.map → install-wallet-5M4OTYLX.js.map} +0 -0
  153. /package/dist/{package-SR2WB6MK.js.map → package-IJFGMWEV.js.map} +0 -0
  154. /package/dist/{pay-OXC3WKYV.js.map → pay-WCG3IH4R.js.map} +0 -0
  155. /package/dist/{payments-3KHMP2MG.js.map → payments-HFPPWHTV.js.map} +0 -0
  156. /package/dist/{plugin-registration-N3GRIZVM.js.map → plugin-registration-PZFI5GZW.js.map} +0 -0
  157. /package/dist/{runtime-fetch-EKFRNR6Z.js.map → runtime-fetch-ZSSSK72Y.js.map} +0 -0
  158. /package/dist/{runtime-layout-BDWZG2TQ.js.map → runtime-layout-WIDILZ6K.js.map} +0 -0
  159. /package/dist/{send-HMKJLT34.js.map → send-GCVEAQKL.js.map} +0 -0
  160. /package/dist/{status-RWXIIWYS.js.map → status-HCVAOCN7.js.map} +0 -0
  161. /package/dist/{status-line-77XYZP7E.js.map → status-line-OPCXDHL2.js.map} +0 -0
  162. /package/dist/{update-LRNOEGSB.js.map → update-CACXLQLR.js.map} +0 -0
  163. /package/dist/{usdc-D6X7EIQ2.js.map → usdc-VG4CIOUK.js.map} +0 -0
  164. /package/dist/{viemAdapter-By13KInL-RL742ETX.js.map → viemAdapter-By13KInL-DOFTEIJV.js.map} +0 -0
  165. /package/dist/{wallet-XFYC27BR.js.map → wallet-QL4UUXEZ.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/output.ts","../src/schemas.ts"],"sourcesContent":["import { WriteStream } from 'node:tty';\nimport { styleText } from 'node:util';\nimport { CliError } from './errors';\nimport type { StdinInput } from './stdin';\nimport { SCHEMA_VERSION } from '../schemas';\nimport type { UpdateAvailable } from '../schemas';\nimport type { FailureEnvelope, OutputError, SuccessEnvelope } from '../schemas';\n\n/**\n * Injected streams + TTY facts. Every command receives one via CommandContext,\n * so tests drive the CLI in-process with memory buffers and no child process.\n * `isTTY` describes stdout; the separate `--json` flag (passed to the emit\n * functions) is what suppresses human rendering — the two are ANDed, never\n * conflated, so `--json` on a TTY still yields pure machine output. `stdin` is\n * optional for compatibility with command-core contexts that never read it;\n * defaultIo supplies the real stream, and only the CLI forwards that capability\n * to commands that accept Markdown on stdin.\n */\nexport interface Io {\n stdin?: StdinInput;\n stdout: NodeJS.WritableStream;\n stderr: NodeJS.WritableStream;\n isTTY: boolean;\n}\n\nexport function defaultIo(): Io {\n return {\n stdin: { stream: process.stdin, isTTY: Boolean(process.stdin.isTTY) },\n stdout: process.stdout,\n stderr: process.stderr,\n isTTY: Boolean(process.stdout.isTTY),\n };\n}\n\nexport interface EmitOptions {\n /** The global --json flag. When true, the JSON envelope is emitted even at a TTY. */\n json?: boolean;\n /**\n * \"A newer tenjin-cli exists\", from the daily check's cache. Rides the\n * envelope so the AGENT running the command learns it; the human at a TTY\n * gets the dim stderr line instead, and neither path fetches anything.\n */\n updateAvailable?: UpdateAvailable | null;\n}\n\n/**\n * The two pure envelope builders, shared by the CLI's emit functions and the MCP\n * adapter so both surfaces produce the identical wire object by construction. They\n * hold no I/O and no --json branching: they turn a (command, data) or a normalized\n * CliError into the exact object that goes to stdout / structuredContent.\n */\nexport function buildSuccessEnvelope(\n command: string,\n data: unknown,\n updateAvailable?: UpdateAvailable | null,\n): SuccessEnvelope {\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: true,\n data,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\nexport function buildFailureEnvelope(\n command: string,\n err: CliError,\n updateAvailable?: UpdateAvailable | null,\n): FailureEnvelope {\n const error: OutputError = {\n code: err.code,\n message: err.message,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n ...(err.details !== undefined ? { details: err.details } : {}),\n };\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: false,\n error,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\n/**\n * Output contract (human-first): at a TTY without `--json`, print ONLY the human\n * rendering to stdout, no JSON envelope. With `--json`, or when stdout is not a\n * TTY (a pipe, an agent), print exactly one JSON envelope to stdout and nothing\n * else. Exit codes are identical on both paths; only the stdout shape differs.\n */\nexport function emitSuccess(\n io: Io,\n command: string,\n data: unknown,\n humanLines: string[] = [],\n opts: EmitOptions = {},\n): void {\n if (humanMode(io, opts)) {\n writeLines(io.stdout, humanLines);\n return;\n }\n writeJson(io.stdout, buildSuccessEnvelope(command, data, opts.updateAvailable));\n}\n\n/**\n * The failure half of the same contract: at a TTY without `--json`, a red error\n * line plus a `fix` line to stdout and no envelope; otherwise exactly one failure\n * envelope to stdout. Accepts a CliError or any thrown value (non-CliError\n * normalizes to INTERNAL). Returns the normalized CliError so the caller reads its\n * `exitCode`.\n */\nexport function emitFailure(\n io: Io,\n command: string,\n err: unknown,\n opts: EmitOptions = {},\n): CliError {\n const cliErr = normalizeError(err);\n if (humanMode(io, opts)) {\n // Error messages can embed server-sourced text (api error passthrough) and\n // never carry intentional ANSI, so sanitize before painting.\n const lines = [paint(io, 'red', `error: ${sanitizeForTerminal(cliErr.message)}`)];\n if (cliErr.fix !== undefined) {\n lines.push(paint(io, 'dim', `fix: ${sanitizeForTerminal(cliErr.fix)}`));\n }\n // Scan findings are the one detail shape a human needs inline: without them\n // an interactive publish hitting NEEDS_CONFIRMATION / PUBLISH_BLOCKED sees\n // the count but not WHICH lines tripped. Every other shape is machine-only.\n lines.push(...findingLines(io, cliErr.details));\n writeLines(io.stdout, lines);\n return cliErr;\n }\n writeJson(io.stdout, buildFailureEnvelope(command, cliErr, opts.updateAvailable));\n return cliErr;\n}\n\n/**\n * One dim advisory line on stderr, human mode only. This is for facts that belong\n * to NO command's result — an unreadable spend ledger, a newer release on npm —\n * so they can never join the envelope on stdout or reach a machine consumer at\n * all. Sanitized here rather than by each caller: what these lines quote (a\n * registry version string, a parse error) is not the command's own prose.\n */\nexport function emitNotice(io: Io, text: string, opts: EmitOptions = {}): void {\n if (!humanMode(io, opts)) return;\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * The same dim stderr line, delivered whatever the surface is: no TTY gate and no\n * `--json` gate. Only for an advisory a piped or agent-driven run must not miss,\n * which today is two things: a WRITE to the operator's own files, and `fund`'s\n * checkout link, which expires long before the stdout envelope that also carries\n * it is written. Anything a piped run can simply do without belongs in\n * {@link emitNotice} instead. stdout is untouched either way, so the exactly-one\n * JSON object contract is unaffected.\n */\nexport function emitWriteNotice(io: Io, text: string): void {\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * Every escape sequence a terminal writes: CSI (colour, cursor), OSC — which\n * covers the OSC-8 hyperlinks pnpm wraps package names in, terminated by BEL\n * or ST — charset selection, and a stray ESC with a single final byte.\n *\n * Safe to reuse despite the `g` flag: {@link sanitizeForTerminal} uses it\n * through `String.replace`, which starts at 0 and resets `lastIndex`. Do not\n * `test()` or `exec()` it.\n */\nexport const ANSI_ESCAPE_RE =\n // eslint-disable-next-line no-control-regex\n /\\x1b(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])/g;\n\n/**\n * Strip ANSI escape sequences, C0/C1 control characters, Unicode bidirectional\n * formatting, and invisible tag/BOM characters from a string headed for a\n * terminal. Commands apply this to every SERVER-sourced string (titles,\n * handles) they put into human lines or the buy confirm prompt; without it a\n * malicious deployment could use cursor-movement escapes to overwrite the very\n * price a human is being asked to confirm, a right-to-left override to reorder\n * that same line on screen into one that reads as a different price, or tag\n * characters to carry a payload that draws as nothing at all. It is not\n * applied to whole human lines here because trusted callers (doctor) paint\n * their own ANSI colors. JSON stdout is untouched: JSON.stringify escapes C0\n * controls itself, but the bidi and tag/BOM sets ride through it raw, and that\n * is deliberate rather than covered — the envelope is machine-read data whose\n * bytes must be what the server said, and a consumer reading codepoints is not\n * deceived by rendering order the way a human reading a drawn line is.\n */\nexport function sanitizeForTerminal(text: string): string {\n return (\n text\n // CSI/OSC/charset escape sequences first, then any stray ESC and the rest\n // of C0 (except \\t) plus DEL and the C1 range.\n .replace(ANSI_ESCAPE_RE, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x08\\x0a-\\x1f\\x7f-\\x9f]/g, '')\n // The UAX#9 directional formatting set: the marks (LRM/RLM/ALM), the\n // embeddings and overrides (U+202A-U+202E), and the isolates\n // (U+2066-U+2069). Removed, not escaped, so what a human reads is the\n // order the bytes are in. Deliberately this set and NOT all of category\n // Cf: U+200D (ZWJ) joins legitimate emoji sequences, and dropping it\n // would corrupt honest titles to defend against dishonest ones.\n .replace(/[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, '')\n // The Unicode tag block (U+E0000-U+E007F) and the BOM/ZWNBSP, neither of\n // which has a legitimate mid-title use. Tag characters render as nothing\n // at all, so a payload spelled in them is invisible in the line a human\n // is reading and in the line they would paste back to report it.\n //\n // The three RGI subdivision flags are the exception and survive\n // byte-identical: they are ordinary title content. The whitelist is those\n // three sequences and NOT \"any well-formed tag sequence\", because a\n // non-RGI sequence draws as a bare black flag with the payload hidden\n // behind it, which is the exact channel this closes.\n //\n // Kept for the same reason as ZWJ above: U+200B (ZWSP) hints line breaks\n // in CJK and U+200C (ZWNJ) is orthographically required in Persian, so\n // stripping them would corrupt honest titles to defend against dishonest\n // ones.\n .replace(\n /(\\u{1F3F4}\\u{E0067}\\u{E0062}(?:\\u{E0065}\\u{E006E}\\u{E0067}|\\u{E0073}\\u{E0063}\\u{E0074}|\\u{E0077}\\u{E006C}\\u{E0073})\\u{E007F})|[\\u{E0000}-\\u{E007F}\\u{FEFF}]/gu,\n (_match, rgiFlag: string | undefined) => rgiFlag ?? '',\n )\n );\n}\n\n/**\n * The same strip, for text that ships to OTHER PEOPLE rather than to this\n * terminal: a post's title, its public excerpt, and every free-text field of the\n * answer card a buyer reads before paying.\n *\n * The threat is the same one {@link sanitizeForTerminal} closes, one hop further\n * out. None of this text is necessarily typed by the person publishing: a card\n * question can be prefilled from a stored search, and every field can arrive over\n * MCP from an agent that read them off a fetched page. `trim()` removes neither a\n * CSI sequence nor a right-to-left override, so without this a payload rides into\n * the marketplace and renders in every future reader's terminal.\n *\n * Newlines and tabs fold to a single space FIRST, because these are all\n * single-line display fields and a bare strip would join the words on either side\n * of a line break into one. NOT for the post BODY: that is the author's document,\n * markdown and all, and rewriting it is not this function's business.\n */\nexport function sanitizeWireText(text: string): string {\n return sanitizeForTerminal(text.replace(/[\\r\\n\\t]+/g, ' ')).trim();\n}\n\n/** CliError passes through; every other thrown value becomes an INTERNAL CliError. */\nexport function normalizeError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n if (err instanceof Error) return new CliError('INTERNAL', err.message, { cause: err });\n return new CliError('INTERNAL', 'Unexpected error', { details: err });\n}\n\n/** True in human-first mode: a TTY without --json. Otherwise the JSON envelope wins. */\nfunction humanMode(io: Io, opts: EmitOptions): boolean {\n return io.isTTY && opts.json !== true;\n}\n\n/**\n * Render `details.findings` (the scan-finding projection publish attaches to\n * NEEDS_CONFIRMATION / PUBLISH_BLOCKED) as one dim line per finding:\n * ` <check> (line N): <excerpt>`. The excerpt is already masked for secret\n * findings at the source; sanitize it anyway since it can echo file content.\n * Returns [] for any other details shape, so no other error leaks a detail dump.\n *\n * A finding the SERVER gate contributed carries a `source`, and the marker is\n * printed because it is the difference between \"fix your file\" and \"the\n * marketplace refused this\": the detector may be one this release predates, so\n * the line has to stand on the server's own words rather than on recognition.\n * The tier rides the same line, for the payloads that mix block and warn.\n */\nfunction findingLines(io: Io, details: unknown): string[] {\n if (typeof details !== 'object' || details === null || !('findings' in details)) return [];\n const { findings } = details as { findings: unknown };\n if (!Array.isArray(findings) || findings.length === 0) return [];\n const rendered: string[] = [];\n for (const f of findings) {\n if (typeof f !== 'object' || f === null) continue;\n const { check, line, excerpt, source, severity } = f as {\n check?: unknown;\n line?: unknown;\n excerpt?: unknown;\n source?: unknown;\n severity?: unknown;\n };\n if (typeof check !== 'string' || typeof line !== 'number' || typeof excerpt !== 'string') {\n continue;\n }\n const from = source === 'server' ? ' [server]' : source === 'both' ? ' [local+server]' : '';\n // THE TIER IS PRINTED because one payload can mix them: a `scan_blocked`\n // envelope ships the block finding alongside the warns the same pass found,\n // and without the tier nothing on the page says which one is the refusal.\n // An open string, sanitized like the rest: the server owns its own tier names.\n const tier = typeof severity === 'string' && severity.length > 0 ? `${severity}, ` : '';\n // The detector id is sanitized too: on a server finding it is a name this\n // release may never have seen, so it is untrusted text like the excerpt.\n rendered.push(\n paint(\n io,\n 'dim',\n ` ${sanitizeForTerminal(check)}${from} (${sanitizeForTerminal(tier)}line ${line}): ${sanitizeForTerminal(excerpt)}`,\n ),\n );\n }\n return rendered;\n}\n\nfunction writeJson(stream: NodeJS.WritableStream, value: unknown): void {\n stream.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction writeLines(stream: NodeJS.WritableStream, lines: string[]): void {\n if (lines.length > 0) stream.write(`${lines.join('\\n')}\\n`);\n}\n\nexport type StyleFormat = Parameters<typeof styleText>[0];\n\n/**\n * Does `stream` take ANSI color? Node's own rule (`shouldColorize`): FORCE_COLOR\n * wins when set, otherwise a TTY whose color depth is above 2 (which reads\n * NO_COLOR, NODE_DISABLE_COLORS and TERM). Decided here because styleText only\n * checks the stream from Node 22.13 and colors unconditionally before it.\n */\nexport function colorCapable(stream: unknown, env: NodeJS.ProcessEnv = process.env): boolean {\n const force = env.FORCE_COLOR;\n if (force !== undefined) return ['', '1', 'true', '2', '3'].includes(force);\n return stream instanceof WriteStream && stream.isTTY && stream.getColorDepth(env) > 2;\n}\n\n/** `text` in `format` when `stream` takes color, else plain. */\nexport function style(format: StyleFormat, text: string, stream: unknown = process.stdout): string {\n return colorCapable(stream) ? styleText(format, text, { validateStream: false }) : text;\n}\n\n/** Color a human line for stdout. A test or redirected sink is no TTY, so it comes out plain. */\nexport function paint(io: Io, format: StyleFormat, text: string): string {\n return style(format, text, io.stdout);\n}\n","import { z } from 'zod';\n\n/**\n * Bumped only on a breaking change to any stdout envelope shape. Agents pin on\n * this: a consumer that sees an unexpected value should refuse to parse rather\n * than guess. Every envelope carries it, success or failure.\n */\nexport const SCHEMA_VERSION = 1;\n\n/**\n * The closed set of machine error codes. `error.code` in a failure envelope is\n * always one of these; agents branch on it, humans read `message`/`fix`. The\n * exit-code mapping lives in lib/errors.ts (this enum is the single source of\n * the code names both sides agree on).\n */\nexport const ErrorCodeSchema = z.enum([\n 'NODE_UNSUPPORTED',\n 'USAGE',\n 'CONFIG_INVALID',\n 'WALLET_EXISTS',\n 'WALLET_MISSING',\n 'WALLET_INVALID_KEY',\n 'PROVIDER_ERROR',\n 'RPC_ERROR',\n 'API_UNREACHABLE',\n 'CONTRACT_MISMATCH',\n 'REFUSED',\n 'NETWORK_ERROR',\n 'INTERNAL',\n 'NOT_IMPLEMENTED',\n // B2 (search/inspect/buy/outcome): a policy refusal (exit 3) has its own code\n // so an agent can distinguish a spend-cap block from a generic REFUSED; a\n // payment that failed after approval (exit 4) is PAYMENT_FAILED; the read\n // route's own coded failures (402 preview parse, 409 gate) surface as these.\n 'POLICY_REFUSED',\n 'PAYMENT_FAILED',\n 'RESOURCE_NOT_FOUND',\n 'SEARCH_NOT_FOUND',\n // A 429 from the anonymous search/outcome/read limits; error.details carries\n // retryAfterSeconds so a looping agent can back off instead of hammering.\n 'RATE_LIMITED',\n // B3 (publish): a publish that needs the human's yes (exit 3) — soft scan\n // findings, or `review` mode always. NEEDS_CONFIRMATION clears with --yes;\n // PUBLISH_BLOCKED is a hard-block finding (a live secret) that no mode or --yes\n // ever clears. PUBLISH_FAILED (exit 4) is a write that failed AFTER approval,\n // mirroring PAYMENT_FAILED's post-decision failure class.\n 'NEEDS_CONFIRMATION',\n 'PUBLISH_BLOCKED',\n 'PUBLISH_FAILED',\n // A send that reverted or produced no receipt AFTER the human approved it and\n // it was broadcast (exit 4), same post-decision class as PAYMENT_FAILED.\n 'SEND_FAILED',\n // `tenjin delete`: the soft-delete failed AFTER the human confirmed it (exit\n // 4). Its own code rather than PUBLISH_FAILED because the two say opposite\n // things about what is now live, and an agent reporting the outcome to a user\n // must not read \"the piece is still up\" as \"the piece went up\".\n 'DELETE_FAILED',\n // `tenjin update`: the npm install it spawned exited nonzero or never started.\n // Exit 1, not the post-decision class: nothing is half-written that the\n // operator must reconcile, and the old build keeps running.\n 'UPDATE_FAILED',\n // `tenjin pay` Bazaar lane: the live 402 does not match what a configured\n // registry publicly advertises for this resource (understood-but-refused, 3);\n // nothing was signed and nothing was spent.\n 'REGISTRY_MISMATCH',\n // The seller's 402 challenge exceeds this process's response-header limit, so\n // its terms could never be read (understood-but-refused, 3). Nothing was\n // signed and nothing was sent; a retry changes nothing without an operator\n // raising `--max-http-header-size` on the process that runs the CLI.\n 'CHALLENGE_TOO_LARGE',\n]);\nexport type ErrorCode = z.infer<typeof ErrorCodeSchema>;\n\n/**\n * All money in machine output is dual-form: `atomic` is the 6-decimal USDC base\n * unit as a decimal string (never a JS number — precision), `usd` is the same\n * value formatted as decimal dollars. Emit both so agents compute on `atomic`\n * and humans read `usd` without either side re-deriving the other.\n */\nexport const MoneySchema = z.object({\n atomic: z.string(),\n usd: z.string(),\n});\nexport type Money = z.infer<typeof MoneySchema>;\n\nexport const OutputErrorSchema = z.object({\n code: ErrorCodeSchema,\n message: z.string(),\n fix: z.string().optional(),\n details: z.unknown().optional(),\n});\nexport type OutputError = z.infer<typeof OutputErrorSchema>;\n\n/**\n * \"A newer tenjin-cli exists\", carried on the envelope so an AGENT learns it.\n *\n * The daily check's other surface is one dim stderr line, which only a human at\n * a terminal ever sees; on the machines that run this CLI most, nobody does.\n * This field is how the agent driving the command finds out it can run\n * `tenjin update` itself. Read from the check's cache, never fetched here: the\n * envelope must not wait on a network call it did not need.\n */\nexport const UpdateAvailableSchema = z.object({\n current: z.string(),\n latest: z.string(),\n});\nexport type UpdateAvailable = z.infer<typeof UpdateAvailableSchema>;\n\nexport const SuccessEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(true),\n data: z.unknown(),\n /** Present only when a newer version is known and update.mode is not `off`. */\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type SuccessEnvelope = z.infer<typeof SuccessEnvelopeSchema>;\n\nexport const FailureEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(false),\n error: OutputErrorSchema,\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type FailureEnvelope = z.infer<typeof FailureEnvelopeSchema>;\n\n/** The one thing every invocation prints to stdout, discriminated on `ok`. */\nexport const OutputEnvelopeSchema = z.discriminatedUnion('ok', [\n SuccessEnvelopeSchema,\n FailureEnvelopeSchema,\n]);\nexport type OutputEnvelope = z.infer<typeof OutputEnvelopeSchema>;\n"],"mappings":";;;;;;;;;AAAA,SAAS,mBAAmB;AAC5B,SAAS,iBAAiB;;;ACMnB,IAAM,iBAAiB;AAQvB,IAAM,kBAAkB,iBAAE,KAAK;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AACF,CAAC;AASM,IAAM,cAAc,iBAAE,OAAO;AAAA,EAClC,QAAQ,iBAAE,OAAO;AAAA,EACjB,KAAK,iBAAE,OA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AAS,oBAAoB;AAKzF,UAAM,OAAO,OAAO,aAAa,YAAY,SAAS,SAAS,IAAI,GAAG,QAAQ,OAAO;AAGrF,aAAS;AAAA,MACP;AAAA,QACE;AAAA,QACA;AAAA,QACA,KAAK,oBAAoB,KAAK,CAAC,GAAG,IAAI,KAAK,oBAAoB,IAAI,CAAC,QAAQ,IAAI,MAAM,oBAAoB,OAAO,CAAC;AAAA,MACpH;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,UAAU,QAA+B,OAAsB;AACtE,SAAO,MAAM,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA,CAAI;AACpD;AAEA,SAAS,WAAW,QAA+B,OAAuB;AACxE,MAAI,MAAM,SAAS,EAAG,QAAO,MAAM,GAAG,MAAM,KAAK,IAAI,CAAC;AAAA,CAAI;AAC5D;AAUO,SAAS,aAAa,QAAiB,MAAyB,QAAQ,KAAc;AAC3F,QAAM,QAAQ,IAAI;AAClB,MAAI,UAAU,OAAW,QAAO,CAAC,IAAI,KAAK,QAAQ,KAAK,GAAG,EAAE,SAAS,KAAK;AAC1E,SAAO,kBAAkB,eAAe,OAAO,SAAS,OAAO,cAAc,GAAG,IAAI;AACtF;AAGO,SAAS,MAAM,QAAqB,MAAc,SAAkB,QAAQ,QAAgB;AACjG,SAAO,aAAa,MAAM,IAAI,UAAU,QAAQ,MAAM,EAAE,gBAAgB,MAAM,CAAC,IAAI;AACrF;AAGO,SAAS,MAAM,IAAQ,QAAqB,MAAsB;AACvE,SAAO,MAAM,QAAQ,MAAM,GAAG,MAAM;AACtC;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  normalizeChannelId
4
- } from "./chunk-445VQTVM.js";
4
+ } from "./chunk-IE7P2BZE.js";
5
5
 
6
6
  // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-3632HGL3.mjs
7
7
  import { mkdir, readFile, rename, unlink, writeFile } from "fs/promises";
@@ -102,4 +102,4 @@ var FileClientChannelStorage = class {
102
102
  export {
103
103
  FileClientChannelStorage
104
104
  };
105
- //# sourceMappingURL=chunk-QF3LSMGS.js.map
105
+ //# sourceMappingURL=chunk-GTTUCOPD.js.map
@@ -8,7 +8,7 @@ import {
8
8
  CODEX_ALLOW_HOOK_COMMAND_WINDOWS,
9
9
  CODEX_HOOK_COUNT,
10
10
  CODEX_LEGS
11
- } from "./chunk-E7LGOMH6.js";
11
+ } from "./chunk-LRW6S53P.js";
12
12
  import {
13
13
  HOOK_TOOL
14
14
  } from "./chunk-UUGOUOVT.js";
@@ -117,4 +117,4 @@ export {
117
117
  listCodexHooks,
118
118
  codexHookRows
119
119
  };
120
- //# sourceMappingURL=chunk-3DIL66VX.js.map
120
+ //# sourceMappingURL=chunk-HGGWCP7W.js.map
@@ -4,13 +4,13 @@ import {
4
4
  } from "./chunk-HGZEPQUT.js";
5
5
  import {
6
6
  getUsdcBalance
7
- } from "./chunk-GAKUQHKA.js";
7
+ } from "./chunk-TC2WZLSC.js";
8
8
  import {
9
9
  markUnlockPending
10
10
  } from "./chunk-WYXUQGOL.js";
11
11
  import {
12
12
  channelCredit
13
- } from "./chunk-D3ZURCG7.js";
13
+ } from "./chunk-TKPF35W6.js";
14
14
  import {
15
15
  commitLocalWallet,
16
16
  createLocalWallet,
@@ -25,10 +25,10 @@ import {
25
25
  verifyAndPreserveOutgoingWallet,
26
26
  walletExistsError,
27
27
  walletFileExists
28
- } from "./chunk-BI673VEJ.js";
28
+ } from "./chunk-UXZONNEQ.js";
29
29
  import {
30
30
  emitNotice
31
- } from "./chunk-VJUVFZ2D.js";
31
+ } from "./chunk-FVIGCDSV.js";
32
32
  import {
33
33
  FUNDING_LINE,
34
34
  FUND_COMMAND_LINE
@@ -60,7 +60,10 @@ import {
60
60
  import {
61
61
  loadRawConfig,
62
62
  resolveSettings
63
- } from "./chunk-2GNOFONN.js";
63
+ } from "./chunk-2M2VPI2E.js";
64
+ import {
65
+ forgetRememberedBalance
66
+ } from "./chunk-WXA2BWTE.js";
64
67
  import {
65
68
  CliError
66
69
  } from "./chunk-3UCIG4TG.js";
@@ -434,6 +437,7 @@ async function runWalletBalance(ctx, opts = {}) {
434
437
  cause: err
435
438
  });
436
439
  }
440
+ await forgetRememberedBalance(ctx.dataDir);
437
441
  const balance = toMoney(atomic.toString());
438
442
  const credit = toMoney(
439
443
  (await channelCredit(ctx.dataDir, desc.address).catch(() => 0n)).toString()
@@ -471,4 +475,4 @@ export {
471
475
  runWalletShow,
472
476
  runWalletBalance
473
477
  };
474
- //# sourceMappingURL=chunk-D5TOQSO4.js.map
478
+ //# sourceMappingURL=chunk-HMWYAUA6.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/wallet.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { emitNotice } from '../lib/output';\nimport { walletPath } from '../lib/paths';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { toMoney } from '../lib/money';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { addressQrLines } from '../lib/qr';\nimport { writePassphraseRecord } from '../lib/passphrase-record';\nimport { NO_KEYRING_LINE, REPAIR_CLAUSE, REPAIR_IN_TERMINAL } from '../lib/wallet-unlock';\nimport { channelCredit } from '../router/channel-credit';\nimport { FUND_COMMAND_LINE, FUNDING_LINE } from '../router/fee';\nimport { markUnlockPending } from '../router/router-observation';\nimport {\n commitLocalWallet,\n createLocalWallet,\n describeWallet,\n openKeystore,\n parkOutgoingWallet,\n prepareLocalWallet,\n repairLocalWalletPassphrase,\n resolveWalletProvider,\n restoreParkedWallet,\n verifyAndPreserveOutgoingWallet,\n type ArchivedWalletInfo,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport {\n readWalletRecord,\n walletExistsError,\n walletFileExists,\n type WalletRecord,\n} from '../lib/wallet/store';\nimport {\n describeStoreLocation,\n promptPassphrase,\n resolvePassphrase,\n resolvePassphraseForCreate,\n STORE_TIMEOUTS,\n storeNoun,\n unstorableWhy,\n type CreatePassphraseResult,\n type DurableStore,\n} from '../lib/wallet/passphrase';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport type { CommandContext, CommandResult } from '../context';\n\nconst KEY_STORAGE = 'encrypted (keystore v3, scrypt)';\nconst isWindows = process.platform === 'win32';\n\n/** The last line `tenjin wallet repair` prints: the save is proven, the unlock is not yet. */\nexport const REPAIR_DONE_LINE = 'Passphrase saved; start a new Claude Code session to verify.';\n\nexport interface WalletCreateOptions {\n /**\n * Explicitly replace the existing active wallet (mirrors the `--yes`-style\n * explicit-flag precedent): the outgoing wallet is ARCHIVED — passphrase\n * verified against its keystore and preserved under its own address, keystore\n * parked beside the new one — never destroyed. Without it, create refuses\n * when a wallet exists. There is always exactly ONE active wallet.\n */\n replace?: boolean;\n /** Test seam for passphrase resolution (keychain exec, TTY prompt, platform). */\n passphrase?: PassphraseOverrides;\n /**\n * The environment TENJIN_WALLET_PASSPHRASE is read from; defaults to\n * process.env. A seam rather than a global read so a caller (and above all a\n * test) can settle the passphrase source WITHOUT mutating the real process\n * environment, which under a parallel runner leaks across whole test files.\n */\n env?: NodeJS.ProcessEnv;\n /**\n * `--insecure-storage`: save the passphrase to the 0600 file even where an OS\n * keychain exists. For a person who chose it; never suggested by an error.\n */\n insecureStorage?: boolean;\n}\n\nexport async function runWalletCreate(\n ctx: CommandContext,\n opts: WalletCreateOptions = {},\n): Promise<CommandResult> {\n const { address, walletPath: path, passphrase, replaced } = await createWalletLocked(ctx, opts);\n\n const note = passphraseNote(passphrase, address, ctx.dataDir);\n const warnings = custodyWarnings();\n return {\n data: {\n address,\n walletPath: path,\n provider: 'local',\n policyEnforcement: 'client-only',\n keyStorage: KEY_STORAGE,\n passphraseSource: passphrase.source,\n passphraseLocation: passphrase.location,\n passphraseOrigin: passphrase.origin,\n passphraseDurable: passphrase.durable,\n passphraseNote: note,\n ...(replaced !== undefined\n ? {\n replaced: {\n address: replaced.address,\n archivedWalletPath: replaced.archivedPath,\n passphrasePreserved: replaced.passphraseLocation,\n ...(replaced.unarchivedReason !== undefined\n ? { unarchivedReason: replaced.unarchivedReason }\n : {}),\n },\n }\n : {}),\n warnings,\n },\n humanLines: [\n `Wallet created: ${address}`,\n `Key stored ${KEY_STORAGE}.`,\n note,\n ...(replaced !== undefined ? replacedNote(replaced, path) : []),\n FUNDING_LINE,\n ...warnings,\n ],\n };\n}\n\n/** Where the outgoing wallet's funds live, why they remain reachable, and how to restore it. */\nfunction replacedNote(replaced: ArchivedWalletInfo, activeWalletPath: string): string[] {\n const passphraseLine =\n replaced.passphraseLocation === 'store'\n ? `its passphrase is preserved in ${replaced.location ?? `the OS credential store (service tenjin-cli, account ${replaced.account})`}.`\n : replaced.passphraseLocation === 'env'\n ? 'its passphrase is TENJIN_WALLET_PASSPHRASE — keep that value.'\n : replaced.unarchivedReason === 'rejected-characters'\n ? 'its passphrase was NOT archived: the macOS keychain writer only stores printable ASCII passphrases, and this typed one contains other characters. Keep it yourself, or set TENJIN_WALLET_PASSPHRASE to it.'\n : 'its passphrase was NOT archived: this platform has no OS credential store. It exists only where you keep it.';\n return [\n `Previous wallet archived: ${replaced.address} still holds any funds sent to it.`,\n `Its keystore was moved to ${replaced.archivedPath}; ${passphraseLine}`,\n `To make it the active wallet again later: move the current ${activeWalletPath} aside first, then \\`mv ${replaced.archivedPath} ${activeWalletPath}\\`.`,\n ];\n}\n\n/**\n * Run `fn` under the cross-process wallet lock (`<dir>/wallet.create.lock`):\n * create, `--replace` and repair all change where a wallet's passphrase lives,\n * and the sidecar's read-modify-write assumes one writer at a time.\n *\n * A lock timeout is not the user's error; it surfaces as INTERNAL with the one\n * manual step (there is no auto-steal), keeping the JSON error contract. Every\n * other error — notably a create loser's WALLET_EXISTS — propagates unchanged.\n */\nexport async function withWalletLock<T>(dir: string, fn: () => Promise<T>): Promise<T> {\n // Ensure the data dir exists so the lock's own mkdir has a parent on a fresh\n // install; the exclusive wallet write re-ensures it at 0700 regardless.\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = join(dir, 'wallet.create.lock');\n try {\n return await withFileLock(lockPath, fn);\n } catch (err) {\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\n/**\n * Run the whole create critical section under the wallet lock: the existence\n * pre-check, the passphrase choose-and-store, and the no-clobber write. Without\n * the lock these interleave across two concurrent creates — each generates a\n * distinct passphrase and persists it BEFORE the exclusive file write, so a\n * different process could win the file while this one's per-address entry\n * names a wallet that never landed. Serializing means the loser blocks until\n * the winner commits, then trips the exists check and exits WALLET_EXISTS\n * having never generated or stored a passphrase. The store-before-write\n * ordering stays (it still guards the single-process crash window), and the\n * exclusive write stays the final authority.\n *\n * The passphrase is resolved inside the prepare step's address callback so the\n * store entry is keyed to the new wallet's own address (issue #32), and the\n * sidecar records where it went BEFORE the key is encrypted: a sidecar that\n * cannot be written aborts the create, so no wallet exists whose passphrase\n * location nobody recorded.\n *\n * `--replace` ordering closes the no-active-wallet window: verify-and-preserve\n * the outgoing wallet (no file moves), fully PREPARE the replacement (key,\n * stored passphrase, encrypted keystore — every fallible step) while the old\n * wallet is still active, and only then park the old keystore and commit the\n * new one. A commit failure rolls the park back, so at every exit either the\n * old or the new wallet is the active one.\n */\nasync function createWalletLocked(\n ctx: CommandContext,\n opts: WalletCreateOptions,\n): Promise<{\n address: string;\n walletPath: string;\n passphrase: CreatePassphraseResult;\n replaced?: ArchivedWalletInfo;\n}> {\n const dir = ctx.dataDir;\n return withWalletLock(dir, async () => {\n const env = opts.env ?? process.env;\n let chosen: CreatePassphraseResult | undefined;\n const passphraseFor = async (forAddress: string): Promise<string> => {\n const resolved = await resolvePassphraseForCreate(\n {\n env,\n dir,\n ...opts.passphrase,\n // Create never prompts; this only picks the 10 s or 60 s write bound.\n isTTY: opts.passphrase?.isTTY ?? ctx.io.isTTY,\n onWait: (line) => emitNotice(ctx.io, line, { json: ctx.flags.json }),\n },\n forAddress,\n { insecureStorage: opts.insecureStorage === true },\n );\n if (resolved.durable && resolved.source !== 'env') {\n await writePassphraseRecord(dir, forAddress, { store: resolved.source, by: 'create' });\n }\n chosen = resolved;\n return resolved.passphrase;\n };\n const result = (path: { address: string; walletPath: string }) => {\n if (chosen === undefined) throw new CliError('INTERNAL', 'No wallet passphrase was chosen.');\n return { ...path, passphrase: chosen };\n };\n\n if (!(await walletFileExists(dir))) {\n return result(await createLocalWallet(dir, passphraseFor));\n }\n\n if (opts.replace !== true) throw walletExistsError(dir);\n const preserved = await verifyAndPreserveOutgoingWallet({\n dir,\n env,\n ...(opts.passphrase !== undefined ? { passphrase: opts.passphrase } : {}),\n });\n const prepared = await prepareLocalWallet(passphraseFor);\n const archivedPath = await parkOutgoingWallet(dir, preserved.account);\n try {\n const committed = await commitLocalWallet(dir, prepared);\n return { ...result(committed), replaced: { ...preserved, archivedPath } };\n } catch (err) {\n try {\n await restoreParkedWallet(dir, archivedPath);\n } catch (restoreErr) {\n // The no-clobber restore also refuses when a wallet.json appeared out\n // of band (commit EEXIST) — never overwrite it; name both files.\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed after the old wallet was parked, and restoring it also failed.',\n {\n fix: `Your old wallet ${preserved.address} is intact at ${archivedPath} with its passphrase preserved. If a ${walletPath(dir)} now exists, another process wrote it — move it aside first. Then restore with \\`mv ${archivedPath} ${walletPath(dir)}\\`.`,\n cause: restoreErr,\n },\n );\n }\n // Old wallet restored as the active one; say so rather than surfacing a\n // raw fs error (or a WALLET_EXISTS whose fix suggests re-running --replace).\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed; the previous wallet was restored and is the active wallet again.',\n {\n fix: 'Nothing was lost. Fix the underlying error, then retry `tenjin wallet create --replace`.',\n cause: err,\n },\n );\n }\n });\n}\n\n/**\n * THE ONE LINE THAT SAYS WHERE THE PASSPHRASE WENT (Q2, S4). A generated secret\n * in an OS store keeps today's three notes byte for byte; an env secret saved\n * there says the variable is no longer needed; the 0600 file says why it was\n * used; and an env secret nothing durable holds says so, and how to fix it\n * once the store answers. Every line that names `tenjin wallet repair` carries\n * REPAIR_CLAUSE, and a file failure never names a keychain (decision 6).\n */\nexport function passphraseNote(p: CreatePassphraseResult, address: string, dir: string): string {\n const account = address.toLowerCase();\n if (!p.durable) {\n const attempted = p.attempted ?? 'keychain';\n const only = 'so Claude Code can unlock this wallet only where that variable is set.';\n switch (p.notSaved) {\n case 'rejected-characters':\n // Repair would refuse the same value: the variable is the fix.\n return `Encrypted with TENJIN_WALLET_PASSPHRASE only: ${unstorableWhy(attempted)}, ${only} Keep it set in the environment Claude Code starts from.`;\n case 'conflict':\n case 'kept-existing':\n return `Encrypted with TENJIN_WALLET_PASSPHRASE only: ${describeStoreLocation(attempted, account, dir)} already holds a different passphrase for this wallet, ${only} Run \\`tenjin wallet repair\\` yourself ${REPAIR_CLAUSE} to replace it.`;\n default:\n break;\n }\n if (attempted === 'file') {\n const path = describeStoreLocation('file', account, dir);\n return `Encrypted with TENJIN_WALLET_PASSPHRASE only: Tenjin could not save the passphrase to ${path}, ${only} Check that ${dirname(path)} is writable, then run \\`tenjin wallet repair\\` yourself ${REPAIR_CLAUSE}.`;\n }\n if (p.notSaved === 'store-failed') {\n return `Encrypted with TENJIN_WALLET_PASSPHRASE only: Tenjin could not save the passphrase to the ${storeNoun(attempted)}, ${only} Run \\`tenjin wallet repair\\` yourself ${REPAIR_CLAUSE}.`;\n }\n return `Encrypted with TENJIN_WALLET_PASSPHRASE only: the ${storeNoun(attempted)} did not answer, ${only} Once it answers, run \\`tenjin wallet repair\\` yourself ${REPAIR_CLAUSE}.`;\n }\n if (p.source === 'file' || p.source === 'env') {\n if (p.fileReason === 'insecure-storage') {\n return `Passphrase saved to ${p.location} (readable only by you). Anyone who can read that file and wallet.json can spend this wallet.`;\n }\n return NO_KEYRING_LINE(p.location);\n }\n if (p.origin === 'env') {\n return `Passphrase from TENJIN_WALLET_PASSPHRASE saved to ${p.location}; Claude Code can unlock this wallet without the variable.`;\n }\n switch (p.source) {\n case 'keychain':\n return `Passphrase saved to your macOS keychain (service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n case 'dpapi':\n return `Passphrase saved to a DPAPI-encrypted per-wallet file (passphrase.${account}.dpapi), readable only by you on this Windows machine; signing will be transparent here.`;\n case 'secret-service':\n return `Passphrase saved to your Linux keyring (Secret Service, service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n }\n}\n\nexport interface WalletRepairOptions {\n /** `--insecure-storage`: save to the 0600 file even where an OS keychain exists. */\n insecureStorage?: boolean;\n /** Test seam for passphrase storage (keychain exec, TTY prompt, platform). */\n passphrase?: PassphraseOverrides;\n /** The environment TENJIN_WALLET_PASSPHRASE is read from; defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** The home directory whose shell startup files are scanned for an export; defaults to os.homedir(). */\n home?: string;\n /** Reads one startup file, null when it cannot be read; a seam for tests. */\n readText?: (path: string) => Promise<string | null>;\n}\n\n/** What `tenjin wallet repair --json` prints. */\nexport interface WalletRepairData {\n address: string;\n passphraseStore: DurableStore;\n location: string;\n alreadySaved: boolean;\n replacedUnusableEntry: boolean;\n envOverride: {\n state: 'unset' | 'matches' | 'wrong';\n exports: Array<{ file: string; line: number }>;\n };\n restartRequired: true;\n next: typeof REPAIR_DONE_LINE;\n}\n\n/** The shell startup files a TENJIN_WALLET_PASSPHRASE export usually lives in, relative to home. */\nconst SHELL_STARTUP_FILES = [\n '.zshrc',\n '.zprofile',\n '.zshenv',\n '.bashrc',\n '.bash_profile',\n '.profile',\n '.config/fish/config.fish',\n];\n\n/**\n * `tenjin wallet repair`: for a wallet Claude Code cannot unlock. A PERSON runs\n * it, in their own terminal: it asks for the passphrase at a hidden prompt (or\n * uses TENJIN_WALLET_PASSPHRASE when that opens the wallet), proves it opens\n * this wallet, saves it where Claude Code's router can read it without a\n * prompt, and marks the unlock as awaiting confirmation, which the next\n * session's router confirms (\"Tenjin wallet unlocked.\").\n *\n * With no terminal and a wrong variable, the saved passphrase is checked in\n * its place, so a headless run still names the variable when the saved one\n * already opens the wallet. With no terminal and nothing usable it refuses with\n * REPAIR_IN_TERMINAL and never suggests passing the passphrase inline (B1): a passphrase never\n * goes on a command line or into chat. It reports success only when the store\n * reads this passphrase back (S1). A TENJIN_WALLET_PASSPHRASE in this shell\n * that does not open the wallet is named, with the startup-file line that\n * exports it, because it shadows the saved passphrase until removed.\n */\nexport async function runWalletRepair(\n ctx: CommandContext,\n opts: WalletRepairOptions = {},\n): Promise<CommandResult> {\n const env = opts.env ?? process.env;\n const dir = ctx.dataDir;\n const record = await readWalletRecord(dir);\n if (record === null) {\n throw new CliError('WALLET_MISSING', 'No wallet found to repair.', {\n fix: 'Run `tenjin wallet create` to create one.',\n });\n }\n const address = record.address;\n const humanPre: string[] = [];\n const envKey = env.TENJIN_WALLET_KEY;\n if (envKey !== undefined && envKey.trim().length > 0) {\n humanPre.push(\n 'TENJIN_WALLET_KEY is set and shadows the wallet file; repair fixes only the file wallet.',\n );\n }\n\n const fromEnv = env.TENJIN_WALLET_PASSPHRASE;\n let envState: WalletRepairData['envOverride']['state'] = 'unset';\n let candidate: string | undefined;\n if (fromEnv !== undefined && fromEnv.length > 0) {\n const opened = await openKeystore(record.keystore, address, fromEnv);\n envState = opened === 'wrong' ? 'wrong' : 'matches';\n // A mismatch is a tampered file; repair refuses it below with the tamper error.\n if (opened !== 'wrong') candidate = fromEnv;\n }\n const interactive = ctx.io.isTTY && (opts.passphrase?.isTTY ?? Boolean(process.stdin.isTTY));\n if (candidate === undefined && !interactive && envState === 'wrong') {\n // Headless with a wrong variable: a SAVED passphrase that opens the wallet\n // is the candidate, so an agent's run reaches the same conflict line (unset\n // the variable) a person's prompt would, instead of a bare USAGE.\n candidate = await savedPassphraseThatOpens(dir, env, record, opts.passphrase);\n }\n if (candidate === undefined) {\n if (!interactive) {\n throw new CliError(\n 'USAGE',\n envState === 'wrong'\n ? 'No passphrase to check: TENJIN_WALLET_PASSPHRASE is set but does not open this wallet, and no saved passphrase does.'\n : 'No passphrase to check.',\n { fix: REPAIR_IN_TERMINAL },\n );\n }\n const entered = await promptPassphrase(\n { env, ...opts.passphrase },\n `Passphrase for wallet ${address}: `,\n );\n if (entered.length === 0) {\n throw new CliError('USAGE', 'No passphrase entered; nothing was saved.', {\n fix: REPAIR_IN_TERMINAL,\n });\n }\n candidate = entered;\n }\n\n const passphrase = candidate;\n const outcome = await withWalletLock(dir, () =>\n repairLocalWalletPassphrase(\n {\n dir,\n env,\n passphrase: {\n ...opts.passphrase,\n isTTY: ctx.io.isTTY,\n onWait: (line) => emitNotice(ctx.io, line, { json: ctx.flags.json }),\n },\n },\n passphrase,\n opts.insecureStorage === true ? { insecureStorage: true } : {},\n ),\n );\n // The next session's router confirms the unlock and says so once. A failure\n // to record that only costs the confirmation line, never the saved passphrase,\n // so it does not fail a repair that is already proven.\n await markUnlockPending(dir, outcome.address).catch(() => undefined);\n\n const exports =\n envState === 'unset' ? [] : await scanShellExports(opts.home ?? homedir(), opts.readText);\n const savedLine = outcome.alreadySaved\n ? `Already saved in ${outcome.location}.`\n : outcome.fileReason === 'no-keyring'\n ? NO_KEYRING_LINE(outcome.location)\n : `Saved to ${outcome.location}.`;\n const envLine =\n envState === 'wrong'\n ? `! TENJIN_WALLET_PASSPHRASE is set in this shell but does not open this wallet. Tenjin now uses the saved passphrase, but remove the variable: \\`unset TENJIN_WALLET_PASSPHRASE\\`${\n exports.length > 0\n ? `, and delete the export at ${exports.map((e) => `${e.file}:${e.line}`).join(', ')}`\n : ''\n }.`\n : envState === 'matches'\n ? 'TENJIN_WALLET_PASSPHRASE in this shell matches; the saved copy is enough, so you can remove it.'\n : null;\n\n const data: WalletRepairData = {\n address: outcome.address,\n passphraseStore: outcome.store,\n location: outcome.location,\n alreadySaved: outcome.alreadySaved,\n replacedUnusableEntry: outcome.replacedUnusableEntry,\n envOverride: { state: envState, exports },\n restartRequired: true,\n next: REPAIR_DONE_LINE,\n };\n return {\n data,\n humanLines: [\n ...humanPre,\n `Wallet: ${outcome.address}`,\n 'Passphrase verified: it opens this wallet.',\n savedLine,\n ...(envLine !== null ? [envLine] : []),\n REPAIR_DONE_LINE,\n ],\n };\n}\n\n/**\n * The saved passphrase (keychain, 0600 file or legacy slot; never the variable\n * and never a prompt) when it opens this wallet, else undefined. Reads are\n * bounded like doctor's verify, so a locked keychain cannot hang a headless\n * run; any failure to read reads as \"none\".\n */\nasync function savedPassphraseThatOpens(\n dir: string,\n env: NodeJS.ProcessEnv,\n record: WalletRecord,\n overrides: PassphraseOverrides | undefined,\n): Promise<string | undefined> {\n try {\n const saved = await resolvePassphrase(\n {\n env,\n dir,\n ...overrides,\n isTTY: false,\n readDeadlineMs: overrides?.timeouts?.verifyReadMs ?? STORE_TIMEOUTS.verifyReadMs,\n },\n record.address,\n { skipEnv: true },\n );\n const opened = await openKeystore(record.keystore, record.address, saved.passphrase);\n return opened === 'ok' ? saved.passphrase : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Every TENJIN_WALLET_PASSPHRASE line in the usual shell startup files, as `~/<file>:<line>`. */\nasync function scanShellExports(\n home: string,\n readText: (path: string) => Promise<string | null> = (path) =>\n readFile(path, 'utf8').catch(() => null),\n): Promise<Array<{ file: string; line: number }>> {\n const files: Array<{ path: string; text: string }> = [];\n for (const rel of SHELL_STARTUP_FILES) {\n const text = await readText(join(home, rel));\n if (text !== null) files.push({ path: `~/${rel}`, text });\n }\n return findPassphraseExports(files);\n}\n\n/**\n * The lines that set TENJIN_WALLET_PASSPHRASE (any `export`, `set -gx` or plain\n * assignment naming it), skipping `#` comments. Line numbers are 1-based, as an\n * editor shows them. Only the location is returned, never the line's text: the\n * line may hold the passphrase itself.\n */\nexport function findPassphraseExports(\n files: Array<{ path: string; text: string }>,\n): Array<{ file: string; line: number }> {\n const found: Array<{ file: string; line: number }> = [];\n for (const { path, text } of files) {\n text.split(/\\r?\\n/).forEach((line, i) => {\n if (line.trimStart().startsWith('#')) return;\n if (/\\bTENJIN_WALLET_PASSPHRASE\\b/.test(line)) found.push({ file: path, line: i + 1 });\n });\n }\n return found;\n}\n\nexport interface WalletShowOptions extends ResolveWalletProviderOptions {\n /** `--no-qr`: print the address without the QR block at a TTY. */\n qr?: boolean;\n}\n\nexport async function runWalletShow(\n ctx: CommandContext,\n opts: WalletShowOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n // Diagnostics are the provider's own: a remote provider reports no local file\n // path or perms warning, so `show` never contaminates a remote wallet's output\n // with a stale local wallet.json's state. keyStorage/passphraseSource are the\n // custody posture reported without decrypting or requiring a passphrase.\n const {\n walletPath: path,\n keyStorage,\n passphraseSource,\n archivedWallets,\n warnings,\n } = await provider.diagnostics();\n\n const humanLines = [\n `Address: ${desc.address}`,\n ...(opts.qr !== false && ctx.io.isTTY && !ctx.flags.json\n ? addressQrLines(desc.address, ctx.io.stdout)\n : []),\n `Key source: ${desc.credentialSource}`,\n ];\n if (keyStorage !== undefined) humanLines.push(`Key storage: ${keyStorage}`);\n if (passphraseSource !== undefined) humanLines.push(`Passphrase: ${passphraseSource}`);\n if (archivedWallets !== undefined && archivedWallets.length > 0) {\n // A recovery hint, not a wallet switcher: exactly one wallet is ever active.\n humanLines.push(\n `Archived (replaced) wallets, funds recoverable via their preserved passphrases: ${archivedWallets.join(', ')}`,\n );\n }\n humanLines.push(...warnings);\n\n return {\n data: {\n address: desc.address,\n provider: desc.provider,\n credentialSource: desc.credentialSource,\n policyEnforcement: desc.policyEnforcement,\n ...(path !== undefined ? { walletPath: path } : {}),\n ...(keyStorage !== undefined ? { keyStorage } : {}),\n ...(passphraseSource !== undefined ? { passphraseSource } : {}),\n ...(archivedWallets !== undefined && archivedWallets.length > 0 ? { archivedWallets } : {}),\n warnings,\n },\n humanLines,\n };\n}\n\nexport async function runWalletBalance(\n ctx: CommandContext,\n opts: ResolveWalletProviderOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n\n const config = await loadRawConfig(ctx.dataDir);\n const rpcUrl = resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n }).rpcUrl.value;\n\n let atomic: bigint;\n try {\n atomic = await getUsdcBalance(desc.address, rpcUrl);\n } catch (err) {\n throw new CliError('RPC_ERROR', `Could not read the USDC balance from ${rpcUrl}.`, {\n fix: 'Check your network, or set a working RPC with `tenjin config set rpcUrl <url>`.',\n cause: err,\n });\n }\n\n const balance = toMoney(atomic.toString());\n // THE ROUTING CREDIT IS STILL THE USER'S: a deposit moved it off the wallet\n // into the routing channel, where the next routing fees draw from it.\n const credit = toMoney(\n (await channelCredit(ctx.dataDir, desc.address).catch(() => 0n)).toString(),\n );\n return {\n data: { address: desc.address, balance, routingCredit: credit },\n humanLines: [\n `Balance: ${balance.usd} USDC on Base` +\n (credit.atomic !== '0' ? ` (+${credit.usd} routing credit)` : ''),\n ...(atomic === 0n ? [FUND_COMMAND_LINE] : []),\n ],\n };\n}\n\nfunction custodyWarnings(): string[] {\n const warnings: string[] = [];\n if (hasEnvKey()) {\n warnings.push('TENJIN_WALLET_KEY is set and shadows this file at runtime.');\n }\n if (isWindows) {\n warnings.push('File permissions are not enforced on Windows; the key file is not restricted.');\n }\n return warnings;\n}\n\nfunction hasEnvKey(): boolean {\n const envKey = process.env.TENJIN_WALLET_KEY;\n return envKey !== undefined && envKey.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,gBAAgB;AAChC,SAAS,eAAe;AACxB,SA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AACF,aAAS,MAAM,eAAe,KAAK,SAAS,MAAM;AAAA,EACpD,SAAS,KAAK;AACZ,UAAM,IAAI,SAAS,aAAa,wCAAwC,MAAM,KAAK;AAAA,MACjF,KAAK;AAAA,MACL,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AAEA,QAAM,UAAU,QAAQ,OAAO,SAAS,CAAC;AAGzC,QAAM,SAAS;AAAA,KACZ,MAAM,cAAc,IAAI,SAAS,KAAK,OAAO,EAAE,MAAM,MAAM,EAAE,GAAG,SAAS;AAAA,EAC5E;AACA,SAAO;AAAA,IACL,MAAM,EAAE,SAAS,KAAK,SAAS,SAAS,eAAe,OAAO;AAAA,IAC9D,YAAY;AAAA,MACV,YAAY,QAAQ,GAAG,mBACpB,OAAO,WAAW,MAAM,MAAM,OAAO,GAAG,qBAAqB;AAAA,MAChE,GAAI,WAAW,KAAK,CAAC,iBAAiB,IAAI,CAAC;AAAA,IAC7C;AAAA,EACF;AACF;AAEA,SAAS,kBAA4B;AACnC,QAAM,WAAqB,CAAC;AAC5B,MAAI,UAAU,GAAG;AACf,aAAS,KAAK,4DAA4D;AAAA,EAC5E;AACA,MAAI,WAAW;AACb,aAAS,KAAK,+EAA+E;AAAA,EAC/F;AACA,SAAO;AACT;AAEA,SAAS,YAAqB;AAC5B,QAAM,SAAS,QAAQ,IAAI;AAC3B,SAAO,WAAW,UAAa,OAAO,SAAS;AACjD;","names":[]}
1
+ {"version":3,"sources":["../src/commands/wallet.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { emitNotice } from '../lib/output';\nimport { walletPath } from '../lib/paths';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { toMoney } from '../lib/money';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { forgetRememberedBalance } from '../lib/usdc-balance';\nimport { addressQrLines } from '../lib/qr';\nimport { writePassphraseRecord } from '../lib/passphrase-record';\nimport { NO_KEYRING_LINE, REPAIR_CLAUSE, REPAIR_IN_TERMINAL } from '../lib/wallet-unlock';\nimport { channelCredit } from '../router/channel-credit';\nimport { FUND_COMMAND_LINE, FUNDING_LINE } from '../router/fee';\nimport { markUnlockPending } from '../router/router-observation';\nimport {\n commitLocalWallet,\n createLocalWallet,\n describeWallet,\n openKeystore,\n parkOutgoingWallet,\n prepareLocalWallet,\n repairLocalWalletPassphrase,\n resolveWalletProvider,\n restoreParkedWallet,\n verifyAndPreserveOutgoingWallet,\n type ArchivedWalletInfo,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport {\n readWalletRecord,\n walletExistsError,\n walletFileExists,\n type WalletRecord,\n} from '../lib/wallet/store';\nimport {\n describeStoreLocation,\n promptPassphrase,\n resolvePassphrase,\n resolvePassphraseForCreate,\n STORE_TIMEOUTS,\n storeNoun,\n unstorableWhy,\n type CreatePassphraseResult,\n type DurableStore,\n} from '../lib/wallet/passphrase';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport type { CommandContext, CommandResult } from '../context';\n\nconst KEY_STORAGE = 'encrypted (keystore v3, scrypt)';\nconst isWindows = process.platform === 'win32';\n\n/** The last line `tenjin wallet repair` prints: the save is proven, the unlock is not yet. */\nexport const REPAIR_DONE_LINE = 'Passphrase saved; start a new Claude Code session to verify.';\n\nexport interface WalletCreateOptions {\n /**\n * Explicitly replace the existing active wallet (mirrors the `--yes`-style\n * explicit-flag precedent): the outgoing wallet is ARCHIVED — passphrase\n * verified against its keystore and preserved under its own address, keystore\n * parked beside the new one — never destroyed. Without it, create refuses\n * when a wallet exists. There is always exactly ONE active wallet.\n */\n replace?: boolean;\n /** Test seam for passphrase resolution (keychain exec, TTY prompt, platform). */\n passphrase?: PassphraseOverrides;\n /**\n * The environment TENJIN_WALLET_PASSPHRASE is read from; defaults to\n * process.env. A seam rather than a global read so a caller (and above all a\n * test) can settle the passphrase source WITHOUT mutating the real process\n * environment, which under a parallel runner leaks across whole test files.\n */\n env?: NodeJS.ProcessEnv;\n /**\n * `--insecure-storage`: save the passphrase to the 0600 file even where an OS\n * keychain exists. For a person who chose it; never suggested by an error.\n */\n insecureStorage?: boolean;\n}\n\nexport async function runWalletCreate(\n ctx: CommandContext,\n opts: WalletCreateOptions = {},\n): Promise<CommandResult> {\n const { address, walletPath: path, passphrase, replaced } = await createWalletLocked(ctx, opts);\n\n const note = passphraseNote(passphrase, address, ctx.dataDir);\n const warnings = custodyWarnings();\n return {\n data: {\n address,\n walletPath: path,\n provider: 'local',\n policyEnforcement: 'client-only',\n keyStorage: KEY_STORAGE,\n passphraseSource: passphrase.source,\n passphraseLocation: passphrase.location,\n passphraseOrigin: passphrase.origin,\n passphraseDurable: passphrase.durable,\n passphraseNote: note,\n ...(replaced !== undefined\n ? {\n replaced: {\n address: replaced.address,\n archivedWalletPath: replaced.archivedPath,\n passphrasePreserved: replaced.passphraseLocation,\n ...(replaced.unarchivedReason !== undefined\n ? { unarchivedReason: replaced.unarchivedReason }\n : {}),\n },\n }\n : {}),\n warnings,\n },\n humanLines: [\n `Wallet created: ${address}`,\n `Key stored ${KEY_STORAGE}.`,\n note,\n ...(replaced !== undefined ? replacedNote(replaced, path) : []),\n FUNDING_LINE,\n ...warnings,\n ],\n };\n}\n\n/** Where the outgoing wallet's funds live, why they remain reachable, and how to restore it. */\nfunction replacedNote(replaced: ArchivedWalletInfo, activeWalletPath: string): string[] {\n const passphraseLine =\n replaced.passphraseLocation === 'store'\n ? `its passphrase is preserved in ${replaced.location ?? `the OS credential store (service tenjin-cli, account ${replaced.account})`}.`\n : replaced.passphraseLocation === 'env'\n ? 'its passphrase is TENJIN_WALLET_PASSPHRASE — keep that value.'\n : replaced.unarchivedReason === 'rejected-characters'\n ? 'its passphrase was NOT archived: the macOS keychain writer only stores printable ASCII passphrases, and this typed one contains other characters. Keep it yourself, or set TENJIN_WALLET_PASSPHRASE to it.'\n : 'its passphrase was NOT archived: this platform has no OS credential store. It exists only where you keep it.';\n return [\n `Previous wallet archived: ${replaced.address} still holds any funds sent to it.`,\n `Its keystore was moved to ${replaced.archivedPath}; ${passphraseLine}`,\n `To make it the active wallet again later: move the current ${activeWalletPath} aside first, then \\`mv ${replaced.archivedPath} ${activeWalletPath}\\`.`,\n ];\n}\n\n/**\n * Run `fn` under the cross-process wallet lock (`<dir>/wallet.create.lock`):\n * create, `--replace` and repair all change where a wallet's passphrase lives,\n * and the sidecar's read-modify-write assumes one writer at a time.\n *\n * A lock timeout is not the user's error; it surfaces as INTERNAL with the one\n * manual step (there is no auto-steal), keeping the JSON error contract. Every\n * other error — notably a create loser's WALLET_EXISTS — propagates unchanged.\n */\nexport async function withWalletLock<T>(dir: string, fn: () => Promise<T>): Promise<T> {\n // Ensure the data dir exists so the lock's own mkdir has a parent on a fresh\n // install; the exclusive wallet write re-ensures it at 0700 regardless.\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = join(dir, 'wallet.create.lock');\n try {\n return await withFileLock(lockPath, fn);\n } catch (err) {\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\n/**\n * Run the whole create critical section under the wallet lock: the existence\n * pre-check, the passphrase choose-and-store, and the no-clobber write. Without\n * the lock these interleave across two concurrent creates — each generates a\n * distinct passphrase and persists it BEFORE the exclusive file write, so a\n * different process could win the file while this one's per-address entry\n * names a wallet that never landed. Serializing means the loser blocks until\n * the winner commits, then trips the exists check and exits WALLET_EXISTS\n * having never generated or stored a passphrase. The store-before-write\n * ordering stays (it still guards the single-process crash window), and the\n * exclusive write stays the final authority.\n *\n * The passphrase is resolved inside the prepare step's address callback so the\n * store entry is keyed to the new wallet's own address (issue #32), and the\n * sidecar records where it went BEFORE the key is encrypted: a sidecar that\n * cannot be written aborts the create, so no wallet exists whose passphrase\n * location nobody recorded.\n *\n * `--replace` ordering closes the no-active-wallet window: verify-and-preserve\n * the outgoing wallet (no file moves), fully PREPARE the replacement (key,\n * stored passphrase, encrypted keystore — every fallible step) while the old\n * wallet is still active, and only then park the old keystore and commit the\n * new one. A commit failure rolls the park back, so at every exit either the\n * old or the new wallet is the active one.\n */\nasync function createWalletLocked(\n ctx: CommandContext,\n opts: WalletCreateOptions,\n): Promise<{\n address: string;\n walletPath: string;\n passphrase: CreatePassphraseResult;\n replaced?: ArchivedWalletInfo;\n}> {\n const dir = ctx.dataDir;\n return withWalletLock(dir, async () => {\n const env = opts.env ?? process.env;\n let chosen: CreatePassphraseResult | undefined;\n const passphraseFor = async (forAddress: string): Promise<string> => {\n const resolved = await resolvePassphraseForCreate(\n {\n env,\n dir,\n ...opts.passphrase,\n // Create never prompts; this only picks the 10 s or 60 s write bound.\n isTTY: opts.passphrase?.isTTY ?? ctx.io.isTTY,\n onWait: (line) => emitNotice(ctx.io, line, { json: ctx.flags.json }),\n },\n forAddress,\n { insecureStorage: opts.insecureStorage === true },\n );\n if (resolved.durable && resolved.source !== 'env') {\n await writePassphraseRecord(dir, forAddress, { store: resolved.source, by: 'create' });\n }\n chosen = resolved;\n return resolved.passphrase;\n };\n const result = (path: { address: string; walletPath: string }) => {\n if (chosen === undefined) throw new CliError('INTERNAL', 'No wallet passphrase was chosen.');\n return { ...path, passphrase: chosen };\n };\n\n if (!(await walletFileExists(dir))) {\n return result(await createLocalWallet(dir, passphraseFor));\n }\n\n if (opts.replace !== true) throw walletExistsError(dir);\n const preserved = await verifyAndPreserveOutgoingWallet({\n dir,\n env,\n ...(opts.passphrase !== undefined ? { passphrase: opts.passphrase } : {}),\n });\n const prepared = await prepareLocalWallet(passphraseFor);\n const archivedPath = await parkOutgoingWallet(dir, preserved.account);\n try {\n const committed = await commitLocalWallet(dir, prepared);\n return { ...result(committed), replaced: { ...preserved, archivedPath } };\n } catch (err) {\n try {\n await restoreParkedWallet(dir, archivedPath);\n } catch (restoreErr) {\n // The no-clobber restore also refuses when a wallet.json appeared out\n // of band (commit EEXIST) — never overwrite it; name both files.\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed after the old wallet was parked, and restoring it also failed.',\n {\n fix: `Your old wallet ${preserved.address} is intact at ${archivedPath} with its passphrase preserved. If a ${walletPath(dir)} now exists, another process wrote it — move it aside first. Then restore with \\`mv ${archivedPath} ${walletPath(dir)}\\`.`,\n cause: restoreErr,\n },\n );\n }\n // Old wallet restored as the active one; say so rather than surfacing a\n // raw fs error (or a WALLET_EXISTS whose fix suggests re-running --replace).\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed; the previous wallet was restored and is the active wallet again.',\n {\n fix: 'Nothing was lost. Fix the underlying error, then retry `tenjin wallet create --replace`.',\n cause: err,\n },\n );\n }\n });\n}\n\n/**\n * THE ONE LINE THAT SAYS WHERE THE PASSPHRASE WENT (Q2, S4). A generated secret\n * in an OS store keeps today's three notes byte for byte; an env secret saved\n * there says the variable is no longer needed; the 0600 file says why it was\n * used; and an env secret nothing durable holds says so, and how to fix it\n * once the store answers. Every line that names `tenjin wallet repair` carries\n * REPAIR_CLAUSE, and a file failure never names a keychain (decision 6).\n */\nexport function passphraseNote(p: CreatePassphraseResult, address: string, dir: string): string {\n const account = address.toLowerCase();\n if (!p.durable) {\n const attempted = p.attempted ?? 'keychain';\n const only = 'so Claude Code can unlock this wallet only where that variable is set.';\n switch (p.notSaved) {\n case 'rejected-characters':\n // Repair would refuse the same value: the variable is the fix.\n return `Encrypted with TENJIN_WALLET_PASSPHRASE only: ${unstorableWhy(attempted)}, ${only} Keep it set in the environment Claude Code starts from.`;\n case 'conflict':\n case 'kept-existing':\n return `Encrypted with TENJIN_WALLET_PASSPHRASE only: ${describeStoreLocation(attempted, account, dir)} already holds a different passphrase for this wallet, ${only} Run \\`tenjin wallet repair\\` yourself ${REPAIR_CLAUSE} to replace it.`;\n default:\n break;\n }\n if (attempted === 'file') {\n const path = describeStoreLocation('file', account, dir);\n return `Encrypted with TENJIN_WALLET_PASSPHRASE only: Tenjin could not save the passphrase to ${path}, ${only} Check that ${dirname(path)} is writable, then run \\`tenjin wallet repair\\` yourself ${REPAIR_CLAUSE}.`;\n }\n if (p.notSaved === 'store-failed') {\n return `Encrypted with TENJIN_WALLET_PASSPHRASE only: Tenjin could not save the passphrase to the ${storeNoun(attempted)}, ${only} Run \\`tenjin wallet repair\\` yourself ${REPAIR_CLAUSE}.`;\n }\n return `Encrypted with TENJIN_WALLET_PASSPHRASE only: the ${storeNoun(attempted)} did not answer, ${only} Once it answers, run \\`tenjin wallet repair\\` yourself ${REPAIR_CLAUSE}.`;\n }\n if (p.source === 'file' || p.source === 'env') {\n if (p.fileReason === 'insecure-storage') {\n return `Passphrase saved to ${p.location} (readable only by you). Anyone who can read that file and wallet.json can spend this wallet.`;\n }\n return NO_KEYRING_LINE(p.location);\n }\n if (p.origin === 'env') {\n return `Passphrase from TENJIN_WALLET_PASSPHRASE saved to ${p.location}; Claude Code can unlock this wallet without the variable.`;\n }\n switch (p.source) {\n case 'keychain':\n return `Passphrase saved to your macOS keychain (service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n case 'dpapi':\n return `Passphrase saved to a DPAPI-encrypted per-wallet file (passphrase.${account}.dpapi), readable only by you on this Windows machine; signing will be transparent here.`;\n case 'secret-service':\n return `Passphrase saved to your Linux keyring (Secret Service, service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n }\n}\n\nexport interface WalletRepairOptions {\n /** `--insecure-storage`: save to the 0600 file even where an OS keychain exists. */\n insecureStorage?: boolean;\n /** Test seam for passphrase storage (keychain exec, TTY prompt, platform). */\n passphrase?: PassphraseOverrides;\n /** The environment TENJIN_WALLET_PASSPHRASE is read from; defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** The home directory whose shell startup files are scanned for an export; defaults to os.homedir(). */\n home?: string;\n /** Reads one startup file, null when it cannot be read; a seam for tests. */\n readText?: (path: string) => Promise<string | null>;\n}\n\n/** What `tenjin wallet repair --json` prints. */\nexport interface WalletRepairData {\n address: string;\n passphraseStore: DurableStore;\n location: string;\n alreadySaved: boolean;\n replacedUnusableEntry: boolean;\n envOverride: {\n state: 'unset' | 'matches' | 'wrong';\n exports: Array<{ file: string; line: number }>;\n };\n restartRequired: true;\n next: typeof REPAIR_DONE_LINE;\n}\n\n/** The shell startup files a TENJIN_WALLET_PASSPHRASE export usually lives in, relative to home. */\nconst SHELL_STARTUP_FILES = [\n '.zshrc',\n '.zprofile',\n '.zshenv',\n '.bashrc',\n '.bash_profile',\n '.profile',\n '.config/fish/config.fish',\n];\n\n/**\n * `tenjin wallet repair`: for a wallet Claude Code cannot unlock. A PERSON runs\n * it, in their own terminal: it asks for the passphrase at a hidden prompt (or\n * uses TENJIN_WALLET_PASSPHRASE when that opens the wallet), proves it opens\n * this wallet, saves it where Claude Code's router can read it without a\n * prompt, and marks the unlock as awaiting confirmation, which the next\n * session's router confirms (\"Tenjin wallet unlocked.\").\n *\n * With no terminal and a wrong variable, the saved passphrase is checked in\n * its place, so a headless run still names the variable when the saved one\n * already opens the wallet. With no terminal and nothing usable it refuses with\n * REPAIR_IN_TERMINAL and never suggests passing the passphrase inline (B1): a passphrase never\n * goes on a command line or into chat. It reports success only when the store\n * reads this passphrase back (S1). A TENJIN_WALLET_PASSPHRASE in this shell\n * that does not open the wallet is named, with the startup-file line that\n * exports it, because it shadows the saved passphrase until removed.\n */\nexport async function runWalletRepair(\n ctx: CommandContext,\n opts: WalletRepairOptions = {},\n): Promise<CommandResult> {\n const env = opts.env ?? process.env;\n const dir = ctx.dataDir;\n const record = await readWalletRecord(dir);\n if (record === null) {\n throw new CliError('WALLET_MISSING', 'No wallet found to repair.', {\n fix: 'Run `tenjin wallet create` to create one.',\n });\n }\n const address = record.address;\n const humanPre: string[] = [];\n const envKey = env.TENJIN_WALLET_KEY;\n if (envKey !== undefined && envKey.trim().length > 0) {\n humanPre.push(\n 'TENJIN_WALLET_KEY is set and shadows the wallet file; repair fixes only the file wallet.',\n );\n }\n\n const fromEnv = env.TENJIN_WALLET_PASSPHRASE;\n let envState: WalletRepairData['envOverride']['state'] = 'unset';\n let candidate: string | undefined;\n if (fromEnv !== undefined && fromEnv.length > 0) {\n const opened = await openKeystore(record.keystore, address, fromEnv);\n envState = opened === 'wrong' ? 'wrong' : 'matches';\n // A mismatch is a tampered file; repair refuses it below with the tamper error.\n if (opened !== 'wrong') candidate = fromEnv;\n }\n const interactive = ctx.io.isTTY && (opts.passphrase?.isTTY ?? Boolean(process.stdin.isTTY));\n if (candidate === undefined && !interactive && envState === 'wrong') {\n // Headless with a wrong variable: a SAVED passphrase that opens the wallet\n // is the candidate, so an agent's run reaches the same conflict line (unset\n // the variable) a person's prompt would, instead of a bare USAGE.\n candidate = await savedPassphraseThatOpens(dir, env, record, opts.passphrase);\n }\n if (candidate === undefined) {\n if (!interactive) {\n throw new CliError(\n 'USAGE',\n envState === 'wrong'\n ? 'No passphrase to check: TENJIN_WALLET_PASSPHRASE is set but does not open this wallet, and no saved passphrase does.'\n : 'No passphrase to check.',\n { fix: REPAIR_IN_TERMINAL },\n );\n }\n const entered = await promptPassphrase(\n { env, ...opts.passphrase },\n `Passphrase for wallet ${address}: `,\n );\n if (entered.length === 0) {\n throw new CliError('USAGE', 'No passphrase entered; nothing was saved.', {\n fix: REPAIR_IN_TERMINAL,\n });\n }\n candidate = entered;\n }\n\n const passphrase = candidate;\n const outcome = await withWalletLock(dir, () =>\n repairLocalWalletPassphrase(\n {\n dir,\n env,\n passphrase: {\n ...opts.passphrase,\n isTTY: ctx.io.isTTY,\n onWait: (line) => emitNotice(ctx.io, line, { json: ctx.flags.json }),\n },\n },\n passphrase,\n opts.insecureStorage === true ? { insecureStorage: true } : {},\n ),\n );\n // The next session's router confirms the unlock and says so once. A failure\n // to record that only costs the confirmation line, never the saved passphrase,\n // so it does not fail a repair that is already proven.\n await markUnlockPending(dir, outcome.address).catch(() => undefined);\n\n const exports =\n envState === 'unset' ? [] : await scanShellExports(opts.home ?? homedir(), opts.readText);\n const savedLine = outcome.alreadySaved\n ? `Already saved in ${outcome.location}.`\n : outcome.fileReason === 'no-keyring'\n ? NO_KEYRING_LINE(outcome.location)\n : `Saved to ${outcome.location}.`;\n const envLine =\n envState === 'wrong'\n ? `! TENJIN_WALLET_PASSPHRASE is set in this shell but does not open this wallet. Tenjin now uses the saved passphrase, but remove the variable: \\`unset TENJIN_WALLET_PASSPHRASE\\`${\n exports.length > 0\n ? `, and delete the export at ${exports.map((e) => `${e.file}:${e.line}`).join(', ')}`\n : ''\n }.`\n : envState === 'matches'\n ? 'TENJIN_WALLET_PASSPHRASE in this shell matches; the saved copy is enough, so you can remove it.'\n : null;\n\n const data: WalletRepairData = {\n address: outcome.address,\n passphraseStore: outcome.store,\n location: outcome.location,\n alreadySaved: outcome.alreadySaved,\n replacedUnusableEntry: outcome.replacedUnusableEntry,\n envOverride: { state: envState, exports },\n restartRequired: true,\n next: REPAIR_DONE_LINE,\n };\n return {\n data,\n humanLines: [\n ...humanPre,\n `Wallet: ${outcome.address}`,\n 'Passphrase verified: it opens this wallet.',\n savedLine,\n ...(envLine !== null ? [envLine] : []),\n REPAIR_DONE_LINE,\n ],\n };\n}\n\n/**\n * The saved passphrase (keychain, 0600 file or legacy slot; never the variable\n * and never a prompt) when it opens this wallet, else undefined. Reads are\n * bounded like doctor's verify, so a locked keychain cannot hang a headless\n * run; any failure to read reads as \"none\".\n */\nasync function savedPassphraseThatOpens(\n dir: string,\n env: NodeJS.ProcessEnv,\n record: WalletRecord,\n overrides: PassphraseOverrides | undefined,\n): Promise<string | undefined> {\n try {\n const saved = await resolvePassphrase(\n {\n env,\n dir,\n ...overrides,\n isTTY: false,\n readDeadlineMs: overrides?.timeouts?.verifyReadMs ?? STORE_TIMEOUTS.verifyReadMs,\n },\n record.address,\n { skipEnv: true },\n );\n const opened = await openKeystore(record.keystore, record.address, saved.passphrase);\n return opened === 'ok' ? saved.passphrase : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Every TENJIN_WALLET_PASSPHRASE line in the usual shell startup files, as `~/<file>:<line>`. */\nasync function scanShellExports(\n home: string,\n readText: (path: string) => Promise<string | null> = (path) =>\n readFile(path, 'utf8').catch(() => null),\n): Promise<Array<{ file: string; line: number }>> {\n const files: Array<{ path: string; text: string }> = [];\n for (const rel of SHELL_STARTUP_FILES) {\n const text = await readText(join(home, rel));\n if (text !== null) files.push({ path: `~/${rel}`, text });\n }\n return findPassphraseExports(files);\n}\n\n/**\n * The lines that set TENJIN_WALLET_PASSPHRASE (any `export`, `set -gx` or plain\n * assignment naming it), skipping `#` comments. Line numbers are 1-based, as an\n * editor shows them. Only the location is returned, never the line's text: the\n * line may hold the passphrase itself.\n */\nexport function findPassphraseExports(\n files: Array<{ path: string; text: string }>,\n): Array<{ file: string; line: number }> {\n const found: Array<{ file: string; line: number }> = [];\n for (const { path, text } of files) {\n text.split(/\\r?\\n/).forEach((line, i) => {\n if (line.trimStart().startsWith('#')) return;\n if (/\\bTENJIN_WALLET_PASSPHRASE\\b/.test(line)) found.push({ file: path, line: i + 1 });\n });\n }\n return found;\n}\n\nexport interface WalletShowOptions extends ResolveWalletProviderOptions {\n /** `--no-qr`: print the address without the QR block at a TTY. */\n qr?: boolean;\n}\n\nexport async function runWalletShow(\n ctx: CommandContext,\n opts: WalletShowOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n // Diagnostics are the provider's own: a remote provider reports no local file\n // path or perms warning, so `show` never contaminates a remote wallet's output\n // with a stale local wallet.json's state. keyStorage/passphraseSource are the\n // custody posture reported without decrypting or requiring a passphrase.\n const {\n walletPath: path,\n keyStorage,\n passphraseSource,\n archivedWallets,\n warnings,\n } = await provider.diagnostics();\n\n const humanLines = [\n `Address: ${desc.address}`,\n ...(opts.qr !== false && ctx.io.isTTY && !ctx.flags.json\n ? addressQrLines(desc.address, ctx.io.stdout)\n : []),\n `Key source: ${desc.credentialSource}`,\n ];\n if (keyStorage !== undefined) humanLines.push(`Key storage: ${keyStorage}`);\n if (passphraseSource !== undefined) humanLines.push(`Passphrase: ${passphraseSource}`);\n if (archivedWallets !== undefined && archivedWallets.length > 0) {\n // A recovery hint, not a wallet switcher: exactly one wallet is ever active.\n humanLines.push(\n `Archived (replaced) wallets, funds recoverable via their preserved passphrases: ${archivedWallets.join(', ')}`,\n );\n }\n humanLines.push(...warnings);\n\n return {\n data: {\n address: desc.address,\n provider: desc.provider,\n credentialSource: desc.credentialSource,\n policyEnforcement: desc.policyEnforcement,\n ...(path !== undefined ? { walletPath: path } : {}),\n ...(keyStorage !== undefined ? { keyStorage } : {}),\n ...(passphraseSource !== undefined ? { passphraseSource } : {}),\n ...(archivedWallets !== undefined && archivedWallets.length > 0 ? { archivedWallets } : {}),\n warnings,\n },\n humanLines,\n };\n}\n\nexport async function runWalletBalance(\n ctx: CommandContext,\n opts: ResolveWalletProviderOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n\n const config = await loadRawConfig(ctx.dataDir);\n const rpcUrl = resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n }).rpcUrl.value;\n\n let atomic: bigint;\n try {\n atomic = await getUsdcBalance(desc.address, rpcUrl);\n } catch (err) {\n throw new CliError('RPC_ERROR', `Could not read the USDC balance from ${rpcUrl}.`, {\n fix: 'Check your network, or set a working RPC with `tenjin config set rpcUrl <url>`.',\n cause: err,\n });\n }\n\n await forgetRememberedBalance(ctx.dataDir);\n\n const balance = toMoney(atomic.toString());\n // THE ROUTING CREDIT IS STILL THE USER'S: a deposit moved it off the wallet\n // into the routing channel, where the next routing fees draw from it.\n const credit = toMoney(\n (await channelCredit(ctx.dataDir, desc.address).catch(() => 0n)).toString(),\n );\n return {\n data: { address: desc.address, balance, routingCredit: credit },\n humanLines: [\n `Balance: ${balance.usd} USDC on Base` +\n (credit.atomic !== '0' ? ` (+${credit.usd} routing credit)` : ''),\n ...(atomic === 0n ? [FUND_COMMAND_LINE] : []),\n ],\n };\n}\n\nfunction custodyWarnings(): string[] {\n const warnings: string[] = [];\n if (hasEnvKey()) {\n warnings.push('TENJIN_WALLET_KEY is set and shadows this file at runtime.');\n }\n if (isWindows) {\n warnings.push('File permissions are not enforced on Windows; the key file is not restricted.');\n }\n return warnings;\n}\n\nfunction hasEnvKey(): boolean {\n const envKey = process.env.TENJIN_WALLET_KEY;\n return envKey !== undefined && envKey.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,gBAAgB;AAChC,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAiD9B,IAAM,cAAc;AACpB,IAAM,YAAY,QAAQ,aAAa;AAGhC,IAAM,mBAAmB;AA2BhC,eAAsB,gBACpB,KACA,OAA4B,CAAC,GACL;AACxB,QAAM,EAAE,SAAS,YAAY,MAAM,YAAY,SAAS,IAAI,MAAM,mBAAmB,KAAK,IAAI;AAE9F,QAAM,OAAO,eAAe,YAAY,SAAS,IAAI,OAAO;AAC5D,QAAM,WAAW,gBAAgB;AACjC,SAAO;AAAA,IACL,MAAM;AAAA,MACJ;AAAA,MACA,YAAY;AAAA,MACZ,UAAU;AAAA,MACV,mBAAmB;AAAA,MACnB,YAAY;AAAA,MACZ,kBAAkB,WAAW;AAAA,MAC7B,oBAAoB,WAAW;AAAA,MAC/B,kBAAkB,WAAW;AAAA,MAC7B,mBAAmB,WAAW;AAAA,MAC9B,gBAAgB;AAAA,MAChB,GAAI,aAAa,SACb;AAAA,QACE,UAAU;AAAA,UACR,SAAS,SAAS;AAAA,UAClB,oBAAoB,SAAS;AAAA,UAC7B,qBAAqB,SAAS;AAAA,UAC9B,GAAI,SAAS,qBAAqB,SAC9B,EAAE,kBAAkB,SAAS,iBAAiB,IAC9C,CAAC;AAAA,QACP;AAAA,MACF,IACA,CAAC;AAAA,MACL;AAAA,IAC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ACA,SAAO;AACT;AAEA,SAAS,YAAqB;AAC5B,QAAM,SAAS,QAAQ,IAAI;AAC3B,SAAO,WAAW,UAAa,OAAO,SAAS;AACjD;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  hashTypedData
4
- } from "./chunk-PJNENX2A.js";
4
+ } from "./chunk-WFSPCCVW.js";
5
5
  import {
6
6
  getAddress,
7
7
  keccak256,
@@ -156,4 +156,4 @@ export {
156
156
  computeChannelId,
157
157
  getBatchSettlementEip712Domain
158
158
  };
159
- //# sourceMappingURL=chunk-445VQTVM.js.map
159
+ //# sourceMappingURL=chunk-IE7P2BZE.js.map