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

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 (125) hide show
  1. package/README.md +6 -17
  2. package/dist/alive-3J3CHOQP.js +21 -0
  3. package/dist/{chunk-SKQQOEWH.js → chunk-3QJREVMX.js} +5 -7
  4. package/dist/{chunk-SKQQOEWH.js.map → chunk-3QJREVMX.js.map} +1 -1
  5. package/dist/{chunk-BOAI23CX.js → chunk-6KA4HFX5.js} +21 -15
  6. package/dist/chunk-6KA4HFX5.js.map +1 -0
  7. package/dist/chunk-6W5GYG3W.js +128 -0
  8. package/dist/chunk-6W5GYG3W.js.map +1 -0
  9. package/dist/{chunk-4L7KMA7P.js → chunk-7H3RN4WJ.js} +7 -9
  10. package/dist/{chunk-4L7KMA7P.js.map → chunk-7H3RN4WJ.js.map} +1 -1
  11. package/dist/{chunk-O7CUHHYU.js → chunk-7R37M6WV.js} +7 -9
  12. package/dist/{chunk-O7CUHHYU.js.map → chunk-7R37M6WV.js.map} +1 -1
  13. package/dist/{chunk-LAIZ2AQA.js → chunk-A5H3E5QA.js} +2 -2
  14. package/dist/{update-RJDA5ZY3.js → chunk-AO54FM4H.js} +147 -26
  15. package/dist/chunk-AO54FM4H.js.map +1 -0
  16. package/dist/{chunk-VNNXAYJE.js → chunk-BRHREK7E.js} +2 -2
  17. package/dist/{chunk-YQOQ6XEI.js → chunk-DJYAPACT.js} +35 -33
  18. package/dist/chunk-DJYAPACT.js.map +1 -0
  19. package/dist/{chunk-GU4GGKYP.js → chunk-DYSDQE7S.js} +36 -2
  20. package/dist/chunk-DYSDQE7S.js.map +1 -0
  21. package/dist/{chunk-YKM2ZTA2.js → chunk-FQ6DHINU.js} +36 -38
  22. package/dist/{chunk-YKM2ZTA2.js.map → chunk-FQ6DHINU.js.map} +1 -1
  23. package/dist/{chunk-6ZSGER3A.js → chunk-FZTSGQVK.js} +2 -2
  24. package/dist/{chunk-AWKQSKUL.js → chunk-KAMRYUK2.js} +2 -2
  25. package/dist/{chunk-2TYQD22Q.js → chunk-MNTQMZJB.js} +6 -8
  26. package/dist/{chunk-2TYQD22Q.js.map → chunk-MNTQMZJB.js.map} +1 -1
  27. package/dist/{chunk-VIOUZW7Z.js → chunk-QTND6XWJ.js} +159 -35
  28. package/dist/chunk-QTND6XWJ.js.map +1 -0
  29. package/dist/chunk-RLPLYUME.js +115 -0
  30. package/dist/{chunk-HC3QEZKT.js.map → chunk-RLPLYUME.js.map} +1 -1
  31. package/dist/{chunk-5NEHH2E5.js → chunk-UEOWNDQG.js} +8 -10
  32. package/dist/{chunk-5NEHH2E5.js.map → chunk-UEOWNDQG.js.map} +1 -1
  33. package/dist/{chunk-OHZYNZSD.js → chunk-UOW5JXYY.js} +5 -7
  34. package/dist/{chunk-OHZYNZSD.js.map → chunk-UOW5JXYY.js.map} +1 -1
  35. package/dist/chunk-VSUHGRVB.js +1455 -0
  36. package/dist/chunk-VSUHGRVB.js.map +1 -0
  37. package/dist/{chunk-64SE3QC5.js → chunk-W6JX4LYF.js} +12 -4
  38. package/dist/chunk-W6JX4LYF.js.map +1 -0
  39. package/dist/{chunk-5FGO6TYT.js → chunk-XVTD7UWR.js} +3 -5
  40. package/dist/{chunk-5FGO6TYT.js.map → chunk-XVTD7UWR.js.map} +1 -1
  41. package/dist/{chunk-X7I343ZY.js → chunk-YFJJYHVG.js} +2 -2
  42. package/dist/{chunk-XVYATBKD.js → chunk-ZG6ZZLO7.js} +898 -521
  43. package/dist/chunk-ZG6ZZLO7.js.map +1 -0
  44. package/dist/{chunk-DATCR7AU.js → chunk-ZO3X5NPG.js} +4 -6
  45. package/dist/{chunk-DATCR7AU.js.map → chunk-ZO3X5NPG.js.map} +1 -1
  46. package/dist/{chunk-VXIBZ6W5.js → chunk-ZP5PV3JB.js} +3 -3
  47. package/dist/{chunk-G4AM2SOL.js → chunk-ZP7AHN7Z.js} +4 -6
  48. package/dist/{chunk-G4AM2SOL.js.map → chunk-ZP7AHN7Z.js.map} +1 -1
  49. package/dist/{cli-6JNIPZQ6.js → cli-234DNHN6.js} +54 -53
  50. package/dist/{cli-6JNIPZQ6.js.map → cli-234DNHN6.js.map} +1 -1
  51. package/dist/{config-G75YT6NC.js → config-IY2OJCAK.js} +10 -13
  52. package/dist/{doctor-3GMDOW4Y.js → doctor-2UZZF44A.js} +267 -242
  53. package/dist/doctor-2UZZF44A.js.map +1 -0
  54. package/dist/{fund-3IPR5YRJ.js → fund-RZ2QFULK.js} +92 -38
  55. package/dist/{fund-3IPR5YRJ.js.map → fund-RZ2QFULK.js.map} +1 -1
  56. package/dist/hook-command-PZHKS7ES.js +31 -0
  57. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  58. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
  59. package/dist/hosts/claude/tenjin/.mcp.json +11 -0
  60. package/dist/hosts/claude/tenjin/hooks/hooks.json +206 -0
  61. package/dist/index.js +12 -3
  62. package/dist/index.js.map +1 -1
  63. package/dist/install-O5FJ5EP3.js +48 -0
  64. package/dist/{install-identity-PM4AGFFX.js → install-identity-QM44IQ6Z.js} +7 -8
  65. package/dist/{install-wallet-6756NOB5.js → install-wallet-Z52EDLPB.js} +14 -15
  66. package/dist/{install-wallet-6756NOB5.js.map → install-wallet-Z52EDLPB.js.map} +1 -1
  67. package/dist/{mcp-33FAAZ7F.js → mcp-33HAADDF.js} +80 -67
  68. package/dist/{mcp-33FAAZ7F.js.map → mcp-33HAADDF.js.map} +1 -1
  69. package/dist/package-RT24HTTP.js +37 -0
  70. package/dist/{pay-XOYR4PCH.js → pay-IR2V76FX.js} +16 -17
  71. package/dist/{payments-UTQDBO7H.js → payments-GFV4HU5R.js} +9 -10
  72. package/dist/{payments-UTQDBO7H.js.map → payments-GFV4HU5R.js.map} +1 -1
  73. package/dist/{send-CVGNOQW3.js → send-PI4NUA7I.js} +12 -14
  74. package/dist/{send-CVGNOQW3.js.map → send-PI4NUA7I.js.map} +1 -1
  75. package/dist/{status-NACN4DGX.js → status-ZUHTJK46.js} +6 -7
  76. package/dist/{status-NACN4DGX.js.map → status-ZUHTJK46.js.map} +1 -1
  77. package/dist/{status-line-3IQKGRUH.js → status-line-2G5JPQAE.js} +6 -7
  78. package/dist/{status-line-3IQKGRUH.js.map → status-line-2G5JPQAE.js.map} +1 -1
  79. package/dist/uninstall-THKUH5ZT.js +136 -0
  80. package/dist/uninstall-THKUH5ZT.js.map +1 -0
  81. package/dist/update-NPZDP24E.js +18 -0
  82. package/dist/update-NPZDP24E.js.map +1 -0
  83. package/dist/{wallet-B3FVHNTS.js → wallet-53EFH4M5.js} +11 -12
  84. package/dist/wallet-53EFH4M5.js.map +1 -0
  85. package/docs/agent-permissions.md +27 -17
  86. package/package.json +1 -1
  87. package/dist/chunk-64SE3QC5.js.map +0 -1
  88. package/dist/chunk-BOAI23CX.js.map +0 -1
  89. package/dist/chunk-DSNXKUXI.js +0 -172
  90. package/dist/chunk-DSNXKUXI.js.map +0 -1
  91. package/dist/chunk-GU4GGKYP.js.map +0 -1
  92. package/dist/chunk-H2L33M7F.js +0 -944
  93. package/dist/chunk-H2L33M7F.js.map +0 -1
  94. package/dist/chunk-HC3QEZKT.js +0 -87
  95. package/dist/chunk-JLEF5WHM.js +0 -132
  96. package/dist/chunk-JLEF5WHM.js.map +0 -1
  97. package/dist/chunk-MAQUL5BD.js +0 -99
  98. package/dist/chunk-MAQUL5BD.js.map +0 -1
  99. package/dist/chunk-PY7MQUKP.js +0 -755
  100. package/dist/chunk-PY7MQUKP.js.map +0 -1
  101. package/dist/chunk-TGLKKLQG.js +0 -11
  102. package/dist/chunk-TGLKKLQG.js.map +0 -1
  103. package/dist/chunk-VIOUZW7Z.js.map +0 -1
  104. package/dist/chunk-XVYATBKD.js.map +0 -1
  105. package/dist/chunk-YQOQ6XEI.js.map +0 -1
  106. package/dist/doctor-3GMDOW4Y.js.map +0 -1
  107. package/dist/hook-command-ZXX4FT4N.js +0 -32
  108. package/dist/install-6OROTYHZ.js +0 -72
  109. package/dist/status-line-wiring-QXBOOY2T.js +0 -31
  110. package/dist/uninstall-NYFKSYW4.js +0 -175
  111. package/dist/uninstall-NYFKSYW4.js.map +0 -1
  112. package/dist/update-RJDA5ZY3.js.map +0 -1
  113. /package/dist/{config-G75YT6NC.js.map → alive-3J3CHOQP.js.map} +0 -0
  114. /package/dist/{chunk-LAIZ2AQA.js.map → chunk-A5H3E5QA.js.map} +0 -0
  115. /package/dist/{chunk-VNNXAYJE.js.map → chunk-BRHREK7E.js.map} +0 -0
  116. /package/dist/{chunk-6ZSGER3A.js.map → chunk-FZTSGQVK.js.map} +0 -0
  117. /package/dist/{chunk-AWKQSKUL.js.map → chunk-KAMRYUK2.js.map} +0 -0
  118. /package/dist/{chunk-X7I343ZY.js.map → chunk-YFJJYHVG.js.map} +0 -0
  119. /package/dist/{chunk-VXIBZ6W5.js.map → chunk-ZP5PV3JB.js.map} +0 -0
  120. /package/dist/{hook-command-ZXX4FT4N.js.map → config-IY2OJCAK.js.map} +0 -0
  121. /package/dist/{install-6OROTYHZ.js.map → hook-command-PZHKS7ES.js.map} +0 -0
  122. /package/dist/{install-identity-PM4AGFFX.js.map → install-O5FJ5EP3.js.map} +0 -0
  123. /package/dist/{pay-XOYR4PCH.js.map → install-identity-QM44IQ6Z.js.map} +0 -0
  124. /package/dist/{status-line-wiring-QXBOOY2T.js.map → package-RT24HTTP.js.map} +0 -0
  125. /package/dist/{wallet-B3FVHNTS.js.map → pay-IR2V76FX.js.map} +0 -0
@@ -1,18 +1,21 @@
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.
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
 
@@ -92,24 +95,31 @@ 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`, 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` from your PATH.
107
+ 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.
108
+
109
+ **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
110
 
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.
111
+ 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
112
 
103
113
  The installer installs no skills. Install/refresh removes only an owned obsolete `tenjin-pay/SKILL.md`, preserving adjacent user files and foreign skills.
104
114
 
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.
115
+ 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
116
 
107
117
  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
118
 
109
119
  ## How one lookup runs
110
120
 
111
121
  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.
122
+ 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
123
  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
124
  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
125
  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/`.
@@ -134,7 +144,7 @@ To stop the router without removing anything, `tenjin config set router.enabled
134
144
  - 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
145
  - 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
146
 
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.
147
+ 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
148
 
139
149
  ## Wallet passphrase storage
140
150
 
@@ -148,8 +158,8 @@ When your assistant delegates, the task it hands over is routed before the subag
148
158
 
149
159
  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
160
 
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.
161
+ 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
162
 
153
163
  ## Not the same as `allowlistCreators`
154
164
 
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.
165
+ `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.
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.28",
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": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { FetchJsonFailure, HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\n\n/**\n * `POST /api/x402-router`: ONE DECISION PER LOOKUP. On the free path it costs\n * nothing. Inside `tenjin mcp`, while the server answers its paid path, the\n * same body goes to that path through the stock x402 client\n * ({@link DecisionRoute}, `routing-payer.ts`); a call that path cannot take\n * falls back to the free path. The rest of this note describes the free path,\n * which is unchanged.\n *\n * The routing decision costs nothing and nobody signs for it. The hook asks for\n * it from the user's own words, the backend answers with what it would do and\n * what the provider charges, and the only payment on the wire is the one\n * `runPay` makes to that provider. That deletes the router fee and everything\n * built to carry it: the 402 probe, the requirements cache, the stale-quote\n * retry, the settlement accounting and one Base settlement of about 1.5 s from\n * every paid lookup.\n *\n * The bounded packet travels with the hook request and the backend keeps it\n * against the decision id until that id expires. What this client keeps is\n * each offer's spec, by its id (`specs.ts`).\n */\n\nexport const ROUTER_PATH = '/api/x402-router';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, a non-execute with no diagnostics parsed\n * with nothing to act on, and a hook answer carrying a contract parsed as\n * though the hook had quoted a price. Each of those is drift the shared\n * fixtures exist to catch, so each is now a parse failure that names itself.\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.strictObject({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. The `request` tool refuses a live\n * 402 above it; `gateSpend` still caps the amount actually signed. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n};\n\n/**\n * STRUCTURE, NEVER WORDING. A hint lands in the model's context verbatim, so\n * its shape is checked the way the id's alphabet is: one line, no control\n * characters, and it has to be the call it claims to be, naming the id this\n * same answer carries. A hint that fails any of these is a protocol error and\n * the turn falls back to the generic line; nothing here rewrites a word of a\n * hint that passes. Both offering arms, `execute` and `discovered`, hold it.\n */\nfunction checkHint(decision: { id: string; hint: string }, ctx: z.RefinementCtx): void {\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n}\n\n/**\n * A PAY-PER-CALL SERVICE NOBODY CURATED. When no capability in the catalog fits\n * but a listed x402 service could do the step, the server names that one\n * service: who sells it, where, for how much, and the input it takes. The\n * candidate is the seller's own listing, so every field is data for the host\n * to judge, never an instruction; the host builds the `input` and the tool\n * call pays through the same `runPay` path and caps as a curated lookup.\n */\nconst DiscoveredCandidateSchema = z.strictObject({\n source: z.string().min(1).max(64),\n provider: z.string().min(1).max(120),\n url: z.string().min(1).max(2_048),\n method: z.enum(['GET', 'POST']),\n description: z.string().max(500),\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n network: z.string().min(1).max(64),\n payTo: z.string().min(1).max(200),\n input: z.strictObject({\n location: z.enum(['body', 'query']),\n schema: z.record(z.string(), z.unknown()),\n }),\n});\n\n/**\n * A REQUEST SPEC: the offered service's real contract, sent beside the line only\n * because this build asks for it (`accepts: [\"spec\"]`). The hook stores it by\n * the offer's id; `request({id})` shows it and `request({id, input})` fills its\n * request and pays the provider directly, with no second decision. Every field\n * is the server's, and so is checked like the rest of the answer: the payee and\n * price still meet the live 402 and the spend policy in `runPay`.\n */\nexport const ToolSpecSchema = z.strictObject({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n description: z.string().min(1).max(500),\n priceAtomic: z.string().regex(/^\\d+$/),\n priceVaries: z.boolean(),\n maxAmountAtomic: z.string().regex(/^\\d+$/),\n payTo: z.string().min(1).max(200),\n network: z.string().min(1).max(64),\n asset: z.string().min(1).max(200),\n request: z.strictObject({\n method: z.enum(['GET', 'POST']),\n url: z.string().min(1).max(2_048),\n fields: z.record(z.string(), z.enum(['path', 'query', 'body'])),\n location: z.enum(['query', 'body']),\n }),\n input: z.record(z.string(), z.unknown()),\n pinned: z.record(z.string(), z.unknown()),\n example: z.record(z.string(), z.unknown()).optional(),\n returns: z.string().min(1).max(200).optional(),\n returnsExample: z.unknown().optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n /** The fields the result promises (type, properties, items, required). The\n * agent is handed only these; the whole body is saved to a file. */\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n});\nexport type ToolSpec = z.infer<typeof ToolSpecSchema>;\n\nexport const OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });\nexport type OfferSpec = z.infer<typeof OfferSpecSchema>;\n\n/** One spec per service the line names: the offer, any alternative, and each\n * option of a choice set. */\nconst SpecsSchema = z.array(OfferSpecSchema).min(1).max(8).optional();\n\n/** Words this client shows the model itself, in its own line: one plain line. */\nconst PlainLine = (max: number) =>\n z\n .string()\n .min(1)\n .max(max)\n .refine((text) => !/[\\p{Cc}\\p{Cf}]/u.test(text), 'one plain line');\n\n/**\n * SERVICES THE USER PICKS BETWEEN, OR RUNS ALL OF. Sent only to a build that\n * lists `choices` in `accepts`. Each option is a real offer: its own id, its\n * own spec in `specs`, and its own one payment, so `request({id, choice})`\n * runs exactly the spec `request({id: option.id})` would. `all` runs every\n * option side by side, one payment each. The set is the server's data:\n * changing it is a deploy there, not a release here. `input` names the open\n * fields the options share, the only ones an `all` call may carry.\n */\nexport const ChoicesSchema = z.strictObject({\n group: PlainLine(64),\n default: PlainLine(64),\n input: z.array(PlainLine(64)).min(1).max(16),\n options: z\n .array(\n z.strictObject({\n key: PlainLine(64),\n label: PlainLine(120),\n strength: PlainLine(300),\n id: IdSchema,\n }),\n )\n .min(2)\n .max(4),\n all: z.strictObject({ totalAtomic: z.string().regex(/^\\d+$/) }),\n});\nexport type Choices = z.infer<typeof ChoicesSchema>;\n\n/** The word that runs every option, so no option may take it as its key. */\nexport const ALL_CHOICES = 'all';\n\n/**\n * A CHOICE NAMES ONLY WHAT THIS ANSWER CARRIES: each key and id once, `all`\n * free for the whole set, a spec for every option, and the default option is\n * the offer this answer's id already names. A set that breaks any of these is\n * a protocol error, and the turn falls back like any unreadable answer.\n */\nfunction checkChoices(\n decision: { id: string; specs?: { id: string }[] | undefined; choices?: Choices | undefined },\n ctx: z.RefinementCtx,\n): void {\n const { choices } = decision;\n if (choices === undefined) return;\n const issue = (message: string) => ctx.addIssue({ code: 'custom', path: ['choices'], message });\n const keys = choices.options.map((option) => option.key);\n const ids = choices.options.map((option) => option.id);\n if (new Set(keys).size !== keys.length) issue('each choice key is named once');\n if (new Set(ids).size !== ids.length) issue('each choice id is named once');\n if (keys.includes(ALL_CHOICES)) issue(`\"${ALL_CHOICES}\" runs every choice, so it is no key`);\n const specIds = new Set((decision.specs ?? []).map((spec) => spec.id));\n if (ids.some((id) => !specIds.has(id))) issue('every choice carries its spec');\n const fallback = choices.options.find((option) => option.key === choices.default);\n if (fallback === undefined) issue('the default is one of the choices');\n else if (fallback.id !== decision.id) issue(\"the default choice is this answer's own offer\");\n}\n\n/** The same answer on both calls: the hook's offer, and the tool's fallback\n * when a query with no id found no curated capability. */\nconst DiscoveredSchema = z\n .strictObject({\n action: z.literal('discovered'),\n id: IdSchema,\n candidate: DiscoveredCandidateSchema,\n /** THE LINE, FINISHED, as on `execute`: it carries the seller's\n * description and the input it takes. */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n choices: ChoicesSchema.optional(),\n })\n .superRefine(checkHint)\n .superRefine(checkChoices);\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .strictObject({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. */\n endpoint: z.string().min(1).max(2_048),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift. The same\n * bound as a discovered line's.\n */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.strictObject({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n /**\n * A query with no id, answered with the spec of the service the server\n * picked under a fresh `id`: kept like a hook's, and never run in the same\n * call. `hint` is the line, with the skeleton of the next call:\n * `request({id, input: {...}})` with the required fields. `input` is what a\n * router from before the binder's removal still sends on a bound pick: it\n * is accepted so that answer parses, and never read, so it never runs.\n */\n z\n .strictObject({\n action: z.literal('spec'),\n id: IdSchema,\n spec: ToolSpecSchema,\n hint: z.string().min(1).max(2_000),\n input: z.record(z.string(), z.unknown()).optional(),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool';\n\n/**\n * What this client can act on beyond the curated answers, sent on both calls.\n * `discovered` is Tenjin's reviewed list of third-party services, on for every\n * build that parses it; the server answers that arm only to a request that\n * lists it, so an older build never sees one. `spec` asks for each offered\n * service's request spec beside its line, and for the picked service's spec in\n * place of a decision on a query with no id, which only a build that parses\n * them can take: the decision schemas are strict. `choices` asks for a set of\n * options the user picks between, or runs all of, beside a discovered offer.\n * `bazaar` widens discovery to the open Bazaar and is sent only while\n * `experimental.bazaar` is on.\n */\nexport const CLIENT_ACCEPTS: readonly string[] = ['discovered', 'spec', 'choices'];\nexport const BAZAAR_ACCEPT = 'bazaar';\n\n/** The `accepts` this build sends, with the open Bazaar or without it. */\nexport function acceptsFor(bazaar: boolean): string[] {\n return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];\n}\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route reads it with a strict object, so an extra field is a\n * 400, and a 400 is a turn with no hint.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone. `sessionId` is the harness's own session id, which the\n * server uses only so one session is not offered the same discovered service\n * twice.\n */\nexport function buildHookBody(\n packet: Packet,\n extras: { sessionId?: string; accepts?: readonly string[] } = {},\n): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(extras.sessionId !== undefined ? { sessionId: extras.sessionId } : {}),\n ...(extras.accepts !== undefined ? { accepts: [...extras.accepts] } : {}),\n packet,\n };\n}\n\n/** The exact body the tool call sends. `id` is the offer the query is for,\n * sent only for an offer with no spec kept; `gateHint` is evidence, never\n * authority. */\nexport function buildToolBody(request: {\n query?: string;\n id?: string;\n gateHint?: GateHint;\n accepts?: readonly string[];\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n ...(request.accepts !== undefined ? { accepts: [...request.accepts] } : {}),\n };\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(kind: CallKind, value: unknown): { success: boolean } {\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n return { success: schema.safeParse(value).success };\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n /** `experimental.bazaar`: add {@link BAZAAR_ACCEPT}, so a service from the\n * open Bazaar may come back. Off by default: curated and the Tenjin list. */\n acceptsBazaar?: boolean;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n /** The paid path, when `tenjin mcp` takes it: the body goes to `path` and is\n * sent by `send`, which pays the routing fee with the stock x402 client.\n * Absent is the free path. */\n route?: DecisionRoute;\n}\n\n/** How a routing call reaches the paid path. `send` throws\n * {@link RouteSkipped} when it has no paid answer for the call, which then\n * takes the free path. */\nexport interface DecisionRoute {\n path: string;\n send: (url: string, options: HttpRequestOptions) => Promise<HttpResult>;\n}\n\n/** The paid path gave this call no answer: the wallet locked, low or over\n * its spend limits, the channel busy, or the payment failed. */\nexport class RouteSkipped extends Error {\n /** `unreached`: the paid call could not reach the router\n * ({@link isUnreachable}), so the free path, on the same host, is not\n * tried and the call reads as that transport failure. */\n constructor(\n readonly why: string,\n readonly unreached?: FetchJsonFailure,\n ) {\n super(`routing fee not paid: ${why}`);\n }\n}\n\n/** Another session's call was in flight on the wallet's routing channel. */\nexport const CHANNEL_BUSY = 'channel_busy';\n/** The server answered no paid path. */\nexport const PAID_PATH_ABSENT = 'paid_path_absent';\n/** The paid call got no answer, a refused payment or a server error. */\nexport const PAYMENT_FAILED = 'payment_failed';\n/** The payment went out and the call's budget ran out before its answer:\n * no fault. `tenjin mcp` lets the request finish, so it is recorded. */\nexport const DEADLINE_AFTER_PAYMENT_SENT = 'deadline_after_payment_sent';\n\nexport type DecisionOutcome<T> =\n /** `freePath`: the paid path skipped the call for this reason and it went\n * to the free path instead, unpaid. */\n | { status: 'decided'; decision: T; freePath?: string }\n /** On the free path nothing was paid and nothing could be, so a failure here\n * costs the turn a routing answer and nothing else. */\n | {\n status: 'failed';\n reason: string;\n errorCode?: string;\n freePath?: string;\n /** The router could not be reached at all ({@link isUnreachable}). */\n unreachable?: true;\n /** No answer came back at all: a transport failure or a timeout. */\n noAnswer?: true;\n }\n /** The paid path gave no answer ({@link RouteSkipped}) and no time was left\n * for the free path: the native tool runs. */\n | { status: 'skipped'; why: string };\n\n/**\n * ONE FREE CALL, IN TWO FORMS. The hook sends `{ packet }`: the backend runs\n * the gate, and on `execute` stores that packet under an id and answers with\n * each offered service's spec. The tool sends `{ query }`, which the backend\n * answers with the spec of the service its gate picks, or `{ query, id }` for\n * the free docs offer, which has no spec and is bound from the query. Every\n * provider call is built here, from a spec, or for the docs lookup by the\n * backend from the query.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet; sessionId?: string },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query: string; id?: string; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n sessionId?: string;\n id?: string;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(deps.route?.path ?? ROUTER_PATH, deps.baseUrl).toString();\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet, {\n ...(request.sessionId !== undefined ? { sessionId: request.sessionId } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n })\n : buildToolBody({\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n const started = Date.now();\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n let response: HttpResult;\n try {\n response = await (deps.route?.send ?? httpRequest)(url, options);\n } catch (err) {\n if (!(err instanceof RouteSkipped)) throw err;\n if (err.unreached !== undefined) return readDecision(err.unreached, schema);\n const left = options.timeoutMs - (Date.now() - started);\n if (left <= 0) return { status: 'skipped', why: err.why };\n // A CALL THE PAID PATH COULD NOT TAKE STILL ROUTES, on the free path,\n // unpaid, inside what is left of its budget, and says why.\n response = await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n ...options,\n timeoutMs: left,\n });\n const free = readDecision(response, schema);\n // A failure here ran on what a paid attempt left of the budget, so it says\n // nothing about the router being down: it never starts the backoff.\n if (free.status === 'failed') {\n return {\n status: 'failed',\n reason: free.reason,\n ...(free.errorCode !== undefined ? { errorCode: free.errorCode } : {}),\n // Still no answer, which must not end another call's backoff.\n ...(free.noAnswer === true ? { noAnswer: true as const } : {}),\n freePath: err.why,\n };\n }\n return free.status === 'skipped' ? free : { ...free, freePath: err.why };\n }\n return readDecision(response, schema);\n}\n\n/** Why a call from a spec stopped before anything was signed: the input did\n * not fit, the live terms were not the spec's, the provider answered\n * something else, it could not be reached, or the wallet could not pay. */\nexport type UnpaidReason = 'input' | 'terms' | 'provider' | 'unreachable' | 'wallet';\n\n/** How a call run from a request spec ended, for the server's offer-to-call\n * count. No text: the id, the outcome, the provider's status and the time. */\nexport interface SpecOutcome {\n id: string;\n /** `unpaid`: stopped before anything was signed, which the server never\n * counts as the offer taken. */\n status: 'fulfilled' | 'unverified' | 'failed' | 'needs_approval' | 'unpaid';\n /** On `unpaid` only, where the server requires it. */\n reason?: UnpaidReason;\n httpStatus?: number;\n ms?: number;\n}\n\n/** The outcome report's own deadline: it is telemetry and never holds a result. */\nexport const OUTCOME_TIMEOUT_MS = 3_000;\n\n/**\n * TELL THE SERVER A SPEC WAS USED. The client called and paid the provider\n * itself, so this is the only word the server gets that its offer was taken,\n * or that a call for it stopped before payment and why. Never throws and never\n * waits on anything the caller needs: a lost report costs one count.\n */\nexport async function reportSpecOutcome(\n outcome: SpecOutcome,\n deps: Pick<DecisionDeps, 'ctx' | 'baseUrl' | 'fetchImpl'>,\n): Promise<void> {\n try {\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: OUTCOME_TIMEOUT_MS,\n blockRedirects: true,\n jsonBody: buildOutcomeBody(outcome),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n } catch {\n // Telemetry only.\n }\n}\n\n/** The exact body of an outcome report, pinned to the shared fixtures. */\nexport function buildOutcomeBody(outcome: SpecOutcome): Record<string, unknown> {\n return {\n schemaVersion: 1,\n id: outcome.id,\n status: outcome.status,\n ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}),\n ...(outcome.httpStatus !== undefined ? { httpStatus: outcome.httpStatus } : {}),\n ...(outcome.ms !== undefined ? { ms: Math.max(0, Math.round(outcome.ms)) } : {}),\n };\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason; nothing was paid either way,\n // because there is nothing to pay for on this route.\n if (!response.ok) {\n return {\n status: 'failed',\n reason: fetchFailureToCliError(response).message,\n ...(isUnreachable(response) ? { unreachable: true as const } : {}),\n ...(response.status === undefined ? { noAnswer: true as const } : {}),\n };\n }\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n\n/** A dropped socket, which a fresh connection usually gets past. */\nconst RESET_CODES = new Set(['ECONNRESET', 'UND_ERR_SOCKET']);\n\n/**\n * A ROUTER THAT CANNOT BE REACHED: the transport named the layer that refused\n * the connection (DNS, TLS, a refused connection, a proxy refusing the tunnel)\n * and no status came back. Never the call's own timeout: that is the gate's\n * few seconds, and a slow decision or a cold start must not take the router\n * away from every session. Never a status, even with a body that failed to\n * read, and never a reset socket, which the free path retries on a fresh one.\n */\nexport function isUnreachable(failure: FetchJsonFailure): boolean {\n return (\n failure.kind === 'network' &&\n failure.status === undefined &&\n failure.transport !== undefined &&\n !RESET_COD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,OAAO,UAAU,SAAU,QAAO;AACxD,QAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,MAAI,OAAO,SAAS,YAAY,KAAK,WAAW,KAAK,KAAK,SAAS,GAAI,QAAO;AAC9E,QAAM,OAAO,OAAO,YAAY,WAAW,QAAQ,MAAM,GAAG,GAAG,IAAI;AACnE,SAAO,EAAE,MAAM,SAAS,KAAK;AAC/B;AAGA,IAAM,cAAc,oBAAI,IAAI,CAAC,cAAc,gBAAgB,CAAC;AAUrD,SAAS,cAAc,SAAoC;AAChE,SACE,QAAQ,SAAS,aACjB,QAAQ,WAAW,UACnB,QAAQ,cAAc,UACtB,CAAC,YAAY,IAAI,QAAQ,UAAU,QAAQ,EAAE;AAEjD;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/agent-tools.ts","../src/router/router-memo.ts"],"sourcesContent":["import { readdir, readFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { MCP_SERVER_NAME, REQUEST_TOOL } from './names';\n\n/**\n * CAN THIS SUBAGENT CALL `request` AT ALL? An offer to an agent whose definition\n * leaves the tool out is a line it cannot act on, and a router call spent to\n * write it. Claude Code defines a custom agent in a Markdown file whose\n * frontmatter may carry `tools:` (an allowlist) and `disallowedTools:`; this\n * reads that, and nothing else, and never writes to it.\n *\n * ONLY `allowed` IS ACTED ON. A subagent is redirected or offered a lookup\n * only when this KNOWS it can make the call: a definition whose tools cover\n * the request tool (or that has no `tools:` and so inherits everything), or a\n * built-in in {@link MCP_INHERITING_BUILTINS}. Every other built-in, and any\n * type with no definition this can find or read, is `unknown`, and `unknown`\n * gets no router call: `claude-code-guide` ships with Bash, Read, WebFetch and\n * WebSearch and no MCP tools, and denying its WebFetch would strand it exactly\n * as #377 reported.\n *\n * WHERE A DEFINITION LIVES, in the harness's own precedence: the project's\n * `.claude/agents` (from `cwd` up to the filesystem root, nearest first), then\n * `~/.claude/agents`, then an installed plugin's `agents/` for a `plugin:agent`\n * type. A file is found by its name first and by its frontmatter `name:`\n * second, because the type is the `name:` and the file name only usually\n * matches it.\n */\n\nexport type RequestToolAccess = 'allowed' | 'excluded' | 'unknown';\n\n/**\n * The built-in agent types that have no definition file and still inherit MCP\n * tools, so can call `mcp__x402__request`. From Claude Code's own Agent tool\n * listing (2.1.28x): `general-purpose` has every tool, and `Explore` and `Plan`\n * exclude only editing and agent tools, never MCP. Built-ins with a fixed tool\n * list, such as `claude-code-guide` (Bash, Read, WebFetch, WebSearch) and\n * `statusline-setup` (Read, Edit), are deliberately absent.\n */\nexport const MCP_INHERITING_BUILTINS: ReadonlySet<string> = new Set([\n 'general-purpose',\n 'Explore',\n 'Plan',\n]);\n\nexport interface AgentLookup {\n cwd?: string;\n homeDir: string;\n}\n\nconst MAX_AGENT_FILE_BYTES = 256 * 1024;\nconst TYPE_RE = /^[A-Za-z0-9_.:-]{1,200}$/;\n\nexport async function requestToolAccess(\n agentType: string | undefined,\n lookup: AgentLookup,\n): Promise<RequestToolAccess> {\n if (agentType === undefined || !TYPE_RE.test(agentType)) return 'unknown';\n try {\n const text = await findDefinition(agentType, lookup);\n if (text !== null) return accessOf(text);\n return MCP_INHERITING_BUILTINS.has(agentType) ? 'allowed' : 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\n/** What one definition's frontmatter says about the request tool. */\nexport function accessOf(definition: string): RequestToolAccess {\n const frontmatter = frontmatterOf(definition);\n if (frontmatter === null) return 'unknown';\n const disallowed = listField(frontmatter, 'disallowedTools');\n if (disallowed !== undefined && disallowed.some(namesRequestTool)) return 'excluded';\n const tools = listField(frontmatter, 'tools');\n if (tools === undefined) return 'allowed';\n return tools.some(namesRequestTool) ? 'allowed' : 'excluded';\n}\n\n/**\n * Does one `tools:` or `disallowedTools:` entry cover the request tool? The\n * tool itself, the bare server, or any `*`-suffixed pattern the tool's name\n * starts with: `*`, `mcp__*`, `mcp__x402__*` and every prefix between.\n */\nfunction namesRequestTool(tool: string): boolean {\n if (tool === REQUEST_TOOL || tool === `mcp__${MCP_SERVER_NAME}`) return true;\n return tool.endsWith('*') && REQUEST_TOOL.startsWith(tool.slice(0, -1));\n}\n\n/**\n * Every custom agent this project and this user define whose tools leave the\n * request tool out, for `doctor` to name. Plugin agents are not listed: their\n * files are not the user's to edit.\n */\nexport async function agentsWithoutRequestTool(lookup: AgentLookup): Promise<string[]> {\n const found: string[] = [];\n const seen = new Set<string>();\n for (const directory of agentDirs(lookup)) {\n for (const { name, text } of await definitionsIn(directory)) {\n const type = nameOf(text) ?? name;\n if (seen.has(type)) continue;\n seen.add(type);\n if (accessOf(text) === 'excluded') found.push(type);\n }\n }\n return found.sort();\n}\n\nasync function findDefinition(agentType: string, lookup: AgentLookup): Promise<string | null> {\n for (const directory of agentDirs(lookup)) {\n const text = await definitionIn(directory, agentType);\n if (text !== null) return text;\n }\n const colon = agentType.indexOf(':');\n if (colon > 0) {\n const plugin = agentType.slice(0, colon);\n const agent = agentType.slice(colon + 1);\n for (const root of await pluginRoots(plugin, lookup.homeDir)) {\n const text = await definitionIn(join(root, 'agents'), agent);\n if (text !== null) return text;\n }\n }\n return null;\n}\n\nfunction agentDirs(lookup: AgentLookup): string[] {\n const dirs: string[] = [];\n if (lookup.cwd !== undefined && lookup.cwd.length > 0) {\n let current = resolve(lookup.cwd);\n for (;;) {\n dirs.push(join(current, '.claude', 'agents'));\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n }\n const user = join(resolve(lookup.homeDir), '.claude', 'agents');\n // The user's directory is also an ancestor of most projects; it counts once,\n // in its own place in the order.\n return [...dirs.filter((d) => d !== user), user];\n}\n\nasync function definitionIn(directory: string, agentType: string): Promise<string | null> {\n const direct = await readBounded(join(directory, `${agentType}.md`));\n if (direct !== null && (nameOf(direct) ?? agentType) === agentType) return direct;\n for (const { text } of await definitionsIn(directory)) {\n if (nameOf(text) === agentType) return text;\n }\n return null;\n}\n\nasync function definitionsIn(directory: string): Promise<{ name: string; text: string }[]> {\n let names: string[];\n try {\n names = (await readdir(directory)).filter((n) => n.endsWith('.md')).slice(0, 200);\n } catch {\n return [];\n }\n const out: { name: string; text: string }[] = [];\n for (const file of names) {\n const text = await readBounded(join(directory, file));\n if (text !== null) out.push({ name: file.slice(0, -3), text });\n }\n return out;\n}\n\n/** Install paths `installed_plugins.json` records for `<plugin>@<marketplace>`. */\nasync function pluginRoots(plugin: string, homeDir: string): Promise<string[]> {\n const raw = await readBounded(join(homeDir, '.claude', 'plugins', 'installed_plugins.json'));\n if (raw === null) return [];\n const parsed = JSON.parse(raw) as { plugins?: Record<string, unknown> };\n const roots: string[] = [];\n for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {\n if (key.split('@')[0] !== plugin || !Array.isArray(entries)) continue;\n for (const entry of entries) {\n const path = (entry as { installPath?: unknown }).installPath;\n if (typeof path === 'string' && path.length > 0) roots.push(path);\n }\n }\n return roots;\n}\n\nasync function readBounded(path: string): Promise<string | null> {\n try {\n const text = await readFile(path, 'utf8');\n return text.length > MAX_AGENT_FILE_BYTES ? null : text;\n } catch {\n return null;\n }\n}\n\nfunction frontmatterOf(text: string): string[] | null {\n const lines = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const open = lines.findIndex((l) => l.trim().length > 0);\n if (open === -1 || lines[open]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > open && l.trim() === '---');\n return end === -1 ? null : lines.slice(open + 1, end);\n}\n\nfunction nameOf(text: string): string | null {\n const frontmatter = frontmatterOf(text);\n if (frontmatter === null) return null;\n const line = frontmatter.find((l) => /^name\\s*:/.test(l));\n const value = line === undefined ? '' : unquote(line.slice(line.indexOf(':') + 1).trim());\n return value.length > 0 ? value : null;\n}\n\n/**\n * A top-level list field in the three spellings agent files use: `a, b, c`,\n * `[a, b]`, or a block of `- a` lines. `undefined` when the key is absent.\n */\nfunction listField(frontmatter: string[], key: string): string[] | undefined {\n const index = frontmatter.findIndex((l) => new RegExp(`^${key}\\\\s*:`).test(l));\n if (index === -1) return undefined;\n const line = frontmatter[index]!;\n const inline = line.slice(line.indexOf(':') + 1).trim();\n if (inline.length > 0) {\n const body = inline.startsWith('[') && inline.endsWith(']') ? inline.slice(1, -1) : inline;\n return body\n .split(',')\n .map((part) => unquote(part.trim()))\n .filter((part) => part.length > 0);\n }\n const items: string[] = [];\n for (const next of frontmatter.slice(index + 1)) {\n const item = /^\\s+-\\s*(.*)$/.exec(next);\n if (item === null) {\n if (next.trim().length === 0) continue;\n break;\n }\n const value = unquote(item[1]!.trim());\n if (value.length > 0) items.push(value);\n }\n return items;\n}\n\nfunction unquote(value: string): string {\n const quoted = /^(['\"])(.*)\\1$/.exec(value);\n return quoted === null ? value : quoted[2]!;\n}\n","import { createHash } from 'node:crypto';\nimport { readFile, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\n\n/**\n * ONE MEMO FOR \"DO NOT ASK THE ROUTER YET\", per machine and per router origin,\n * in the data dir, so every hook leg and every `tenjin mcp` process reads the\n * same answer. Two facts use it:\n *\n * - `unreachable`: a routing leg's call could not reach the router (DNS, TLS,\n * a refused connection, a proxy refusing the tunnel; see `isUnreachable`). For\n * {@link UNREACHABLE_BACKOFF_MS} every leg skips the router and the native\n * tool runs at once, instead of each prompt and search waiting out the gate.\n * Doctor's probe ends it early when it reaches the router.\n * - `paid-path-absent`: the router answered no paid path (the fee is off), so\n * calls take the free path without asking for an hour, or until the free\n * path answers `fee_required`.\n *\n * A memo is a file written atomically and read with the clock: one older than\n * its window, or dated in the future, reads as absent, so nothing cleans up\n * after it. An unreadable file reads as absent too: the cost of a lost memo is\n * one more call to the router.\n */\nexport type RouterMemoKind = 'unreachable' | 'paid-path-absent';\n\nexport interface RouterMemo {\n /** When it was written, in epoch ms. */\n at: number;\n /** When it ends, in epoch ms. */\n until: number;\n /** What happened, for doctor. */\n detail?: string;\n}\n\n/** How long routing legs skip a router that did not answer. */\nexport const UNREACHABLE_BACKOFF_MS = 60_000;\n\nfunction memoPath(dataDir: string, kind: RouterMemoKind, baseUrl: string): string {\n const origin = new URL(baseUrl).origin;\n const key = createHash('sha256').update(origin).digest('hex').slice(0, 16);\n return join(dataDir, 'router-memo', `${kind}-${key}.json`);\n}\n\n/** The memo in force at `now`, or null. Never throws. */\nexport async function readRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n now: number,\n): Promise<RouterMemo | null> {\n try {\n const raw = JSON.parse(await readFile(memoPath(dataDir, kind, baseUrl), 'utf8')) as unknown;\n if (raw === null || typeof raw !== 'object') return null;\n const { at, until, detail } = raw as Record<string, unknown>;\n if (typeof at !== 'number' || typeof until !== 'number') return null;\n if (at > now || until <= now) return null;\n return { at, until, ...(typeof detail === 'string' ? { detail } : {}) };\n } catch {\n return null;\n }\n}\n\n/** Starts a memo of `ttlMs` from `now`. Never throws. */\nexport async function writeRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n memo: { now: number; ttlMs: number; detail?: string },\n): Promise<void> {\n const body: RouterMemo = {\n at: memo.now,\n until: memo.now + memo.ttlMs,\n ...(memo.detail !== undefined ? { detail: memo.detail.slice(0, 300) } : {}),\n };\n try {\n await writeFileAtomic(memoPath(dataDir, kind, baseUrl), `${JSON.stringify(body)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch {\n // Best effort: a memo that did not land costs one more call.\n }\n}\n\n/** Ends a memo before its window does. Never throws. */\nexport async function clearRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n): Promise<void> {\n try {\n await rm(memoPath(dataDir, kind, baseUrl), { force: true });\n } catch {\n // Best effort: the window ends it anyway.\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,SAAS,gBAAgB;AAClC,SAAS,SAAS,MAAM,eAAe;AAqChC,IAAM,0BAA+C,oBAAI,IAAI;AAAA,EAClE;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOD,IAAM,uBAAuB,MAAM;AACnC,IAAM,UAAU;AAEhB,eAAsB,kB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MAAI;AACF,UAAM,gBAAgB,SAAS,SAAS,MAAM,OAAO,GAAG,GAAG,KAAK,UAAU,IAAI,CAAC;AAAA,GAAM;AAAA,MACnF,MAAM;AAAA,MACN,SAAS;AAAA,IACX,CAAC;AAAA,EACH,QAAQ;AAAA,EAER;AACF;AAGA,eAAsB,gBACpB,SACA,MACA,SACe;AACf,MAAI;AACF,UAAM,GAAG,SAAS,SAAS,MAAM,OAAO,GAAG,EAAE,OAAO,KAAK,CAAC;AAAA,EAC5D,QAAQ;AAAA,EAER;AACF;","names":["readFile","join","join","readFile"]}
@@ -1,172 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- inspectHooksFile
4
- } from "./chunk-XVYATBKD.js";
5
- import {
6
- CliError,
7
- writeFileAtomic
8
- } from "./chunk-JLEF5WHM.js";
9
-
10
- // src/router/status-line-wiring.ts
11
- import { readFile, stat } from "node:fs/promises";
12
- var STATUS_LINE_COMMAND = "tenjin status-line";
13
- var STATUS_LINE_REFRESH_SECONDS = 1;
14
- var OUR_MARKER = STATUS_LINE_COMMAND;
15
- var MODES = ["own", "compose", "skip"];
16
- function statusLineMode(value) {
17
- const mode = MODES.find((known) => known === value);
18
- if (mode === void 0) {
19
- throw new CliError("USAGE", `--status-line takes ${MODES.join(", ")}, not "${value}".`, {
20
- fix: "Run `tenjin install --status-line own`."
21
- });
22
- }
23
- return mode;
24
- }
25
- function classifyStatusLine(value) {
26
- if (value === null || value === void 0) return "absent";
27
- const command = typeof value === "string" ? value : typeof value === "object" && !Array.isArray(value) ? value.command : void 0;
28
- if (typeof command !== "string" || command.trim().length === 0) return "foreign";
29
- if (command.trim() === OUR_MARKER) return "ours";
30
- return command.includes(OUR_MARKER) ? "composed" : "foreign";
31
- }
32
- function ours() {
33
- return {
34
- type: "command",
35
- command: STATUS_LINE_COMMAND,
36
- refreshInterval: STATUS_LINE_REFRESH_SECONDS
37
- };
38
- }
39
- var shQuote = (value) => `'${value.replaceAll("'", String.raw`'\''`)}'`;
40
- var shUnquote = (value) => value.replaceAll(String.raw`'\''`, "'");
41
- function composedScript(existing) {
42
- return [
43
- "event=$(cat)",
44
- `yours=$(printf %s "$event" | ${existing})`,
45
- `tenjin=$(printf %s "$event" | ${STATUS_LINE_COMMAND})`,
46
- 'printf %s "$yours${tenjin:+ \xB7 $tenjin}"'
47
- ].join("; ");
48
- }
49
- function decomposeCommand(command) {
50
- const trimmed = command.trim();
51
- if (!trimmed.startsWith("sh -c '") || !trimmed.endsWith("'")) return null;
52
- const script = shUnquote(trimmed.slice("sh -c '".length, -1));
53
- const prefix = 'event=$(cat); yours=$(printf %s "$event" | ';
54
- if (!script.startsWith(prefix)) return null;
55
- const rest = script.slice(prefix.length);
56
- const suffix = `); tenjin=$(printf %s "$event" | ${STATUS_LINE_COMMAND}); printf %s "$yours\${tenjin:+ \xB7 $tenjin}"`;
57
- if (!rest.endsWith(suffix)) return null;
58
- const existing = rest.slice(0, -suffix.length);
59
- return existing.length > 0 && composedScript(existing) === script ? existing : null;
60
- }
61
- function composeCommand(existing) {
62
- return `sh -c ${shQuote(composedScript(existing))}`;
63
- }
64
- function commandOf(value) {
65
- const command = typeof value === "string" ? value : typeof value === "object" && value !== null && !Array.isArray(value) ? value.command : void 0;
66
- return typeof command === "string" && command.trim().length > 0 ? command.trim() : void 0;
67
- }
68
- function composeFor(value) {
69
- const command = commandOf(value);
70
- return command === void 0 ? void 0 : composeCommand(command);
71
- }
72
- async function ensureStatusLine(settingsPath, opts = {}) {
73
- const found = await inspectHooksFile(settingsPath);
74
- if ("refusal" in found) {
75
- return { path: settingsPath, state: "absent", wrote: false, warning: found.refusal.reason };
76
- }
77
- const { path, settings } = found;
78
- const current = settings.statusLine;
79
- const state = classifyStatusLine(current);
80
- if (opts.mode === "skip") {
81
- return { path, state, wrote: false, ...state === "foreign" ? kept(current) : {} };
82
- }
83
- if (opts.mode === "compose") {
84
- const composed = composeFor(current);
85
- if (composed === void 0) return writeStatusLine(found, ours(), "ours");
86
- const base = typeof current === "object" && current !== null && !Array.isArray(current) ? current : ours();
87
- return state === "composed" ? { path, state, wrote: false, command: composed } : writeStatusLine(found, { ...base, command: composed }, "composed");
88
- }
89
- if (state === "foreign") {
90
- return { path, state, wrote: false, ...kept(current) };
91
- }
92
- if (state === "composed") return { path, state, wrote: false };
93
- if (state === "absent" && opts.refreshOnly === true) {
94
- return { path, state, wrote: false };
95
- }
96
- return writeStatusLine(found, ours(), "ours");
97
- }
98
- async function removeStatusLine(settingsPath) {
99
- const found = await inspectHooksFile(settingsPath);
100
- if ("refusal" in found) {
101
- return { path: settingsPath, state: "absent", wrote: false, warning: found.refusal.reason };
102
- }
103
- const { path, settings } = found;
104
- const current = settings.statusLine;
105
- const state = classifyStatusLine(current);
106
- if (state === "ours") return writeStatusLine(found, void 0, "absent");
107
- if (state === "composed") {
108
- const command = commandOf(current);
109
- const original = command === void 0 ? null : decomposeCommand(command);
110
- if (original === null) return { path, state, wrote: false };
111
- const kept2 = { ...current, command: original };
112
- return writeStatusLine(found, kept2, "foreign");
113
- }
114
- return { path, state, wrote: false };
115
- }
116
- async function inspectStatusLine(settingsPath) {
117
- const found = await inspectHooksFile(settingsPath);
118
- if ("refusal" in found) {
119
- return { path: settingsPath, state: "absent", warning: found.refusal.reason };
120
- }
121
- return { path: found.path, state: classifyStatusLine(found.settings.statusLine) };
122
- }
123
- function kept(current) {
124
- const compose = composeFor(current);
125
- return compose === void 0 ? {} : { compose };
126
- }
127
- async function writeStatusLine(found, value, state) {
128
- const { path, raw, settings } = found;
129
- const next = { ...settings };
130
- if (value === void 0) delete next.statusLine;
131
- else next.statusLine = value;
132
- const body = `${JSON.stringify(next, null, 2)}
133
- `;
134
- const result = {
135
- path,
136
- state,
137
- wrote: false,
138
- ...typeof value?.command === "string" ? { command: value.command } : {}
139
- };
140
- if (body === raw) return result;
141
- const mode = await stat(path).then((s) => ({ mode: s.mode & 511 })).catch(() => ({}));
142
- if (raw !== null && await readFile(path, "utf8").catch(() => null) !== raw) {
143
- return {
144
- ...result,
145
- state: classifyStatusLine(settings.statusLine),
146
- warning: "changed-since-read"
147
- };
148
- }
149
- try {
150
- await writeFileAtomic(path, body, mode);
151
- } catch (err) {
152
- return {
153
- ...result,
154
- state: classifyStatusLine(settings.statusLine),
155
- warning: err instanceof Error ? err.message : String(err)
156
- };
157
- }
158
- return { ...result, wrote: true };
159
- }
160
-
161
- export {
162
- STATUS_LINE_COMMAND,
163
- STATUS_LINE_REFRESH_SECONDS,
164
- statusLineMode,
165
- classifyStatusLine,
166
- decomposeCommand,
167
- composeCommand,
168
- ensureStatusLine,
169
- removeStatusLine,
170
- inspectStatusLine
171
- };
172
- //# sourceMappingURL=chunk-DSNXKUXI.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/status-line-wiring.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { CliError } from '../lib/errors';\nimport { inspectHooksFile } from '../lib/harness-hooks';\n\n/**\n * The `statusLine` key in Claude Code's settings file: the one setting the live\n * footer needs, and the one piece of harness configuration a person is most\n * likely to have already set for themselves.\n *\n * SO IT IS NEVER REPLACED. An existing status line that is not ours is left\n * exactly as it is, and `install` prints the composition line instead;\n * `--status-line compose` writes that line only because it was asked for by\n * name. Writing over it and saying so in the output destroys a configuration\n * this CLI did not create.\n *\n * OWNERSHIP IS ONE MARKER, the command naming `tenjin status-line`, used by\n * `install`, `install --refresh`, `uninstall` and `doctor` alike, so the four\n * can never disagree about which status line is Tenjin's.\n */\n\n/** The command `install` registers, in the shape the hook entries use: a plain\n * command line on PATH, with no path into this build's dist directory. */\nexport const STATUS_LINE_COMMAND = 'tenjin status-line';\n/** Claude Code re-runs the command on this interval, in seconds. */\nexport const STATUS_LINE_REFRESH_SECONDS = 1;\n/** The marker that makes a status line ours, composed or not. */\nconst OUR_MARKER = STATUS_LINE_COMMAND;\n\n/** What the user asked for, when they asked. Absent means the default path. */\nexport type StatusLineMode = 'own' | 'compose' | 'skip';\n\nconst MODES: readonly StatusLineMode[] = ['own', 'compose', 'skip'];\n\n/** `--status-line <mode>`, refused rather than guessed at. */\nexport function statusLineMode(value: string): StatusLineMode {\n const mode = MODES.find((known) => known === value);\n if (mode === undefined) {\n throw new CliError('USAGE', `--status-line takes ${MODES.join(', ')}, not \"${value}\".`, {\n fix: 'Run `tenjin install --status-line own`.',\n });\n }\n return mode;\n}\n\n/**\n * What is in the file: ours alone, ours appended to someone else's, someone\n * else's alone, or nothing.\n */\nexport type StatusLineState = 'ours' | 'composed' | 'foreign' | 'absent';\n\nexport interface StatusLineResult {\n path: string;\n state: StatusLineState;\n /** True when this run changed the file. */\n wrote: boolean;\n /** The command now registered, when one of ours is. */\n command?: string;\n /** The exact command to set by hand, printed when a foreign line is kept. */\n compose?: string;\n /** Why nothing was written, for a file this run would not touch. */\n warning?: string;\n}\n\nexport function classifyStatusLine(value: unknown): StatusLineState {\n if (value === null || value === undefined) return 'absent';\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n // A status line whose command this build cannot read is still the user's.\n if (typeof command !== 'string' || command.trim().length === 0) return 'foreign';\n if (command.trim() === OUR_MARKER) return 'ours';\n return command.includes(OUR_MARKER) ? 'composed' : 'foreign';\n}\n\nfunction ours(): Record<string, unknown> {\n return {\n type: 'command',\n command: STATUS_LINE_COMMAND,\n refreshInterval: STATUS_LINE_REFRESH_SECONDS,\n };\n}\n\nconst shQuote = (value: string): string => `'${value.replaceAll(\"'\", String.raw`'\\''`)}'`;\nconst shUnquote = (value: string): string => value.replaceAll(String.raw`'\\''`, \"'\");\n\n/** The inner script, with the user's own command as the one hole in it. */\nfunction composedScript(existing: string): string {\n return [\n 'event=$(cat)',\n `yours=$(printf %s \"$event\" | ${existing})`,\n `tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND})`,\n 'printf %s \"$yours${tenjin:+ · $tenjin}\"',\n ].join('; ');\n}\n\n/**\n * The command a composition was built from, or null when this is not a\n * composition this build wrote. It is the exact inverse of\n * {@link composeCommand}: a hand-edited line matches nothing and is kept whole,\n * because guessing at someone's shell is how an uninstall breaks a prompt.\n */\nexport function decomposeCommand(command: string): string | null {\n const trimmed = command.trim();\n if (!trimmed.startsWith(\"sh -c '\") || !trimmed.endsWith(\"'\")) return null;\n const script = shUnquote(trimmed.slice(\"sh -c '\".length, -1));\n const prefix = 'event=$(cat); yours=$(printf %s \"$event\" | ';\n if (!script.startsWith(prefix)) return null;\n const rest = script.slice(prefix.length);\n const suffix = `); tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND}); printf %s \"$yours\\${tenjin:+ · $tenjin}\"`;\n if (!rest.endsWith(suffix)) return null;\n const existing = rest.slice(0, -suffix.length);\n return existing.length > 0 && composedScript(existing) === script ? existing : null;\n}\n\n/**\n * The user's status line with ours appended after a separator, on one line.\n *\n * The harness writes its event on stdin ONCE, so a composition cannot simply\n * run two commands in sequence: the event is captured first and replayed into\n * each. Ours contributes nothing when this session has no activity, and the\n * separator goes with it, so a quiet session looks exactly as it did before.\n */\nexport function composeCommand(existing: string): string {\n return `sh -c ${shQuote(composedScript(existing))}`;\n}\n\n/** The command a status-line setting runs, in either shape it can take. */\nfunction commandOf(value: unknown): string | undefined {\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n return typeof command === 'string' && command.trim().length > 0 ? command.trim() : undefined;\n}\n\n/** What a foreign status line's owner is told to set, verbatim. */\nfunction composeFor(value: unknown): string | undefined {\n const command = commandOf(value);\n return command === undefined ? undefined : composeCommand(command);\n}\n\nexport interface EnsureStatusLineOpts {\n mode?: StatusLineMode;\n /**\n * `install --refresh` and the refresh `tenjin update` spawns: converge a\n * status line of ours that is already registered, and ADD NOTHING. A machine\n * whose owner removed ours, or never had it, keeps that answer across every\n * upgrade without a second place to record it.\n */\n refreshOnly?: boolean;\n}\n\nexport async function ensureStatusLine(\n settingsPath: string,\n opts: EnsureStatusLineOpts = {},\n): Promise<StatusLineResult> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', wrote: false, warning: found.refusal.reason };\n }\n const { path, settings } = found;\n const current = settings.statusLine;\n const state = classifyStatusLine(current);\n if (opts.mode === 'skip') {\n return { path, state, wrote: false, ...(state === 'foreign' ? kept(current) : {}) };\n }\n if (opts.mode === 'compose') {\n const composed = composeFor(current);\n if (composed === undefined) return writeStatusLine(found, ours(), 'ours');\n // THEIR OBJECT, with the command swapped. Rebuilding it from ours would\n // drop whatever else they had set on it, such as their own padding.\n const base =\n typeof current === 'object' && current !== null && !Array.isArray(current)\n ? (current as Record<string, unknown>)\n : ours();\n return state === 'composed'\n ? { path, state, wrote: false, command: composed }\n : writeStatusLine(found, { ...base, command: composed }, 'composed');\n }\n if (state === 'foreign') {\n // NOT REPLACED, AND NOT WRITTEN AROUND. The user keeps what they set, and\n // gets the one command that adds ours to it.\n return { path, state, wrote: false, ...kept(current) };\n }\n if (state === 'composed') return { path, state, wrote: false };\n if (state === 'absent' && opts.refreshOnly === true) {\n return { path, state, wrote: false };\n }\n return writeStatusLine(found, ours(), 'ours');\n}\n\n/** `uninstall`: take out a status line of OURS, and only if it is ours alone. */\nexport async function removeStatusLine(settingsPath: string): Promise<StatusLineResult> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', wrote: false, warning: found.refusal.reason };\n }\n const { path, settings } = found;\n const current = settings.statusLine;\n const state = classifyStatusLine(current);\n if (state === 'ours') return writeStatusLine(found, undefined, 'absent');\n // A COMPOSED LINE IS MOSTLY THE USER'S TEXT, so it is not deleted: the half\n // this build wrote is unwound and their own command is put back exactly as it\n // was. A composition that was hand-edited since inverts to nothing and is\n // left whole, because guessing at someone's shell is the worse failure.\n if (state === 'composed') {\n const command = commandOf(current);\n const original = command === undefined ? null : decomposeCommand(command);\n if (original === null) return { path, state, wrote: false };\n const kept = { ...(current as Record<string, unknown>), command: original };\n return writeStatusLine(found, kept, 'foreign');\n }\n return { path, state, wrote: false };\n}\n\n/** What `doctor` reports, without writing anything. */\nexport async function inspectStatusLine(\n settingsPath: string,\n): Promise<{ path: string; state: StatusLineState; warning?: string }> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', warning: found.refusal.reason };\n }\n return { path: found.path, state: classifyStatusLine(found.settings.statusLine) };\n}\n\nfunction kept(current: unknown): { compose?: string } {\n const compose = composeFor(current);\n return compose === undefined ? {} : { compose };\n}\n\ntype Inspection = { path: string; raw: string | null; settings: Record<string, unknown> };\n\n/**\n * One key, written through the same read-compare-write the hooks writer uses:\n * every other key is copied through in its original order, the bytes are\n * re-read before the rename so a concurrent edit is refused rather than lost,\n * and the file keeps its mode.\n */\nasync function writeStatusLine(\n found: Inspection,\n value: Record<string, unknown> | undefined,\n state: StatusLineState,\n): Promise<StatusLineResult> {\n const { path, raw, settings } = found;\n const next: Record<string, unknown> = { ...settings };\n if (value === undefined) delete next.statusLine;\n else next.statusLine = value;\n const body = `${JSON.stringify(next, null, 2)}\\n`;\n const result: StatusLineResult = {\n path,\n state,\n wrote: false,\n ...(typeof value?.command === 'string' ? { command: value.command } : {}),\n };\n if (body === raw) return result;\n const mode = await stat(path)\n .then((s) => ({ mode: s.mode & 0o777 }))\n .catch(() => ({}));\n if (raw !== null && (await readFile(path, 'utf8').catch(() => null)) !== raw) {\n return {\n ...result,\n state: classifyStatusLine(settings.statusLine),\n warning: 'changed-since-read',\n };\n }\n try {\n await writeFileAtomic(path, body, mode);\n } catch (err) {\n return {\n ...result,\n state: classifyStatusLine(settings.statusLine),\n warning: err instanceof Error ? err.message : String(err),\n };\n }\n return { ...result, wrote: true };\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,UAAU,YAAY;AAuBxB,IAAM,sBAAs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AAAA,MACL,GAAG;AAAA,MACH,OAAO,mBAAmB,SAAS,UAAU;AAAA,MAC7C,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,IAC1D;AAAA,EACF;AACA,SAAO,EAAE,GAAG,QAAQ,OAAO,KAAK;AAClC;","names":["kept"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/fee.ts","../src/router/spend-question.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { mkdir, open, readFile, readdir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { hasCode } from '../lib/errno';\nimport { formatUsdDisplay } from '../lib/money';\nimport { evaluateSpendPolicy, type PolicyReason, type SpendPolicy } from '../lib/policy';\nimport type { DecisionRoute } from './decision';\n\n/**\n * THE ROUTING FEE, WITHOUT ANYTHING THAT PAYS. Every routing call on the paid\n * path pays $0.003 over x402 `batch-settlement`, and the stock SDK client in\n * `tenjin mcp` does all of it (`routing-payer.ts`). Everything else, `tenjin\n * hook` included, is the free path exactly as before this fee existed.\n *\n * Hook-safe: `tenjin hook` loads this module, and its chunk graph stays free\n * of the wallet and the x402 SDK (`dist-chunks.test.ts`).\n */\n\nexport const ROUTE_PAID_PATH = '/api/x402-router/route';\n\n/** The flat fee per routing call, atomic USDC ($0.003). */\nexport const ROUTING_FEE_ATOMIC = 3_000n;\n/** The largest channel deposit, atomic USDC ($0.25), made inline by the SDK\n * on the first paid call of a channel that cannot cover the next fee. */\nexport const CHANNEL_DEPOSIT_ATOMIC = 250_000n;\n/**\n * The smallest deposit worth signing: ten fees ($0.03). A per-call limit under\n * $0.25 sizes the deposit down to the limit while it still covers this many.\n */\nexport const MIN_DEPOSIT_ATOMIC = 10n * ROUTING_FEE_ATOMIC;\n\n/** A spend refusal, as the reason the call was not paid. */\nconst REFUSED: Partial<Record<PolicyReason, string>> = {\n not_allowlisted: 'not_allowlisted',\n session_budget_exceeded: 'budget_reached',\n above_auto_spend: 'limit_below_deposit',\n};\n\n/** The reason a spend refusal leaves a routing call unpaid. */\nexport function refusedWhy(reason: PolicyReason): string {\n return REFUSED[reason] ?? reason;\n}\n\n/**\n * THE DEPOSIT IS THE SPEND. It meets the whole policy once, the day's budget\n * included, when the SDK's `depositStrategy` reserves it. Each fee paid from\n * it then gets only the per-payment checks: the per-call limit, the creator\n * allowlist (the router's host) and an explicit zero daily limit. It is never\n * refused for the day's running total, which the deposit already consumed.\n * Null when those checks allow the fee.\n */\nexport function feeRefusal(policy: SpendPolicy, host: string): string | null {\n const evaluation = evaluateSpendPolicy(\n { ...policy, sessionBudgetAtomic: policy.sessionBudgetAtomic === 0n ? 0n : null },\n { mode: 'automatic', amountAtomic: ROUTING_FEE_ATOMIC, creator: host, sessionSpentAtomic: 0n },\n );\n return evaluation.decision === 'allow' ? null : refusedWhy(evaluation.reason);\n}\n\n/** The paid path for this call, or null for the free path. `tenjin mcp` passes\n * its payer's; absent, every call is free. */\nexport type RouteFor = (baseUrl: string) => Promise<DecisionRoute | null>;\n\n/** The free path's reason code once the server routes only paid calls. */\nexport const FEE_REQUIRED = 'fee_required';\n\n/** Whether a decision is the free path's `fee_required` answer. */\nexport function isFeeRequired(response: unknown): boolean {\n const decision = (response as { decision?: { action?: unknown; diagnostics?: unknown } })\n ?.decision;\n const diagnostics = decision?.diagnostics as { reasonCode?: unknown } | undefined;\n return decision?.action === 'native' && diagnostics?.reasonCode === FEE_REQUIRED;\n}\n\n/**\n * WHY A CALL WAS NOT PAID, for the user: the reason and the fix, keyed by the\n * payer's skip reason (or `fee_required`, when the free path answered it and\n * nothing else explains why). Null for a reason that is no fault and needs no\n * fix: another session's call on the channel, a server with no paid path, or\n * a call queued past its own budget, or a payment still out when the call's\n * budget ran out (it finishes in the background).\n */\nconst UNPAID: Record<string, { reason: string; fix: string }> = {\n wallet_low: {\n reason: `the wallet holds less than the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,\n fix: `Fund it with \\`tenjin wallet fund ${usd(CHANNEL_DEPOSIT_ATOMIC)}\\`.`,\n },\n wallet_locked: {\n reason: '`tenjin mcp` cannot unlock the wallet without a prompt',\n fix: 'Set TENJIN_WALLET_PASSPHRASE in the environment Claude Code starts from, then restart Claude Code.',\n },\n no_wallet: {\n reason: 'this machine has no wallet',\n fix: 'Run `tenjin doctor`.',\n },\n limit_below_deposit: {\n reason: `the per-call spend limit is below the smallest routing deposit ($${usd(MIN_DEPOSIT_ATOMIC)})`,\n fix: 'Run `tenjin doctor`.',\n },\n budget_reached: {\n reason: 'the daily spend limit has no room left for the routing fee or its deposit',\n fix: 'Run `tenjin doctor`.',\n },\n not_allowlisted: {\n reason: 'allowlistCreators does not include the router',\n fix: 'Run `tenjin doctor`.',\n },\n payment_failed: {\n reason: 'the routing payment failed',\n fix: 'Run `tenjin doctor`.',\n },\n [FEE_REQUIRED]: {\n reason: 'the router now charges it, and this session cannot pay it',\n fix: 'Run `tenjin doctor`.',\n },\n};\nconst NO_FAULT = new Set([\n 'channel_busy',\n 'paid_path_absent',\n 'busy',\n 'no_call',\n 'deadline_after_payment_sent',\n]);\n\n/** The reason and fix for an unpaid call, or null when it needs no word. */\nexport function unpaid(why: string): { reason: string; fix: string } | null {\n if (NO_FAULT.has(why)) return null;\n return UNPAID[why] ?? UNPAID['payment_failed']!;\n}\n\n/** The one line the user sees, once per session, when a call was not paid. */\nexport function unpaidSentence(why: string): string | null {\n const u = unpaid(why);\n if (u === null) return null;\n return `Tenjin routing could not pay its $${usd(ROUTING_FEE_ATOMIC)} fee (${u.reason}), so calls take the free path until that is fixed. ${u.fix}`;\n}\n\nconst ADDRESS_RE = /^0x[0-9a-f]{40}$/;\n\n/** One wallet's folder: the SDK's file storage for its routing channel\n * (`client/<channelId>.json`). */\nexport function payerDir(dataDir: string, payer: string): string {\n const name = payer.toLowerCase();\n if (!ADDRESS_RE.test(name)) throw new Error(`not a wallet address: ${payer}`);\n return join(dataDir, 'router', 'fee', name);\n}\n\n/** Atomic USDC as dollars with at least two decimals, never a float. */\nexport function usd(atomic: bigint): string {\n return formatUsdDisplay(atomic.toString());\n}\n\n/** How long a session's notice marker is kept. */\nconst NOTICE_KEEP_MS = 7 * 86_400_000;\n\n/**\n * TRUE ONCE PER SESSION: the first caller for a session id creates its marker\n * and gets true; every later one gets false. Each marker holds the time it was\n * made, and those older than a week go on the way past, so the directory does\n * not grow with every session ever run.\n */\nexport async function firstNoticeFor(\n dataDir: string,\n sessionId: string,\n now: number,\n): Promise<boolean> {\n const dir = join(dataDir, 'router', 'notices');\n const name = createHash('sha256').update(sessionId).digest('hex').slice(0, 32);\n const created = await createExclusive(join(dir, name), String(now));\n if (created) {\n for (const entry of await readdir(dir).catch(() => [] as string[])) {\n const path = join(dir, entry);\n const at = Number(await readFile(path, 'utf8').catch(() => 'NaN'));\n if (!Number.isFinite(at) || now - at > NOTICE_KEEP_MS) await rm(path, { force: true });\n }\n }\n return created;\n}\n\nasync function createExclusive(path: string, body: string): Promise<boolean> {\n try {\n await mkdir(join(path, '..'), { recursive: true, mode: 0o700 });\n const handle = await open(path, 'wx', 0o600);\n try {\n await handle.writeFile(body);\n } finally {\n await handle.close();\n }\n return true;\n } catch (err) {\n if (hasCode(err, 'EEXIST')) return false;\n throw err;\n }\n}\n","import { toMoney } from '../lib/money';\nimport { CHANNEL_DEPOSIT_ATOMIC, ROUTING_FEE_ATOMIC, unpaidSentence, usd } from './fee';\n\n/**\n * THE SPEND QUESTION, ONE TEXT FOR EVERY PLACE THAT ASKS IT. The selector in a\n * terminal, the question an install that could not ask hands to its agent,\n * doctor's warning and the routing notice all show the same limits, the same\n * routing-fee terms and the same one-step yes, so the agent can put to the\n * user exactly what the selector would have.\n */\n\n/** Absent-only automatic router defaults, in atomic USDC. */\nexport const ROUTER_DEFAULTS = {\n maxAutoSpend: '250000',\n sessionBudget: '5000000',\n} as const;\n\n/** The automatic limits a fresh install fills in, in atomic USDC; `sessionBudget` may be `none`. */\nexport interface RouterLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\n/** What the question shows: the file's own value where it names one, else the default. */\nexport function shownLimits(config: {\n maxAutoSpend?: string | undefined;\n sessionBudget?: string | undefined;\n}): RouterLimits {\n return {\n maxAutoSpend: config.maxAutoSpend ?? ROUTER_DEFAULTS.maxAutoSpend,\n sessionBudget: config.sessionBudget ?? ROUTER_DEFAULTS.sessionBudget,\n };\n}\n\n/** The limits in USD, as the question shows them. */\nexport function limitsUsd(limits: RouterLimits): { maxAutoSpend: string; sessionBudget: string } {\n return {\n maxAutoSpend: toMoney(limits.maxAutoSpend).usd,\n sessionBudget: limits.sessionBudget === 'none' ? 'none' : toMoney(limits.sessionBudget).usd,\n };\n}\n\n/** \"up to $0.25 a call and $5 a day\" */\nexport function limitsPhrase(limits: RouterLimits): string {\n const usdOf = limitsUsd(limits);\n const daily =\n usdOf.sessionBudget === 'none' ? 'with no daily limit' : `and $${usdOf.sessionBudget} a day`;\n return `up to $${usdOf.maxAutoSpend} a call ${daily}`;\n}\n\n/** The routing fee's terms, as the selector names them. */\nexport const ROUTING_FEE_TERMS = `Routing costs $${usd(ROUTING_FEE_ATOMIC)} a call, paid from channel deposits of up to $${usd(CHANNEL_DEPOSIT_ATOMIC)} that stay yours until spent; each deposit counts against these limits.`;\n\n/**\n * The yes to the limits shown, where the command install ran is not known\n * (doctor, the routing notice, the request tool): the per-call limit only.\n * The daily limit already defaults to the one shown. A bare `install --yes`\n * here would undo a `--project`, `--no-wallet` or `--status-line skip`\n * install; install's own output names that command with its flags instead.\n */\nexport const ACCEPT_COMMAND = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;\n\n/** The commands for limits of the user's own, each in backticks. */\nexport const OWN_LIMITS_COMMANDS =\n '`tenjin config set maxAutoSpend <usd>` and `tenjin config set sessionBudget <usd|none>`';\n\n/** The selector's own line: either answer approves the fee. */\nexport const FEE_APPROVAL =\n 'Using these limits or choosing your own also approves the routing fee.';\n\n/** The question, for the agent to put to the user as written. */\nexport function spendQuestion(limits: RouterLimits): string {\n return `May Tenjin pay for tool calls without asking you each time, ${limitsPhrase(limits)}? ${ROUTING_FEE_TERMS} ${FEE_APPROVAL}`;\n}\n\n/** Who reads a notice: the user, in the hook's `systemMessage`, or the agent,\n * in the request tool's answer. */\nexport type NoticeReader = 'user' | 'agent';\n\n/**\n * The routing notice for a machine whose limits nobody has answered: the\n * question and the one-step yes, put to the user directly, or handed to the\n * agent to ask.\n */\nexport function unansweredNotice(limits: RouterLimits, reader: NoticeReader): string {\n const open = 'Tenjin pays for nothing on its own yet: the spend limits are not answered.';\n if (reader === 'agent') {\n return `${open} Ask the user: ${spendQuestion(limits)} For a yes, run \\`${ACCEPT_COMMAND}\\`; for other amounts, run ${OWN_LIMITS_COMMANDS}.`;\n }\n return `${open} It can pay for tool calls without asking you each time, ${limitsPhrase(limits)}. ${ROUTING_FEE_TERMS} ${FEE_APPROVAL} To use these limits, run \\`${ACCEPT_COMMAND}\\`; to choose your own, run ${OWN_LIMITS_COMMANDS}.`;\n}\n\n/**\n * The routing notice for a call that was not paid: the limits question when\n * the per-call limit is the code default's zero because nobody has answered\n * it, else the reason and fix for `why`.\n */\nexport function unpaidNotice(\n why: string,\n config: { maxAutoSpend?: string | undefined; sessionBudget?: string | undefined },\n reader: NoticeReader,\n): string | null {\n if (why === 'limit_below_deposit' && config.maxAutoSpend === undefined) {\n return unansweredNotice(shownLimits(config), reader);\n }\n return unpaidSentence(why);\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,MAAM,UAAU,SAAS,UAAU;AACnD,SAAS,YAAY;AAgBd,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;AAG3B,IAAM,yBAAyB;AAK/B,IAAM,qBAAqB,MAAM;AAGxC,IAAM,UAAiD;AAAA,EACrD,iBAAiB;AAAA,EACjB,yBAAyB;AAAA,EACzB,kBAAkB;AACpB;AAGO,SAAS,WAAW,QAA8B;AACvD,SAAO,QAAQ,MAAM,KAAK;AAC5B;AAUO,S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