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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +18 -26
  2. package/dist/alive-3J3CHOQP.js +21 -0
  3. package/dist/{chunk-XVYATBKD.js → chunk-25GGN553.js} +897 -522
  4. package/dist/chunk-25GGN553.js.map +1 -0
  5. package/dist/{chunk-B2L53TMK.js → chunk-2SNUOHAT.js} +28 -23
  6. package/dist/chunk-2SNUOHAT.js.map +1 -0
  7. package/dist/{chunk-5NEHH2E5.js → chunk-3FY5HG7R.js} +86 -19
  8. package/dist/chunk-3FY5HG7R.js.map +1 -0
  9. package/dist/{chunk-YQOQ6XEI.js → chunk-4FYMDRD3.js} +51 -41
  10. package/dist/chunk-4FYMDRD3.js.map +1 -0
  11. package/dist/chunk-6W5GYG3W.js +128 -0
  12. package/dist/chunk-6W5GYG3W.js.map +1 -0
  13. package/dist/{chunk-G4AM2SOL.js → chunk-AMEUXNJT.js} +4 -8
  14. package/dist/{chunk-G4AM2SOL.js.map → chunk-AMEUXNJT.js.map} +1 -1
  15. package/dist/chunk-EWLU46J6.js +100 -0
  16. package/dist/chunk-EWLU46J6.js.map +1 -0
  17. package/dist/chunk-LRCJ2IZ5.js +115 -0
  18. package/dist/{chunk-HC3QEZKT.js.map → chunk-LRCJ2IZ5.js.map} +1 -1
  19. package/dist/{chunk-X7I343ZY.js → chunk-LX5OT4TQ.js} +3 -3
  20. package/dist/{chunk-X7I343ZY.js.map → chunk-LX5OT4TQ.js.map} +1 -1
  21. package/dist/{chunk-DATCR7AU.js → chunk-MG3G644T.js} +5 -7
  22. package/dist/{chunk-DATCR7AU.js.map → chunk-MG3G644T.js.map} +1 -1
  23. package/dist/{chunk-BOAI23CX.js → chunk-MOG7PB3A.js} +21 -15
  24. package/dist/chunk-MOG7PB3A.js.map +1 -0
  25. package/dist/{chunk-GU4GGKYP.js → chunk-MRUPDSUM.js} +14 -59
  26. package/dist/chunk-MRUPDSUM.js.map +1 -0
  27. package/dist/{chunk-AWKQSKUL.js → chunk-OOSRB3OF.js} +2 -2
  28. package/dist/{chunk-PZ5N6BAL.js → chunk-ORWL5BSN.js} +5 -4
  29. package/dist/chunk-ORWL5BSN.js.map +1 -0
  30. package/dist/chunk-P4LVLFO4.js +29 -0
  31. package/dist/chunk-P4LVLFO4.js.map +1 -0
  32. package/dist/{chunk-VXIBZ6W5.js → chunk-QTGUDCIR.js} +5 -5
  33. package/dist/{chunk-YKM2ZTA2.js → chunk-R4AO7GC2.js} +462 -105
  34. package/dist/chunk-R4AO7GC2.js.map +1 -0
  35. package/dist/{chunk-OHZYNZSD.js → chunk-RJEPZMYY.js} +12 -8
  36. package/dist/chunk-RJEPZMYY.js.map +1 -0
  37. package/dist/chunk-SBL4THYT.js +2074 -0
  38. package/dist/chunk-SBL4THYT.js.map +1 -0
  39. package/dist/{chunk-VNNXAYJE.js → chunk-SFEQGENI.js} +2 -2
  40. package/dist/{chunk-K6AXXYCG.js → chunk-SJLTEINJ.js} +10 -2
  41. package/dist/{chunk-K6AXXYCG.js.map → chunk-SJLTEINJ.js.map} +1 -1
  42. package/dist/{chunk-5FGO6TYT.js → chunk-TROZ6HL4.js} +3 -5
  43. package/dist/{chunk-5FGO6TYT.js.map → chunk-TROZ6HL4.js.map} +1 -1
  44. package/dist/{chunk-SKQQOEWH.js → chunk-USOLCBKC.js} +6 -8
  45. package/dist/{chunk-SKQQOEWH.js.map → chunk-USOLCBKC.js.map} +1 -1
  46. package/dist/{chunk-64SE3QC5.js → chunk-VKQXVCZR.js} +54 -5
  47. package/dist/chunk-VKQXVCZR.js.map +1 -0
  48. package/dist/{chunk-VIOUZW7Z.js → chunk-VVAHFCX2.js} +209 -37
  49. package/dist/chunk-VVAHFCX2.js.map +1 -0
  50. package/dist/{chunk-4L7KMA7P.js → chunk-WM7TJEBP.js} +8 -10
  51. package/dist/{chunk-4L7KMA7P.js.map → chunk-WM7TJEBP.js.map} +1 -1
  52. package/dist/{chunk-2TYQD22Q.js → chunk-XDYKZRLN.js} +23 -16
  53. package/dist/chunk-XDYKZRLN.js.map +1 -0
  54. package/dist/{chunk-LAIZ2AQA.js → chunk-XJQ6CH7X.js} +3 -2
  55. package/dist/{chunk-O7CUHHYU.js → chunk-ZQNGTLOC.js} +8 -10
  56. package/dist/{chunk-O7CUHHYU.js.map → chunk-ZQNGTLOC.js.map} +1 -1
  57. package/dist/{cli-6JNIPZQ6.js → cli-JPTDHGRX.js} +58 -52
  58. package/dist/{cli-6JNIPZQ6.js.map → cli-JPTDHGRX.js.map} +1 -1
  59. package/dist/{config-G75YT6NC.js → config-YYKDH2TH.js} +12 -15
  60. package/dist/{doctor-3GMDOW4Y.js → doctor-SSTXGCHX.js} +298 -269
  61. package/dist/doctor-SSTXGCHX.js.map +1 -0
  62. package/dist/{fund-3IPR5YRJ.js → fund-QWVWRVDK.js} +95 -43
  63. package/dist/{fund-3IPR5YRJ.js.map → fund-QWVWRVDK.js.map} +1 -1
  64. package/dist/hook-command-VWJXRT7H.js +31 -0
  65. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  66. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
  67. package/dist/hosts/claude/tenjin/.mcp.json +12 -0
  68. package/dist/hosts/claude/tenjin/hooks/hooks.json +221 -0
  69. package/dist/index.js +13 -4
  70. package/dist/index.js.map +1 -1
  71. package/dist/install-2GXXD4DK.js +51 -0
  72. package/dist/{install-identity-PM4AGFFX.js → install-identity-FK3YF227.js} +7 -9
  73. package/dist/{install-wallet-6756NOB5.js → install-wallet-TC22U52X.js} +21 -17
  74. package/dist/{install-wallet-6756NOB5.js.map → install-wallet-TC22U52X.js.map} +1 -1
  75. package/dist/{mcp-33FAAZ7F.js → mcp-42H2F4NY.js} +2128 -372
  76. package/dist/mcp-42H2F4NY.js.map +1 -0
  77. package/dist/package-6DJA3Y2O.js +37 -0
  78. package/dist/{paths-MUXHUOCM.js → paths-POPTXJO6.js} +6 -2
  79. package/dist/{pay-XOYR4PCH.js → pay-LSDJBIAZ.js} +20 -18
  80. package/dist/payments-SPECLBRQ.js +105 -0
  81. package/dist/payments-SPECLBRQ.js.map +1 -0
  82. package/dist/{send-CVGNOQW3.js → send-MHAOLPK3.js} +13 -17
  83. package/dist/{send-CVGNOQW3.js.map → send-MHAOLPK3.js.map} +1 -1
  84. package/dist/status-O2RWLPS5.js +114 -0
  85. package/dist/status-O2RWLPS5.js.map +1 -0
  86. package/dist/{status-line-3IQKGRUH.js → status-line-45TVCRM3.js} +7 -9
  87. package/dist/{status-line-3IQKGRUH.js.map → status-line-45TVCRM3.js.map} +1 -1
  88. package/dist/uninstall-VOK2Z5M4.js +146 -0
  89. package/dist/uninstall-VOK2Z5M4.js.map +1 -0
  90. package/dist/update-FGP3HNLD.js +33 -0
  91. package/dist/update-FGP3HNLD.js.map +1 -0
  92. package/dist/{wallet-B3FVHNTS.js → wallet-DA7OFNEW.js} +18 -14
  93. package/dist/wallet-DA7OFNEW.js.map +1 -0
  94. package/docs/agent-permissions.md +35 -22
  95. package/docs/safety-model.md +3 -1
  96. package/package.json +2 -2
  97. package/dist/chunk-2TYQD22Q.js.map +0 -1
  98. package/dist/chunk-5NEHH2E5.js.map +0 -1
  99. package/dist/chunk-64SE3QC5.js.map +0 -1
  100. package/dist/chunk-6ZSGER3A.js +0 -52
  101. package/dist/chunk-6ZSGER3A.js.map +0 -1
  102. package/dist/chunk-B2L53TMK.js.map +0 -1
  103. package/dist/chunk-BOAI23CX.js.map +0 -1
  104. package/dist/chunk-DSNXKUXI.js +0 -172
  105. package/dist/chunk-DSNXKUXI.js.map +0 -1
  106. package/dist/chunk-GU4GGKYP.js.map +0 -1
  107. package/dist/chunk-H2L33M7F.js +0 -944
  108. package/dist/chunk-H2L33M7F.js.map +0 -1
  109. package/dist/chunk-HC3QEZKT.js +0 -87
  110. package/dist/chunk-JLEF5WHM.js +0 -132
  111. package/dist/chunk-JLEF5WHM.js.map +0 -1
  112. package/dist/chunk-MAQUL5BD.js +0 -99
  113. package/dist/chunk-MAQUL5BD.js.map +0 -1
  114. package/dist/chunk-OHZYNZSD.js.map +0 -1
  115. package/dist/chunk-PY7MQUKP.js +0 -755
  116. package/dist/chunk-PY7MQUKP.js.map +0 -1
  117. package/dist/chunk-PZ5N6BAL.js.map +0 -1
  118. package/dist/chunk-TGLKKLQG.js +0 -11
  119. package/dist/chunk-TGLKKLQG.js.map +0 -1
  120. package/dist/chunk-VIOUZW7Z.js.map +0 -1
  121. package/dist/chunk-XVYATBKD.js.map +0 -1
  122. package/dist/chunk-YKM2ZTA2.js.map +0 -1
  123. package/dist/chunk-YQOQ6XEI.js.map +0 -1
  124. package/dist/doctor-3GMDOW4Y.js.map +0 -1
  125. package/dist/hook-command-ZXX4FT4N.js +0 -32
  126. package/dist/install-6OROTYHZ.js +0 -72
  127. package/dist/mcp-33FAAZ7F.js.map +0 -1
  128. package/dist/payments-UTQDBO7H.js +0 -48
  129. package/dist/payments-UTQDBO7H.js.map +0 -1
  130. package/dist/status-NACN4DGX.js +0 -72
  131. package/dist/status-NACN4DGX.js.map +0 -1
  132. package/dist/status-line-wiring-QXBOOY2T.js +0 -31
  133. package/dist/uninstall-NYFKSYW4.js +0 -175
  134. package/dist/uninstall-NYFKSYW4.js.map +0 -1
  135. package/dist/update-RJDA5ZY3.js +0 -442
  136. package/dist/update-RJDA5ZY3.js.map +0 -1
  137. /package/dist/{config-G75YT6NC.js.map → alive-3J3CHOQP.js.map} +0 -0
  138. /package/dist/{chunk-AWKQSKUL.js.map → chunk-OOSRB3OF.js.map} +0 -0
  139. /package/dist/{chunk-VXIBZ6W5.js.map → chunk-QTGUDCIR.js.map} +0 -0
  140. /package/dist/{chunk-VNNXAYJE.js.map → chunk-SFEQGENI.js.map} +0 -0
  141. /package/dist/{chunk-LAIZ2AQA.js.map → chunk-XJQ6CH7X.js.map} +0 -0
  142. /package/dist/{hook-command-ZXX4FT4N.js.map → config-YYKDH2TH.js.map} +0 -0
  143. /package/dist/{install-6OROTYHZ.js.map → hook-command-VWJXRT7H.js.map} +0 -0
  144. /package/dist/{install-identity-PM4AGFFX.js.map → install-2GXXD4DK.js.map} +0 -0
  145. /package/dist/{paths-MUXHUOCM.js.map → install-identity-FK3YF227.js.map} +0 -0
  146. /package/dist/{pay-XOYR4PCH.js.map → package-6DJA3Y2O.js.map} +0 -0
  147. /package/dist/{status-line-wiring-QXBOOY2T.js.map → paths-POPTXJO6.js.map} +0 -0
  148. /package/dist/{wallet-B3FVHNTS.js.map → pay-LSDJBIAZ.js.map} +0 -0
@@ -0,0 +1,146 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ findClaudeBinary,
4
+ folderFor,
5
+ inspectLegacyInstall,
6
+ jsonList,
7
+ jsonResult,
8
+ ownMarketplace,
9
+ projectInstallHere,
10
+ removeLegacyInstall,
11
+ removePluginFolder,
12
+ runClaude,
13
+ settingsInstallPaths
14
+ } from "./chunk-SBL4THYT.js";
15
+ import "./chunk-VKQXVCZR.js";
16
+ import "./chunk-WM7TJEBP.js";
17
+ import {
18
+ persistRouterProject
19
+ } from "./chunk-25GGN553.js";
20
+ import "./chunk-AKWGE6JQ.js";
21
+ import {
22
+ MARKETPLACE_NAME,
23
+ PLUGIN_ID
24
+ } from "./chunk-EWLU46J6.js";
25
+ import "./chunk-A36LQPHV.js";
26
+ import "./chunk-P7LABKCW.js";
27
+ import "./chunk-MRUPDSUM.js";
28
+ import "./chunk-MEFB5KHA.js";
29
+ import "./chunk-2SNUOHAT.js";
30
+ import "./chunk-TROZ6HL4.js";
31
+ import "./chunk-MG3G644T.js";
32
+ import {
33
+ removeAliveState
34
+ } from "./chunk-6W5GYG3W.js";
35
+ import "./chunk-S4SAZ7OD.js";
36
+ import "./chunk-RJEPZMYY.js";
37
+ import "./chunk-2I4QTOLB.js";
38
+ import "./chunk-AMEUXNJT.js";
39
+ import "./chunk-VVAHFCX2.js";
40
+ import "./chunk-SJLTEINJ.js";
41
+ import "./chunk-LRCJ2IZ5.js";
42
+ import "./chunk-ZXTAQYNA.js";
43
+
44
+ // src/router/uninstall.ts
45
+ import { homedir } from "node:os";
46
+ import { isAbsolute } from "node:path";
47
+ async function runRouterUninstall(args, ctx, deps = {}) {
48
+ const env = deps.env ?? process.env;
49
+ const home = deps.homeDir ?? homedir();
50
+ if (!isAbsolute(home)) throw new Error("The home directory is not an absolute path.");
51
+ const cwd = deps.cwd ?? process.cwd();
52
+ const project = args.project === true;
53
+ const scope = project ? "local" : "user";
54
+ const binary = (deps.findClaude ?? findClaudeBinary)(env);
55
+ const plugin = await removePlugin(binary, scope, env, home, cwd);
56
+ const paths = settingsInstallPaths(project, env, home, cwd);
57
+ const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);
58
+ const settings = legacy.present ? await removeLegacyInstall(legacy, { binary, env, cwd, mcpScope: paths.mcpScope }) : null;
59
+ const alive = await removeAliveState(ctx.dataDir);
60
+ if (project) await persistRouterProject(ctx.dataDir, cwd, false).catch(() => void 0);
61
+ const projectLeft = !project && await projectInstallHere(cwd, home, env);
62
+ const data = {
63
+ plugin,
64
+ settings: { path: paths.settingsPath, found: legacy.present, removed: settings },
65
+ aliveRemoved: alive,
66
+ ...projectLeft ? { projectInstallLeft: cwd } : {},
67
+ kept: ["wallet.json", "spend.json", "config.json"]
68
+ };
69
+ const lines = uninstallLines(plugin, paths.settingsPath, settings);
70
+ if (projectLeft) {
71
+ lines.splice(
72
+ -1,
73
+ 0,
74
+ "This project has its own Tenjin install, which this left in place; `tenjin uninstall --project` here removes it."
75
+ );
76
+ }
77
+ return { data, humanLines: lines };
78
+ }
79
+ async function removePlugin(binary, scope, env, home, cwd) {
80
+ const folder = await removePluginFolder(folderFor(scope, env, home, cwd));
81
+ if (binary === null) {
82
+ return {
83
+ plugin: "kept",
84
+ marketplace: "kept",
85
+ folder,
86
+ reason: `no claude binary on PATH or in CLAUDE_CODE_EXECPATH, so ${PLUGIN_ID} could not be checked; if Claude Code still lists it, type /plugin uninstall ${PLUGIN_ID} in a Claude Code session`
87
+ };
88
+ }
89
+ const run = (a) => runClaude(binary, a, { env, cwd });
90
+ const uninstall = await run(["plugin", "uninstall", PLUGIN_ID, "--scope", scope, "--json"]);
91
+ const result = jsonResult(uninstall.stdout);
92
+ const pluginState = uninstall.code === 0 ? "removed" : result?.failureCode === "not_installed" ? "absent" : "kept";
93
+ const listed = jsonList((await run(["plugin", "marketplace", "list", "--json"])).stdout) ?? [];
94
+ const row = listed.find((m) => m.name === MARKETPLACE_NAME);
95
+ let marketplace = "absent";
96
+ if (row !== void 0) {
97
+ if (await ownMarketplace(row)) {
98
+ const scoped = scope === "user" ? [] : ["--scope", scope];
99
+ const removed = await run([
100
+ "plugin",
101
+ "marketplace",
102
+ "remove",
103
+ MARKETPLACE_NAME,
104
+ ...scoped,
105
+ "--json"
106
+ ]);
107
+ marketplace = removed.code === 0 ? "removed" : "kept";
108
+ } else marketplace = "kept";
109
+ }
110
+ const message = typeof result?.message === "string" ? result.message : uninstall.stderr.trim().slice(0, 200);
111
+ return {
112
+ plugin: pluginState,
113
+ marketplace,
114
+ folder,
115
+ ...pluginState === "kept" ? { reason: `claude plugin uninstall did not succeed: ${message}` } : {}
116
+ };
117
+ }
118
+ function uninstallLines(plugin, settingsPath, settings) {
119
+ const lines = [
120
+ plugin.plugin === "removed" ? `removed the ${PLUGIN_ID} plugin` : plugin.plugin === "absent" ? `plugin: ${PLUGIN_ID} was not installed` : `plugin: ${plugin.reason ?? "left in place"}`
121
+ ];
122
+ if (plugin.marketplace === "removed") lines.push(`removed the ${MARKETPLACE_NAME} marketplace`);
123
+ if (plugin.folder.removed) {
124
+ lines.push(
125
+ plugin.folder.left.length === 0 ? `removed the plugin folder ${plugin.folder.path}` : `removed the plugin's files from ${plugin.folder.path}; kept what is not Tenjin's: ${plugin.folder.left.join(", ")}`
126
+ );
127
+ } else if (plugin.folder.reason !== void 0) lines.push(`folder: ${plugin.folder.reason}`);
128
+ if (settings !== null) {
129
+ const parts = [
130
+ ...settings.events.length > 0 ? [`hook entries (${settings.events.join(", ")})`] : [],
131
+ ...settings.allowRule || settings.denyRule ? ["the permission rules"] : [],
132
+ ...settings.statusLine !== "kept" ? ["the status line"] : [],
133
+ ...settings.mcp === "removed" ? ["the x402 MCP server"] : []
134
+ ];
135
+ if (parts.length > 0) {
136
+ lines.push(`removed the settings install's ${parts.join(", ")} from ${settingsPath}`);
137
+ }
138
+ lines.push(...settings.warnings.map((w) => `settings: ${w}`));
139
+ }
140
+ lines.push("Your wallet, spend ledger and config are kept.");
141
+ return lines;
142
+ }
143
+ export {
144
+ runRouterUninstall
145
+ };
146
+ //# sourceMappingURL=uninstall-VOK2Z5M4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/uninstall.ts"],"sourcesContent":["import { homedir } from 'node:os';\nimport { isAbsolute } from 'node:path';\nimport { persistRouterProject } from '../commands/config';\nimport type { CommandContext, CommandResult } from '../context';\nimport { removeAliveState } from './alive';\nimport { findClaudeBinary, jsonList, jsonResult, runClaude, type ClaudeBinary } from './claude-cli';\nimport { projectInstallHere, settingsInstallPaths } from './install';\nimport { inspectLegacyInstall, removeLegacyInstall, type LegacyRemoval } from './legacy-install';\nimport { MARKETPLACE_NAME, PLUGIN_ID } from './names';\nimport { removePluginFolder, type FolderRemoval } from './plugin-folder';\nimport { folderFor, ownMarketplace, type PluginScope } from './plugin-registration';\n\n/**\n * `tenjin uninstall`: take out the plugin and anything a settings install of\n * an earlier release left, and nothing else.\n *\n * THE PLUGIN goes through Claude Code's own commands (`claude plugin\n * uninstall`, then `claude plugin marketplace remove` for the marketplace\n * `install` added), and a plugin folder of ours loses its listed files. The\n * settings install's hook entries, rules, status line and `x402` server go\n * under the exact-shape rules of `legacy-install.ts`.\n *\n * THE WALLET AND `spend.json` STAY. Removing an integration is not a reason to\n * destroy a key that holds funds or a ledger that records what was spent; both\n * are the user's, and `tenjin wallet` is where they go to move either.\n */\n\nexport interface RouterUninstallArgs {\n project?: boolean;\n}\n\nexport interface RouterUninstallDeps {\n homeDir?: string;\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n findClaude?: (env: NodeJS.ProcessEnv) => ClaudeBinary | null;\n}\n\nexport interface PluginRemoval {\n /** `removed`, `absent` (it was not installed), or `kept` with the reason. */\n plugin: 'removed' | 'absent' | 'kept';\n marketplace: 'removed' | 'absent' | 'kept';\n folder: FolderRemoval;\n reason?: string;\n}\n\nexport async function runRouterUninstall(\n args: RouterUninstallArgs,\n ctx: CommandContext,\n deps: RouterUninstallDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n if (!isAbsolute(home)) throw new Error('The home directory is not an absolute path.');\n const cwd = deps.cwd ?? process.cwd();\n const project = args.project === true;\n const scope: PluginScope = project ? 'local' : 'user';\n const binary = (deps.findClaude ?? findClaudeBinary)(env);\n\n const plugin = await removePlugin(binary, scope, env, home, cwd);\n const paths = settingsInstallPaths(project, env, home, cwd);\n const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);\n const settings: LegacyRemoval | null = legacy.present\n ? await removeLegacyInstall(legacy, { binary, env, cwd, mcpScope: paths.mcpScope })\n : null;\n const alive = await removeAliveState(ctx.dataDir);\n // Forgotten, so a later `tenjin update` does not go looking for a project\n // this machine no longer wires.\n if (project) await persistRouterProject(ctx.dataDir, cwd, false).catch(() => undefined);\n // A BARE UNINSTALL TOUCHES USER SCOPE ONLY: a project install here is left,\n // and said to be, with the command that removes it.\n const projectLeft = !project && (await projectInstallHere(cwd, home, env));\n const data = {\n plugin,\n settings: { path: paths.settingsPath, found: legacy.present, removed: settings },\n aliveRemoved: alive,\n ...(projectLeft ? { projectInstallLeft: cwd } : {}),\n kept: ['wallet.json', 'spend.json', 'config.json'],\n };\n const lines = uninstallLines(plugin, paths.settingsPath, settings);\n if (projectLeft) {\n lines.splice(\n -1,\n 0,\n 'This project has its own Tenjin install, which this left in place; `tenjin uninstall --project` here removes it.',\n );\n }\n return { data, humanLines: lines };\n}\n\nasync function removePlugin(\n binary: ClaudeBinary | null,\n scope: PluginScope,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<PluginRemoval> {\n const folder = await removePluginFolder(folderFor(scope, env, home, cwd));\n if (binary === null) {\n return {\n plugin: 'kept',\n marketplace: 'kept',\n folder,\n reason: `no claude binary on PATH or in CLAUDE_CODE_EXECPATH, so ${PLUGIN_ID} could not be checked; if Claude Code still lists it, type /plugin uninstall ${PLUGIN_ID} in a Claude Code session`,\n };\n }\n const run = (a: string[]) => runClaude(binary, a, { env, cwd });\n const uninstall = await run(['plugin', 'uninstall', PLUGIN_ID, '--scope', scope, '--json']);\n const result = jsonResult(uninstall.stdout);\n const pluginState: PluginRemoval['plugin'] =\n uninstall.code === 0 ? 'removed' : result?.failureCode === 'not_installed' ? 'absent' : 'kept';\n // THE MARKETPLACE GOES ONLY WHEN IT IS THE ONE `install` ADDED. A marketplace\n // of the same name from anywhere else is somebody else's.\n const listed = jsonList((await run(['plugin', 'marketplace', 'list', '--json'])).stdout) ?? [];\n const row = listed.find((m) => m.name === MARKETPLACE_NAME);\n let marketplace: PluginRemoval['marketplace'] = 'absent';\n if (row !== undefined) {\n if (await ownMarketplace(row)) {\n // Named only for a project install, as `install` added it.\n const scoped = scope === 'user' ? [] : ['--scope', scope];\n const removed = await run([\n 'plugin',\n 'marketplace',\n 'remove',\n MARKETPLACE_NAME,\n ...scoped,\n '--json',\n ]);\n marketplace = removed.code === 0 ? 'removed' : 'kept';\n } else marketplace = 'kept';\n }\n const message =\n typeof result?.message === 'string' ? result.message : uninstall.stderr.trim().slice(0, 200);\n return {\n plugin: pluginState,\n marketplace,\n folder,\n ...(pluginState === 'kept'\n ? { reason: `claude plugin uninstall did not succeed: ${message}` }\n : {}),\n };\n}\n\nfunction uninstallLines(\n plugin: PluginRemoval,\n settingsPath: string,\n settings: LegacyRemoval | null,\n): string[] {\n const lines: string[] = [\n plugin.plugin === 'removed'\n ? `removed the ${PLUGIN_ID} plugin`\n : plugin.plugin === 'absent'\n ? `plugin: ${PLUGIN_ID} was not installed`\n : `plugin: ${plugin.reason ?? 'left in place'}`,\n ];\n if (plugin.marketplace === 'removed') lines.push(`removed the ${MARKETPLACE_NAME} marketplace`);\n if (plugin.folder.removed) {\n lines.push(\n plugin.folder.left.length === 0\n ? `removed the plugin folder ${plugin.folder.path}`\n : `removed the plugin's files from ${plugin.folder.path}; kept what is not Tenjin's: ${plugin.folder.left.join(', ')}`,\n );\n } else if (plugin.folder.reason !== undefined) lines.push(`folder: ${plugin.folder.reason}`);\n if (settings !== null) {\n const parts = [\n ...(settings.events.length > 0 ? [`hook entries (${settings.events.join(', ')})`] : []),\n ...(settings.allowRule || settings.denyRule ? ['the permission rules'] : []),\n ...(settings.statusLine !== 'kept' ? ['the status line'] : []),\n ...(settings.mcp === 'removed' ? ['the x402 MCP server'] : []),\n ];\n if (parts.length > 0) {\n lines.push(`removed the settings install's ${parts.join(', ')} from ${settingsPath}`);\n }\n lines.push(...settings.warnings.map((w) => `settings: ${w}`));\n }\n lines.push('Your wallet, spend ledger and config are kept.');\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,eAAe;AACxB,SAAS,kBAAkB;AA6C3B,eAAsB,mBACpB,MACA,KACA,OAA4B,CAAC,GACL;AACxB,QAAM,MAAM,KAAK,OAAO,QAAQ;AAChC,QAAM,OAAO,KAAK,WAAW,QAAQ;AACrC,MAAI,CAAC,WAAW,IAAI,EAAG,OAAM,IAAI,MAAM,6CAA6C;AACpF,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,QAAM,UAAU,KAAK,YAAY;AACjC,QAAM,QAAqB,UAAU,UAAU;AAC/C,QAAM,UAAU,KAAK,cAAc,kBAAkB,GAAG;AAExD,QAAM,SAAS,MAAM,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AAI,KAC/C,mCAAmC,OAAO,OAAO,IAAI,gCAAgC,OAAO,OAAO,KAAK,KAAK,IAAI,CAAC;AAAA,IACxH;AAAA,EACF,WAAW,OAAO,OAAO,WAAW,OAAW,OAAM,KAAK,WAAW,OAAO,OAAO,MAAM,EAAE;AAC3F,MAAI,aAAa,MAAM;AACrB,UAAM,QAAQ;AAAA,MACZ,GAAI,SAAS,OAAO,SAAS,IAAI,CAAC,iBAAiB,SAAS,OAAO,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;AAAA,MACrF,GAAI,SAAS,aAAa,SAAS,WAAW,CAAC,sBAAsB,IAAI,CAAC;AAAA,MAC1E,GAAI,SAAS,eAAe,SAAS,CAAC,iBAAiB,IAAI,CAAC;AAAA,MAC5D,GAAI,SAAS,QAAQ,YAAY,CAAC,qBAAqB,IAAI,CAAC;AAAA,IAC9D;AACA,QAAI,MAAM,SAAS,GAAG;AACpB,YAAM,KAAK,kCAAkC,MAAM,KAAK,IAAI,CAAC,SAAS,YAAY,EAAE;AAAA,IACtF;AACA,UAAM,KAAK,GAAG,SAAS,SAAS,IAAI,CAAC,MAAM,aAAa,CAAC,EAAE,CAAC;AAAA,EAC9D;AACA,QAAM,KAAK,gDAAgD;AAC3D,SAAO;AACT;","names":[]}
@@ -0,0 +1,33 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ runUpdate,
4
+ spawnCapture,
5
+ versionFreeEntry
6
+ } from "./chunk-SBL4THYT.js";
7
+ import "./chunk-VKQXVCZR.js";
8
+ import "./chunk-WM7TJEBP.js";
9
+ import "./chunk-25GGN553.js";
10
+ import "./chunk-AKWGE6JQ.js";
11
+ import "./chunk-EWLU46J6.js";
12
+ import "./chunk-A36LQPHV.js";
13
+ import "./chunk-P7LABKCW.js";
14
+ import "./chunk-MRUPDSUM.js";
15
+ import "./chunk-MEFB5KHA.js";
16
+ import "./chunk-2SNUOHAT.js";
17
+ import "./chunk-TROZ6HL4.js";
18
+ import "./chunk-MG3G644T.js";
19
+ import "./chunk-6W5GYG3W.js";
20
+ import "./chunk-S4SAZ7OD.js";
21
+ import "./chunk-RJEPZMYY.js";
22
+ import "./chunk-2I4QTOLB.js";
23
+ import "./chunk-AMEUXNJT.js";
24
+ import "./chunk-VVAHFCX2.js";
25
+ import "./chunk-SJLTEINJ.js";
26
+ import "./chunk-LRCJ2IZ5.js";
27
+ import "./chunk-ZXTAQYNA.js";
28
+ export {
29
+ runUpdate,
30
+ spawnCapture,
31
+ versionFreeEntry
32
+ };
33
+ //# sourceMappingURL=update-FGP3HNLD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -3,12 +3,21 @@ import {
3
3
  runWalletBalance,
4
4
  runWalletCreate,
5
5
  runWalletShow
6
- } from "./chunk-2TYQD22Q.js";
7
- import "./chunk-PZ5N6BAL.js";
8
- import "./chunk-VNNXAYJE.js";
9
- import "./chunk-O7CUHHYU.js";
10
- import "./chunk-VXIBZ6W5.js";
11
- import "./chunk-X7I343ZY.js";
6
+ } from "./chunk-XDYKZRLN.js";
7
+ import "./chunk-ORWL5BSN.js";
8
+ import "./chunk-SFEQGENI.js";
9
+ import "./chunk-P4LVLFO4.js";
10
+ import "./chunk-YHKXNYTB.js";
11
+ import "./chunk-LFZJM56J.js";
12
+ import "./chunk-EL56RW2J.js";
13
+ import "./chunk-ZQNGTLOC.js";
14
+ import "./chunk-QTGUDCIR.js";
15
+ import "./chunk-LX5OT4TQ.js";
16
+ import "./chunk-TTNESUPQ.js";
17
+ import "./chunk-MRUPDSUM.js";
18
+ import "./chunk-MEFB5KHA.js";
19
+ import "./chunk-2SNUOHAT.js";
20
+ import "./chunk-TROZ6HL4.js";
12
21
  import "./chunk-AWQPGIR6.js";
13
22
  import "./chunk-N35E6CM2.js";
14
23
  import "./chunk-JRGFKVAZ.js";
@@ -17,18 +26,13 @@ import "./chunk-EGELTSPU.js";
17
26
  import "./chunk-KG3D7FIF.js";
18
27
  import "./chunk-RBJPAZFI.js";
19
28
  import "./chunk-BPMWXTFX.js";
20
- import "./chunk-MEFB5KHA.js";
21
- import "./chunk-B2L53TMK.js";
22
- import "./chunk-5FGO6TYT.js";
23
29
  import "./chunk-2I4QTOLB.js";
24
- import "./chunk-6ZSGER3A.js";
25
- import "./chunk-VIOUZW7Z.js";
26
- import "./chunk-JLEF5WHM.js";
27
- import "./chunk-K6AXXYCG.js";
30
+ import "./chunk-VVAHFCX2.js";
31
+ import "./chunk-SJLTEINJ.js";
28
32
  import "./chunk-ZXTAQYNA.js";
29
33
  export {
30
34
  runWalletBalance,
31
35
  runWalletCreate,
32
36
  runWalletShow
33
37
  };
34
- //# sourceMappingURL=wallet-B3FVHNTS.js.map
38
+ //# sourceMappingURL=wallet-DA7OFNEW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,30 +1,33 @@
1
1
  # Agent permissions
2
2
 
3
- `tenjin install` writes one permission rule into `~/.claude/settings.json`, and this page is the whole reasoning behind it: what it clears, what it cannot clear, and what stays a decision you make by hand.
3
+ `tenjin install` registers one Claude Code plugin, `tenjin`, and writes no permission rule. This page is the whole reasoning behind what the plugin allows: what it clears, what it cannot clear, and what stays a decision you make by hand.
4
4
 
5
- Harnesses that run unattended deny tools they have not been told about. Without the rule below, every lookup stops on a permission prompt, and a session left alone stops with it.
5
+ Harnesses that run unattended deny tools they have not been told about. Without the answer below, every lookup stops on a permission prompt, and a session left alone stops with it.
6
6
 
7
- ## The one rule
7
+ ## The plugin's two permission answers
8
+
9
+ A plugin cannot carry permission rules, so the plugin answers two permission questions itself, with two `PreToolUse` hooks:
8
10
 
9
11
  ```
10
- mcp__x402__request
12
+ mcp__plugin_tenjin_router__request allow
13
+ mcp__plugin_tenjin_router__hook deny
11
14
  ```
12
15
 
13
- That is it. It clears the `request` tool on the `x402` MCP server `tenjin install` registers, and nothing else: no shell verb, no other tool, no price.
16
+ The first clears the `request` tool on the plugin's `router` MCP server, and nothing else: no shell verb, no other tool, no price. A hook's allow never overrides a `deny` or `ask` rule you wrote for that tool, so a rule of yours still wins. The second blocks your assistant from calling `hook`, the tool the plugin's own hook legs call, in every permission mode, bypass included; Claude Code's own hook calls to it still run. The tool stays in your assistant's tool list, and a call to it returns the reason instead of running. Each answer is a fixed line of JSON that `node -e` prints, started with no shell.
14
17
 
15
- It is a tool grant, not a spending grant. Every payment the tool makes still passes the local spend policy, and the policy is the only thing that decides an amount.
18
+ The allow is a tool grant, not a spending grant. Every payment the tool makes still passes the local spend policy, and the policy is the only thing that decides an amount.
16
19
 
17
20
  ## What bounds a payment
18
21
 
19
22
  Router on/off controls automatic routing. The spending controls and ledger are local; the router cannot read or raise them:
20
23
 
21
- - **`maxAutoSpend`** caps automatic router purchases per call. `tenjin install` asks you to approve or change these limits (0.25 USD a call and 5 USD a day) in an interactive terminal. When it cannot ask (`--json`, or a shell with no terminal, which is how an agent runs it), it writes neither limit, exactly as when you cancel at the question in a terminal, and sets up everything else. Its output shows what the terminal question shows (the limits, the routing fee they also approve, `spend.approval` in `--json`) and the command for each answer, so your agent puts the same question to you and, for a yes, runs the same install again with `--yes` (for example `tenjin install --no-wallet --yes`), which writes the limits shown just as "Use these limits" does; everything else it writes is what the first run wrote. Until someone answers, the bare CLI's zero holds and the router pays for nothing on its own; `tenjin doctor` and the first unpaid routing call in a session show the same question and one-step yes. A script or CI that ignores the question stays at zero. A 0 you set yourself is an answer, and doctor reports it as a failure. Above the cap, automatic payment is refused without prompting.
24
+ - **`maxAutoSpend`** caps what one router call pays on its own: all its payments together, so several takes of one call or every option of a compare count as one total. `tenjin install` asks you to approve or change these limits (0.25 USD a call and 5 USD a day) in an interactive terminal. When it cannot ask (`--json`, or a shell with no terminal, which is how an agent runs it), it writes neither limit, exactly as when you cancel at the question in a terminal, and sets up everything else. Its output shows what the terminal question shows (the limits, the routing fee they also approve, `spend.approval` in `--json`) and the command for each answer, so your agent puts the same question to you and, for a yes, runs the same install again with `--yes` (for example `tenjin install --no-wallet --yes`), which writes the limits shown just as "Use these limits" does; everything else it writes is what the first run wrote. Until someone answers, the bare CLI's zero holds and the router pays for nothing on its own; `tenjin doctor` and the first unpaid routing call in a session show the same question and one-step yes. A script or CI that ignores the question stays at zero. A 0 you set yourself is an answer, and doctor reports it as a failure. Above the cap, nothing is paid on its own (below).
22
25
  - **`sessionBudget`** caps automatic exposure in the existing 24 hour ledger window. It defaults to 5.00 USD before and after install. Explicit zero blocks positive automatic spending; `none` removes the automatic daily ceiling.
23
26
  - **`spend.json`** records all payments, with separate automatic exposure and reservation modes. Only automatic exposure and pending automatic reservations consume the daily budget. Manual payments remain in total reporting. Older records without a mode/counter conservatively count as automatic until their window expires. Both modes retain the keyed duplicate guard, including under `none`.
24
27
 
25
28
  Manual pay ignores both configured limits and always requires user consent. The retired `bazaarPay` and `confirm` keys have no effect after upgrade, regardless of their old values. Doctor/status warn while they remain. Install/refresh removes and reports exactly those keys, preserving current router/limit settings and unrelated fields. `config set` rejects the retired keys.
26
29
 
27
- A router refusal retains the `needs_approval` status with the summary “Blocked by spending policy.” It does not offer an approval/resume flow or automatically raise limits.
30
+ A router call whose total is over `maxAutoSpend` or what is left of the day's `sessionBudget` pays nothing, and returns `needs_approval` with one sentence your assistant repeats ("5 takes of AiSpace (Hailuo 3 Max) cost $0.775 in total ($0.155 each)."). In Claude Code 2.1.214 or later, the `router` server also offers the `approve` tool, and the result carries a quote and the call your assistant makes next, `approve({quote, total, what})`. Claude Code shows its own permission prompt for that tool, with the total and what it buys, on every call and in every permission mode; no allow rule or hook skips it, and where nobody can answer (`dontAsk`, or `-p` with a permission-prompt tool) the call is denied. Your yes to that prompt is the only approval: nothing on disk, and no command, approves a quote. It then runs the quoted call exactly, once. A quote lasts ten minutes. An approved call may pass both limits, and counts as your own payment, outside the automatic budget, as manual pay does; it never runs past the wallet's balance. Any other host, and an older Claude Code, gets no `approve` tool: the call is refused with what it would cost and nothing paid. Nothing raises a limit on your behalf: `tenjin config set` below changes them, and only you run it.
28
31
 
29
32
  ```bash
30
33
  tenjin status # spent, reserved, and the caps in force
@@ -37,10 +40,10 @@ tenjin config set sessionBudget 2.00
37
40
  The routing decision comes from a server, and each call costs a flat $0.003 from the wallet's channel, paid from deposits of up to $0.25 that count against the limits (the deposit is counted when it leaves the wallet, the fees from it are not counted again): it proposes, it never authorizes. These checks are what keep a wrong or hostile one from being worth anything:
38
41
 
39
42
  - The routing fee is paid only by `tenjin mcp`, with the stock x402 client, and only at exactly $0.003 in USDC on Base over `batch-settlement`. The wallet has one routing channel. When it cannot cover the next fee, the call carries a deposit of up to $0.25, sized down to `maxAutoSpend` while that still covers ten fees ($0.03), and refused below that. A deposit is an automatic payment: it is reserved in `spend.json` before it is signed, so it must fit `maxAutoSpend`, the day's `sessionBudget` and `allowlistCreators` (the router's host is the creator), and it is counted from the moment it is sent, so a lost answer or a killed process leaves it counted; only an answered 4xx or 5xx, on which the server settles nothing, gives it back. The deposit is the spend: the fees come out of it and are not counted again, so the day's running total never refuses one. Each fee still gets the per-payment checks: it has to fit `maxAutoSpend` (a 0 you set, or the 0 that holds until the spend question is answered, refuses it) and pass `allowlistCreators`, and a `sessionBudget` of 0 refuses it. A fee that fails one is not paid, even from a channel that is already funded, and the call takes the free path. Approving the limits at install, where the question names the fee, is what approves it.
40
- - A routing call that cannot be paid takes the free path: the wallet holds less than the deposit, `tenjin mcp` cannot unlock the wallet without a prompt, a limit refuses the deposit, the payment fails, or the channel is carrying another session's call at that moment. The first such call in a session tells you, in Claude Code's own message line, the reason and the fix (`tenjin wallet fund 0.25`, `TENJIN_WALLET_PASSPHRASE`, or `tenjin doctor`); a busy channel says nothing, and while the router charges no fee the wallet is not touched and nothing is said. The native tools are never blocked for it, and `tenjin doctor` names the same reasons.
43
+ - A routing call that cannot be paid takes the free path: the wallet holds less than the deposit, `tenjin mcp` cannot unlock the wallet without a prompt, a limit refuses the deposit, the payment fails, or the channel is carrying another session's call at that moment. The first such call in a session tells you, in Claude Code's own message line, the reason and the fix (`tenjin wallet fund 5`, `TENJIN_WALLET_PASSPHRASE`, or `tenjin doctor`); a busy channel says nothing, and while the router charges no fee the wallet is not touched and nothing is said. The native tools are never blocked for it, and `tenjin doctor` names the same reasons.
41
44
  - A routing call that cannot reach the router (DNS, TLS, a refused connection, a proxy refusing the tunnel) makes every hook leg skip the router for the next 60 seconds, so the native tools run at once instead of each waiting out the gate. A call that runs out of its few seconds, a dropped socket (a paid call's is retried once on the free path) or an answer of any status does not start the pause. The pause is a timestamp under `~/.tenjin/router-memo/` that every session on the machine reads, beside the one-hour note that the router charges no fee, which ends as soon as the router says the fee is on. The pause ends after its 60 seconds, or at once when `tenjin doctor` reaches the router; while doctor cannot reach it either, it names the pause with the seconds left.
42
45
 
43
- - The amount actually signed has to fit `maxAutoSpend` and the day's `sessionBudget`. A live price above the one the decision quoted is refused before anything is signed, so a provider or a stale catalog cannot charge more than it advertised; a hostile server sets that quote itself, so against one the bound stays `maxAutoSpend`.
46
+ - The call's payments, together, have to fit `maxAutoSpend` and the day's `sessionBudget` unless you approved that call's quote, and each one is signed only against that plan, never above its planned amount. A live price above the one the decision quoted is refused before anything is signed, so a provider or a stale catalog cannot charge more than it advertised; a hostile server sets that quote itself, so against one the bound stays `maxAutoSpend`.
44
47
  - An offer carries the service's spec: its input schema, the fields Tenjin pins, and the HTTP request those fields become. Your assistant fills the fields; this CLI puts the pins over them, validates the result against the schema, builds the request and pays the spec's own payee, never above the spec's price ceiling. The one lookup without a spec, the free docs lookup, is bound by the backend from your assistant's query, and nothing is paid for it.
45
48
  - The destination has to be a public HTTPS endpoint whose name resolves to a public address. This is a check, not a pin: the request resolves the name again on its own, so a host that answers publicly at check time and privately a moment later is not closed by it. See [safety-model.md](./safety-model.md).
46
49
  - A 2xx whose body fails the decision's own success rule is delivered as `unverified`, never `fulfilled`, with a caveat naming the rule it missed. The money has already moved, so the body is not withheld.
@@ -92,27 +95,37 @@ Prefer the narrow rules on this page to a broad `Bash(tenjin:*)`, `Bash(tenjin w
92
95
 
93
96
  ## What `tenjin install` writes, in full
94
97
 
95
- 1. Seven hook entries in `~/.claude/settings.json` (`--project` writes the project file instead), each a Claude Code `mcp_tool` hook that calls the `hook` tool of the `x402` server (item 3) with the event's fields: `UserPromptSubmit`, `PreToolUse` on `WebSearch|WebFetch`, `PreToolUse` on `Agent|Task`, `PostToolUse` and `PostToolUseFailure` on `WebSearch|WebFetch`, and `PreToolUse` and `PostToolUse` on `AskUserQuestion`. So each routing step runs inside the session's own `tenjin mcp`, the one process that holds the wallet. That tool reads history only from a file whose real path, symlinks resolved, lies under Claude Code's projects directory (`$CLAUDE_CONFIG_DIR/projects` when that variable is set, else `~/.claude/projects/`) and that is named for the calling session or one of its subagents; a session's first prompt, which fires before that transcript is written, routes on the prompt alone, and any other call reads, sends and pays nothing. Each has a 5 second timeout, so a stuck server never holds a prompt longer, and the two after-call entries on `WebSearch|WebFetch` 15 seconds so a search can wait for the free docs described below. A call that carries a routing channel's deposit waits 4.5 of those seconds instead of 3.5, and a routing payment still out when its time ends says nothing: that prompt runs on the native tools while `tenjin mcp` lets the request finish, for 15 seconds at most, so the channel records it; a deposit in it was counted in the spend ledger when it was sent. A session where the `x402` server is not running routes nothing, and its native tools run. No daemon, no generated script; the one background process is that docs fetch, a single `node` process per such search that exits within 12 seconds. An install from an earlier release has `tenjin hook ...` command entries instead; `tenjin install --refresh` (which `tenjin update` runs) rewrites them into these, and leaves every entry that is not Tenjin's alone. `tenjin hook <prompt|native|shortfall|agent|ask|answer>` still exists for a host with no MCP server, and always takes the free path.
96
- 2. The `mcp__x402__request` rule in `permissions.allow`, and the `mcp__x402__hook` rule in `permissions.deny`. The deny rule hides the hook entries' tool from your assistant in every permission mode, so it cannot call that tool itself, while Claude Code's own hook calls to it still run. Nothing else goes into either list, and no hook ever approves a call, so WebSearch and WebFetch stay under your own permission rules. Before each one, when a paid lookup fits it, the hook redirects your assistant to `mcp__x402__request` in its place, as earlier releases did; a subagent is redirected only when it is known to have `mcp__x402__request` and your spend policy would pay without asking, and otherwise its call simply runs. For library documentation, which is a free lookup, it never redirects, in the main agent or a subagent: a WebSearch runs as your assistant wrote it while the hook fetches Context7 docs for the same query (up to 500 characters of it go to Tenjin's docs lookup, which asks Context7), and when docs are found they are added above the search's own results, with a line saying the web results below are there if the docs do not cover it; when none are found, or the lookup is slow or fails, the search result is left exactly as it was. One agent's identical search is not looked up again for five minutes, and the fetched docs wait in the status line's 0700 directory (item 5) only until that search reads them, ten minutes at most. A WebFetch with a free lookup simply runs. It never redirects the same call twice: once a search or URL has been redirected, your assistant's own retry of that same search or URL runs as it is, whether the redirected lookup succeeded, failed or was never called, and however many other calls ran in between, for ten minutes and separately for each agent, while every other search or URL is routed as usual. After a call that came back short (a failed call, a page that answers 401, 402, 403, 429 or 5xx, an empty page, a search with no results; never a 404 or 410, since a missing page is missing for a paid reader too), the router may offer a paid lookup.
97
- 3. The `x402` MCP server, through `claude mcp add x402 -s user -- tenjin mcp` when the `claude` binary is on PATH, and printed for you to run when it is not. Under `--project` it registers at project scope instead, from the project directory, so the server lands in that project's `.mcp.json` and your `~/.claude.json` is not touched; `tenjin uninstall --project` removes it from the same place. The scope's own file is read first: a registration that already launches `tenjin mcp` is left exactly as it is and nothing is spawned, an `x402` entry launching anything else is removed and re-added, and a registration file this build cannot parse is reported rather than written over.
98
- 4. The two automatic spend limits above, only where your config file is silent, and only after you answer the question in a terminal. When your agent runs the install, it writes neither: your agent asks you the same question and runs the same install again with `--yes` if you say yes. Explicit zero, unlimited, custom registry lists and router opt-outs are preserved. Ignored `bazaarPay` and `confirm` keys are removed and reported; refresh removes retired keys without filling absent settings.
99
- 5. `statusLine`, running `tenjin status-line` once a second, ONLY when that key is not already set. A status line of your own is never replaced: the install prints the command that runs both, and `--status-line compose` writes it only if you ask. The status line stores nothing new off your machine. It reads local files this CLI already writes under your Tenjin data dir: per session, the tool, the provider endpoint, the bounded redacted parameters of the call, its outcome and its price. No prompt text, no result body. Records expire after ten minutes, live in a 0700 directory under a hash of the session id, and are deleted by the next lookup that passes over them.
98
+ Claude Code 2.1.287 or later is required. `tenjin install` and `tenjin doctor` read `claude --version`, and on an older one say to run `claude update` in the session.
99
+
100
+ 1. A wallet, when this machine has none (`--no-wallet` skips it).
101
+ 2. The two automatic spend limits above, only where your config file is silent, and only after you answer the question in a terminal. When your agent runs the install, it writes neither: your agent asks you the same question and runs the same install again with `--yes` if you say yes. Explicit zero, unlimited, custom registry lists and router opt-outs are preserved. Ignored `bazaarPay` and `confirm` keys are removed and reported; refresh removes retired keys without filling absent settings.
102
+ 3. The Claude Code plugin `tenjin`, registered with Claude Code's own commands, which leave no step to you: `claude plugin marketplace add <package>/dist/hosts/claude` and then `claude plugin install tenjin@tenjin` (with `--scope local` under `--project`, so only this project loads it), and `claude plugin update tenjin@tenjin` when Claude Code holds an older version. The marketplace is the installed package's own folder, read in place, so there is no download and the plugin is the build you installed. Claude Code writes `extraKnownMarketplaces` and `enabledPlugins` into its settings; this CLI writes nothing into `settings.json` or `~/.claude.json` itself. The binary is `claude` on PATH, else the one Claude Code names in `CLAUDE_CODE_EXECPATH`; with neither, or when a `claude plugin` command fails, the same plugin is written as a folder, `skills/tenjin-router/` under Claude Code's config directory (`$CLAUDE_CONFIG_DIR` when set, else `~/.claude`), which Claude Code loads as `tenjin@skills-dir` with no command at all. `skills/tenjin`, where tenjin.sh suggests dropping its hosted skill, is never touched, and in the folder only the plugin's own three files are ever written or removed. The plugin carries:
103
+ - Seven hook legs, each a Claude Code `mcp_tool` hook that calls the `hook` tool of the plugin's `router` server with the event's fields: `UserPromptSubmit`, `PreToolUse` on `WebSearch|WebFetch`, `PreToolUse` on `Agent|Task`, `PostToolUse` and `PostToolUseFailure` on `WebSearch|WebFetch`, and `PreToolUse` and `PostToolUse` on `AskUserQuestion`. So each routing step runs inside the session's own `tenjin mcp`, the one process that holds the wallet. That tool reads history only from a file whose real path, symlinks resolved, lies under Claude Code's projects directory (`$CLAUDE_CONFIG_DIR/projects` when that variable is set, else `~/.claude/projects/`) and that is named for the calling session or one of its subagents; a session's first prompt, which fires before that transcript is written, routes on the prompt alone, and any other call reads, sends and pays nothing. Each has a 5 second timeout, so a stuck server never holds a prompt longer, and the two after-call entries on `WebSearch|WebFetch` 15 seconds so a search can wait for the free docs described below. A call that carries a routing channel's deposit waits 4.5 of those seconds instead of 3.5, and a routing payment still out when its time ends says nothing: that prompt runs on the native tools while `tenjin mcp` lets the request finish, for 15 seconds at most, so the channel records it; a deposit in it was counted in the spend ledger when it was sent. A session where the `router` server is not running routes nothing, and its native tools run. No daemon, no generated script; the one background process is that docs fetch, a single `node` process per such search that exits within 12 seconds. `tenjin hook <prompt|native|shortfall|agent|ask|answer>` still exists for a host with no MCP server, and always takes the free path.
104
+ - The two permission answers above. No hook approves any other call, so WebSearch and WebFetch stay under your own permission rules. Before each one, when a paid lookup fits it, the hook redirects your assistant to `mcp__plugin_tenjin_router__request` in its place; a subagent is redirected only when it is known to have that tool and your spend policy would pay without asking, and otherwise its call simply runs. For library documentation, which is a free lookup, it never redirects, in the main agent or a subagent: a WebSearch runs as your assistant wrote it while the hook fetches Context7 docs for the same query (up to 500 characters of it go to Tenjin's docs lookup, which asks Context7), and when docs are found they are added above the search's own results, with a line saying the web results below are there if the docs do not cover it; when none are found, or the lookup is slow or fails, the search result is left exactly as it was. One agent's identical search is not looked up again for five minutes, and the fetched docs wait in a 0700 directory under your Tenjin data dir only until that search reads them, ten minutes at most. A WebFetch with a free lookup simply runs. It never redirects the same call twice: once a search or URL has been redirected, your assistant's own retry of that same search or URL runs as it is, whether the redirected lookup succeeded, failed or was never called, and however many other calls ran in between, for ten minutes and separately for each agent, while every other search or URL is routed as usual. After a call that came back short (a failed call, a page that answers 401, 402, 403, 429 or 5xx, an empty page, a search with no results; never a 404 or 410, since a missing page is missing for a paid reader too), the router may offer a paid lookup.
105
+ - One `SessionStart` command, `tenjin hook alive`, run as `node` with the package's own `dist/index.js`, which writes two small files under `~/.tenjin/alive/`: a marker for the session (a hash of its id) and a stamp saying the plugin has loaded on this machine. It prints nothing and sends nothing.
106
+ - The `router` MCP server, `tenjin mcp --plugin`, run as `node` from your PATH with the package's own `dist/index.js`.
107
+
108
+ Every command the plugin carries is a Claude Code exec-form command: `node` and its arguments, started with no shell and never through the `tenjin` npm shim, so Windows runs the same files macOS and Linux run. The shipped plugin finds the entry three folders above `${CLAUDE_PLUGIN_ROOT}`, since Claude Code loads it in place from the package. The `skills/tenjin-router/` folder carries the absolute entry of the CLI that wrote it.
109
+
110
+ 4. Nothing else. The status line is no longer set up: `tenjin status-line` still exists, and you can set it as your status line command yourself.
111
+
112
+ **An install from an earlier release** wrote seven hook entries, the `mcp__x402__request` allow rule, the `mcp__x402__hook` deny rule and possibly a `statusLine` into your settings, and registered an `x402` MCP server. On a Claude Code older than 2.1.287, install and `tenjin update` do not register the plugin at all while that install is there, and say so: the old install keeps routing until `claude update` and the next `tenjin install`. Otherwise it keeps working until the plugin has proven to load on this machine: Claude Code at 2.1.287 or later lists the plugin enabled, and its `SessionStart` leg has run in a real session. Until then both stay, and in any session the plugin serves, the old entries say nothing, so nothing is offered twice. The next `tenjin install` or `tenjin update` after that removes the old install, and only in the exact shapes it wrote: a hook handler that calls the `x402` server's `hook` tool or is exactly `tenjin hook <leg>`, the two rules (only when the `x402` server is Tenjin's or gone), a status line that runs `tenjin status-line` (a composition is put back to your own command; install and `tenjin update` both name the status line they removed, and you can set `tenjin status-line` again yourself), and the `x402` server, through `claude mcp remove x402`, only after this CLI read that entry and found it launching `tenjin mcp`. A command that only mentions `tenjin hook`, a handler of yours in the same group, your own rules and your own `x402` server stay, and doctor names what it left alone. This migration is removed on or after 2026-12-01; doctor keeps naming an unmigrated machine after that.
100
113
 
101
- Install then sends the router one empty, unsigned request to check that this machine can reach it. When it cannot, install still succeeds, and it names the layer that refused (a proxy, DNS, TLS, or the connection) with the fix. `tenjin doctor` runs the same check. Both also look for running `tenjin mcp` processes that started before this install: Claude Code keeps an MCP server for the whole session, so one of those still runs the old build, and the new hooks can fail there with "Tool hook not found". They name the count and the fix (reconnect `x402` with `/mcp`, or start a new session) and stop nothing.
114
+ Install then sends the router one empty, unsigned request to check that this machine can reach it. When it cannot, install still succeeds, and it names the layer that refused (a proxy, DNS, TLS, or the connection) with the fix. `tenjin doctor` runs the same check. Both also look for running `tenjin mcp` processes that started before this install: Claude Code keeps an MCP server for the whole session, so one of those still runs the old build, and the new hooks can fail there with "Tool hook not found". They name the count and the fix (type `/reload-plugins` in the session, or start a new one; only a new session while an earlier release's settings install is still here) and stop nothing.
102
115
 
103
116
  The installer installs no skills. Install/refresh removes only an owned obsolete `tenjin-pay/SKILL.md`, preserving adjacent user files and foreign skills.
104
117
 
105
- Every other key in the settings file is preserved byte for byte, a second run writes the same bytes, and `tenjin uninstall` removes exactly those five things and keeps your wallet, your ledger and your config.
118
+ After install, type `/reload-plugins` in the same Claude Code session, or start a new session, and the plugin loads. While an earlier release's settings install is still on the machine, start a new session instead: `/reload-plugins` reconnects plugin servers only, so it would load the plugin beside the old `x402` server that session is still running, and every event would route twice. `tenjin uninstall` runs `claude plugin uninstall tenjin@tenjin`, removes the `tenjin` marketplace only when it is the one install added, unlinks the plugin folder's own files, removes an earlier release's settings install under the rules above, and keeps your wallet, your ledger and your config.
106
119
 
107
120
  To stop the router without removing anything, `tenjin config set router.enabled false` stops it on this machine, and `tenjin config set --project router.enabled false` stops it in this repository. Off means no router hook reads or sends anything and the `request` tool refuses without paying. The project value lives in `<project>/.tenjin/config.json`, which you commit; `--project --local` writes `.tenjin/config.local.json` beside it instead, which is yours alone and belongs in `.gitignore`. Every such file from where the session runs up to the git root applies, and in a git worktree so do the main checkout's; a key a file leaves out is inherited from the files around it. A project file can only turn the router off or narrow what it sends; it cannot enable anything or change a spend setting. From a git worktree, `config set --project` writes at the worktree's own root, never the main checkout's file, though the router reads both.
108
121
 
109
122
  ## How one lookup runs
110
123
 
111
124
  1. You type a turn. The hook sends the bounded packet to Tenjin, which answers whether a paid capability fits and, if it does, keeps that packet under a short-lived id.
112
- 2. When one fits, your assistant sees one line, opening with `Tenjin router (installed by the user):`, that names the service, its price and the call to make: `mcp__x402__request({id, input})` with the required fields as placeholders, or already filled in when the hook holds them (the search a native call was about to run, or the page it was about to fetch). The hook keeps the service's spec on this machine under the id.
125
+ 2. When one fits, your assistant sees one line, opening with `Tenjin router (installed by the user):`, that names the service, its price and the call to make: `mcp__plugin_tenjin_router__request({id, input})` with the required fields as placeholders, or already filled in when the hook holds them (the search a native call was about to run, or the page it was about to fetch). The hook keeps the service's spec on this machine under the id.
113
126
  3. Your assistant fills the fields and calls `request({id, input})` once. This CLI validates the input against the spec, builds the request, pays that provider once under your limits, hands back the result, and tells Tenjin only how the call ended. Deciding costs nothing. Where the spec names the fields its result promises, the result holds only those, and the provider's whole response is saved under `~/.tenjin/results/` (readable by you alone, kept a day) at the path the result names in `fullResultPath`.
114
127
  4. An input that does not fit the spec is refused before anything is sent to the provider: your assistant gets every problem and the whole spec (each input with its description and allowed values, the required fields inside a nested object, an example and what comes back), locally and with nothing paid, and calls again. `request({id})` alone shows the same spec. A spec whose input schema this CLI cannot compile is refused outright, with nothing sent to the provider or paid.
115
- 5. Some lines offer a choice of services for the same step, such as several image models. Your assistant uses the one you named or asked to compare, asks you when you have not said and you are there to answer, and otherwise uses the line's default, then calls `request({id, choice, input})`. One choice runs exactly as that service's own offer. `all` runs every choice side by side, each paid once to its own provider, but only after one check that the whole set fits your limits: each payment within `maxAutoSpend`, and their total inside the day's `sessionBudget`. A set that does not fit returns `needs_approval` with nothing paid. The result lists each choice with its cost and the file it saved under `~/.tenjin/downloads/`.
128
+ 5. Some lines offer a choice of services for the same step, such as several image models. Your assistant uses the one you named or asked to compare, asks you when you have not said and you are there to answer, and otherwise uses the line's default, then calls `request({id, choice, input})`. One choice runs exactly as that service's own offer. `all` runs every choice side by side, each paid once to its own provider, but only after each is quoted at its live price and the whole set's total fits your limits: within `maxAutoSpend`, which is per call, and inside the day's `sessionBudget`. A set that does not fit returns `needs_approval` with nothing paid, and in Claude Code runs once you approve it. The result lists each choice with its cost and the file it saved under `~/.tenjin/downloads/`.
116
129
 
117
130
  ## What a paid lookup leaves on your machine
118
131
 
@@ -134,7 +147,7 @@ To stop the router without removing anything, `tenjin config set router.enabled
134
147
  - On a paid lookup: the capability chosen, a hash of the contract, a hash of the arguments, your wallet address, the amount and the transaction hash are kept.
135
148
  - On every call run from an offer's spec: the offer's id, how the call ended, the provider's HTTP status and how long it took. A call stopped before anything was paid says which side stopped it: the input, the offer's terms, the provider's answer, the network, or the wallet. Never the input or the result.
136
149
 
137
- The answer can put one line into your session, or into a task your assistant delegates: the service that fits, what it does, its listed price, and the `mcp__x402__request` call carrying the id that brings your context to it. The line says it comes from the Tenjin router you installed, and it is an option: your assistant's own tools keep working. Which service actually runs, and what it costs, is decided when your assistant makes that call, under your spend policy.
150
+ The answer can put one line into your session, or into a task your assistant delegates: the service that fits, what it does, its listed price, and the `mcp__plugin_tenjin_router__request` call carrying the id that brings your context to it. The line says it comes from the Tenjin router you installed, and it is an option: your assistant's own tools keep working. Which service actually runs, and what it costs, is decided when your assistant makes that call, under your spend policy.
138
151
 
139
152
  ## Wallet passphrase storage
140
153
 
@@ -148,8 +161,8 @@ When your assistant delegates, the task it hands over is routed before the subag
148
161
 
149
162
  A subagent cannot reach you to approve a spend, so it is only offered lookups your spend policy would pay without asking: within `maxAutoSpend`, inside the day's `sessionBudget`, and to a host `allowlistCreators` permits. Its payments run through the same ledger and the same caps as the lead's, because the lock is on the file rather than on the process. A subagent is not a second budget.
150
163
 
151
- A subagent is only redirected or offered a lookup when it is known to have `mcp__x402__request`: a custom agent whose definition (`.claude/agents/<name>.md` in the project, `~/.claude/agents/<name>.md`, or an installed plugin's) lists it in `tools:` or has no `tools:` line at all, or one of the built-in `general-purpose`, `Explore` and `Plan` agents, which inherit MCP tools. Any other subagent, such as the built-in `claude-code-guide` (which has WebFetch and WebSearch but no MCP tools) or a type with no definition to read, is left alone: its native calls and delegated tasks are not sent to the router at all, and its calls run free. `tenjin doctor` names your own agents that leave the tool out; add `mcp__x402__request` to their `tools:` to allow paid lookups there. Nothing here edits your agent files.
164
+ A subagent is only redirected or offered a lookup when it is known to have `mcp__plugin_tenjin_router__request`: a custom agent whose definition (`.claude/agents/<name>.md` in the project, `~/.claude/agents/<name>.md`, or an installed plugin's) lists it in `tools:` or has no `tools:` line at all, or one of the built-in `general-purpose`, `Explore` and `Plan` agents, which inherit MCP tools. Any other subagent, such as the built-in `claude-code-guide` (which has WebFetch and WebSearch but no MCP tools) or a type with no definition to read, is left alone: its native calls and delegated tasks are not sent to the router at all, and its calls run free. `tenjin doctor` names your own agents that leave the tool out, including one that still lists only the earlier `mcp__x402__request`; add `mcp__plugin_tenjin_router__request` to their `tools:` to allow paid lookups there. Nothing here edits your agent files.
152
165
 
153
166
  ## Not the same as `allowlistCreators`
154
167
 
155
- `allowlistCreators` is a spend-policy key that restricts which hosts may be paid at all. The permission rule on this page is a harness setting about which tool may run. They are separate gates and neither substitutes for the other.
168
+ `allowlistCreators` is a spend-policy key that restricts which hosts may be paid at all. The plugin's permission answers on this page are a harness setting about which tool may run. They are separate gates and neither substitutes for the other.
@@ -20,12 +20,14 @@ Do not copy commands from a provider result into an allowlist, `AGENTS.md`, `CLA
20
20
 
21
21
  Wallet display, balance checks, doctor, and checkout-link creation are separated from payments and transfers.
22
22
 
23
- The x402 router's `request` tool and `tenjin pay` are the paying commands, and they run one gate between them: `maxAutoSpend` and `sessionBudget` as limits on automatic router spending only, mandatory consent for manual pay, and a reservation that counts a signed authorization as spent the moment it leaves. A router lookup is ONE payment, to the provider: deciding where to route costs nothing and nobody signs for it. The boundary is split on purpose: an offer's spec carries the service's schema, pinned fields and request shape, and this client validates the agent's input against it and builds the call (the free docs lookup, which has no spec and costs nothing, is bound by the backend); this client alone checks the three things only it can: the amount signed against the spend caps, the body that comes back against the success rule the decision carries, and the destination resolving to a public address. That destination check is a check, not a pin, for the paid request: it resolves the name again on its own, so a host that answers publicly at check time and privately a moment later is not closed by it. The router's download of media a discovered service links to does pin: it connects to the address it validated, on every redirect hop. `--max-price` is always a hard cap on `tenjin pay`. Every automatic authorization that LEAVES the process counts against the automatic session budget until the 24 hour window rolls, even where the provider never settles it: a signed EIP-3009 authorization is a bearer instrument, so a 200 that reports no match, or a 402 that rejects the payment, is the counterparty saying it did not take the money rather than proof that it cannot. Manual exposure remains recorded in the same ledger but does not consume automatic headroom. Older records without a mode or automatic counter count conservatively as automatic. The budget is deliberately the conservative side of that, and a caller can be left with less headroom than it actually spent. The one release is proof from the chain, not the counterparty: `tenjin payments reconcile` (and the `request` tool, for up to three records beside each lookup) gives an authorization's amount back only when USDC's `authorizationState` shows it unused at a block whose timestamp is past its `validBefore`, so it can never be charged, and only inside the window that counted it, once per nonce.
23
+ The x402 router's `request` tool and `tenjin pay` are the paying commands, and they run one gate between them: `maxAutoSpend` and `sessionBudget` as limits on automatic router spending only, mandatory consent for manual pay, and a reservation that counts a signed authorization as spent the moment it leaves. A router call plans every payment it will make before it signs any (`src/lib/spend-plan.ts`): the plan's total meets `maxAutoSpend`, which is per call, the day's `sessionBudget` and the balance once, and `runPay` signs a router payment only against a slot an admitted plan minted, once, never above its planned amount. A plan over the limits pays nothing. Only for Claude Code 2.1.214 or later is it kept as a quote (`~/.tenjin/quotes`, mode 0600, ten minutes, single use) and the `approve` tool offered, marked `anthropic/requiresUserInteraction` so Claude Code puts every call of it to a person; that prompt is the only approval, and nothing in the quote file counts as one. `approve` runs the quote exactly, signed as a manual payment: past both automatic limits, never past the balance. Any other client gets no `approve` tool, and the call is refused with nothing paid and nothing kept. A router lookup is ONE payment, to the provider: deciding where to route costs nothing and nobody signs for it. The boundary is split on purpose: an offer's spec carries the service's schema, pinned fields and request shape, and this client validates the agent's input against it and builds the call (the free docs lookup, which has no spec and costs nothing, is bound by the backend); this client alone checks the three things only it can: the amount signed against the spend caps, the body that comes back against the success rule the decision carries, and the destination resolving to a public address. That destination check is a check, not a pin, for the paid request: it resolves the name again on its own, so a host that answers publicly at check time and privately a moment later is not closed by it. The router's download of media a discovered service links to does pin: it connects to the address it validated, on every redirect hop. `--max-price` is always a hard cap on `tenjin pay`. Every automatic authorization that LEAVES the process counts against the automatic session budget until the 24 hour window rolls, even where the provider never settles it: a signed EIP-3009 authorization is a bearer instrument, so a 200 that reports no match, or a 402 that rejects the payment, is the counterparty saying it did not take the money rather than proof that it cannot. Manual exposure remains recorded in the same ledger but does not consume automatic headroom. Older records without a mode or automatic counter count conservatively as automatic. The budget is deliberately the conservative side of that, and a caller can be left with less headroom than it actually spent. The one release is proof from the chain, not the counterparty: `tenjin payments reconcile` (and the `request` tool, for up to three records beside each lookup) gives an authorization's amount back only when USDC's `authorizationState` shows it unused at a block whose timestamp is past its `validBefore`, so it can never be charged, and only inside the window that counted it, once per nonce.
24
24
 
25
25
  The automatic daily limit is zero, a finite amount or `none`: zero blocks positive automatic payments and `none` removes that ceiling while retaining reservations and duplicate protection. Manual pay requires explicit user consent and is subject to neither automatic limit. Retired `bazaarPay` and `confirm` values are ignored after upgrade; doctor/status warn, and install/refresh remove and report them while preserving current controls and unrelated fields.
26
26
 
27
27
  Direct third-party payments use the supported live 402 quote. Unavailable/incomplete verification and differences from an exact listing block payment unless this invocation supplies `--ignore-warnings`. Missing listings or a missing Bazaar extension require no warning or flag. Warnings remain visible and structured in JSON. This flag acknowledges registry evidence only; `--yes` confirms payment only. Manual pay requires explicit user consent regardless of configured automatic limits and must never be an autonomous workaround for router refusal. Neither flag bypasses an explicit price cap, supported challenge, destination checks or balance check. Router payments retain the offered-price ceiling and hard checks on supplied terms, with no direct-payment fallback. An offer's spec supplies the recipient, network and asset beside the price, and the live 402 has to match them; a lookup without a spec is quoted on price alone, which does not provide complete endpoint/payee quote binding.
28
28
 
29
+ A paid call whose seller answers before the result is ready (a 202, or a body the offer's `job` rules call running) is a job, polled for up to 300 s inside one call (in Claude Code 2.1.212 or later, which moves a long call into the background, until the job's own `maxWaitS`, with each poll sent as an MCP progress notification) and resumable with `request({job})` until the job's keep time ends. A poll goes only to the submit's host over HTTPS, checked when the job starts and again before every poll, connected to the public address it resolved, with no redirect followed. A poll never carries a payment: a take's cost is its one payment, made at the submit, and nothing is signed or re-sent for a poll, a status or a complete URL. A poll that answers 402 ends the take failed, with nothing more paid. The job's record (`~/.tenjin/jobs`, mode 0600, read with `O_NOFOLLOW`) holds where to poll and how the take ended, and no payment header. `count` runs 2 to 5 takes of one media call, each its own payment and request key: one unpaid probe quotes the input's live price, the same number a single call is planned at, and the takes' total must fit `maxAutoSpend`, the day's `sessionBudget` and the balance before any take is signed; a take quoted above its plan when it is signed is refused there with nothing signed.
30
+
29
31
  After policy confirmation and immediately before signing, the actual signer's USDC balance must be readable and sufficient. Refusal releases the reservation and does not count spend; free and entitled delivery skips this read. The hook's bounded advisory read suppresses known unusable offers but does not authorize payment. Balances can change after a read, so settlement is not guaranteed. Once a payment authorization is transmitted, the conservative accounting described above applies, with that one chain-proven release.
30
32
 
31
33
  `tenjin wallet send` moves USDC out of the wallet. It exists as a human escape hatch, not as part of the agent flow.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tenjin-cli",
3
- "version": "0.1.0-alpha.27",
3
+ "version": "0.1.0-alpha.29",
4
4
  "type": "module",
5
5
  "description": "The tool router for coding agents. Tenjin picks the right tool when your agent needs one, and one wallet pays for every call.",
6
6
  "repository": {
@@ -40,7 +40,7 @@
40
40
  "@changesets/cli": "^3.0.3",
41
41
  "@clack/prompts": "^1.7.0",
42
42
  "@eslint/js": "^10",
43
- "@modelcontextprotocol/sdk": "1.31.0",
43
+ "@modelcontextprotocol/sdk": "1.32.0",
44
44
  "@types/node": "^22.20.5",
45
45
  "@x402/core": "2.28.0",
46
46
  "@x402/evm": "2.28.0",
@@ -1 +0,0 @@
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;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,EACF,IAAI,MAAM,mBAAmB,IAAI,SAAS,IAAI;AAE9C,QAAM,WAAW,gBAAgB;AACjC,SAAO;AAAA,IACL,MAAM;AAAA,MACJ;AAAA,MACA,YAAY;AAAA,MACZ,UAAU;AAAA,MACV,mBAAmB;AAAA,MACnB,YAAY;AAAA,MACZ,kBAAkB;AAAA,MAClB,GAAI,aAAa,SACb;AAAA,QACE,UAAU;AAAA,UACR,SAAS,SAAS;AAAA,UAClB,oBAAoB,SAAS;AAAA,UAC7B,qBAAqB,SAAS;AAAA,UAC9B,GAAI,SAAS,qBAAqB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