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

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 (110) hide show
  1. package/README.md +3 -3
  2. package/dist/{chunk-ALJRB7NG.js → chunk-2TYQD22Q.js} +8 -6
  3. package/dist/{chunk-ALJRB7NG.js.map → chunk-2TYQD22Q.js.map} +1 -1
  4. package/dist/{chunk-W36HL4TB.js → chunk-4L7KMA7P.js} +4 -4
  5. package/dist/{chunk-UDWGT4FX.js → chunk-5FGO6TYT.js} +13 -5
  6. package/dist/chunk-5FGO6TYT.js.map +1 -0
  7. package/dist/{chunk-5HS54CLI.js → chunk-5NEHH2E5.js} +3 -3
  8. package/dist/{chunk-Z7R2QDX2.js → chunk-64SE3QC5.js} +42 -7
  9. package/dist/chunk-64SE3QC5.js.map +1 -0
  10. package/dist/chunk-6ZSGER3A.js +52 -0
  11. package/dist/chunk-6ZSGER3A.js.map +1 -0
  12. package/dist/{chunk-QF4SSCQV.js → chunk-AWKQSKUL.js} +4 -3
  13. package/dist/chunk-AWKQSKUL.js.map +1 -0
  14. package/dist/{chunk-XMIVHQ35.js → chunk-B2L53TMK.js} +17 -2
  15. package/dist/{chunk-XMIVHQ35.js.map → chunk-B2L53TMK.js.map} +1 -1
  16. package/dist/{chunk-OZ3LWLCI.js → chunk-DATCR7AU.js} +3 -3
  17. package/dist/{chunk-65EJJVT3.js → chunk-DSNXKUXI.js} +2 -2
  18. package/dist/{chunk-HII5HOQV.js → chunk-G4AM2SOL.js} +5 -3
  19. package/dist/{chunk-HII5HOQV.js.map → chunk-G4AM2SOL.js.map} +1 -1
  20. package/dist/{chunk-OBPZ36HG.js → chunk-GU4GGKYP.js} +58 -5
  21. package/dist/chunk-GU4GGKYP.js.map +1 -0
  22. package/dist/{chunk-VNT3CQFV.js → chunk-H2L33M7F.js} +17 -13
  23. package/dist/{chunk-VNT3CQFV.js.map → chunk-H2L33M7F.js.map} +1 -1
  24. package/dist/{chunk-GHR4BTNJ.js → chunk-HC3QEZKT.js} +4 -4
  25. package/dist/chunk-HC3QEZKT.js.map +1 -0
  26. package/dist/{chunk-H4BOQLWW.js → chunk-MAQUL5BD.js} +2 -2
  27. package/dist/{chunk-4HAV6IFE.js → chunk-O7CUHHYU.js} +6 -6
  28. package/dist/{chunk-4HAV6IFE.js.map → chunk-O7CUHHYU.js.map} +1 -1
  29. package/dist/{chunk-5INS5ZZF.js → chunk-OHZYNZSD.js} +3 -3
  30. package/dist/{chunk-YHWBDCGS.js → chunk-PY7MQUKP.js} +20 -18
  31. package/dist/{chunk-YHWBDCGS.js.map → chunk-PY7MQUKP.js.map} +1 -1
  32. package/dist/{chunk-ZLD6MJVJ.js → chunk-S4SAZ7OD.js} +1 -1
  33. package/dist/chunk-S4SAZ7OD.js.map +1 -0
  34. package/dist/{chunk-WT7DHJNJ.js → chunk-SKQQOEWH.js} +4 -4
  35. package/dist/{chunk-XICKN3CH.js → chunk-VIOUZW7Z.js} +2 -46
  36. package/dist/chunk-VIOUZW7Z.js.map +1 -0
  37. package/dist/{chunk-YTM7OURD.js → chunk-VNNXAYJE.js} +2 -2
  38. package/dist/{chunk-5NUF4BHR.js → chunk-VXIBZ6W5.js} +3 -3
  39. package/dist/{chunk-6JIYGYRB.js → chunk-X7I343ZY.js} +2 -2
  40. package/dist/{chunk-DI7WHXOZ.js → chunk-XVYATBKD.js} +2 -2
  41. package/dist/{chunk-EJXIK6WY.js → chunk-YKM2ZTA2.js} +56 -22
  42. package/dist/chunk-YKM2ZTA2.js.map +1 -0
  43. package/dist/{chunk-YLCWI6ZR.js → chunk-YQOQ6XEI.js} +59 -18
  44. package/dist/chunk-YQOQ6XEI.js.map +1 -0
  45. package/dist/{cli-2U5JB7OQ.js → cli-6JNIPZQ6.js} +32 -31
  46. package/dist/{cli-2U5JB7OQ.js.map → cli-6JNIPZQ6.js.map} +1 -1
  47. package/dist/{config-44EGO636.js → config-G75YT6NC.js} +11 -10
  48. package/dist/{doctor-BD42BBEG.js → doctor-3GMDOW4Y.js} +28 -28
  49. package/dist/{doctor-BD42BBEG.js.map → doctor-3GMDOW4Y.js.map} +1 -1
  50. package/dist/{env-proxy-KEGEMWKX.js → env-proxy-XL4P73MZ.js} +2 -2
  51. package/dist/{fund-WQOOUESE.js → fund-3IPR5YRJ.js} +17 -15
  52. package/dist/{fund-WQOOUESE.js.map → fund-3IPR5YRJ.js.map} +1 -1
  53. package/dist/{hook-command-23LC5NRN.js → hook-command-ZXX4FT4N.js} +14 -14
  54. package/dist/index.js +6 -6
  55. package/dist/index.js.map +1 -1
  56. package/dist/{install-REPLHNU7.js → install-6OROTYHZ.js} +17 -17
  57. package/dist/{install-identity-4RDWTLJ2.js → install-identity-PM4AGFFX.js} +7 -6
  58. package/dist/{install-wallet-USHWL7AX.js → install-wallet-6756NOB5.js} +10 -9
  59. package/dist/{install-wallet-USHWL7AX.js.map → install-wallet-6756NOB5.js.map} +1 -1
  60. package/dist/{mcp-T5SYCLP7.js → mcp-33FAAZ7F.js} +503 -77
  61. package/dist/mcp-33FAAZ7F.js.map +1 -0
  62. package/dist/{pay-276DSSYG.js → pay-XOYR4PCH.js} +13 -12
  63. package/dist/{payments-TZYLJXK3.js → payments-UTQDBO7H.js} +8 -7
  64. package/dist/{payments-TZYLJXK3.js.map → payments-UTQDBO7H.js.map} +1 -1
  65. package/dist/{send-YHDKZPED.js → send-CVGNOQW3.js} +12 -10
  66. package/dist/{send-YHDKZPED.js.map → send-CVGNOQW3.js.map} +1 -1
  67. package/dist/{status-X2INT6VD.js → status-NACN4DGX.js} +10 -8
  68. package/dist/{status-X2INT6VD.js.map → status-NACN4DGX.js.map} +1 -1
  69. package/dist/{status-line-QKDJYZGV.js → status-line-3IQKGRUH.js} +6 -5
  70. package/dist/{status-line-QKDJYZGV.js.map → status-line-3IQKGRUH.js.map} +1 -1
  71. package/dist/{status-line-wiring-LW4HFRHB.js → status-line-wiring-QXBOOY2T.js} +4 -4
  72. package/dist/{uninstall-NVTGU7JD.js → uninstall-NYFKSYW4.js} +17 -17
  73. package/dist/{update-QXVH2DE7.js → update-RJDA5ZY3.js} +7 -16
  74. package/dist/update-RJDA5ZY3.js.map +1 -0
  75. package/dist/{wallet-CKKB23D5.js → wallet-B3FVHNTS.js} +10 -9
  76. package/docs/agent-permissions.md +5 -4
  77. package/package.json +3 -3
  78. package/dist/chunk-EJXIK6WY.js.map +0 -1
  79. package/dist/chunk-GHR4BTNJ.js.map +0 -1
  80. package/dist/chunk-OBPZ36HG.js.map +0 -1
  81. package/dist/chunk-PM2MOXJ3.js +0 -66
  82. package/dist/chunk-PM2MOXJ3.js.map +0 -1
  83. package/dist/chunk-QF4SSCQV.js.map +0 -1
  84. package/dist/chunk-UDWGT4FX.js.map +0 -1
  85. package/dist/chunk-XICKN3CH.js.map +0 -1
  86. package/dist/chunk-YLCWI6ZR.js.map +0 -1
  87. package/dist/chunk-Z7R2QDX2.js.map +0 -1
  88. package/dist/chunk-ZLD6MJVJ.js.map +0 -1
  89. package/dist/mcp-T5SYCLP7.js.map +0 -1
  90. package/dist/update-QXVH2DE7.js.map +0 -1
  91. /package/dist/{chunk-W36HL4TB.js.map → chunk-4L7KMA7P.js.map} +0 -0
  92. /package/dist/{chunk-5HS54CLI.js.map → chunk-5NEHH2E5.js.map} +0 -0
  93. /package/dist/{chunk-OZ3LWLCI.js.map → chunk-DATCR7AU.js.map} +0 -0
  94. /package/dist/{chunk-65EJJVT3.js.map → chunk-DSNXKUXI.js.map} +0 -0
  95. /package/dist/{chunk-H4BOQLWW.js.map → chunk-MAQUL5BD.js.map} +0 -0
  96. /package/dist/{chunk-5INS5ZZF.js.map → chunk-OHZYNZSD.js.map} +0 -0
  97. /package/dist/{chunk-WT7DHJNJ.js.map → chunk-SKQQOEWH.js.map} +0 -0
  98. /package/dist/{chunk-YTM7OURD.js.map → chunk-VNNXAYJE.js.map} +0 -0
  99. /package/dist/{chunk-5NUF4BHR.js.map → chunk-VXIBZ6W5.js.map} +0 -0
  100. /package/dist/{chunk-6JIYGYRB.js.map → chunk-X7I343ZY.js.map} +0 -0
  101. /package/dist/{chunk-DI7WHXOZ.js.map → chunk-XVYATBKD.js.map} +0 -0
  102. /package/dist/{config-44EGO636.js.map → config-G75YT6NC.js.map} +0 -0
  103. /package/dist/{env-proxy-KEGEMWKX.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
  104. /package/dist/{hook-command-23LC5NRN.js.map → hook-command-ZXX4FT4N.js.map} +0 -0
  105. /package/dist/{install-REPLHNU7.js.map → install-6OROTYHZ.js.map} +0 -0
  106. /package/dist/{install-identity-4RDWTLJ2.js.map → install-identity-PM4AGFFX.js.map} +0 -0
  107. /package/dist/{pay-276DSSYG.js.map → pay-XOYR4PCH.js.map} +0 -0
  108. /package/dist/{status-line-wiring-LW4HFRHB.js.map → status-line-wiring-QXBOOY2T.js.map} +0 -0
  109. /package/dist/{uninstall-NVTGU7JD.js.map → uninstall-NYFKSYW4.js.map} +0 -0
  110. /package/dist/{wallet-CKKB23D5.js.map → wallet-B3FVHNTS.js.map} +0 -0
package/README.md CHANGED
@@ -47,7 +47,7 @@ Install Tenjin from tenjin.sh
47
47
 
48
48
  Your agent installs it, asks you about spend limits in the session, and helps you fund the wallet.
49
49
 
50
- Or in a terminal (Node.js 24 or newer):
50
+ Or in a terminal (Node.js 22 or newer):
51
51
 
52
52
  ```bash
53
53
  npm i -g tenjin-cli
@@ -57,7 +57,7 @@ tenjin wallet fund 2 # optional: add $2 with a card, via Coinbase
57
57
 
58
58
  ## What it can do
59
59
 
60
- The router picks from a catalog we curate and maintain. When nothing in it fits, it can point your agent at a reviewed third-party pay-per-call service from the [Tenjin list](#tenjin-list-and-experimental-bazaar), and your agent decides whether to use it or to ask you first. Routing is free today: you pay the provider's price and nothing else. A flat [routing fee](#routing-fee) of $0.003 per routing call is coming, under the spend limits you approve at install.
60
+ The router picks from a catalog we curate and maintain. When nothing in it fits, it can point your agent at a reviewed third-party pay-per-call service from the [Tenjin list](#tenjin-list-and-experimental-bazaar), and your agent decides whether to use it or to ask you first. Each routing call costs a flat [routing fee](#routing-fee) of $0.003, on top of the provider's price, paid from channel deposits of up to $0.25 that count against the spend limits you approve at install.
61
61
 
62
62
  | Tool | What your agent gets | Price per call |
63
63
  | -------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | -------------- |
@@ -126,7 +126,7 @@ Tenjin pays for tools with [x402](https://www.x402.org), an open standard that b
126
126
 
127
127
  ### Routing fee
128
128
 
129
- Once Tenjin's server turns it on, each routing call costs a flat $0.003, paid over x402 `batch-settlement` by `tenjin mcp` from a channel deposit of up to $0.25 (less when your per-call limit is lower). A deposit is an automatic payment: it counts against the limits above, and approving them at install approves the fee. The fees come out of the deposit and are not counted again. When a call cannot be paid, it takes the free path, and Claude Code tells you once per session why and what fixes it; `tenjin doctor` says the same. Details are in [docs/agent-permissions.md](docs/agent-permissions.md#what-bounds-a-router-payment-on-top-of-that).
129
+ Each routing call costs a flat $0.003, paid over x402 `batch-settlement` by `tenjin mcp` from a channel deposit of up to $0.25 (less when your per-call limit is lower). A deposit is an automatic payment: it counts against the limits above, and approving them at install approves the fee. The fees come out of the deposit and are not counted again. When a call cannot be paid, it takes the free path, and Claude Code tells you once per session why and what fixes it; `tenjin doctor` says the same. Details are in [docs/agent-permissions.md](docs/agent-permissions.md#what-bounds-a-router-payment-on-top-of-that).
130
130
 
131
131
  ### Funding
132
132
 
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-PZ5N6BAL.js";
5
5
  import {
6
6
  getUsdcBalance
7
- } from "./chunk-YTM7OURD.js";
7
+ } from "./chunk-VNNXAYJE.js";
8
8
  import {
9
9
  commitLocalWallet,
10
10
  createLocalWallet,
@@ -17,16 +17,18 @@ import {
17
17
  verifyAndPreserveOutgoingWallet,
18
18
  walletExistsError,
19
19
  walletFileExists
20
- } from "./chunk-4HAV6IFE.js";
20
+ } from "./chunk-O7CUHHYU.js";
21
21
  import {
22
22
  LockTimeoutError,
23
23
  withFileLock
24
24
  } from "./chunk-MEFB5KHA.js";
25
25
  import {
26
- loadRawConfig,
27
- resolveSettings,
28
26
  toMoney
29
- } from "./chunk-XICKN3CH.js";
27
+ } from "./chunk-6ZSGER3A.js";
28
+ import {
29
+ loadRawConfig,
30
+ resolveSettings
31
+ } from "./chunk-VIOUZW7Z.js";
30
32
  import {
31
33
  CliError
32
34
  } from "./chunk-JLEF5WHM.js";
@@ -244,4 +246,4 @@ export {
244
246
  runWalletShow,
245
247
  runWalletBalance
246
248
  };
247
- //# sourceMappingURL=chunk-ALJRB7NG.js.map
249
+ //# sourceMappingURL=chunk-2TYQD22Q.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/wallet.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { CliError } from '../lib/errors';\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 {\n commitLocalWallet,\n createLocalWallet,\n describeWallet,\n parkOutgoingWallet,\n prepareLocalWallet,\n resolveWalletProvider,\n restoreParkedWallet,\n verifyAndPreserveOutgoingWallet,\n type ArchivedWalletInfo,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { walletExistsError, walletFileExists } from '../lib/wallet/store';\nimport { resolvePassphraseForCreate, type PassphraseSource } from '../lib/wallet/passphrase';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport type { CommandContext, CommandResult } from '../context';\n\nconst FUNDING_LINE =\n 'Fund it with `tenjin wallet fund` (card via Coinbase), or send USDC on Base. $5 covers ~50 typical resources.';\nconst KEY_STORAGE = 'encrypted (keystore v3, scrypt)';\nconst isWindows = process.platform === 'win32';\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\nexport async function runWalletCreate(\n ctx: CommandContext,\n opts: WalletCreateOptions = {},\n): Promise<CommandResult> {\n const {\n address,\n walletPath: path,\n source,\n replaced,\n } = await createWalletLocked(ctx.dataDir, opts);\n\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: source,\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 passphraseNote(source, address),\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 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 machine-generated (base64url) passphrases, and this typed one contains other characters. Keep it yourself, or set TENJIN_WALLET_PASSPHRASE to it.'\n : replaced.unarchivedReason === 'no-store'\n ? 'its passphrase was NOT archived: this platform has no OS credential store. It exists only where you keep it.'\n : 'its passphrase was NOT archived: the OS credential store write failed. 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 the whole create critical section under a cross-process file lock: the\n * existence pre-check, the passphrase generate-and-store, and the no-clobber\n * write. Without the lock these interleave across two concurrent creates — each\n * generates a distinct passphrase and persists it to the OS store BEFORE the\n * exclusive file write, so a different process could win the file while this\n * one's per-address entry names a wallet that never landed. Serializing means\n * the loser blocks until the winner commits, then trips the exists check and\n * exits WALLET_EXISTS having never generated or stored a passphrase. The\n * store-before-write ordering stays (it still guards the single-process crash\n * window), and the exclusive write stays the final authority.\n *\n * The passphrase is resolved inside the prepare step's address callback so the\n * OS-store entry is keyed to the new wallet's own address (issue #32).\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 dir: string,\n opts: WalletCreateOptions,\n): Promise<{\n address: string;\n walletPath: string;\n source: PassphraseSource;\n replaced?: ArchivedWalletInfo;\n}> {\n // Ensure the data dir exists so the lock's own mkdir has a parent on a fresh\n // install; the exclusive wallet write below 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, async () => {\n const env = opts.env ?? process.env;\n let source: PassphraseSource = 'env';\n const passphraseFor = async (forAddress: string): Promise<string> => {\n const resolved = await resolvePassphraseForCreate(\n { env, dir, ...opts.passphrase },\n forAddress,\n );\n source = resolved.source;\n return resolved.passphrase;\n };\n\n if (!(await walletFileExists(dir))) {\n const { address, walletPath: path } = await createLocalWallet(dir, passphraseFor);\n return { address, walletPath: path, source };\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 { address, walletPath: path } = await commitLocalWallet(dir, prepared);\n return { address, walletPath: path, source, 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 } catch (err) {\n // A lock timeout is not the user's error; surface it as INTERNAL with the one\n // manual step (there is no auto-steal), keeping the JSON error contract. Every\n // other error — notably the loser's WALLET_EXISTS — propagates unchanged.\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/** Where the encryption passphrase lives, and what the user must remember. */\nfunction passphraseNote(source: PassphraseSource, address: string): string {\n const account = address.toLowerCase();\n switch (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 case 'env':\n return 'Encrypted with TENJIN_WALLET_PASSPHRASE; keep that value to sign.';\n case 'prompt':\n return 'Remember your passphrase: it is required to sign and cannot be recovered.';\n }\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 return {\n data: { address: desc.address, balance },\n humanLines: [`Balance: ${balance.usd} USDC on Base`],\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,aAAa;AACtB,SAAS,YAAY;AAyBrB,IAAM,eACJ;AACF,IAAM,cAAc;AACpB,IA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AAY,QAAQ,GAAG,eAAe;AAAA,EACrD;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 } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { CliError } from '../lib/errors';\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 {\n commitLocalWallet,\n createLocalWallet,\n describeWallet,\n parkOutgoingWallet,\n prepareLocalWallet,\n resolveWalletProvider,\n restoreParkedWallet,\n verifyAndPreserveOutgoingWallet,\n type ArchivedWalletInfo,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { walletExistsError, walletFileExists } from '../lib/wallet/store';\nimport { resolvePassphraseForCreate, type PassphraseSource } from '../lib/wallet/passphrase';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport type { CommandContext, CommandResult } from '../context';\n\nconst FUNDING_LINE =\n 'Fund it with `tenjin wallet fund` (card via Coinbase), or send USDC on Base. $5 covers ~50 typical resources.';\nconst KEY_STORAGE = 'encrypted (keystore v3, scrypt)';\nconst isWindows = process.platform === 'win32';\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\nexport async function runWalletCreate(\n ctx: CommandContext,\n opts: WalletCreateOptions = {},\n): Promise<CommandResult> {\n const {\n address,\n walletPath: path,\n source,\n replaced,\n } = await createWalletLocked(ctx.dataDir, opts);\n\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: source,\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 passphraseNote(source, address),\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 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 machine-generated (base64url) passphrases, and this typed one contains other characters. Keep it yourself, or set TENJIN_WALLET_PASSPHRASE to it.'\n : replaced.unarchivedReason === 'no-store'\n ? 'its passphrase was NOT archived: this platform has no OS credential store. It exists only where you keep it.'\n : 'its passphrase was NOT archived: the OS credential store write failed. 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 the whole create critical section under a cross-process file lock: the\n * existence pre-check, the passphrase generate-and-store, and the no-clobber\n * write. Without the lock these interleave across two concurrent creates — each\n * generates a distinct passphrase and persists it to the OS store BEFORE the\n * exclusive file write, so a different process could win the file while this\n * one's per-address entry names a wallet that never landed. Serializing means\n * the loser blocks until the winner commits, then trips the exists check and\n * exits WALLET_EXISTS having never generated or stored a passphrase. The\n * store-before-write ordering stays (it still guards the single-process crash\n * window), and the exclusive write stays the final authority.\n *\n * The passphrase is resolved inside the prepare step's address callback so the\n * OS-store entry is keyed to the new wallet's own address (issue #32).\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 dir: string,\n opts: WalletCreateOptions,\n): Promise<{\n address: string;\n walletPath: string;\n source: PassphraseSource;\n replaced?: ArchivedWalletInfo;\n}> {\n // Ensure the data dir exists so the lock's own mkdir has a parent on a fresh\n // install; the exclusive wallet write below 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, async () => {\n const env = opts.env ?? process.env;\n let source: PassphraseSource = 'env';\n const passphraseFor = async (forAddress: string): Promise<string> => {\n const resolved = await resolvePassphraseForCreate(\n { env, dir, ...opts.passphrase },\n forAddress,\n );\n source = resolved.source;\n return resolved.passphrase;\n };\n\n if (!(await walletFileExists(dir))) {\n const { address, walletPath: path } = await createLocalWallet(dir, passphraseFor);\n return { address, walletPath: path, source };\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 { address, walletPath: path } = await commitLocalWallet(dir, prepared);\n return { address, walletPath: path, source, 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 } catch (err) {\n // A lock timeout is not the user's error; surface it as INTERNAL with the one\n // manual step (there is no auto-steal), keeping the JSON error contract. Every\n // other error — notably the loser's WALLET_EXISTS — propagates unchanged.\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/** Where the encryption passphrase lives, and what the user must remember. */\nfunction passphraseNote(source: PassphraseSource, address: string): string {\n const account = address.toLowerCase();\n switch (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 case 'env':\n return 'Encrypted with TENJIN_WALLET_PASSPHRASE; keep that value to sign.';\n case 'prompt':\n return 'Remember your passphrase: it is required to sign and cannot be recovered.';\n }\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 return {\n data: { address: desc.address, balance },\n humanLines: [`Balance: ${balance.usd} USDC on Base`],\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,aAAa;AACtB,SAAS,YAAY;AAyBrB,IAAM,eACJ;AACF,IAAM,cAAc;AACpB,IAAM,YAAY,QAAQ,aAAa;AAsBvC,eAAsB,gBACpB,KACA,OAA4B,CAAC,GACL;AACxB,QAAM;AAAA,IACJ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5B,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,14 +1,14 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  emitNotice
4
- } from "./chunk-UDWGT4FX.js";
4
+ } from "./chunk-5FGO6TYT.js";
5
5
  import {
6
6
  package_default
7
- } from "./chunk-GHR4BTNJ.js";
7
+ } from "./chunk-HC3QEZKT.js";
8
8
  import {
9
9
  external_exports,
10
10
  loadConfig
11
- } from "./chunk-XICKN3CH.js";
11
+ } from "./chunk-VIOUZW7Z.js";
12
12
  import {
13
13
  writeFileAtomic
14
14
  } from "./chunk-JLEF5WHM.js";
@@ -191,4 +191,4 @@ export {
191
191
  fetchDistTags,
192
192
  isNewer
193
193
  };
194
- //# sourceMappingURL=chunk-W36HL4TB.js.map
194
+ //# sourceMappingURL=chunk-4L7KMA7P.js.map
@@ -1,14 +1,14 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  external_exports
4
- } from "./chunk-XICKN3CH.js";
4
+ } from "./chunk-VIOUZW7Z.js";
5
5
  import {
6
6
  CliError
7
7
  } from "./chunk-JLEF5WHM.js";
8
8
 
9
9
  // src/lib/output.ts
10
+ import { WriteStream } from "node:tty";
10
11
  import { styleText } from "node:util";
11
- import { Stream } from "node:stream";
12
12
 
13
13
  // src/schemas.ts
14
14
  var SCHEMA_VERSION = 1;
@@ -214,9 +214,16 @@ function writeLines(stream, lines) {
214
214
  if (lines.length > 0) stream.write(`${lines.join("\n")}
215
215
  `);
216
216
  }
217
+ function colorCapable(stream, env = process.env) {
218
+ const force = env.FORCE_COLOR;
219
+ if (force !== void 0) return ["", "1", "true", "2", "3"].includes(force);
220
+ return stream instanceof WriteStream && stream.isTTY && stream.getColorDepth(env) > 2;
221
+ }
222
+ function style(format, text, stream = process.stdout) {
223
+ return colorCapable(stream) ? styleText(format, text, { validateStream: false }) : text;
224
+ }
217
225
  function paint(io, format, text) {
218
- if (io.stdout instanceof Stream) return styleText(format, text, { stream: io.stdout });
219
- return styleText(format, text);
226
+ return style(format, text, io.stdout);
220
227
  }
221
228
 
222
229
  export {
@@ -226,6 +233,7 @@ export {
226
233
  emitNotice,
227
234
  emitWriteNotice,
228
235
  sanitizeForTerminal,
236
+ style,
229
237
  paint
230
238
  };
231
- //# sourceMappingURL=chunk-UDWGT4FX.js.map
239
+ //# sourceMappingURL=chunk-5FGO6TYT.js.map
@@ -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 * ONE COPY, because the other reader is the failure lane: `stripAnsi`\n * (`hooks/text.ts`) takes colour off a runner's output before the arm scans it\n * for a diagnostic, and a pattern that misses OSC-8 leaves `]8;;https://…`\n * sitting in front of the very line the start-anchored markers must match.\n * That reader CANNOT call {@link sanitizeForTerminal}: this is only its first\n * clause, and the second strips `\\n`, which would flatten the output it is\n * about to split into lines.\n *\n * Safe to share despite the `g` flag: both callers use it through\n * `String.replace`, which starts at 0 and resets `lastIndex`. Do not `test()`\n * 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,OAAO;AAChB,CAAC;AAGM,IAAM,oBAAoB,iBAAE,OAAO;AAAA,EACxC,MAAM;AAAA,EACN,SAAS,iBAAE,OAAO;AAAA,EAClB,KAAK,iBAAE,OAAO,EAAE,SAAS;AAAA,EACzB,SAAS,iB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AAK,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":[]}
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-LAIZ2AQA.js";
5
5
  import {
6
6
  releaseUnchargedExposure
7
- } from "./chunk-5NUF4BHR.js";
7
+ } from "./chunk-VXIBZ6W5.js";
8
8
  import {
9
9
  mask
10
10
  } from "./chunk-7QKHZQKW.js";
@@ -16,7 +16,7 @@ import {
16
16
  } from "./chunk-2I4QTOLB.js";
17
17
  import {
18
18
  USDC_ADDRESS
19
- } from "./chunk-XICKN3CH.js";
19
+ } from "./chunk-VIOUZW7Z.js";
20
20
  import {
21
21
  writeFileAtomic
22
22
  } from "./chunk-JLEF5WHM.js";
@@ -334,4 +334,4 @@ export {
334
334
  writeAll,
335
335
  createUniqueFile
336
336
  };
337
- //# sourceMappingURL=chunk-5HS54CLI.js.map
337
+ //# sourceMappingURL=chunk-5NEHH2E5.js.map
@@ -2,10 +2,10 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  fetchFailureToCliError,
4
4
  httpRequest
5
- } from "./chunk-5INS5ZZF.js";
5
+ } from "./chunk-OHZYNZSD.js";
6
6
  import {
7
7
  external_exports
8
- } from "./chunk-XICKN3CH.js";
8
+ } from "./chunk-VIOUZW7Z.js";
9
9
 
10
10
  // src/router/decision.ts
11
11
  var ROUTER_PATH = "/api/x402-router";
@@ -101,7 +101,38 @@ var ToolSpecSchema = external_exports.strictObject({
101
101
  outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
102
102
  });
103
103
  var OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });
104
- var SpecsSchema = external_exports.array(OfferSpecSchema).min(1).max(4).optional();
104
+ var SpecsSchema = external_exports.array(OfferSpecSchema).min(1).max(8).optional();
105
+ var PlainLine = (max) => external_exports.string().min(1).max(max).refine((text) => !/[\p{Cc}\p{Cf}]/u.test(text), "one plain line");
106
+ var ChoicesSchema = external_exports.strictObject({
107
+ group: PlainLine(64),
108
+ default: PlainLine(64),
109
+ input: external_exports.array(PlainLine(64)).min(1).max(16),
110
+ options: external_exports.array(
111
+ external_exports.strictObject({
112
+ key: PlainLine(64),
113
+ label: PlainLine(120),
114
+ strength: PlainLine(300),
115
+ id: IdSchema
116
+ })
117
+ ).min(2).max(4),
118
+ all: external_exports.strictObject({ totalAtomic: external_exports.string().regex(/^\d+$/) })
119
+ });
120
+ var ALL_CHOICES = "all";
121
+ function checkChoices(decision, ctx) {
122
+ const { choices } = decision;
123
+ if (choices === void 0) return;
124
+ const issue = (message) => ctx.addIssue({ code: "custom", path: ["choices"], message });
125
+ const keys = choices.options.map((option) => option.key);
126
+ const ids = choices.options.map((option) => option.id);
127
+ if (new Set(keys).size !== keys.length) issue("each choice key is named once");
128
+ if (new Set(ids).size !== ids.length) issue("each choice id is named once");
129
+ if (keys.includes(ALL_CHOICES)) issue(`"${ALL_CHOICES}" runs every choice, so it is no key`);
130
+ const specIds = new Set((decision.specs ?? []).map((spec) => spec.id));
131
+ if (ids.some((id) => !specIds.has(id))) issue("every choice carries its spec");
132
+ const fallback = choices.options.find((option) => option.key === choices.default);
133
+ if (fallback === void 0) issue("the default is one of the choices");
134
+ else if (fallback.id !== decision.id) issue("the default choice is this answer's own offer");
135
+ }
105
136
  var DiscoveredSchema = external_exports.strictObject({
106
137
  action: external_exports.literal("discovered"),
107
138
  id: IdSchema,
@@ -109,8 +140,9 @@ var DiscoveredSchema = external_exports.strictObject({
109
140
  /** THE LINE, FINISHED, as on `execute`: it carries the seller's
110
141
  * description and the input it takes. */
111
142
  hint: external_exports.string().min(1).max(2e3),
112
- specs: SpecsSchema
113
- }).superRefine(checkHint);
143
+ specs: SpecsSchema,
144
+ choices: ChoicesSchema.optional()
145
+ }).superRefine(checkHint).superRefine(checkChoices);
114
146
  var HookDecisionSchema = external_exports.discriminatedUnion("action", [
115
147
  external_exports.strictObject({
116
148
  action: external_exports.literal("execute"),
@@ -172,7 +204,7 @@ function envelope(decision) {
172
204
  }
173
205
  var HookResponseSchema = envelope(HookDecisionSchema);
174
206
  var ToolResponseSchema = envelope(ToolDecisionSchema);
175
- var CLIENT_ACCEPTS = ["discovered", "spec"];
207
+ var CLIENT_ACCEPTS = ["discovered", "spec", "choices"];
176
208
  var BAZAAR_ACCEPT = "bazaar";
177
209
  function acceptsFor(bazaar) {
178
210
  return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];
@@ -274,6 +306,7 @@ function buildOutcomeBody(outcome) {
274
306
  schemaVersion: 1,
275
307
  id: outcome.id,
276
308
  status: outcome.status,
309
+ ...outcome.reason !== void 0 ? { reason: outcome.reason } : {},
277
310
  ...outcome.httpStatus !== void 0 ? { httpStatus: outcome.httpStatus } : {},
278
311
  ...outcome.ms !== void 0 ? { ms: Math.max(0, Math.round(outcome.ms)) } : {}
279
312
  };
@@ -320,6 +353,8 @@ function isUnreachable(failure) {
320
353
  export {
321
354
  ROUTER_PATH,
322
355
  OfferSpecSchema,
356
+ ChoicesSchema,
357
+ ALL_CHOICES,
323
358
  RouteSkipped,
324
359
  CHANNEL_BUSY,
325
360
  PAID_PATH_ABSENT,
@@ -329,4 +364,4 @@ export {
329
364
  reportSpecOutcome,
330
365
  isUnreachable
331
366
  };
332
- //# sourceMappingURL=chunk-Z7R2QDX2.js.map
367
+ //# sourceMappingURL=chunk-64SE3QC5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { FetchJsonFailure, HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\n\n/**\n * `POST /api/x402-router`: ONE DECISION PER LOOKUP. On the free path it costs\n * nothing. Inside `tenjin mcp`, while the server answers its paid path, the\n * same body goes to that path through the stock x402 client\n * ({@link DecisionRoute}, `routing-payer.ts`); a call that path cannot take\n * falls back to the free path. The rest of this note describes the free path,\n * which is unchanged.\n *\n * The routing decision costs nothing and nobody signs for it. The hook asks for\n * it from the user's own words, the backend answers with what it would do and\n * what the provider charges, and the only payment on the wire is the one\n * `runPay` makes to that provider. That deletes the router fee and everything\n * built to carry it: the 402 probe, the requirements cache, the stale-quote\n * retry, the settlement accounting and one Base settlement of about 1.5 s from\n * every paid lookup.\n *\n * The bounded packet travels with the hook request and the backend keeps it\n * against the decision id until that id expires. What this client keeps is\n * each offer's spec, by its id (`specs.ts`).\n */\n\nexport const ROUTER_PATH = '/api/x402-router';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, a non-execute with no diagnostics parsed\n * with nothing to act on, and a hook answer carrying a contract parsed as\n * though the hook had quoted a price. Each of those is drift the shared\n * fixtures exist to catch, so each is now a parse failure that names itself.\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.strictObject({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. The `request` tool refuses a live\n * 402 above it; `gateSpend` still caps the amount actually signed. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n};\n\n/**\n * STRUCTURE, NEVER WORDING. A hint lands in the model's context verbatim, so\n * its shape is checked the way the id's alphabet is: one line, no control\n * characters, and it has to be the call it claims to be, naming the id this\n * same answer carries. A hint that fails any of these is a protocol error and\n * the turn falls back to the generic line; nothing here rewrites a word of a\n * hint that passes. Both offering arms, `execute` and `discovered`, hold it.\n */\nfunction checkHint(decision: { id: string; hint: string }, ctx: z.RefinementCtx): void {\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n}\n\n/**\n * A PAY-PER-CALL SERVICE NOBODY CURATED. When no capability in the catalog fits\n * but a listed x402 service could do the step, the server names that one\n * service: who sells it, where, for how much, and the input it takes. The\n * candidate is the seller's own listing, so every field is data for the host\n * to judge, never an instruction; the host builds the `input` and the tool\n * call pays through the same `runPay` path and caps as a curated lookup.\n */\nconst DiscoveredCandidateSchema = z.strictObject({\n source: z.string().min(1).max(64),\n provider: z.string().min(1).max(120),\n url: z.string().min(1).max(2_048),\n method: z.enum(['GET', 'POST']),\n description: z.string().max(500),\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n network: z.string().min(1).max(64),\n payTo: z.string().min(1).max(200),\n input: z.strictObject({\n location: z.enum(['body', 'query']),\n schema: z.record(z.string(), z.unknown()),\n }),\n});\n\n/**\n * A REQUEST SPEC: the offered service's real contract, sent beside the line only\n * because this build asks for it (`accepts: [\"spec\"]`). The hook stores it by\n * the offer's id; `request({id})` shows it and `request({id, input})` fills its\n * request and pays the provider directly, with no second decision. Every field\n * is the server's, and so is checked like the rest of the answer: the payee and\n * price still meet the live 402 and the spend policy in `runPay`.\n */\nexport const ToolSpecSchema = z.strictObject({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n description: z.string().min(1).max(500),\n priceAtomic: z.string().regex(/^\\d+$/),\n priceVaries: z.boolean(),\n maxAmountAtomic: z.string().regex(/^\\d+$/),\n payTo: z.string().min(1).max(200),\n network: z.string().min(1).max(64),\n asset: z.string().min(1).max(200),\n request: z.strictObject({\n method: z.enum(['GET', 'POST']),\n url: z.string().min(1).max(2_048),\n fields: z.record(z.string(), z.enum(['path', 'query', 'body'])),\n location: z.enum(['query', 'body']),\n }),\n input: z.record(z.string(), z.unknown()),\n pinned: z.record(z.string(), z.unknown()),\n example: z.record(z.string(), z.unknown()).optional(),\n returns: z.string().min(1).max(200).optional(),\n returnsExample: z.unknown().optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n /** The fields the result promises (type, properties, items, required). The\n * agent is handed only these; the whole body is saved to a file. */\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n});\nexport type ToolSpec = z.infer<typeof ToolSpecSchema>;\n\nexport const OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });\nexport type OfferSpec = z.infer<typeof OfferSpecSchema>;\n\n/** One spec per service the line names: the offer, any alternative, and each\n * option of a choice set. */\nconst SpecsSchema = z.array(OfferSpecSchema).min(1).max(8).optional();\n\n/** Words this client shows the model itself, in its own line: one plain line. */\nconst PlainLine = (max: number) =>\n z\n .string()\n .min(1)\n .max(max)\n .refine((text) => !/[\\p{Cc}\\p{Cf}]/u.test(text), 'one plain line');\n\n/**\n * SERVICES THE USER PICKS BETWEEN, OR RUNS ALL OF. Sent only to a build that\n * lists `choices` in `accepts`. Each option is a real offer: its own id, its\n * own spec in `specs`, and its own one payment, so `request({id, choice})`\n * runs exactly the spec `request({id: option.id})` would. `all` runs every\n * option side by side, one payment each. The set is the server's data:\n * changing it is a deploy there, not a release here. `input` names the open\n * fields the options share, the only ones an `all` call may carry.\n */\nexport const ChoicesSchema = z.strictObject({\n group: PlainLine(64),\n default: PlainLine(64),\n input: z.array(PlainLine(64)).min(1).max(16),\n options: z\n .array(\n z.strictObject({\n key: PlainLine(64),\n label: PlainLine(120),\n strength: PlainLine(300),\n id: IdSchema,\n }),\n )\n .min(2)\n .max(4),\n all: z.strictObject({ totalAtomic: z.string().regex(/^\\d+$/) }),\n});\nexport type Choices = z.infer<typeof ChoicesSchema>;\n\n/** The word that runs every option, so no option may take it as its key. */\nexport const ALL_CHOICES = 'all';\n\n/**\n * A CHOICE NAMES ONLY WHAT THIS ANSWER CARRIES: each key and id once, `all`\n * free for the whole set, a spec for every option, and the default option is\n * the offer this answer's id already names. A set that breaks any of these is\n * a protocol error, and the turn falls back like any unreadable answer.\n */\nfunction checkChoices(\n decision: { id: string; specs?: { id: string }[] | undefined; choices?: Choices | undefined },\n ctx: z.RefinementCtx,\n): void {\n const { choices } = decision;\n if (choices === undefined) return;\n const issue = (message: string) => ctx.addIssue({ code: 'custom', path: ['choices'], message });\n const keys = choices.options.map((option) => option.key);\n const ids = choices.options.map((option) => option.id);\n if (new Set(keys).size !== keys.length) issue('each choice key is named once');\n if (new Set(ids).size !== ids.length) issue('each choice id is named once');\n if (keys.includes(ALL_CHOICES)) issue(`\"${ALL_CHOICES}\" runs every choice, so it is no key`);\n const specIds = new Set((decision.specs ?? []).map((spec) => spec.id));\n if (ids.some((id) => !specIds.has(id))) issue('every choice carries its spec');\n const fallback = choices.options.find((option) => option.key === choices.default);\n if (fallback === undefined) issue('the default is one of the choices');\n else if (fallback.id !== decision.id) issue(\"the default choice is this answer's own offer\");\n}\n\n/** The same answer on both calls: the hook's offer, and the tool's fallback\n * when a query with no id found no curated capability. */\nconst DiscoveredSchema = z\n .strictObject({\n action: z.literal('discovered'),\n id: IdSchema,\n candidate: DiscoveredCandidateSchema,\n /** THE LINE, FINISHED, as on `execute`: it carries the seller's\n * description and the input it takes. */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n choices: ChoicesSchema.optional(),\n })\n .superRefine(checkHint)\n .superRefine(checkChoices);\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .strictObject({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. */\n endpoint: z.string().min(1).max(2_048),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift. The same\n * bound as a discovered line's.\n */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.strictObject({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n /**\n * A query with no id, answered with the spec of the service the server\n * picked under a fresh `id`: kept like a hook's, and never run in the same\n * call. `hint` is the line, with the skeleton of the next call:\n * `request({id, input: {...}})` with the required fields. `input` is what a\n * router from before the binder's removal still sends on a bound pick: it\n * is accepted so that answer parses, and never read, so it never runs.\n */\n z\n .strictObject({\n action: z.literal('spec'),\n id: IdSchema,\n spec: ToolSpecSchema,\n hint: z.string().min(1).max(2_000),\n input: z.record(z.string(), z.unknown()).optional(),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool';\n\n/**\n * What this client can act on beyond the curated answers, sent on both calls.\n * `discovered` is Tenjin's reviewed list of third-party services, on for every\n * build that parses it; the server answers that arm only to a request that\n * lists it, so an older build never sees one. `spec` asks for each offered\n * service's request spec beside its line, and for the picked service's spec in\n * place of a decision on a query with no id, which only a build that parses\n * them can take: the decision schemas are strict. `choices` asks for a set of\n * options the user picks between, or runs all of, beside a discovered offer.\n * `bazaar` widens discovery to the open Bazaar and is sent only while\n * `experimental.bazaar` is on.\n */\nexport const CLIENT_ACCEPTS: readonly string[] = ['discovered', 'spec', 'choices'];\nexport const BAZAAR_ACCEPT = 'bazaar';\n\n/** The `accepts` this build sends, with the open Bazaar or without it. */\nexport function acceptsFor(bazaar: boolean): string[] {\n return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];\n}\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route reads it with a strict object, so an extra field is a\n * 400, and a 400 is a turn with no hint.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone. `sessionId` is the harness's own session id, which the\n * server uses only so one session is not offered the same discovered service\n * twice.\n */\nexport function buildHookBody(\n packet: Packet,\n extras: { sessionId?: string; accepts?: readonly string[] } = {},\n): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(extras.sessionId !== undefined ? { sessionId: extras.sessionId } : {}),\n ...(extras.accepts !== undefined ? { accepts: [...extras.accepts] } : {}),\n packet,\n };\n}\n\n/** The exact body the tool call sends. `id` is the offer the query is for,\n * sent only for an offer with no spec kept; `gateHint` is evidence, never\n * authority. */\nexport function buildToolBody(request: {\n query?: string;\n id?: string;\n gateHint?: GateHint;\n accepts?: readonly string[];\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n ...(request.accepts !== undefined ? { accepts: [...request.accepts] } : {}),\n };\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(kind: CallKind, value: unknown): { success: boolean } {\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n return { success: schema.safeParse(value).success };\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n /** `experimental.bazaar`: add {@link BAZAAR_ACCEPT}, so a service from the\n * open Bazaar may come back. Off by default: curated and the Tenjin list. */\n acceptsBazaar?: boolean;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n /** The paid path, when `tenjin mcp` takes it: the body goes to `path` and is\n * sent by `send`, which pays the routing fee with the stock x402 client.\n * Absent is the free path. */\n route?: DecisionRoute;\n}\n\n/** How a routing call reaches the paid path. `send` throws\n * {@link RouteSkipped} when it has no paid answer for the call, which then\n * takes the free path. */\nexport interface DecisionRoute {\n path: string;\n send: (url: string, options: HttpRequestOptions) => Promise<HttpResult>;\n}\n\n/** The paid path gave this call no answer: the wallet locked, low or over\n * its spend limits, the channel busy, or the payment failed. */\nexport class RouteSkipped extends Error {\n /** `unreached`: the paid call could not reach the router\n * ({@link isUnreachable}), so the free path, on the same host, is not\n * tried and the call reads as that transport failure. */\n constructor(\n readonly why: string,\n readonly unreached?: FetchJsonFailure,\n ) {\n super(`routing fee not paid: ${why}`);\n }\n}\n\n/** Another session's call was in flight on the wallet's routing channel. */\nexport const CHANNEL_BUSY = 'channel_busy';\n/** The server answered no paid path. */\nexport const PAID_PATH_ABSENT = 'paid_path_absent';\n/** The paid call got no answer, a refused payment or a server error. */\nexport const PAYMENT_FAILED = 'payment_failed';\n/** The payment went out and the call's budget ran out before its answer:\n * no fault. `tenjin mcp` lets the request finish, so it is recorded. */\nexport const DEADLINE_AFTER_PAYMENT_SENT = 'deadline_after_payment_sent';\n\nexport type DecisionOutcome<T> =\n /** `freePath`: the paid path skipped the call for this reason and it went\n * to the free path instead, unpaid. */\n | { status: 'decided'; decision: T; freePath?: string }\n /** On the free path nothing was paid and nothing could be, so a failure here\n * costs the turn a routing answer and nothing else. */\n | {\n status: 'failed';\n reason: string;\n errorCode?: string;\n freePath?: string;\n /** The router could not be reached at all ({@link isUnreachable}). */\n unreachable?: true;\n /** No answer came back at all: a transport failure or a timeout. */\n noAnswer?: true;\n }\n /** The paid path gave no answer ({@link RouteSkipped}) and no time was left\n * for the free path: the native tool runs. */\n | { status: 'skipped'; why: string };\n\n/**\n * ONE FREE CALL, IN TWO FORMS. The hook sends `{ packet }`: the backend runs\n * the gate, and on `execute` stores that packet under an id and answers with\n * each offered service's spec. The tool sends `{ query }`, which the backend\n * answers with the spec of the service its gate picks, or `{ query, id }` for\n * the free docs offer, which has no spec and is bound from the query. Every\n * provider call is built here, from a spec, or for the docs lookup by the\n * backend from the query.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet; sessionId?: string },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query: string; id?: string; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n sessionId?: string;\n id?: string;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(deps.route?.path ?? ROUTER_PATH, deps.baseUrl).toString();\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet, {\n ...(request.sessionId !== undefined ? { sessionId: request.sessionId } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n })\n : buildToolBody({\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n const started = Date.now();\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n let response: HttpResult;\n try {\n response = await (deps.route?.send ?? httpRequest)(url, options);\n } catch (err) {\n if (!(err instanceof RouteSkipped)) throw err;\n if (err.unreached !== undefined) return readDecision(err.unreached, schema);\n const left = options.timeoutMs - (Date.now() - started);\n if (left <= 0) return { status: 'skipped', why: err.why };\n // A CALL THE PAID PATH COULD NOT TAKE STILL ROUTES, on the free path,\n // unpaid, inside what is left of its budget, and says why.\n response = await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n ...options,\n timeoutMs: left,\n });\n const free = readDecision(response, schema);\n // A failure here ran on what a paid attempt left of the budget, so it says\n // nothing about the router being down: it never starts the backoff.\n if (free.status === 'failed') {\n return {\n status: 'failed',\n reason: free.reason,\n ...(free.errorCode !== undefined ? { errorCode: free.errorCode } : {}),\n // Still no answer, which must not end another call's backoff.\n ...(free.noAnswer === true ? { noAnswer: true as const } : {}),\n freePath: err.why,\n };\n }\n return free.status === 'skipped' ? free : { ...free, freePath: err.why };\n }\n return readDecision(response, schema);\n}\n\n/** Why a call from a spec stopped before anything was signed: the input did\n * not fit, the live terms were not the spec's, the provider answered\n * something else, it could not be reached, or the wallet could not pay. */\nexport type UnpaidReason = 'input' | 'terms' | 'provider' | 'unreachable' | 'wallet';\n\n/** How a call run from a request spec ended, for the server's offer-to-call\n * count. No text: the id, the outcome, the provider's status and the time. */\nexport interface SpecOutcome {\n id: string;\n /** `unpaid`: stopped before anything was signed, which the server never\n * counts as the offer taken. */\n status: 'fulfilled' | 'unverified' | 'failed' | 'needs_approval' | 'unpaid';\n /** On `unpaid` only, where the server requires it. */\n reason?: UnpaidReason;\n httpStatus?: number;\n ms?: number;\n}\n\n/** The outcome report's own deadline: it is telemetry and never holds a result. */\nexport const OUTCOME_TIMEOUT_MS = 3_000;\n\n/**\n * TELL THE SERVER A SPEC WAS USED. The client called and paid the provider\n * itself, so this is the only word the server gets that its offer was taken,\n * or that a call for it stopped before payment and why. Never throws and never\n * waits on anything the caller needs: a lost report costs one count.\n */\nexport async function reportSpecOutcome(\n outcome: SpecOutcome,\n deps: Pick<DecisionDeps, 'ctx' | 'baseUrl' | 'fetchImpl'>,\n): Promise<void> {\n try {\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: OUTCOME_TIMEOUT_MS,\n blockRedirects: true,\n jsonBody: buildOutcomeBody(outcome),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n } catch {\n // Telemetry only.\n }\n}\n\n/** The exact body of an outcome report, pinned to the shared fixtures. */\nexport function buildOutcomeBody(outcome: SpecOutcome): Record<string, unknown> {\n return {\n schemaVersion: 1,\n id: outcome.id,\n status: outcome.status,\n ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}),\n ...(outcome.httpStatus !== undefined ? { httpStatus: outcome.httpStatus } : {}),\n ...(outcome.ms !== undefined ? { ms: Math.max(0, Math.round(outcome.ms)) } : {}),\n };\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason; nothing was paid either way,\n // because there is nothing to pay for on this route.\n if (!response.ok) {\n return {\n status: 'failed',\n reason: fetchFailureToCliError(response).message,\n ...(isUnreachable(response) ? { unreachable: true as const } : {}),\n ...(response.status === undefined ? { noAnswer: true as const } : {}),\n };\n }\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n\n/** A dropped socket, which a fresh connection usually gets past. */\nconst RESET_CODES = new Set(['ECONNRESET', 'UND_ERR_SOCKET']);\n\n/**\n * A ROUTER THAT CANNOT BE REACHED: the transport named the layer that refused\n * the connection (DNS, TLS, a refused connection, a proxy refusing the tunnel)\n * and no status came back. Never the call's own timeout: that is the gate's\n * few seconds, and a slow decision or a cold start must not take the router\n * away from every session. Never a status, even with a body that failed to\n * read, and never a reset socket, which the free path retries on a fresh one.\n */\nexport function isUnreachable(failure: FetchJsonFailure): boolean {\n return (\n failure.kind === 'network' &&\n failure.status === undefined &&\n failure.transport !== undefined &&\n !RESET_CODES.has(failure.transport.code ?? '')\n );\n}\n"],"mappings":";;;;;;;;;;AA2BO,IAAM,cAAc;AAO3B,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EAC7B,KAAK,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM;AAAA,EACjC,QAAQ,iBAAE,KAAK,CAAC,OAAO,QAAQ,OAAO,SAAS,UAAU,QAAQ,SAAS,CAAC;AAAA,EAC3E,SAAS,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,OAAO,CAAC;AAAA,EACxC,MAAM,iBACH,OAAO,EACP,IAAI,MAAM,IAAI,EACd,SAAS;AACd,CAAC;AAED,IAAM,iBAAiB,iBAAE,OAAO;AAAA;AAAA;AAAA,EAG9B,WAAW,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACtD,cAAc,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACzD,SAAS;AACX,CAAC;AAQD,IAAM,oBAAoB,iBAAE,OAAO;AAAA,EACjC,YAAY,iBAAE,OAAO,EAAE,IAAI,CAAC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QACE,UAAU,OACN,gCAAgC,SAAS,MAAM,MAC/C,gCAAgC,SAAS,MAAM,KAAK,MAAM,IAAI,MAAM,MAAM,OAAO;AAAA,MACvF,GAAI,UAAU,OAAO,EAAE,WAAW,MAAM,KAAK,IAAI,CAAC;AAAA,IACpD;AAAA,EACF;AACA,QAAM,SAAS,OAAO,UAAU,SAAS,IAAI;AAC7C,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,EAAE,QAAQ,UAAU,QAAQ,yDAAyD;AAAA,EAC9F;AACA,SAAO,EAAE,QAAQ,WAAW,UAAU,OAAO,KAAmB;AAClE;AAIA,SAAS,QAAQ,MAAyD;AACxE,MAAI,SAAS,QAAQ,OAAO,SAAS,SAAU,QAAO;AACtD,QAAM,QAAS,KAA6B;AAC5C,MAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AACxD,QAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,MAAI,OAAO,SAAS,YAAY,KAAK,WAAW,KAAK,KAAK,SAAS,GAAI,QAAO;AAC9E,QAAM,OAAO,OAAO,YAAY,WAAW,QAAQ,MAAM,GAAG,GAAG,IAAI;AACnE,SAAO,EAAE,MAAM,SAAS,KAAK;AAC/B;AAGA,IAAM,cAAc,oBAAI,IAAI,CAAC,cAAc,gBAAgB,CAAC;AAUrD,SAAS,cAAc,SAAoC;AAChE,SACE,QAAQ,SAAS,aACjB,QAAQ,WAAW,UACnB,QAAQ,cAAc,UACtB,CAAC,YAAY,IAAI,QAAQ,UAAU,QAAQ,EAAE;AAEjD;","names":[]}
@@ -0,0 +1,52 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ CliError
4
+ } from "./chunk-JLEF5WHM.js";
5
+
6
+ // src/lib/money.ts
7
+ var USDC_DECIMALS = 6;
8
+ function parseUsdToAtomic(input) {
9
+ const trimmed = input.trim();
10
+ if (!/^\d+(\.\d+)?$/.test(trimmed)) {
11
+ throw new CliError("USAGE", `Invalid USD amount: ${JSON.stringify(input)}`, {
12
+ fix: "Pass a non-negative decimal like 0.25 or 5."
13
+ });
14
+ }
15
+ const [whole, frac = ""] = trimmed.split(".");
16
+ if (frac.length > USDC_DECIMALS) {
17
+ throw new CliError(
18
+ "USAGE",
19
+ `USD amount ${JSON.stringify(input)} has more than 6 decimal places`,
20
+ {
21
+ fix: "USDC supports at most 6 decimal places (micro-dollars)."
22
+ }
23
+ );
24
+ }
25
+ const atomic = BigInt(`${whole}${frac.padEnd(USDC_DECIMALS, "0")}`);
26
+ return atomic.toString();
27
+ }
28
+ function atomicToUsd(atomic) {
29
+ const trimmed = atomic.trim();
30
+ if (!/^\d+$/.test(trimmed)) {
31
+ throw new CliError("INTERNAL", `Malformed atomic amount: ${JSON.stringify(atomic)}`);
32
+ }
33
+ const value = BigInt(trimmed);
34
+ const base = 10n ** BigInt(USDC_DECIMALS);
35
+ const whole = value / base;
36
+ const frac = (value % base).toString().padStart(USDC_DECIMALS, "0").replace(/0+$/, "");
37
+ return frac.length > 0 ? `${whole}.${frac}` : whole.toString();
38
+ }
39
+ function toMoney(atomic) {
40
+ return { atomic, usd: atomicToUsd(atomic) };
41
+ }
42
+ function formatUsdDisplay(atomic) {
43
+ const [whole, frac = ""] = atomicToUsd(atomic).split(".");
44
+ return `${whole}.${frac.padEnd(2, "0")}`;
45
+ }
46
+
47
+ export {
48
+ parseUsdToAtomic,
49
+ toMoney,
50
+ formatUsdDisplay
51
+ };
52
+ //# sourceMappingURL=chunk-6ZSGER3A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/money.ts"],"sourcesContent":["import { CliError } from './errors';\nimport { ATOMIC_RE } from './ids';\nimport type { Money } from '../schemas';\n\n/** USDC is a 6-decimal token; one dollar is 1_000_000 atomic units. */\nconst USDC_DECIMALS = 6;\n\n/**\n * Decimal USD at the CLI edge -> atomic USDC string (O1). Accepts \"0\", \"0.25\",\n * \"5\"; rejects negatives, non-numeric input, and more than 6 decimal places as\n * USAGE so a fat-fingered amount fails loudly instead of truncating money.\n * String math throughout — a float would lose precision at the 6th decimal.\n */\nexport function parseUsdToAtomic(input: string): string {\n const trimmed = input.trim();\n if (!/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n throw new CliError('USAGE', `Invalid USD amount: ${JSON.stringify(input)}`, {\n fix: 'Pass a non-negative decimal like 0.25 or 5.',\n });\n }\n const [whole, frac = ''] = trimmed.split('.');\n if (frac.length > USDC_DECIMALS) {\n throw new CliError(\n 'USAGE',\n `USD amount ${JSON.stringify(input)} has more than 6 decimal places`,\n {\n fix: 'USDC supports at most 6 decimal places (micro-dollars).',\n },\n );\n }\n const atomic = BigInt(`${whole}${frac.padEnd(USDC_DECIMALS, '0')}`);\n return atomic.toString();\n}\n\n/**\n * Atomic USDC string -> decimal USD string, trailing zeros trimmed (\"250000\" ->\n * \"0.25\", \"5000000\" -> \"5\", \"0\" -> \"0\"). Throws INTERNAL on a malformed atomic\n * value: atomic strings come from validated config or on-chain reads, so a bad\n * one is a bug, not user input.\n */\nexport function atomicToUsd(atomic: string): string {\n const trimmed = atomic.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new CliError('INTERNAL', `Malformed atomic amount: ${JSON.stringify(atomic)}`);\n }\n const value = BigInt(trimmed);\n const base = 10n ** BigInt(USDC_DECIMALS);\n const whole = value / base;\n const frac = (value % base).toString().padStart(USDC_DECIMALS, '0').replace(/0+$/, '');\n return frac.length > 0 ? `${whole}.${frac}` : whole.toString();\n}\n\n/**\n * Whether an atomic price would actually cost something: true paid, false free,\n * null when the string is not an atomic amount at all and so cannot answer.\n *\n * A Tenjin piece may be priced at zero and is then delivered by `read` with no\n * payment, so \"there is a price field\" and \"there is a purchase to make\" are\n * different questions. The third state is not decoration: only the wire schema\n * enforces ATOMIC_RE, and the local search store types `price` as a bare string,\n * so a hand-edited or half-written entry can hold \"-1\" or \"0.1\". Those must not\n * read as \"free\", or corrupt local data would start refusing honest reports.\n * Never throws, which is why the check is a regex and not a BigInt compare.\n *\n * Matched against the RAW string, with no trimming. The contract carries the\n * canonical form and nothing else, so \" 0 \" did not come off the wire; padding is\n * evidence the value was edited, and normalizing it away would launder a corrupt\n * entry into a confident \"free\" and hand back the false refusal this avoids.\n */\nexport function isPaidPrice(atomic: string): boolean | null {\n if (!ATOMIC_RE.test(atomic)) return null;\n return /[1-9]/.test(atomic);\n}\n\n/** Dual-form money object for machine output. */\nexport function toMoney(atomic: string): Money {\n return { atomic, usd: atomicToUsd(atomic) };\n}\n\n/**\n * Canonical USD for human COPY (a price a person reads): always at least two\n * decimals (\"0.10\", \"5.00\"), keeping any finer precision below a cent\n * (\"0.000001\"). Distinct from `atomicToUsd`, which trims to the shortest exact\n * form for machine output; use this only where a dollar amount is shown to a human.\n */\nexport function formatUsdDisplay(atomic: string): string {\n const [whole, frac = ''] = atomicToUsd(atomic).split('.');\n return `${whole}.${frac.padEnd(2, '0')}`;\n}\n"],"mappings":";;;;;;AAKA,IAAM,gBAAgB;AAQf,SAAS,iBAAiB,OAAuB;AACtD,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,gBAAgB,KAAK,OAAO,GAAG;AAClC,UAAM,IAAI,SAAS,SAAS,uBAAuB,KAAK,UAAU,KAAK,CAAC,IAAI;AAAA,MAC1E,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,QAAM,CAAC,OAAO,OAAO,EAAE,IAAI,QAAQ,MAAM,GAAG;AAC5C,MAAI,KAAK,SAAS,eAAe;AAC/B,UAAM,IAAI;AAAA,MACR;AAAA,MACA,cAAc,KAAK,UAAU,KAAK,CAAC;AAAA,MACnC;AAAA,QACE,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACA,QAAM,SAAS,OAAO,GAAG,KAAK,GAAG,KAAK,OAAO,eAAe,GAAG,CAAC,EAAE;AAClE,SAAO,OAAO,SAAS;AACzB;AAQO,SAAS,YAAY,QAAwB;AAClD,QAAM,UAAU,OAAO,KAAK;AAC5B,MAAI,CAAC,QAAQ,KAAK,OAAO,GAAG;AAC1B,UAAM,IAAI,SAAS,YAAY,4BAA4B,KAAK,UAAU,MAAM,CAAC,EAAE;AAAA,EACrF;AACA,QAAM,QAAQ,OAAO,OAAO;AAC5B,QAAM,OAAO,OAAO,OAAO,aAAa;AACxC,QAAM,QAAQ,QAAQ;AACtB,QAAM,QAAQ,QAAQ,MAAM,SAAS,EAAE,SAAS,eAAe,GAAG,EAAE,QAAQ,OAAO,EAAE;AACrF,SAAO,KAAK,SAAS,IAAI,GAAG,KAAK,IAAI,IAAI,KAAK,MAAM,SAAS;AAC/D;AAyBO,SAAS,QAAQ,QAAuB;AAC7C,SAAO,EAAE,QAAQ,KAAK,YAAY,MAAM,EAAE;AAC5C;AAQO,SAAS,iBAAiB,QAAwB;AACvD,QAAM,CAAC,OAAO,OAAO,EAAE,IAAI,YAAY,MAAM,EAAE,MAAM,GAAG;AACxD,SAAO,GAAG,KAAK,IAAI,KAAK,OAAO,GAAG,GAAG,CAAC;AACxC;","names":[]}
@@ -184,7 +184,7 @@ async function writeProgress(directory, callId, step, now = Date.now()) {
184
184
  };
185
185
  await write(join(directory, `${digest(callId)}.json`), saved);
186
186
  }
187
- var SILENT = {
187
+ var SILENT_FOOTER = {
188
188
  routing: async () => void 0,
189
189
  calling: async () => void 0,
190
190
  done: async () => void 0
@@ -195,7 +195,7 @@ async function openLookupFooter(dataDir, opts = {}) {
195
195
  ...opts.id !== void 0 ? { id: opts.id } : {},
196
196
  now: now()
197
197
  }).catch(() => null);
198
- if (directory === null) return SILENT;
198
+ if (directory === null) return SILENT_FOOTER;
199
199
  const callId = newCallId();
200
200
  const operation = opts.operation ?? "request";
201
201
  const step = async (patch) => {
@@ -369,9 +369,10 @@ export {
369
369
  claimRedirect,
370
370
  redirectClaimed,
371
371
  writeProgress,
372
+ SILENT_FOOTER,
372
373
  openLookupFooter,
373
374
  pruneProgress,
374
375
  pruneSessions,
375
376
  renderProgress
376
377
  };
377
- //# sourceMappingURL=chunk-QF4SSCQV.js.map
378
+ //# sourceMappingURL=chunk-AWKQSKUL.js.map