tenjin-cli 0.1.0-alpha.26 → 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.
- package/README.md +9 -20
- package/dist/alive-3J3CHOQP.js +21 -0
- package/dist/{chunk-WT7DHJNJ.js → chunk-3QJREVMX.js} +5 -7
- package/dist/{chunk-WT7DHJNJ.js.map → chunk-3QJREVMX.js.map} +1 -1
- package/dist/{chunk-BOAI23CX.js → chunk-6KA4HFX5.js} +21 -15
- package/dist/chunk-6KA4HFX5.js.map +1 -0
- package/dist/chunk-6W5GYG3W.js +128 -0
- package/dist/chunk-6W5GYG3W.js.map +1 -0
- package/dist/{chunk-W36HL4TB.js → chunk-7H3RN4WJ.js} +7 -9
- package/dist/{chunk-W36HL4TB.js.map → chunk-7H3RN4WJ.js.map} +1 -1
- package/dist/{chunk-4HAV6IFE.js → chunk-7R37M6WV.js} +5 -7
- package/dist/{chunk-4HAV6IFE.js.map → chunk-7R37M6WV.js.map} +1 -1
- package/dist/{chunk-LAIZ2AQA.js → chunk-A5H3E5QA.js} +2 -2
- package/dist/{update-QXVH2DE7.js → chunk-AO54FM4H.js} +147 -35
- package/dist/chunk-AO54FM4H.js.map +1 -0
- package/dist/{chunk-XMIVHQ35.js → chunk-B2L53TMK.js} +17 -2
- package/dist/{chunk-XMIVHQ35.js.map → chunk-B2L53TMK.js.map} +1 -1
- package/dist/{chunk-YTM7OURD.js → chunk-BRHREK7E.js} +2 -2
- package/dist/{chunk-YLCWI6ZR.js → chunk-DJYAPACT.js} +79 -36
- package/dist/chunk-DJYAPACT.js.map +1 -0
- package/dist/{chunk-OBPZ36HG.js → chunk-DYSDQE7S.js} +92 -5
- package/dist/chunk-DYSDQE7S.js.map +1 -0
- package/dist/{chunk-EJXIK6WY.js → chunk-FQ6DHINU.js} +80 -48
- package/dist/chunk-FQ6DHINU.js.map +1 -0
- package/dist/chunk-FZTSGQVK.js +52 -0
- package/dist/chunk-FZTSGQVK.js.map +1 -0
- package/dist/{chunk-QF4SSCQV.js → chunk-KAMRYUK2.js} +5 -4
- package/dist/chunk-KAMRYUK2.js.map +1 -0
- package/dist/{chunk-ALJRB7NG.js → chunk-MNTQMZJB.js} +8 -8
- package/dist/{chunk-XICKN3CH.js → chunk-QTND6XWJ.js} +160 -80
- package/dist/chunk-QTND6XWJ.js.map +1 -0
- package/dist/chunk-RLPLYUME.js +115 -0
- package/dist/chunk-RLPLYUME.js.map +1 -0
- package/dist/{chunk-ZLD6MJVJ.js → chunk-S4SAZ7OD.js} +1 -1
- package/dist/chunk-S4SAZ7OD.js.map +1 -0
- package/dist/{chunk-5HS54CLI.js → chunk-UEOWNDQG.js} +8 -10
- package/dist/{chunk-5HS54CLI.js.map → chunk-UEOWNDQG.js.map} +1 -1
- package/dist/{chunk-5INS5ZZF.js → chunk-UOW5JXYY.js} +5 -7
- package/dist/{chunk-5INS5ZZF.js.map → chunk-UOW5JXYY.js.map} +1 -1
- package/dist/chunk-VSUHGRVB.js +1455 -0
- package/dist/chunk-VSUHGRVB.js.map +1 -0
- package/dist/{chunk-Z7R2QDX2.js → chunk-W6JX4LYF.js} +50 -7
- package/dist/chunk-W6JX4LYF.js.map +1 -0
- package/dist/{chunk-UDWGT4FX.js → chunk-XVTD7UWR.js} +14 -8
- package/dist/chunk-XVTD7UWR.js.map +1 -0
- package/dist/{chunk-6JIYGYRB.js → chunk-YFJJYHVG.js} +2 -2
- package/dist/{chunk-DI7WHXOZ.js → chunk-ZG6ZZLO7.js} +898 -521
- package/dist/chunk-ZG6ZZLO7.js.map +1 -0
- package/dist/{chunk-OZ3LWLCI.js → chunk-ZO3X5NPG.js} +4 -6
- package/dist/{chunk-OZ3LWLCI.js.map → chunk-ZO3X5NPG.js.map} +1 -1
- package/dist/{chunk-5NUF4BHR.js → chunk-ZP5PV3JB.js} +4 -4
- package/dist/{chunk-HII5HOQV.js → chunk-ZP7AHN7Z.js} +6 -6
- package/dist/{cli-2U5JB7OQ.js → cli-234DNHN6.js} +53 -51
- package/dist/{cli-2U5JB7OQ.js.map → cli-234DNHN6.js.map} +1 -1
- package/dist/{config-44EGO636.js → config-IY2OJCAK.js} +11 -13
- package/dist/{doctor-BD42BBEG.js → doctor-2UZZF44A.js} +275 -250
- package/dist/doctor-2UZZF44A.js.map +1 -0
- package/dist/{env-proxy-KEGEMWKX.js → env-proxy-XL4P73MZ.js} +2 -2
- package/dist/{fund-WQOOUESE.js → fund-RZ2QFULK.js} +92 -36
- package/dist/{fund-WQOOUESE.js.map → fund-RZ2QFULK.js.map} +1 -1
- package/dist/hook-command-PZHKS7ES.js +31 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
- package/dist/hosts/claude/tenjin/.mcp.json +11 -0
- package/dist/hosts/claude/tenjin/hooks/hooks.json +206 -0
- package/dist/index.js +15 -6
- package/dist/index.js.map +1 -1
- package/dist/install-O5FJ5EP3.js +48 -0
- package/dist/{install-identity-4RDWTLJ2.js → install-identity-QM44IQ6Z.js} +7 -7
- package/dist/{install-wallet-USHWL7AX.js → install-wallet-Z52EDLPB.js} +14 -14
- package/dist/{mcp-T5SYCLP7.js → mcp-33HAADDF.js} +557 -118
- package/dist/mcp-33HAADDF.js.map +1 -0
- package/dist/package-RT24HTTP.js +37 -0
- package/dist/{pay-276DSSYG.js → pay-IR2V76FX.js} +16 -16
- package/dist/{payments-TZYLJXK3.js → payments-GFV4HU5R.js} +10 -10
- package/dist/{send-YHDKZPED.js → send-PI4NUA7I.js} +13 -13
- package/dist/{status-X2INT6VD.js → status-ZUHTJK46.js} +10 -9
- package/dist/{status-X2INT6VD.js.map → status-ZUHTJK46.js.map} +1 -1
- package/dist/{status-line-QKDJYZGV.js → status-line-2G5JPQAE.js} +6 -6
- package/dist/uninstall-THKUH5ZT.js +136 -0
- package/dist/uninstall-THKUH5ZT.js.map +1 -0
- package/dist/update-NPZDP24E.js +18 -0
- package/dist/update-NPZDP24E.js.map +1 -0
- package/dist/{wallet-CKKB23D5.js → wallet-53EFH4M5.js} +11 -11
- package/dist/wallet-53EFH4M5.js.map +1 -0
- package/docs/agent-permissions.md +32 -21
- package/package.json +3 -3
- package/dist/chunk-65EJJVT3.js +0 -172
- package/dist/chunk-65EJJVT3.js.map +0 -1
- package/dist/chunk-BOAI23CX.js.map +0 -1
- package/dist/chunk-DI7WHXOZ.js.map +0 -1
- package/dist/chunk-EJXIK6WY.js.map +0 -1
- package/dist/chunk-GHR4BTNJ.js +0 -87
- package/dist/chunk-GHR4BTNJ.js.map +0 -1
- package/dist/chunk-H4BOQLWW.js +0 -99
- package/dist/chunk-H4BOQLWW.js.map +0 -1
- package/dist/chunk-JLEF5WHM.js +0 -132
- package/dist/chunk-JLEF5WHM.js.map +0 -1
- package/dist/chunk-OBPZ36HG.js.map +0 -1
- package/dist/chunk-PM2MOXJ3.js +0 -66
- package/dist/chunk-PM2MOXJ3.js.map +0 -1
- package/dist/chunk-QF4SSCQV.js.map +0 -1
- package/dist/chunk-TGLKKLQG.js +0 -11
- package/dist/chunk-TGLKKLQG.js.map +0 -1
- package/dist/chunk-UDWGT4FX.js.map +0 -1
- package/dist/chunk-VNT3CQFV.js +0 -940
- package/dist/chunk-VNT3CQFV.js.map +0 -1
- package/dist/chunk-XICKN3CH.js.map +0 -1
- package/dist/chunk-YHWBDCGS.js +0 -753
- package/dist/chunk-YHWBDCGS.js.map +0 -1
- package/dist/chunk-YLCWI6ZR.js.map +0 -1
- package/dist/chunk-Z7R2QDX2.js.map +0 -1
- package/dist/chunk-ZLD6MJVJ.js.map +0 -1
- package/dist/doctor-BD42BBEG.js.map +0 -1
- package/dist/hook-command-23LC5NRN.js +0 -32
- package/dist/install-REPLHNU7.js +0 -72
- package/dist/mcp-T5SYCLP7.js.map +0 -1
- package/dist/status-line-wiring-LW4HFRHB.js +0 -31
- package/dist/uninstall-NVTGU7JD.js +0 -175
- package/dist/uninstall-NVTGU7JD.js.map +0 -1
- package/dist/update-QXVH2DE7.js.map +0 -1
- /package/dist/{config-44EGO636.js.map → alive-3J3CHOQP.js.map} +0 -0
- /package/dist/{chunk-LAIZ2AQA.js.map → chunk-A5H3E5QA.js.map} +0 -0
- /package/dist/{chunk-YTM7OURD.js.map → chunk-BRHREK7E.js.map} +0 -0
- /package/dist/{chunk-ALJRB7NG.js.map → chunk-MNTQMZJB.js.map} +0 -0
- /package/dist/{chunk-6JIYGYRB.js.map → chunk-YFJJYHVG.js.map} +0 -0
- /package/dist/{chunk-5NUF4BHR.js.map → chunk-ZP5PV3JB.js.map} +0 -0
- /package/dist/{chunk-HII5HOQV.js.map → chunk-ZP7AHN7Z.js.map} +0 -0
- /package/dist/{env-proxy-KEGEMWKX.js.map → config-IY2OJCAK.js.map} +0 -0
- /package/dist/{hook-command-23LC5NRN.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
- /package/dist/{install-REPLHNU7.js.map → hook-command-PZHKS7ES.js.map} +0 -0
- /package/dist/{install-identity-4RDWTLJ2.js.map → install-O5FJ5EP3.js.map} +0 -0
- /package/dist/{pay-276DSSYG.js.map → install-identity-QM44IQ6Z.js.map} +0 -0
- /package/dist/{install-wallet-USHWL7AX.js.map → install-wallet-Z52EDLPB.js.map} +0 -0
- /package/dist/{status-line-wiring-LW4HFRHB.js.map → package-RT24HTTP.js.map} +0 -0
- /package/dist/{wallet-CKKB23D5.js.map → pay-IR2V76FX.js.map} +0 -0
- /package/dist/{payments-TZYLJXK3.js.map → payments-GFV4HU5R.js.map} +0 -0
- /package/dist/{send-YHDKZPED.js.map → send-PI4NUA7I.js.map} +0 -0
- /package/dist/{status-line-QKDJYZGV.js.map → status-line-2G5JPQAE.js.map} +0 -0
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
# Agent permissions
|
|
2
2
|
|
|
3
|
-
`tenjin install`
|
|
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
|
|
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
|
|
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
|
-
|
|
12
|
+
mcp__plugin_tenjin_router__request allow
|
|
13
|
+
mcp__plugin_tenjin_router__hook deny
|
|
11
14
|
```
|
|
12
15
|
|
|
13
|
-
|
|
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
|
-
|
|
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
|
|
|
@@ -34,7 +37,7 @@ tenjin config set sessionBudget 2.00
|
|
|
34
37
|
|
|
35
38
|
## What bounds a ROUTER payment, on top of that
|
|
36
39
|
|
|
37
|
-
The routing decision comes from a server, and
|
|
40
|
+
The routing decision comes from a server, and each call costs a flat $0.003 from the wallet's channel, paid from deposits of up to $0.25 that count against the limits (the deposit is counted when it leaves the wallet, the fees from it are not counted again): it proposes, it never authorizes. These checks are what keep a wrong or hostile one from being worth anything:
|
|
38
41
|
|
|
39
42
|
- The routing fee is paid only by `tenjin mcp`, with the stock x402 client, and only at exactly $0.003 in USDC on Base over `batch-settlement`. The wallet has one routing channel. When it cannot cover the next fee, the call carries a deposit of up to $0.25, sized down to `maxAutoSpend` while that still covers ten fees ($0.03), and refused below that. A deposit is an automatic payment: it is reserved in `spend.json` before it is signed, so it must fit `maxAutoSpend`, the day's `sessionBudget` and `allowlistCreators` (the router's host is the creator), and it is counted from the moment it is sent, so a lost answer or a killed process leaves it counted; only an answered 4xx or 5xx, on which the server settles nothing, gives it back. The deposit is the spend: the fees come out of it and are not counted again, so the day's running total never refuses one. Each fee still gets the per-payment checks: it has to fit `maxAutoSpend` (a 0 you set, or the 0 that holds until the spend question is answered, refuses it) and pass `allowlistCreators`, and a `sessionBudget` of 0 refuses it. A fee that fails one is not paid, even from a channel that is already funded, and the call takes the free path. Approving the limits at install, where the question names the fee, is what approves it.
|
|
40
43
|
- A routing call that cannot be paid takes the free path: the wallet holds less than the deposit, `tenjin mcp` cannot unlock the wallet without a prompt, a limit refuses the deposit, the payment fails, or the channel is carrying another session's call at that moment. The first such call in a session tells you, in Claude Code's own message line, the reason and the fix (`tenjin wallet fund 0.25`, `TENJIN_WALLET_PASSPHRASE`, or `tenjin doctor`); a busy channel says nothing, and while the router charges no fee the wallet is not touched and nothing is said. The native tools are never blocked for it, and `tenjin doctor` names the same reasons.
|
|
@@ -92,31 +95,39 @@ 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
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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 (
|
|
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
|
-
|
|
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: `
|
|
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
|
-
4. An input that does not fit the spec is refused before anything is sent: 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 or paid.
|
|
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.
|
|
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/`.
|
|
115
126
|
|
|
116
127
|
## What a paid lookup leaves on your machine
|
|
117
128
|
|
|
118
129
|
- Every paid lookup is recorded in `~/.tenjin/paid/ledger.jsonl`: what was sent (masked), who was paid, how much, the settlement transaction, and any files saved.
|
|
119
|
-
- Files a paid lookup returns, and media files a paid third-party service links to, are saved under `~/.tenjin/downloads/`.
|
|
130
|
+
- Files a paid lookup returns, and media files a paid third-party service links to or returns inline as base64 in its JSON, are saved under `~/.tenjin/downloads/`. An inline file is replaced in the result by a note naming where it was saved.
|
|
120
131
|
- When a tool names the fields it returns, your agent gets those fields and the provider's whole response is saved under `~/.tenjin/results/` for a day, at the path the result names.
|
|
121
132
|
- When a seller never confirmed settlement, `tenjin payments reconcile` asks USDC on Base whether the payment was used once it has expired, and one that was never charged goes back to today's limit; the `request` tool does the same for up to three beside each lookup, without waiting for it.
|
|
122
133
|
|
|
@@ -131,9 +142,9 @@ To stop the router without removing anything, `tenjin config set router.enabled
|
|
|
131
142
|
- Slash commands and one-word acknowledgements are never sent at all.
|
|
132
143
|
- The packet is stored on the backend against the decision id, so the lookup your assistant sends next is decided with the context you gave. Expired packets are unreadable after 15 minutes (the route refuses an expired id) and are deleted by the next router request or the daily cleanup, whichever comes first.
|
|
133
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.
|
|
134
|
-
- On
|
|
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.
|
|
135
146
|
|
|
136
|
-
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 `
|
|
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.
|
|
137
148
|
|
|
138
149
|
## Wallet passphrase storage
|
|
139
150
|
|
|
@@ -147,8 +158,8 @@ When your assistant delegates, the task it hands over is routed before the subag
|
|
|
147
158
|
|
|
148
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.
|
|
149
160
|
|
|
150
|
-
A subagent is only redirected or offered a lookup when it is known to have `
|
|
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.
|
|
151
162
|
|
|
152
163
|
## Not the same as `allowlistCreators`
|
|
153
164
|
|
|
154
|
-
`allowlistCreators` is a spend-policy key that restricts which hosts may be paid at all. The permission
|
|
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.
|
|
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": {
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"tenjin": "dist/index.js"
|
|
30
30
|
},
|
|
31
31
|
"engines": {
|
|
32
|
-
"node": ">=
|
|
32
|
+
"node": ">=22.0.0"
|
|
33
33
|
},
|
|
34
34
|
"files": [
|
|
35
35
|
"dist",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"@clack/prompts": "^1.7.0",
|
|
42
42
|
"@eslint/js": "^10",
|
|
43
43
|
"@modelcontextprotocol/sdk": "1.31.0",
|
|
44
|
-
"@types/node": "^
|
|
44
|
+
"@types/node": "^22.20.5",
|
|
45
45
|
"@x402/core": "2.28.0",
|
|
46
46
|
"@x402/evm": "2.28.0",
|
|
47
47
|
"@x402/extensions": "2.28.0",
|
package/dist/chunk-65EJJVT3.js
DELETED
|
@@ -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-DI7WHXOZ.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-65EJJVT3.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,sBAAsB;AAE5B,IAAM,8BAA8B;AAE3C,IAAM,aAAa;AAKnB,IAAM,QAAmC,CAAC,OAAO,WAAW,MAAM;AAG3D,SAAS,eAAe,OAA+B;AAC5D,QAAM,OAAO,MAAM,KAAK,CAAC,UAAU,UAAU,KAAK;AAClD,MAAI,SAAS,QAAW;AACtB,UAAM,IAAI,SAAS,SAAS,uBAAuB,MAAM,KAAK,IAAI,CAAC,UAAU,KAAK,MAAM;AAAA,MACtF,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAqBO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W,OAAO;AAClC,SAAO,YAAY,SAAY,CAAC,IAAI,EAAE,QAAQ;AAChD;AAUA,eAAe,gBACb,OACA,OACA,OAC2B;AAC3B,QAAM,EAAE,MAAM,KAAK,SAAS,IAAI;AAChC,QAAM,OAAgC,EAAE,GAAG,SAAS;AACpD,MAAI,UAAU,OAAW,QAAO,KAAK;AAAA,MAChC,MAAK,aAAa;AACvB,QAAM,OAAO,GAAG,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAAA;AAC7C,QAAM,SAA2B;AAAA,IAC/B;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,GAAI,OAAO,OAAO,YAAY,WAAW,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,EACzE;AACA,MAAI,SAAS,IAAK,QAAO;AACzB,QAAM,OAAO,MAAM,KAAK,IAAI,EACzB,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,IAAM,EAAE,EACtC,MAAM,OAAO,CAAC,EAAE;AACnB,MAAI,QAAQ,QAAS,MAAM,SAAS,MAAM,MAAM,EAAE,MAAM,MAAM,IAAI,MAAO,KAAK;AAC5E,WAAO;AAAA,MACL,GAAG;AAAA,MACH,OAAO,mBAAmB,SAAS,UAAU;AAAA,MAC7C,SAAS;AAAA,IACX;AAAA,EACF;AACA,MAAI;AACF,UAAM,gBAAgB,MAAM,MAAM,IAAI;AAAA,EACxC,SAAS,KAAK;AACZ,WAAO;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/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,kBACpB,WACA,QAC4B;AAC5B,MAAI,cAAc,UAAa,CAAC,QAAQ,KAAK,SAAS,EAAG,QAAO;AAChE,MAAI;AACF,UAAM,OAAO,MAAM,eAAe,WAAW,MAAM;AACnD,QAAI,SAAS,KAAM,QAAO,SAAS,IAAI;AACvC,WAAO,wBAAwB,IAAI,SAAS,IAAI,YAAY;AAAA,EAC9D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,SAAS,YAAuC;AAC9D,QAAM,cAAc,cAAc,UAAU;AAC5C,MAAI,gBAAgB,KAAM,QAAO;AACjC,QAAM,aAAa,UAAU,aAAa,iBAAiB;AAC3D,MAAI,eAAe,UAAa,WAAW,KAAK,gBAAgB,EAAG,QAAO;AAC1E,QAAM,QAAQ,UAAU,aAAa,OAAO;AAC5C,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO,MAAM,KAAK,gBAAgB,IAAI,YAAY;AACpD;AAOA,SAAS,iBAAiB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