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

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 (133) hide show
  1. package/README.md +19 -42
  2. package/dist/{chunk-GPLSNGKX.js → chunk-4HAV6IFE.js} +6 -6
  3. package/dist/{chunk-UXSF7IFD.js → chunk-5HS54CLI.js} +3 -3
  4. package/dist/{chunk-RCJ64OXH.js → chunk-5INS5ZZF.js} +36 -7
  5. package/dist/chunk-5INS5ZZF.js.map +1 -0
  6. package/dist/{chunk-XZUGRTSV.js → chunk-5NUF4BHR.js} +5 -3
  7. package/dist/{chunk-XZUGRTSV.js.map → chunk-5NUF4BHR.js.map} +1 -1
  8. package/dist/{chunk-YZTIYDWU.js → chunk-65EJJVT3.js} +2 -2
  9. package/dist/{chunk-ZMFDMALH.js → chunk-6JIYGYRB.js} +3 -53
  10. package/dist/chunk-6JIYGYRB.js.map +1 -0
  11. package/dist/chunk-7EKYXMUO.js +7536 -0
  12. package/dist/chunk-7EKYXMUO.js.map +1 -0
  13. package/dist/chunk-AKWGE6JQ.js +49 -0
  14. package/dist/chunk-AKWGE6JQ.js.map +1 -0
  15. package/dist/{chunk-KC24CYGV.js → chunk-ALJRB7NG.js} +14 -9
  16. package/dist/chunk-ALJRB7NG.js.map +1 -0
  17. package/dist/{chunk-S2NRVRPF.js → chunk-BOAI23CX.js} +53 -2
  18. package/dist/chunk-BOAI23CX.js.map +1 -0
  19. package/dist/{chunk-SQSKVKX6.js → chunk-DI7WHXOZ.js} +20 -16
  20. package/dist/chunk-DI7WHXOZ.js.map +1 -0
  21. package/dist/{chunk-UBOFYC6J.js → chunk-EJXIK6WY.js} +1817 -137
  22. package/dist/chunk-EJXIK6WY.js.map +1 -0
  23. package/dist/{chunk-RGVOODF4.js → chunk-EL56RW2J.js} +164 -7463
  24. package/dist/chunk-EL56RW2J.js.map +1 -0
  25. package/dist/{chunk-ZNZGBUV6.js → chunk-GHR4BTNJ.js} +9 -7
  26. package/dist/chunk-GHR4BTNJ.js.map +1 -0
  27. package/dist/chunk-H4BOQLWW.js +99 -0
  28. package/dist/chunk-H4BOQLWW.js.map +1 -0
  29. package/dist/{chunk-TMLCEPCD.js → chunk-HII5HOQV.js} +3 -5
  30. package/dist/chunk-HII5HOQV.js.map +1 -0
  31. package/dist/chunk-LFZJM56J.js +159 -0
  32. package/dist/chunk-LFZJM56J.js.map +1 -0
  33. package/dist/chunk-OBPZ36HG.js +145 -0
  34. package/dist/chunk-OBPZ36HG.js.map +1 -0
  35. package/dist/{chunk-NSDZESRS.js → chunk-OZ3LWLCI.js} +3 -3
  36. package/dist/chunk-PM2MOXJ3.js +66 -0
  37. package/dist/chunk-PM2MOXJ3.js.map +1 -0
  38. package/dist/chunk-PZ5N6BAL.js +268 -0
  39. package/dist/chunk-PZ5N6BAL.js.map +1 -0
  40. package/dist/{chunk-O2WN732M.js → chunk-UDWGT4FX.js} +2 -2
  41. package/dist/{chunk-W2ARIOAZ.js → chunk-VNT3CQFV.js} +23 -25
  42. package/dist/chunk-VNT3CQFV.js.map +1 -0
  43. package/dist/{chunk-XRW4N23F.js → chunk-W36HL4TB.js} +6 -6
  44. package/dist/{chunk-IIE65SJC.js → chunk-WT7DHJNJ.js} +4 -4
  45. package/dist/{chunk-P22ZWXFX.js → chunk-XICKN3CH.js} +49 -4
  46. package/dist/chunk-XICKN3CH.js.map +1 -0
  47. package/dist/chunk-XMIVHQ35.js +55 -0
  48. package/dist/chunk-XMIVHQ35.js.map +1 -0
  49. package/dist/chunk-YHKXNYTB.js +105 -0
  50. package/dist/chunk-YHKXNYTB.js.map +1 -0
  51. package/dist/{chunk-H5UR3GFJ.js → chunk-YHWBDCGS.js} +272 -54
  52. package/dist/chunk-YHWBDCGS.js.map +1 -0
  53. package/dist/{hook-command-GMIDXVFK.js → chunk-YLCWI6ZR.js} +231 -40
  54. package/dist/chunk-YLCWI6ZR.js.map +1 -0
  55. package/dist/{chunk-FFL5M5BC.js → chunk-YTM7OURD.js} +2 -2
  56. package/dist/{chunk-EP5P2STS.js → chunk-Z7R2QDX2.js} +67 -10
  57. package/dist/chunk-Z7R2QDX2.js.map +1 -0
  58. package/dist/chunk-ZLD6MJVJ.js +30 -0
  59. package/dist/chunk-ZLD6MJVJ.js.map +1 -0
  60. package/dist/{cli-GGNOQQEB.js → cli-2U5JB7OQ.js} +38 -36
  61. package/dist/{cli-GGNOQQEB.js.map → cli-2U5JB7OQ.js.map} +1 -1
  62. package/dist/{config-XUUFICXK.js → config-44EGO636.js} +14 -9
  63. package/dist/{doctor-3LGF6CWI.js → doctor-BD42BBEG.js} +231 -97
  64. package/dist/doctor-BD42BBEG.js.map +1 -0
  65. package/dist/env-proxy-KEGEMWKX.js +15 -0
  66. package/dist/{fund-3URFMBMN.js → fund-WQOOUESE.js} +26 -17
  67. package/dist/fund-WQOOUESE.js.map +1 -0
  68. package/dist/hook-command-23LC5NRN.js +32 -0
  69. package/dist/index.js +5 -3
  70. package/dist/index.js.map +1 -1
  71. package/dist/{install-FRTG4KHF.js → install-REPLHNU7.js} +25 -16
  72. package/dist/{install-identity-WNXSYP6N.js → install-identity-4RDWTLJ2.js} +6 -7
  73. package/dist/{install-wallet-MXLJJP3N.js → install-wallet-USHWL7AX.js} +10 -9
  74. package/dist/{install-wallet-MXLJJP3N.js.map → install-wallet-USHWL7AX.js.map} +1 -1
  75. package/dist/{mcp-O2WJ3QBW.js → mcp-T5SYCLP7.js} +778 -83
  76. package/dist/mcp-T5SYCLP7.js.map +1 -0
  77. package/dist/{pay-43WUYTW5.js → pay-276DSSYG.js} +16 -14
  78. package/dist/{payments-7UTMMTIO.js → payments-TZYLJXK3.js} +7 -7
  79. package/dist/{send-ALHG2RXT.js → send-YHDKZPED.js} +10 -11
  80. package/dist/{send-ALHG2RXT.js.map → send-YHDKZPED.js.map} +1 -1
  81. package/dist/{status-CFPNHB6R.js → status-X2INT6VD.js} +8 -9
  82. package/dist/{status-CFPNHB6R.js.map → status-X2INT6VD.js.map} +1 -1
  83. package/dist/{status-line-FJ6N7MKJ.js → status-line-QKDJYZGV.js} +4 -5
  84. package/dist/{status-line-FJ6N7MKJ.js.map → status-line-QKDJYZGV.js.map} +1 -1
  85. package/dist/{status-line-wiring-GXFNXHPE.js → status-line-wiring-LW4HFRHB.js} +6 -4
  86. package/dist/status-line-wiring-LW4HFRHB.js.map +1 -0
  87. package/dist/{uninstall-5P2GFYBY.js → uninstall-NVTGU7JD.js} +43 -33
  88. package/dist/uninstall-NVTGU7JD.js.map +1 -0
  89. package/dist/{update-QJ5YHJ7I.js → update-QXVH2DE7.js} +25 -7
  90. package/dist/update-QXVH2DE7.js.map +1 -0
  91. package/dist/{wallet-6OJPGNEV.js → wallet-CKKB23D5.js} +10 -9
  92. package/dist/wallet-CKKB23D5.js.map +1 -0
  93. package/docs/agent-permissions.md +18 -5
  94. package/docs/troubleshooting.md +13 -0
  95. package/package.json +8 -6
  96. package/dist/chunk-EP5P2STS.js.map +0 -1
  97. package/dist/chunk-H5UR3GFJ.js.map +0 -1
  98. package/dist/chunk-KC24CYGV.js.map +0 -1
  99. package/dist/chunk-O2JYBOUO.js +0 -47
  100. package/dist/chunk-O2JYBOUO.js.map +0 -1
  101. package/dist/chunk-P22ZWXFX.js.map +0 -1
  102. package/dist/chunk-RCJ64OXH.js.map +0 -1
  103. package/dist/chunk-RGVOODF4.js.map +0 -1
  104. package/dist/chunk-S2NRVRPF.js.map +0 -1
  105. package/dist/chunk-SQSKVKX6.js.map +0 -1
  106. package/dist/chunk-TMLCEPCD.js.map +0 -1
  107. package/dist/chunk-UBOFYC6J.js.map +0 -1
  108. package/dist/chunk-W2ARIOAZ.js.map +0 -1
  109. package/dist/chunk-YXLG7Q6Q.js +0 -140
  110. package/dist/chunk-YXLG7Q6Q.js.map +0 -1
  111. package/dist/chunk-ZMFDMALH.js.map +0 -1
  112. package/dist/chunk-ZNZGBUV6.js.map +0 -1
  113. package/dist/doctor-3LGF6CWI.js.map +0 -1
  114. package/dist/fund-3URFMBMN.js.map +0 -1
  115. package/dist/hook-command-GMIDXVFK.js.map +0 -1
  116. package/dist/mcp-O2WJ3QBW.js.map +0 -1
  117. package/dist/uninstall-5P2GFYBY.js.map +0 -1
  118. package/dist/update-QJ5YHJ7I.js.map +0 -1
  119. /package/dist/{chunk-GPLSNGKX.js.map → chunk-4HAV6IFE.js.map} +0 -0
  120. /package/dist/{chunk-UXSF7IFD.js.map → chunk-5HS54CLI.js.map} +0 -0
  121. /package/dist/{chunk-YZTIYDWU.js.map → chunk-65EJJVT3.js.map} +0 -0
  122. /package/dist/{chunk-NSDZESRS.js.map → chunk-OZ3LWLCI.js.map} +0 -0
  123. /package/dist/{chunk-O2WN732M.js.map → chunk-UDWGT4FX.js.map} +0 -0
  124. /package/dist/{chunk-XRW4N23F.js.map → chunk-W36HL4TB.js.map} +0 -0
  125. /package/dist/{chunk-IIE65SJC.js.map → chunk-WT7DHJNJ.js.map} +0 -0
  126. /package/dist/{chunk-FFL5M5BC.js.map → chunk-YTM7OURD.js.map} +0 -0
  127. /package/dist/{config-XUUFICXK.js.map → config-44EGO636.js.map} +0 -0
  128. /package/dist/{install-FRTG4KHF.js.map → env-proxy-KEGEMWKX.js.map} +0 -0
  129. /package/dist/{install-identity-WNXSYP6N.js.map → hook-command-23LC5NRN.js.map} +0 -0
  130. /package/dist/{pay-43WUYTW5.js.map → install-REPLHNU7.js.map} +0 -0
  131. /package/dist/{status-line-wiring-GXFNXHPE.js.map → install-identity-4RDWTLJ2.js.map} +0 -0
  132. /package/dist/{wallet-6OJPGNEV.js.map → pay-276DSSYG.js.map} +0 -0
  133. /package/dist/{payments-7UTMMTIO.js.map → payments-TZYLJXK3.js.map} +0 -0
@@ -0,0 +1,55 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/lib/policy.ts
4
+ function normCreator(value) {
5
+ return value.trim().toLowerCase();
6
+ }
7
+ function evaluateSpendPolicy(policy, req) {
8
+ if (req.maxPriceAtomic !== void 0 && req.amountAtomic > req.maxPriceAtomic) {
9
+ return {
10
+ decision: "deny",
11
+ reason: "price_cap_exceeded",
12
+ message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`
13
+ };
14
+ }
15
+ if (policy.allowlistCreators.length > 0) {
16
+ const allowed = policy.allowlistCreators.map(normCreator);
17
+ if (!allowed.includes(normCreator(req.creator))) {
18
+ return {
19
+ decision: "deny",
20
+ reason: "not_allowlisted",
21
+ message: `Creator "${req.creator}" is not in allowlistCreators.`
22
+ };
23
+ }
24
+ }
25
+ if (req.mode === "manual") {
26
+ return req.amountAtomic > 0n ? {
27
+ decision: "confirm",
28
+ reason: "confirm_always",
29
+ message: "Manual payment requires explicit consent."
30
+ } : { decision: "allow", reason: "within_policy", message: "No payment required." };
31
+ }
32
+ if (policy.sessionBudgetAtomic !== null) {
33
+ const projected = req.sessionSpentAtomic + req.amountAtomic;
34
+ if (projected > policy.sessionBudgetAtomic) {
35
+ return {
36
+ decision: "deny",
37
+ reason: "session_budget_exceeded",
38
+ message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`
39
+ };
40
+ }
41
+ }
42
+ if (req.amountAtomic > policy.maxAutoSpendAtomic) {
43
+ return {
44
+ decision: "deny",
45
+ reason: "above_auto_spend",
46
+ message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; automatic payment refused.`
47
+ };
48
+ }
49
+ return { decision: "allow", reason: "within_policy", message: "within spend policy" };
50
+ }
51
+
52
+ export {
53
+ evaluateSpendPolicy
54
+ };
55
+ //# sourceMappingURL=chunk-XMIVHQ35.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/policy.ts"],"sourcesContent":["/**\n * Spend-policy evaluation, pure and provider-agnostic. The wallet provider layer\n * (lib/wallet/spend.ts) owns the ledger and calls this; a future hosted provider\n * (Privy, B5) reuses the same decision rules, so the knobs live in exactly one\n * place. Nothing here does IO, the caller supplies the already-spent total and\n * decides how to satisfy a `confirm` decision (a `--yes`, a TTY prompt, or a\n * non-interactive refusal).\n */\n\nexport type PaymentMode = 'automatic' | 'manual';\n\nexport interface SpendPolicy {\n /** Automatic per-call ceiling; zero blocks positive automatic payments. */\n maxAutoSpendAtomic: bigint;\n /** Rolling ceiling on automatic exposure. null = no ceiling; zero blocks positive automatic payments. */\n sessionBudgetAtomic: bigint | null;\n /** Creators (handle or 0x-address, lowercased) all payments are restricted to.\n * Empty = no restriction. A non-empty list is a hard gate: a non-member is\n * denied even with `--yes`. */\n allowlistCreators: string[];\n}\n\nexport interface SpendRequest {\n /** Omitted by legacy consumers: conservatively automatic. */\n mode?: PaymentMode;\n amountAtomic: bigint;\n /** Creator identity from the 402 preview / candidate, handle or 0x address. */\n creator: string;\n /** The caller's `--max-price` cap, if given. A hard ceiling, never bypassable. */\n maxPriceAtomic?: bigint;\n /** Cumulative spend already recorded in this rolling session window. */\n sessionSpentAtomic: bigint;\n}\n\n/**\n * `allow`: within policy, proceed silently. `confirm`: an approval is required ,\n * the caller satisfies it with `--yes`, an interactive prompt, or refuses. `deny`:\n * a hard gate blocked it (price cap, allowlist, session budget); NOT satisfiable\n * by `--yes` or a prompt.\n */\nexport type SpendDecision = 'allow' | 'confirm' | 'deny';\n\n/**\n * `duplicate_in_flight` is the one reason this pure evaluator never returns: it\n * is a fact about the ledger (an identical request already holds a reservation\n * in this turn), so the authorizer raises it. It lives in the union because\n * every caller renders a decision's reason from one vocabulary.\n */\nexport type PolicyReason =\n | 'within_policy'\n | 'duplicate_in_flight'\n | 'price_cap_exceeded'\n | 'not_allowlisted'\n | 'session_budget_exceeded'\n | 'above_auto_spend'\n | 'confirm_always';\n\nexport interface PolicyEvaluation {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n}\n\n/** Normalize a creator identity for allowlist comparison (case-insensitive; a\n * word-handle and a 0x address are both single tokens). */\nfunction normCreator(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/** Hard price/creator checks apply in both modes. Manual payments require consent;\n * automatic payments must fit both configured ceilings without prompting. */\nexport function evaluateSpendPolicy(policy: SpendPolicy, req: SpendRequest): PolicyEvaluation {\n if (req.maxPriceAtomic !== undefined && req.amountAtomic > req.maxPriceAtomic) {\n return {\n decision: 'deny',\n reason: 'price_cap_exceeded',\n message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`,\n };\n }\n\n if (policy.allowlistCreators.length > 0) {\n const allowed = policy.allowlistCreators.map(normCreator);\n if (!allowed.includes(normCreator(req.creator))) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${req.creator}\" is not in allowlistCreators.`,\n };\n }\n }\n\n if (req.mode === 'manual') {\n return req.amountAtomic > 0n\n ? {\n decision: 'confirm',\n reason: 'confirm_always',\n message: 'Manual payment requires explicit consent.',\n }\n : { decision: 'allow', reason: 'within_policy', message: 'No payment required.' };\n }\n\n if (policy.sessionBudgetAtomic !== null) {\n const projected = req.sessionSpentAtomic + req.amountAtomic;\n if (projected > policy.sessionBudgetAtomic) {\n return {\n decision: 'deny',\n reason: 'session_budget_exceeded',\n message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`,\n };\n }\n }\n\n if (req.amountAtomic > policy.maxAutoSpendAtomic) {\n return {\n decision: 'deny',\n reason: 'above_auto_spend',\n message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; automatic payment refused.`,\n };\n }\n\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n"],"mappings":";;;AAiEA,SAAS,YAAY,OAAuB;AAC1C,SAAO,MAAM,KAAK,EAAE,YAAY;AAClC;AAIO,SAAS,oBAAoB,QAAqB,KAAqC;AAC5F,MAAI,IAAI,mBAAmB,UAAa,IAAI,eAAe,IAAI,gBAAgB;AAC7E,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,gCAAgC,IAAI,cAAc;AAAA,IACtF;AAAA,EACF;AAEA,MAAI,OAAO,kBAAkB,SAAS,GAAG;AACvC,UAAM,UAAU,OAAO,kBAAkB,IAAI,WAAW;AACxD,QAAI,CAAC,QAAQ,SAAS,YAAY,IAAI,OAAO,CAAC,GAAG;AAC/C,aAAO;AAAA,QACL,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,SAAS,YAAY,IAAI,OAAO;AAAA,MAClC;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,SAAS,UAAU;AACzB,WAAO,IAAI,eAAe,KACtB;AAAA,MACE,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS;AAAA,IACX,IACA,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,uBAAuB;AAAA,EACpF;AAEA,MAAI,OAAO,wBAAwB,MAAM;AACvC,UAAM,YAAY,IAAI,qBAAqB,IAAI;AAC/C,QAAI,YAAY,OAAO,qBAAqB;AAC1C,aAAO;AAAA,QACL,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,SAAS,+CAA+C,SAAS,wBAAwB,OAAO,mBAAmB;AAAA,MACrH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,oBAAoB;AAChD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,0BAA0B,OAAO,kBAAkB;AAAA,IACvF;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,sBAAsB;AACtF;","names":[]}
@@ -0,0 +1,105 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ normalizeChannelId
4
+ } from "./chunk-LFZJM56J.js";
5
+
6
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-3632HGL3.mjs
7
+ import { mkdir, readFile, rename, unlink, writeFile } from "fs/promises";
8
+ import { dirname, join, resolve, sep } from "path";
9
+ function resolveWithinDir(baseDir, filename) {
10
+ const base = resolve(baseDir);
11
+ const target = resolve(base, filename);
12
+ if (target !== base && !target.startsWith(base + sep)) {
13
+ throw new Error("resolved channel path escapes storage root");
14
+ }
15
+ return target;
16
+ }
17
+ function isNodeEnoent(err) {
18
+ if (!err || typeof err !== "object" || !("code" in err)) return false;
19
+ return err.code === "ENOENT";
20
+ }
21
+ async function readJsonFile(filePath) {
22
+ try {
23
+ const raw = await readFile(filePath, "utf8");
24
+ return JSON.parse(raw);
25
+ } catch (err) {
26
+ if (isNodeEnoent(err)) return void 0;
27
+ throw err;
28
+ }
29
+ }
30
+ async function writeJsonAtomic(filePath, value) {
31
+ const dir = dirname(filePath);
32
+ await mkdir(dir, { recursive: true });
33
+ const tmp = join(dir, `.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
34
+ const body = `${JSON.stringify(value, null, 2)}
35
+ `;
36
+ await writeFile(tmp, body, "utf8");
37
+ try {
38
+ await rename(tmp, filePath);
39
+ } catch {
40
+ await unlink(filePath).catch(() => {
41
+ });
42
+ await rename(tmp, filePath);
43
+ }
44
+ }
45
+
46
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/batch-settlement/client/file-storage.mjs
47
+ import { unlink as unlink2 } from "fs/promises";
48
+ import { join as join2 } from "path";
49
+ var FileClientChannelStorage = class {
50
+ /**
51
+ * Creates file-backed client channel storage under the given root directory.
52
+ *
53
+ * @param options - Configuration including the storage root directory.
54
+ */
55
+ constructor(options) {
56
+ this.root = options.directory;
57
+ }
58
+ /**
59
+ * Loads the stored client context for a channel, if present.
60
+ *
61
+ * @param key - Channel storage key (typically a lowercased channelId).
62
+ * @returns Parsed context or `undefined` when the file is missing.
63
+ */
64
+ async get(key) {
65
+ return readJsonFile(this.filePath(key));
66
+ }
67
+ /**
68
+ * Persists the client context for a channel.
69
+ *
70
+ * @param key - Channel storage key.
71
+ * @param context - Context record to write.
72
+ */
73
+ async set(key, context) {
74
+ await writeJsonAtomic(this.filePath(key), context);
75
+ }
76
+ /**
77
+ * Removes the persisted context file for a channel, if it exists.
78
+ *
79
+ * @param key - Channel storage key.
80
+ */
81
+ async delete(key) {
82
+ try {
83
+ await unlink2(this.filePath(key));
84
+ } catch (err) {
85
+ if (isNodeEnoent(err)) return;
86
+ throw err;
87
+ }
88
+ }
89
+ /**
90
+ * Absolute path to the JSON file for a channel.
91
+ *
92
+ * @param key - Channel storage key (a canonical `bytes32` channel id).
93
+ * @returns Filesystem path under `{root}/client/...`.
94
+ * @throws When `key` is not a canonical `bytes32` string or escapes the storage root.
95
+ */
96
+ filePath(key) {
97
+ const id = normalizeChannelId(key);
98
+ return resolveWithinDir(join2(this.root, "client"), `${id}.json`);
99
+ }
100
+ };
101
+
102
+ export {
103
+ FileClientChannelStorage
104
+ };
105
+ //# sourceMappingURL=chunk-YHKXNYTB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/storage-utils.ts","../node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/client/fileStorage.ts"],"sourcesContent":["import { mkdir, readFile, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve, sep } from \"node:path\";\n\n/**\n * Resolves `filename` under `baseDir` and asserts the result stays within `baseDir`.\n *\n * @param baseDir - Directory that must contain the resolved path.\n * @param filename - Filename to resolve against `baseDir`.\n * @returns The absolute resolved path.\n * @throws When the resolved path escapes `baseDir` (e.g. via `..` or separators).\n */\nexport function resolveWithinDir(baseDir: string, filename: string): string {\n const base = resolve(baseDir);\n const target = resolve(base, filename);\n if (target !== base && !target.startsWith(base + sep)) {\n throw new Error(\"resolved channel path escapes storage root\");\n }\n return target;\n}\n\n/**\n * Returns true when `err` is a Node.js `ENOENT` filesystem error (file does not exist).\n *\n * @param err - The thrown value to inspect.\n * @returns `true` for `ENOENT`, `false` for any other value or error code.\n */\nexport function isNodeEnoent(err: unknown): boolean {\n if (!err || typeof err !== \"object\" || !(\"code\" in err)) return false;\n return (err as NodeJS.ErrnoException).code === \"ENOENT\";\n}\n\n/**\n * Reads a JSON file and parses it. Returns `undefined` if the file does not exist.\n * Other errors (permission, malformed JSON) are rethrown.\n *\n * @param filePath - Path to the JSON file.\n * @returns Parsed value, or `undefined` for `ENOENT`.\n */\nexport async function readJsonFile<T>(filePath: string): Promise<T | undefined> {\n try {\n const raw = await readFile(filePath, \"utf8\");\n return JSON.parse(raw) as T;\n } catch (err: unknown) {\n if (isNodeEnoent(err)) return undefined;\n throw err;\n }\n}\n\n/**\n * Writes JSON to `filePath` atomically (temp file in the same directory, then rename).\n * Creates parent directories as needed.\n *\n * @param filePath - Destination file path; parent dirs are created if missing.\n * @param value - JSON-serializable value to persist.\n */\nexport async function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n const dir = dirname(filePath);\n await mkdir(dir, { recursive: true });\n const tmp = join(dir, `.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);\n const body = `${JSON.stringify(value, null, 2)}\\n`;\n await writeFile(tmp, body, \"utf8\");\n try {\n await rename(tmp, filePath);\n } catch {\n // On Windows, rename() onto an existing file throws EEXIST; unlink + rename is intentional.\n await unlink(filePath).catch(() => {});\n await rename(tmp, filePath);\n }\n}\n","import { unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { isNodeEnoent, readJsonFile, resolveWithinDir, writeJsonAtomic } from \"../storage-utils\";\nimport { normalizeChannelId } from \"../utils\";\nimport type { FileChannelStorageOptions } from \"../types\";\nimport type { ClientChannelStorage, BatchSettlementClientContext } from \"./storage\";\n\nexport type { FileChannelStorageOptions };\n\n/**\n * Node.js file-backed {@link ClientChannelStorage} for the batched client scheme.\n * Each channel's context is persisted as `{root}/client/{channelId}.json` so that channel\n * records survive process restarts.\n */\nexport class FileClientChannelStorage implements ClientChannelStorage {\n private readonly root: string;\n\n /**\n * Creates file-backed client channel storage under the given root directory.\n *\n * @param options - Configuration including the storage root directory.\n */\n constructor(options: FileChannelStorageOptions) {\n this.root = options.directory;\n }\n\n /**\n * Loads the stored client context for a channel, if present.\n *\n * @param key - Channel storage key (typically a lowercased channelId).\n * @returns Parsed context or `undefined` when the file is missing.\n */\n async get(key: string): Promise<BatchSettlementClientContext | undefined> {\n return readJsonFile<BatchSettlementClientContext>(this.filePath(key));\n }\n\n /**\n * Persists the client context for a channel.\n *\n * @param key - Channel storage key.\n * @param context - Context record to write.\n */\n async set(key: string, context: BatchSettlementClientContext): Promise<void> {\n await writeJsonAtomic(this.filePath(key), context);\n }\n\n /**\n * Removes the persisted context file for a channel, if it exists.\n *\n * @param key - Channel storage key.\n */\n async delete(key: string): Promise<void> {\n try {\n await unlink(this.filePath(key));\n } catch (err: unknown) {\n if (isNodeEnoent(err)) return;\n throw err;\n }\n }\n\n /**\n * Absolute path to the JSON file for a channel.\n *\n * @param key - Channel storage key (a canonical `bytes32` channel id).\n * @returns Filesystem path under `{root}/client/...`.\n * @throws When `key` is not a canonical `bytes32` string or escapes the storage root.\n */\n private filePath(key: string): string {\n const id = normalizeChannelId(key);\n return resolveWithinDir(join(this.root, \"client\"), `${id}.json`);\n }\n}\n"],"mappings":";;;;;;AAAA,SAAS,OAAO,UAAU,QAAQ,QAAQ,iBAAiB;AAC3D,SAAS,SAAS,MAAM,SAAS,WAAW;AAUrC,SAAS,iBAAiB,SAAiB,UAA0B;AAC1E,QAAM,OAAO,QAAQ,OAAO;AAC5B,QAAM,SAAS,QAAQ,MAAM,QAAQ;AACrC,MAAI,WAAW,QAAQ,CAAC,OAAO,WAAW,OAAO,GAAG,GAAG;AACrD,UAAM,IAAI,MAAM,4CAA4C;EAC9D;AACA,SAAO;AACT;AAQO,SAAS,aAAa,KAAuB;AAClD,MAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,EAAE,UAAU,KAAM,QAAO;AAChE,SAAQ,IAA8B,SAAS;AACjD;AASA,eAAsB,aAAgB,UAA0C;AAC9E,MAAI;AACF,UAAM,MAAM,MAAM,SAAS,UAAU,MAAM;AAC3C,WAAO,KAAK,MAAM,GAAG;EACvB,SAAS,KAAc;AACrB,QAAI,aAAa,GAAG,EAAG,QAAO;AAC9B,UAAM;EACR;AACF;AASA,eAAsB,gBAAgB,UAAkB,OAA+B;AACrF,QAAM,MAAM,QAAQ,QAAQ;AAC5B,QAAM,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;AACpC,QAAM,MAAM,KAAK,KAAK,IAAI,QAAQ,GAAG,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC,MAAM;AAChG,QAAM,OAAO,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;;AAC9C,QAAM,UAAU,KAAK,MAAM,MAAM;AACjC,MAAI;AACF,UAAM,OAAO,KAAK,QAAQ;EAC5B,QAAQ;AAEN,UAAM,OAAO,QAAQ,EAAE,MAAM,MAAM;IAAC,CAAC;AACrC,UAAM,OAAO,KAAK,QAAQ;EAC5B;AACF;;;ACpEA,SAAS,UAAAA,eAAc;AACvB,SAAS,QAAAC,aAAY;AAcd,IAAM,2BAAN,MAA+D;;;;;;EAQpE,YAAY,SAAoC;AAC9C,SAAK,OAAO,QAAQ;EACtB;;;;;;;EAQA,MAAM,IAAI,KAAgE;AACxE,WAAO,aAA2C,KAAK,SAAS,GAAG,CAAC;EACtE;;;;;;;EAQA,MAAM,IAAI,KAAa,SAAsD;AAC3E,UAAM,gBAAgB,KAAK,SAAS,GAAG,GAAG,OAAO;EACnD;;;;;;EAOA,MAAM,OAAO,KAA4B;AACvC,QAAI;AACF,YAAMD,QAAO,KAAK,SAAS,GAAG,CAAC;IACjC,SAAS,KAAc;AACrB,UAAI,aAAa,GAAG,EAAG;AACvB,YAAM;IACR;EACF;;;;;;;;EASQ,SAAS,KAAqB;AACpC,UAAM,KAAK,mBAAmB,GAAG;AACjC,WAAO,iBAAiBC,MAAK,KAAK,MAAM,QAAQ,GAAG,GAAG,EAAE,OAAO;EACjE;AACF;","names":["unlink","join"]}
@@ -1,22 +1,59 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
- MCP_SERVER_NAME,
4
- REQUEST_TOOL
5
- } from "./chunk-TGLKKLQG.js";
3
+ ROUTER_PATH
4
+ } from "./chunk-Z7R2QDX2.js";
5
+ import {
6
+ RECONNECT_FIX,
7
+ readMcpServers
8
+ } from "./chunk-H4BOQLWW.js";
9
+ import {
10
+ ensureStatusLine
11
+ } from "./chunk-65EJJVT3.js";
6
12
  import {
7
13
  paint
8
- } from "./chunk-O2WN732M.js";
14
+ } from "./chunk-UDWGT4FX.js";
15
+ import {
16
+ envProxySupported,
17
+ proxyVariable
18
+ } from "./chunk-ZLD6MJVJ.js";
19
+ import {
20
+ httpRequest
21
+ } from "./chunk-5INS5ZZF.js";
9
22
  import {
10
23
  CLI_SKILL_NAMES,
11
24
  RETIRED_SKILL_NAMES,
12
- ROUTER_DEFAULTS,
13
25
  SHIPPED_SKILL_FILES,
14
26
  onPath,
15
27
  persistRouterDefaults,
16
28
  readSkillFile,
17
29
  skillFrontmatterName,
18
30
  skillsDirsFor
19
- } from "./chunk-W2ARIOAZ.js";
31
+ } from "./chunk-VNT3CQFV.js";
32
+ import {
33
+ FEE_APPROVAL,
34
+ OWN_LIMITS_COMMANDS,
35
+ ROUTER_DEFAULTS,
36
+ ROUTING_FEE_TERMS,
37
+ limitsUsd,
38
+ shownLimits,
39
+ spendQuestion
40
+ } from "./chunk-PM2MOXJ3.js";
41
+ import {
42
+ appendAllowlistRules,
43
+ claudeAdapter,
44
+ claudeSettingsPath,
45
+ inspectHooksFile,
46
+ ownsHookEntry,
47
+ writeHooks
48
+ } from "./chunk-DI7WHXOZ.js";
49
+ import {
50
+ HOOK_TOOL,
51
+ hookToolInput
52
+ } from "./chunk-AKWGE6JQ.js";
53
+ import {
54
+ MCP_SERVER_NAME,
55
+ REQUEST_TOOL
56
+ } from "./chunk-TGLKKLQG.js";
20
57
  import {
21
58
  askText,
22
59
  selectOne
@@ -26,25 +63,14 @@ import {
26
63
  } from "./chunk-2I4QTOLB.js";
27
64
  import {
28
65
  resolveContextSettings
29
- } from "./chunk-TMLCEPCD.js";
66
+ } from "./chunk-HII5HOQV.js";
30
67
  import {
68
+ PRODUCTION_ORIGIN,
69
+ isSameDeployment,
70
+ loadRawConfig,
31
71
  parseUsdToAtomic,
32
72
  toMoney
33
- } from "./chunk-O2JYBOUO.js";
34
- import {
35
- loadRawConfig
36
- } from "./chunk-P22ZWXFX.js";
37
- import {
38
- ensureStatusLine
39
- } from "./chunk-YZTIYDWU.js";
40
- import {
41
- appendAllowlistRules,
42
- claudeAdapter,
43
- claudeSettingsPath,
44
- inspectHooksFile,
45
- ownsHookEntry,
46
- writeHooks
47
- } from "./chunk-SQSKVKX6.js";
73
+ } from "./chunk-XICKN3CH.js";
48
74
  import {
49
75
  CliError
50
76
  } from "./chunk-JLEF5WHM.js";
@@ -109,11 +135,126 @@ async function removeRetiredSkills(home, project) {
109
135
  return removed;
110
136
  }
111
137
 
138
+ // src/router/reachability.ts
139
+ async function probeRouter(baseUrl, opts) {
140
+ const fail = (detail, fix) => ({
141
+ name: "router",
142
+ status: "fail",
143
+ required: true,
144
+ detail,
145
+ fix
146
+ });
147
+ let url;
148
+ try {
149
+ url = new URL(ROUTER_PATH, baseUrl).toString();
150
+ } catch {
151
+ return fail(
152
+ `the base URL ${JSON.stringify(baseUrl)} is not a URL`,
153
+ `Check TENJIN_BASE_URL, or set it with \`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\`.`
154
+ );
155
+ }
156
+ const host = new URL(url).host;
157
+ const probe = await httpRequest(url, {
158
+ method: "POST",
159
+ timeoutMs: opts.timeoutMs,
160
+ blockRedirects: true,
161
+ // A reachability check, not use: it must not count this machine as an install.
162
+ anonymous: true,
163
+ jsonBody: {},
164
+ ...opts.fetchImpl !== void 0 ? { fetchImpl: opts.fetchImpl } : {}
165
+ });
166
+ const production = isSameDeployment(new URL(url).origin, PRODUCTION_ORIGIN);
167
+ const checkBase = production ? "Try again later." : "Check that the configured base URL names the Tenjin router (`tenjin config get baseUrl`), then try again later.";
168
+ const env = opts.env ?? process.env;
169
+ const network = networkFix(host, env, production, opts.proxySupported ?? envProxySupported());
170
+ const credentials = proxyCredentialsFix(env);
171
+ const unreached = production ? network : checkBase;
172
+ if (!probe.ok) {
173
+ const t = probe.transport;
174
+ if (t?.layer === "proxy" && t.proxyStatus === 407) {
175
+ return fail(
176
+ `a proxy between this machine and ${host} asked for its own credentials (407)`,
177
+ credentials
178
+ );
179
+ }
180
+ if (t?.layer === "proxy") {
181
+ return fail(
182
+ `a proxy refused the connection to ${host} (${t.proxyStatus}), so the router never answered`,
183
+ unreached
184
+ );
185
+ }
186
+ if (t?.layer === "dns") {
187
+ return fail(`${host} did not resolve (${t.code}), so the router was not reached`, unreached);
188
+ }
189
+ if (t?.layer === "tls") {
190
+ return fail(
191
+ `the TLS connection to ${host} failed (${t.code}). A proxy that inspects TLS causes this`,
192
+ `If this network inspects TLS, set NODE_EXTRA_CA_CERTS to its CA certificate. ${unreached}`
193
+ );
194
+ }
195
+ if (t?.layer === "connect") {
196
+ return fail(`could not connect to ${host} (${t.code})`, unreached);
197
+ }
198
+ return fail(`the router at ${url} is unreachable or erroring (${probe.message})`, unreached);
199
+ }
200
+ if (probe.status === 200 || probe.status === 400 || probe.status === 429) {
201
+ return { name: "router", status: "ok", required: true, detail: `${url} is live` };
202
+ }
203
+ if (probe.status === 404) {
204
+ return fail(`the router is not enabled at ${url}`, checkBase);
205
+ }
206
+ if (probe.status === 407) {
207
+ return fail(
208
+ `a proxy between this machine and ${host} asked for its own credentials (407)`,
209
+ credentials
210
+ );
211
+ }
212
+ if (probe.status === 401 || probe.status === 403) {
213
+ if (!fromDeployment(probe)) {
214
+ return fail(
215
+ `${host} answered ${probe.status} without the headers a Tenjin deployment sends, so a proxy, firewall or VPN on the way most likely refused the request`,
216
+ network
217
+ );
218
+ }
219
+ if (production) {
220
+ return fail(`${url} refused this machine (${probe.status})`, checkBase);
221
+ }
222
+ return fail(
223
+ `${url} is not a Tenjin router (it asked for credentials)`,
224
+ `Set the router URL with \`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\`.`
225
+ );
226
+ }
227
+ if (probe.status >= 500) {
228
+ return fail(`the router at ${url} is unreachable or erroring (${probe.status})`, checkBase);
229
+ }
230
+ return fail(
231
+ `${url} answered ${probe.status}, which a Tenjin router does not`,
232
+ "Check that the configured base URL names a Tenjin deployment (`tenjin config get baseUrl`)."
233
+ );
234
+ }
235
+ function fromDeployment(probe) {
236
+ return probe.header("x-vercel-id") !== void 0 || probe.header("x-request-id") !== void 0;
237
+ }
238
+ function networkFix(host, env, production, proxySupported) {
239
+ const proxy = proxyVariable(env);
240
+ const config = production ? " Tenjin's own config is correct and needs no change." : "";
241
+ if (proxy !== void 0 && !proxySupported) {
242
+ return `This shell sets ${proxy}, but Node ${process.versions.node} cannot send Tenjin's requests through it. Upgrade to Node 24.14 or newer, or run from a network that reaches ${host} directly.${config}`;
243
+ }
244
+ const via = proxy !== void 0 ? ` (this shell sets ${proxy})` : "";
245
+ return `Allow ${host} through your proxy, firewall or VPN${via}, or run from a network that reaches it.${config}`;
246
+ }
247
+ function proxyCredentialsFix(env) {
248
+ const proxy = proxyVariable(env) ?? "HTTPS_PROXY";
249
+ return `Put the proxy's credentials in ${proxy} (\`http://user:password@proxy:port\`), then try again.`;
250
+ }
251
+
112
252
  // src/router/install.ts
113
253
  var exec = promisify(execFile);
114
- var HOOK_TIMEOUT_SECONDS = 5;
254
+ var ROUTE_HOOK_TIMEOUT_SECONDS = 5;
115
255
  var AFTER_CALL_TIMEOUT_SECONDS = 15;
116
256
  var ALLOW_RULE = REQUEST_TOOL;
257
+ var DENY_RULE = `mcp__${MCP_SERVER_NAME}__${HOOK_TOOL}`;
117
258
  function mcpScope(project) {
118
259
  return project === true ? "project" : "user";
119
260
  }
@@ -132,18 +273,24 @@ var DELEGATION_MATCHER = "Agent|Task";
132
273
  var NATIVE_MATCHER = "WebSearch|WebFetch";
133
274
  var ASK_MATCHER = "AskUserQuestion";
134
275
  function routerHookPlan() {
135
- const handler = (command, timeout = HOOK_TIMEOUT_SECONDS) => [
136
- { type: "command", command, timeout }
276
+ const leg = (kind, timeout = ROUTE_HOOK_TIMEOUT_SECONDS) => [
277
+ {
278
+ type: "mcp_tool",
279
+ server: MCP_SERVER_NAME,
280
+ tool: HOOK_TOOL,
281
+ input: hookToolInput(kind),
282
+ timeout
283
+ }
137
284
  ];
138
- const afterCall = () => handler("tenjin hook shortfall", AFTER_CALL_TIMEOUT_SECONDS);
285
+ const afterCall = () => leg("shortfall", AFTER_CALL_TIMEOUT_SECONDS);
139
286
  return [
140
- { event: "UserPromptSubmit", hooks: handler("tenjin hook prompt") },
141
- { event: "PreToolUse", matcher: NATIVE_MATCHER, hooks: handler("tenjin hook native") },
142
- { event: "PreToolUse", matcher: DELEGATION_MATCHER, hooks: handler("tenjin hook agent") },
287
+ { event: "UserPromptSubmit", hooks: leg("prompt") },
288
+ { event: "PreToolUse", matcher: NATIVE_MATCHER, hooks: leg("native") },
289
+ { event: "PreToolUse", matcher: DELEGATION_MATCHER, hooks: leg("agent") },
143
290
  { event: "PostToolUse", matcher: NATIVE_MATCHER, hooks: afterCall() },
144
291
  { event: "PostToolUseFailure", matcher: NATIVE_MATCHER, hooks: afterCall() },
145
- { event: "PreToolUse", matcher: ASK_MATCHER, hooks: handler("tenjin hook ask") },
146
- { event: "PostToolUse", matcher: ASK_MATCHER, hooks: handler("tenjin hook answer") }
292
+ { event: "PreToolUse", matcher: ASK_MATCHER, hooks: leg("ask") },
293
+ { event: "PostToolUse", matcher: ASK_MATCHER, hooks: leg("answer") }
147
294
  ];
148
295
  }
149
296
  var DISCLOSURE = [
@@ -200,7 +347,7 @@ async function runRouterInstall(args, ctx, deps = {}) {
200
347
  }
201
348
  const humanOutput = ctx.flags.json === true ? false : deps.isInteractive ?? ctx.io.isTTY;
202
349
  const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));
203
- const limits = args.refresh !== true && canPrompt ? await approveLimits(config, deps) : void 0;
350
+ const limits = args.refresh === true ? void 0 : args.yes === true ? shownLimits(config) : canPrompt ? await approveLimits(config, deps) : {};
204
351
  const spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true, limits);
205
352
  const removedKeysLines = spend.removed.length > 0 ? [
206
353
  `Removed retired settings: ${spend.removed.join(", ")}. Automatic router limits remain in effect; manual pay always requires consent.`
@@ -214,12 +361,14 @@ async function runRouterInstall(args, ctx, deps = {}) {
214
361
  plan: routerHookPlan(),
215
362
  settingsPath
216
363
  });
217
- const permissions = await ensureAllowRule(settingsPath);
364
+ const permissions = await ensurePermissionRules(settingsPath);
218
365
  const statusLine = await ensureStatusLine(settingsPath, {
219
366
  ...args.statusLine !== void 0 ? { mode: args.statusLine } : {},
220
367
  ...args.refresh === true ? { refreshOnly: true } : {}
221
368
  });
222
369
  const mcp = await registerMcpServer(deps, env, project, cwd, home);
370
+ const servers = await readMcpServers(deps);
371
+ const serverLines = servers.stale > 0 ? [paint(ctx.io, "yellow", `! ${servers.check.detail}. ${RECONNECT_FIX}`)] : [];
223
372
  if (args.refresh === true) {
224
373
  if (mcp.reconciled === "unrepaired") {
225
374
  throw new CliError(
@@ -238,27 +387,45 @@ async function runRouterInstall(args, ctx, deps = {}) {
238
387
  refresh: true,
239
388
  spend,
240
389
  removedSkills,
241
- scope: mcpScope(project)
390
+ scope: mcpScope(project),
391
+ mcpServer: servers.check
242
392
  },
243
393
  humanLines: [
244
394
  ...refreshLines(ctx, problems(ctx, hooks, permissions, statusLine, mcp)),
245
- ...removedKeysLines
395
+ ...removedKeysLines,
396
+ ...serverLines
246
397
  ]
247
398
  };
248
399
  }
249
- const { resolveWallet } = await import("./install-wallet-MXLJJP3N.js");
400
+ const { resolveWallet } = await import("./install-wallet-USHWL7AX.js");
250
401
  const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? "flag" : void 0, false);
251
402
  const effective = await resolveContextSettings(ctx);
403
+ const approval = !canPrompt && args.yes !== true && !spend.kept.includes("maxAutoSpend") ? spendApproval(config, args) : void 0;
404
+ const router = await probeRouter(effective.baseUrl, {
405
+ timeoutMs: ctx.flags.timeout,
406
+ env,
407
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
408
+ });
252
409
  const data = {
253
410
  settingsPath,
254
411
  hooks,
255
412
  permissions,
256
413
  statusLine,
257
- spend: { ...spend, effective: effectiveLimits(effective.policy) },
414
+ spend: {
415
+ ...spend,
416
+ effective: effectiveLimits(effective.policy),
417
+ ...approval !== void 0 ? { approval } : {}
418
+ },
258
419
  mcp,
259
420
  wallet,
421
+ router: {
422
+ status: router.status === "ok" ? "ok" : "warn",
423
+ detail: router.detail,
424
+ ...router.fix !== void 0 ? { fix: router.fix } : {}
425
+ },
260
426
  disclosure: DISCLOSURE,
261
- removedSkills
427
+ removedSkills,
428
+ mcpServer: servers.check
262
429
  };
263
430
  return {
264
431
  data,
@@ -270,24 +437,50 @@ async function runRouterInstall(args, ctx, deps = {}) {
270
437
  statusLine,
271
438
  mcp,
272
439
  wallet,
273
- policy: effective.policy
440
+ policy: effective.policy,
441
+ ...approval !== void 0 ? { approval } : {},
442
+ router
274
443
  }),
275
- ...removedKeysLines
444
+ ...removedKeysLines,
445
+ ...serverLines
276
446
  ]
277
447
  };
278
448
  }
279
- async function approveLimits(config, deps) {
280
- const shown = {
281
- maxAutoSpend: config.maxAutoSpend ?? ROUTER_DEFAULTS.maxAutoSpend,
282
- sessionBudget: config.sessionBudget ?? ROUTER_DEFAULTS.sessionBudget
449
+ var AUTO_SPEND_FIX = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;
450
+ var DECLINED = "the router then pays for nothing on its own, and the question stays open until `tenjin install` in a terminal or `tenjin config set` answers it";
451
+ function spendApproval(config, args) {
452
+ const limits = shownLimits(config);
453
+ const approve = yesCommand(args);
454
+ return {
455
+ question: spendQuestion(limits),
456
+ limits: limitsUsd(limits),
457
+ routingFee: ROUTING_FEE_TERMS,
458
+ next: `In this session, show the user these limits and ask this question before you change any limit. If they say yes, run the same install again with --yes: \`${approve}\`. If they give other amounts, run ${OWN_LIMITS_COMMANDS}. If they say no, run nothing: ${DECLINED}.`,
459
+ approve,
460
+ own: OWN_LIMITS_COMMANDS.replaceAll("`", "")
283
461
  };
462
+ }
463
+ function yesCommand(args) {
464
+ return [
465
+ "tenjin install",
466
+ ...args.project === true ? ["--project"] : [],
467
+ ...args.noWallet === true ? ["--no-wallet"] : [],
468
+ ...args.statusLine !== void 0 ? [`--status-line ${args.statusLine}`] : [],
469
+ "--yes"
470
+ ].join(" ");
471
+ }
472
+ async function approveLimits(config, deps) {
473
+ const shown = shownLimits(config);
284
474
  const askCall = config.maxAutoSpend === void 0;
285
475
  const askDay = config.sessionBudget === void 0;
286
476
  if (!askCall && !askDay) return void 0;
287
477
  const daily = shown.sessionBudget === "none" ? "no daily limit" : `$${toMoney(shown.sessionBudget).usd} a day`;
478
+ const fee = `
479
+ ${ROUTING_FEE_TERMS}
480
+ ${FEE_APPROVAL}`;
288
481
  const choice = await (deps.promptLimits ?? promptLimits)(
289
482
  `The router pays for tool calls without asking, up to:
290
- $${toMoney(shown.maxAutoSpend).usd} a call, ${daily}`
483
+ $${toMoney(shown.maxAutoSpend).usd} a call, ${daily}${fee}`
291
484
  );
292
485
  if (choice === null) throw installCancelled();
293
486
  if (choice === "approve") return shown;
@@ -338,15 +531,22 @@ function promptLimits(message) {
338
531
  function promptAmount(message, placeholder) {
339
532
  return askText({ message, placeholder });
340
533
  }
341
- async function ensureAllowRule(path) {
342
- const result = await appendAllowlistRules(path, [ALLOW_RULE]);
534
+ async function ensurePermissionRules(path) {
535
+ const allow = await appendAllowlistRules(path, [ALLOW_RULE]);
536
+ const deny = await appendAllowlistRules(path, [DENY_RULE], "deny");
537
+ const warning = writerWarning(allow) ?? writerWarning(deny);
343
538
  return {
344
- path: result.path,
539
+ path: allow.path,
345
540
  rule: ALLOW_RULE,
346
- added: result.added.length > 0,
347
- ...result.warning !== void 0 ? { warning: result.warning } : result.skipped !== void 0 ? { warning: `${result.path} was left untouched (${result.skipped}).` } : {}
541
+ added: allow.added.length > 0,
542
+ denyRule: DENY_RULE,
543
+ denyAdded: deny.added.length > 0,
544
+ ...warning !== void 0 ? { warning } : {}
348
545
  };
349
546
  }
547
+ function writerWarning(result) {
548
+ return result.warning ?? (result.skipped !== void 0 ? `${result.path} was left untouched (${result.skipped}).` : void 0);
549
+ }
350
550
  async function registerMcpServer(deps, env, project, cwd, home) {
351
551
  const scope = mcpScope(project);
352
552
  const command = mcpAddCommand(project);
@@ -453,8 +653,23 @@ function statusLineProblems(ctx, result) {
453
653
  }
454
654
  function lines(ctx, s) {
455
655
  const ok = paint(ctx.io, "green", "\u2713");
656
+ const warn = (text) => paint(ctx.io, "yellow", `! ${text}`);
456
657
  const limits = effectiveLimits(s.policy);
457
658
  const daily = s.policy.sessionBudgetAtomic === null ? "no daily limit" : `$${limits.sessionBudget} a day`;
659
+ const spend = s.approval !== void 0 ? [
660
+ warn("Automatic payments are off until the user approves a spend limit"),
661
+ ` Ask the user in this session: ${s.approval.question}`,
662
+ ` Yes: ${s.approval.approve}`,
663
+ ` Other amounts: ${s.approval.own}`,
664
+ ` No: run nothing, ${DECLINED.replaceAll("`", "")}`
665
+ ] : s.policy.maxAutoSpendAtomic === 0n ? [
666
+ warn("Automatic payments are off: every paid lookup needs your approval"),
667
+ ` To let the router pay without asking, run: ${AUTO_SPEND_FIX}`
668
+ ] : [` Automatic router: up to $${limits.maxAutoSpend} per call; daily limit ${daily}`];
669
+ const router = s.router.status === "ok" ? [] : [
670
+ warn(`The router did not answer: ${s.router.detail}`),
671
+ ...s.router.fix !== void 0 ? [` ${s.router.fix}`] : []
672
+ ];
458
673
  const blocked = s.hooks.skipped !== void 0;
459
674
  const needsMcp = !blocked && !s.mcp.registered;
460
675
  const where = s.project ? " in this project" : "";
@@ -462,11 +677,12 @@ function lines(ctx, s) {
462
677
  return [
463
678
  blocked ? paint(ctx.io, "yellow", `! Tenjin could not finish setting up Claude Code${where}`) : needsMcp ? paint(ctx.io, "yellow", "! Almost done: Claude Code needs one command") : `${ok} Tenjin is set up for Claude Code${where}`,
464
679
  ...walletLines(ctx, ok, s.wallet),
465
- ` Automatic router: up to $${limits.maxAutoSpend} per call; daily limit ${daily}`,
680
+ ...spend,
466
681
  ...s.statusLine.state === "ours" || s.statusLine.state === "composed" ? [" Live status line on: each lookup names its provider while it runs"] : [],
467
682
  ...problems(ctx, s.hooks, s.permissions, s.statusLine, s.mcp),
683
+ ...router,
468
684
  "",
469
- blocked ? "Next: fix the file above, then run tenjin install again" : needsMcp ? s.wallet.status === "created" ? `Next: run the command above and ${fund}, then restart Claude Code` : "Next: run the command above, then restart Claude Code" : s.wallet.status === "created" ? `Next: ${fund}, then restart Claude Code` : "Next: restart Claude Code"
685
+ blocked ? "Next: fix the file above, then run tenjin install again" : needsMcp ? s.wallet.status === "created" ? `Next: run the command above and ${fund}, then start a new Claude Code session so the hooks and the server load` : "Next: run the command above, then start a new Claude Code session so the hooks and the server load" : s.wallet.status === "created" ? `Next: ${fund}, then start a new Claude Code session so the hooks and the server load` : "Next: start a new Claude Code session so the hooks and the server load"
470
686
  ];
471
687
  }
472
688
  function refreshLines(ctx, issues) {
@@ -514,9 +730,11 @@ async function probeOurEntries(path, dataDir) {
514
730
  }
515
731
 
516
732
  export {
517
- HOOK_TIMEOUT_SECONDS,
733
+ probeRouter,
734
+ ROUTE_HOOK_TIMEOUT_SECONDS,
518
735
  AFTER_CALL_TIMEOUT_SECONDS,
519
736
  ALLOW_RULE,
737
+ DENY_RULE,
520
738
  mcpScope,
521
739
  mcpAddCommand,
522
740
  mcpRemoveCommand,
@@ -532,4 +750,4 @@ export {
532
750
  readMcpEntry,
533
751
  statusLineProblems
534
752
  };
535
- //# sourceMappingURL=chunk-H5UR3GFJ.js.map
753
+ //# sourceMappingURL=chunk-YHWBDCGS.js.map