tenjin-cli 0.1.0-alpha.26 → 0.1.0-alpha.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/{chunk-ALJRB7NG.js → chunk-2TYQD22Q.js} +8 -6
- package/dist/{chunk-ALJRB7NG.js.map → chunk-2TYQD22Q.js.map} +1 -1
- package/dist/{chunk-W36HL4TB.js → chunk-4L7KMA7P.js} +4 -4
- package/dist/{chunk-UDWGT4FX.js → chunk-5FGO6TYT.js} +13 -5
- package/dist/chunk-5FGO6TYT.js.map +1 -0
- package/dist/{chunk-5HS54CLI.js → chunk-5NEHH2E5.js} +3 -3
- package/dist/{chunk-Z7R2QDX2.js → chunk-64SE3QC5.js} +42 -7
- package/dist/chunk-64SE3QC5.js.map +1 -0
- package/dist/chunk-6ZSGER3A.js +52 -0
- package/dist/chunk-6ZSGER3A.js.map +1 -0
- package/dist/{chunk-QF4SSCQV.js → chunk-AWKQSKUL.js} +4 -3
- package/dist/chunk-AWKQSKUL.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-OZ3LWLCI.js → chunk-DATCR7AU.js} +3 -3
- package/dist/{chunk-65EJJVT3.js → chunk-DSNXKUXI.js} +2 -2
- package/dist/{chunk-HII5HOQV.js → chunk-G4AM2SOL.js} +5 -3
- package/dist/{chunk-HII5HOQV.js.map → chunk-G4AM2SOL.js.map} +1 -1
- package/dist/{chunk-OBPZ36HG.js → chunk-GU4GGKYP.js} +58 -5
- package/dist/chunk-GU4GGKYP.js.map +1 -0
- package/dist/{chunk-VNT3CQFV.js → chunk-H2L33M7F.js} +17 -13
- package/dist/{chunk-VNT3CQFV.js.map → chunk-H2L33M7F.js.map} +1 -1
- package/dist/{chunk-GHR4BTNJ.js → chunk-HC3QEZKT.js} +4 -4
- package/dist/chunk-HC3QEZKT.js.map +1 -0
- package/dist/{chunk-H4BOQLWW.js → chunk-MAQUL5BD.js} +2 -2
- package/dist/{chunk-4HAV6IFE.js → chunk-O7CUHHYU.js} +6 -6
- package/dist/{chunk-4HAV6IFE.js.map → chunk-O7CUHHYU.js.map} +1 -1
- package/dist/{chunk-5INS5ZZF.js → chunk-OHZYNZSD.js} +3 -3
- package/dist/{chunk-YHWBDCGS.js → chunk-PY7MQUKP.js} +20 -18
- package/dist/{chunk-YHWBDCGS.js.map → chunk-PY7MQUKP.js.map} +1 -1
- package/dist/{chunk-ZLD6MJVJ.js → chunk-S4SAZ7OD.js} +1 -1
- package/dist/chunk-S4SAZ7OD.js.map +1 -0
- package/dist/{chunk-WT7DHJNJ.js → chunk-SKQQOEWH.js} +4 -4
- package/dist/{chunk-XICKN3CH.js → chunk-VIOUZW7Z.js} +2 -46
- package/dist/chunk-VIOUZW7Z.js.map +1 -0
- package/dist/{chunk-YTM7OURD.js → chunk-VNNXAYJE.js} +2 -2
- package/dist/{chunk-5NUF4BHR.js → chunk-VXIBZ6W5.js} +3 -3
- package/dist/{chunk-6JIYGYRB.js → chunk-X7I343ZY.js} +2 -2
- package/dist/{chunk-DI7WHXOZ.js → chunk-XVYATBKD.js} +2 -2
- package/dist/{chunk-EJXIK6WY.js → chunk-YKM2ZTA2.js} +56 -22
- package/dist/chunk-YKM2ZTA2.js.map +1 -0
- package/dist/{chunk-YLCWI6ZR.js → chunk-YQOQ6XEI.js} +59 -18
- package/dist/chunk-YQOQ6XEI.js.map +1 -0
- package/dist/{cli-2U5JB7OQ.js → cli-6JNIPZQ6.js} +32 -31
- package/dist/{cli-2U5JB7OQ.js.map → cli-6JNIPZQ6.js.map} +1 -1
- package/dist/{config-44EGO636.js → config-G75YT6NC.js} +11 -10
- package/dist/{doctor-BD42BBEG.js → doctor-3GMDOW4Y.js} +28 -28
- package/dist/{doctor-BD42BBEG.js.map → doctor-3GMDOW4Y.js.map} +1 -1
- package/dist/{env-proxy-KEGEMWKX.js → env-proxy-XL4P73MZ.js} +2 -2
- package/dist/{fund-WQOOUESE.js → fund-3IPR5YRJ.js} +17 -15
- package/dist/{fund-WQOOUESE.js.map → fund-3IPR5YRJ.js.map} +1 -1
- package/dist/{hook-command-23LC5NRN.js → hook-command-ZXX4FT4N.js} +14 -14
- package/dist/index.js +6 -6
- package/dist/index.js.map +1 -1
- package/dist/{install-REPLHNU7.js → install-6OROTYHZ.js} +17 -17
- package/dist/{install-identity-4RDWTLJ2.js → install-identity-PM4AGFFX.js} +7 -6
- package/dist/{install-wallet-USHWL7AX.js → install-wallet-6756NOB5.js} +10 -9
- package/dist/{install-wallet-USHWL7AX.js.map → install-wallet-6756NOB5.js.map} +1 -1
- package/dist/{mcp-T5SYCLP7.js → mcp-33FAAZ7F.js} +503 -77
- package/dist/mcp-33FAAZ7F.js.map +1 -0
- package/dist/{pay-276DSSYG.js → pay-XOYR4PCH.js} +13 -12
- package/dist/{payments-TZYLJXK3.js → payments-UTQDBO7H.js} +8 -7
- package/dist/{payments-TZYLJXK3.js.map → payments-UTQDBO7H.js.map} +1 -1
- package/dist/{send-YHDKZPED.js → send-CVGNOQW3.js} +12 -10
- package/dist/{send-YHDKZPED.js.map → send-CVGNOQW3.js.map} +1 -1
- package/dist/{status-X2INT6VD.js → status-NACN4DGX.js} +10 -8
- package/dist/{status-X2INT6VD.js.map → status-NACN4DGX.js.map} +1 -1
- package/dist/{status-line-QKDJYZGV.js → status-line-3IQKGRUH.js} +6 -5
- package/dist/{status-line-QKDJYZGV.js.map → status-line-3IQKGRUH.js.map} +1 -1
- package/dist/{status-line-wiring-LW4HFRHB.js → status-line-wiring-QXBOOY2T.js} +4 -4
- package/dist/{uninstall-NVTGU7JD.js → uninstall-NYFKSYW4.js} +17 -17
- package/dist/{update-QXVH2DE7.js → update-RJDA5ZY3.js} +7 -16
- package/dist/update-RJDA5ZY3.js.map +1 -0
- package/dist/{wallet-CKKB23D5.js → wallet-B3FVHNTS.js} +10 -9
- package/docs/agent-permissions.md +5 -4
- package/package.json +3 -3
- package/dist/chunk-EJXIK6WY.js.map +0 -1
- package/dist/chunk-GHR4BTNJ.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-UDWGT4FX.js.map +0 -1
- package/dist/chunk-XICKN3CH.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/mcp-T5SYCLP7.js.map +0 -1
- package/dist/update-QXVH2DE7.js.map +0 -1
- /package/dist/{chunk-W36HL4TB.js.map → chunk-4L7KMA7P.js.map} +0 -0
- /package/dist/{chunk-5HS54CLI.js.map → chunk-5NEHH2E5.js.map} +0 -0
- /package/dist/{chunk-OZ3LWLCI.js.map → chunk-DATCR7AU.js.map} +0 -0
- /package/dist/{chunk-65EJJVT3.js.map → chunk-DSNXKUXI.js.map} +0 -0
- /package/dist/{chunk-H4BOQLWW.js.map → chunk-MAQUL5BD.js.map} +0 -0
- /package/dist/{chunk-5INS5ZZF.js.map → chunk-OHZYNZSD.js.map} +0 -0
- /package/dist/{chunk-WT7DHJNJ.js.map → chunk-SKQQOEWH.js.map} +0 -0
- /package/dist/{chunk-YTM7OURD.js.map → chunk-VNNXAYJE.js.map} +0 -0
- /package/dist/{chunk-5NUF4BHR.js.map → chunk-VXIBZ6W5.js.map} +0 -0
- /package/dist/{chunk-6JIYGYRB.js.map → chunk-X7I343ZY.js.map} +0 -0
- /package/dist/{chunk-DI7WHXOZ.js.map → chunk-XVYATBKD.js.map} +0 -0
- /package/dist/{config-44EGO636.js.map → config-G75YT6NC.js.map} +0 -0
- /package/dist/{env-proxy-KEGEMWKX.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
- /package/dist/{hook-command-23LC5NRN.js.map → hook-command-ZXX4FT4N.js.map} +0 -0
- /package/dist/{install-REPLHNU7.js.map → install-6OROTYHZ.js.map} +0 -0
- /package/dist/{install-identity-4RDWTLJ2.js.map → install-identity-PM4AGFFX.js.map} +0 -0
- /package/dist/{pay-276DSSYG.js.map → pay-XOYR4PCH.js.map} +0 -0
- /package/dist/{status-line-wiring-LW4HFRHB.js.map → status-line-wiring-QXBOOY2T.js.map} +0 -0
- /package/dist/{uninstall-NVTGU7JD.js.map → uninstall-NYFKSYW4.js.map} +0 -0
- /package/dist/{wallet-CKKB23D5.js.map → wallet-B3FVHNTS.js.map} +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
package_default
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-HC3QEZKT.js";
|
|
5
5
|
import {
|
|
6
6
|
PRODUCTION_ORIGIN
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-VIOUZW7Z.js";
|
|
8
8
|
import {
|
|
9
9
|
CliError
|
|
10
10
|
} from "./chunk-JLEF5WHM.js";
|
|
@@ -317,4 +317,4 @@ export {
|
|
|
317
317
|
httpRequest,
|
|
318
318
|
fetchFailureToCliError
|
|
319
319
|
};
|
|
320
|
-
//# sourceMappingURL=chunk-
|
|
320
|
+
//# sourceMappingURL=chunk-OHZYNZSD.js.map
|
|
@@ -1,24 +1,21 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
ROUTER_PATH
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-64SE3QC5.js";
|
|
5
5
|
import {
|
|
6
6
|
RECONNECT_FIX,
|
|
7
7
|
readMcpServers
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-MAQUL5BD.js";
|
|
9
9
|
import {
|
|
10
10
|
ensureStatusLine
|
|
11
|
-
} from "./chunk-
|
|
12
|
-
import {
|
|
13
|
-
paint
|
|
14
|
-
} from "./chunk-UDWGT4FX.js";
|
|
11
|
+
} from "./chunk-DSNXKUXI.js";
|
|
15
12
|
import {
|
|
16
13
|
envProxySupported,
|
|
17
14
|
proxyVariable
|
|
18
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-S4SAZ7OD.js";
|
|
19
16
|
import {
|
|
20
17
|
httpRequest
|
|
21
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-OHZYNZSD.js";
|
|
22
19
|
import {
|
|
23
20
|
CLI_SKILL_NAMES,
|
|
24
21
|
RETIRED_SKILL_NAMES,
|
|
@@ -28,7 +25,7 @@ import {
|
|
|
28
25
|
readSkillFile,
|
|
29
26
|
skillFrontmatterName,
|
|
30
27
|
skillsDirsFor
|
|
31
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-H2L33M7F.js";
|
|
32
29
|
import {
|
|
33
30
|
FEE_APPROVAL,
|
|
34
31
|
OWN_LIMITS_COMMANDS,
|
|
@@ -37,7 +34,7 @@ import {
|
|
|
37
34
|
limitsUsd,
|
|
38
35
|
shownLimits,
|
|
39
36
|
spendQuestion
|
|
40
|
-
} from "./chunk-
|
|
37
|
+
} from "./chunk-GU4GGKYP.js";
|
|
41
38
|
import {
|
|
42
39
|
appendAllowlistRules,
|
|
43
40
|
claudeAdapter,
|
|
@@ -45,7 +42,7 @@ import {
|
|
|
45
42
|
inspectHooksFile,
|
|
46
43
|
ownsHookEntry,
|
|
47
44
|
writeHooks
|
|
48
|
-
} from "./chunk-
|
|
45
|
+
} from "./chunk-XVYATBKD.js";
|
|
49
46
|
import {
|
|
50
47
|
HOOK_TOOL,
|
|
51
48
|
hookToolInput
|
|
@@ -58,19 +55,24 @@ import {
|
|
|
58
55
|
askText,
|
|
59
56
|
selectOne
|
|
60
57
|
} from "./chunk-P7LABKCW.js";
|
|
58
|
+
import {
|
|
59
|
+
paint
|
|
60
|
+
} from "./chunk-5FGO6TYT.js";
|
|
61
61
|
import {
|
|
62
62
|
hasCode
|
|
63
63
|
} from "./chunk-2I4QTOLB.js";
|
|
64
64
|
import {
|
|
65
65
|
resolveContextSettings
|
|
66
|
-
} from "./chunk-
|
|
66
|
+
} from "./chunk-G4AM2SOL.js";
|
|
67
67
|
import {
|
|
68
|
-
PRODUCTION_ORIGIN,
|
|
69
|
-
isSameDeployment,
|
|
70
|
-
loadRawConfig,
|
|
71
68
|
parseUsdToAtomic,
|
|
72
69
|
toMoney
|
|
73
|
-
} from "./chunk-
|
|
70
|
+
} from "./chunk-6ZSGER3A.js";
|
|
71
|
+
import {
|
|
72
|
+
PRODUCTION_ORIGIN,
|
|
73
|
+
isSameDeployment,
|
|
74
|
+
loadRawConfig
|
|
75
|
+
} from "./chunk-VIOUZW7Z.js";
|
|
74
76
|
import {
|
|
75
77
|
CliError
|
|
76
78
|
} from "./chunk-JLEF5WHM.js";
|
|
@@ -397,7 +399,7 @@ async function runRouterInstall(args, ctx, deps = {}) {
|
|
|
397
399
|
]
|
|
398
400
|
};
|
|
399
401
|
}
|
|
400
|
-
const { resolveWallet } = await import("./install-wallet-
|
|
402
|
+
const { resolveWallet } = await import("./install-wallet-6756NOB5.js");
|
|
401
403
|
const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? "flag" : void 0, false);
|
|
402
404
|
const effective = await resolveContextSettings(ctx);
|
|
403
405
|
const approval = !canPrompt && args.yes !== true && !spend.kept.includes("maxAutoSpend") ? spendApproval(config, args) : void 0;
|
|
@@ -750,4 +752,4 @@ export {
|
|
|
750
752
|
readMcpEntry,
|
|
751
753
|
statusLineProblems
|
|
752
754
|
};
|
|
753
|
-
//# sourceMappingURL=chunk-
|
|
755
|
+
//# sourceMappingURL=chunk-PY7MQUKP.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/install.ts","../src/lib/skill-placement.ts","../src/router/reachability.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, realpath } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { claudeAdapter } from '../adapters/claude';\nimport { persistRouterDefaults, ROUTER_DEFAULTS, type RouterLimits } from '../commands/config';\nimport { askText, selectOne } from '../lib/clack';\nimport { CliError } from '../lib/errors';\nimport {\n appendAllowlistRules,\n claudeSettingsPath,\n type AppendAllowlistResult,\n} from '../lib/harness-permissions';\nimport {\n inspectHooksFile,\n ownsHookEntry,\n pruneHooks,\n writeHooks,\n type HooksResult,\n} from '../lib/harness-hooks';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { paint } from '../lib/output';\nimport { resolveContextSettings } from '../lib/settings';\nimport type { SpendPolicy } from '../lib/policy';\nimport { removeRetiredSkills } from '../lib/skill-placement';\nimport { loadRawConfig, type PartialConfig } from '../lib/config';\nimport { onPath } from '../lib/skill-wiring';\nimport type { WalletDeps, WalletOutcome } from '../commands/install-wallet';\nimport type { CommandContext, CommandResult } from '../context';\nimport { HOOK_TOOL, hookToolInput, type HookKind } from './hook-tool';\nimport { MCP_SERVER_NAME, REQUEST_TOOL } from './names';\nimport { probeRouter, type RouterCheck } from './reachability';\nimport {\n readMcpServers,\n RECONNECT_FIX,\n type InstalledAt,\n type ListMcpProcesses,\n} from './mcp-processes';\nimport { ensureStatusLine, type StatusLineMode, type StatusLineResult } from './status-line-wiring';\nimport {\n FEE_APPROVAL,\n limitsUsd,\n OWN_LIMITS_COMMANDS,\n ROUTING_FEE_TERMS,\n shownLimits,\n spendQuestion,\n} from './spend-question';\n\n/**\n * `tenjin install` for the router product: seven hook entries, one MCP server,\n * one permission rule, the spend defaults, and a wallet when there is none.\n *\n * WHAT IT WRITES IS WHAT IT SAYS. There is no skill to materialize and no\n * daemon to start: each hook entry is a Claude Code `mcp_tool` hook that calls\n * the `hook` tool of the session's own router MCP server (`tenjin mcp`), which\n * runs the leg and holds the wallet, and every other key in the settings file\n * is preserved byte for byte. The one process a leg starts is the free docs\n * fetch beside a search, which exits within `PREFETCH_TIMEOUT_MS`.\n */\n\nconst exec = promisify(execFile);\n\n/**\n * The harness's kill budget for each routing leg: a stuck server never holds a\n * prompt longer than this. Every wait inside the leg is cut from it: the gate's\n * 3.5 s, which holds the paid path's 402, the reads before a deposit and the\n * paid request, with 500 ms left for the transcript read and the reply\n * (`wire.test.ts` pins the sum). A whole leg whose call carried a deposit took\n * 2.8 to 3.3 s on Base Sepolia, so it fits; a slower one (a wallet unlock, a\n * slow settlement) loses only that prompt's hint, and the SDK recovers the\n * channel on the next call.\n *\n * A machine carrying an older entry is converged by the writer, not by the\n * user: the entries are ours by marker, so `install`, `install --refresh` and\n * the refresh `tenjin update` spawns all rewrite them in place.\n */\nexport const ROUTE_HOOK_TIMEOUT_SECONDS = 5;\n/**\n * The after-call entries' kill budget, longer than the rest for the one wait\n * a leg makes: a search the pre-call leg is fetching free docs for waits up to\n * `AUGMENT_WAIT_MS` (9 s) for them, and when none came back and the search was\n * short, the gate's 3.5 s follow, with startup to spare (`wire.test.ts` pins\n * the sum). Every other after-call event\n * returns as fast as before, so the number is a ceiling, not a cost.\n */\nexport const AFTER_CALL_TIMEOUT_SECONDS = 15;\nexport { MCP_SERVER_NAME };\nexport const ALLOW_RULE = REQUEST_TOOL;\n/**\n * THE HOOK ENTRIES' TOOL IS DENIED TO THE MODEL. Its event fields are plain\n * arguments, so the model calling it could forge a routing leg. A deny rule\n * takes the tool out of the model's tool list in every permission mode,\n * bypass included, while Claude Code's own `mcp_tool` hook calls to it still\n * run (checked on Claude Code 2.1.289). The tool's transcript check\n * (`admitHookEvent`) stays for a settings file without the rule.\n */\nexport const DENY_RULE = `mcp__${MCP_SERVER_NAME}__${HOOK_TOOL}`;\n/**\n * The MCP registration follows the SAME SCOPE the hook entries do. A\n * `--project` install that wrote its hooks into the project and then registered\n * the server at user scope would reach into `~/.claude.json` on a run whose\n * whole point is to touch this project and nothing else, and `tenjin uninstall\n * --project` would leave that behind.\n *\n * Project scope writes `<project>/.mcp.json`, so the registration lives beside\n * the settings file that names the hooks and travels with the repository.\n */\nexport function mcpScope(project: boolean | undefined): 'user' | 'project' {\n return project === true ? 'project' : 'user';\n}\n\nexport function mcpAddCommand(project?: boolean): string {\n return `claude mcp add ${MCP_SERVER_NAME} -s ${mcpScope(project)} -- tenjin mcp`;\n}\n\nexport function mcpRemoveCommand(project?: boolean): string {\n return `claude mcp remove ${MCP_SERVER_NAME} -s ${mcpScope(project)}`;\n}\n\n/** The user-scope form, kept as the name the docs and the tests already use. */\nexport const MCP_ADD_COMMAND = mcpAddCommand();\n\n/**\n * Which settings file this machine's router wiring lives in, spelled once so\n * `install`, `uninstall` and `doctor` can never disagree about where to look.\n * A doctor reading the home file on a `--project` install reported a correctly\n * wired machine as unwired and exited 3.\n */\nexport function routerSettingsPath(\n opts: { project?: boolean; homeDir?: string; cwd?: string } = {},\n): string {\n if (opts.project === true) return join(opts.cwd ?? process.cwd(), '.claude', 'settings.json');\n return claudeSettingsPath(opts.homeDir ?? homedir());\n}\n\n/** The subagent tool, under its current name and its older one. */\nexport const DELEGATION_MATCHER = 'Agent|Task';\n\n/** The native tools both native arms watch. */\nexport const NATIVE_MATCHER = 'WebSearch|WebFetch';\n\n/** The host's question to the user, watched before it is asked and after. */\nexport const ASK_MATCHER = 'AskUserQuestion';\n\n/**\n * The seven entries, spelled once so `uninstall`, `doctor` and the tests read\n * the same list. The native tools are routed twice over one lookup: BEFORE the\n * call, as every release has, with a line pointing to a paid lookup when one\n * fits; and AFTER it, only when it came back short and nothing was said before,\n * or to add the free docs the pre-call arm fetched to a search's results. A\n * failed call fires PostToolUseFailure rather than PostToolUse, so the second\n * takes both. The host's question to the user is routed the same two ways:\n * before it is asked, when a service could stand in for what it asks for, and\n * after, with the user's answers read as their own words.\n */\nexport function routerHookPlan(): unknown[] {\n const leg = (kind: HookKind, timeout = ROUTE_HOOK_TIMEOUT_SECONDS) => [\n {\n type: 'mcp_tool',\n server: MCP_SERVER_NAME,\n tool: HOOK_TOOL,\n input: hookToolInput(kind),\n timeout,\n },\n ];\n const afterCall = () => leg('shortfall', AFTER_CALL_TIMEOUT_SECONDS);\n return [\n { event: 'UserPromptSubmit', hooks: leg('prompt') },\n { event: 'PreToolUse', matcher: NATIVE_MATCHER, hooks: leg('native') },\n { event: 'PreToolUse', matcher: DELEGATION_MATCHER, hooks: leg('agent') },\n { event: 'PostToolUse', matcher: NATIVE_MATCHER, hooks: afterCall() },\n { event: 'PostToolUseFailure', matcher: NATIVE_MATCHER, hooks: afterCall() },\n { event: 'PreToolUse', matcher: ASK_MATCHER, hooks: leg('ask') },\n { event: 'PostToolUse', matcher: ASK_MATCHER, hooks: leg('answer') },\n ];\n}\n\nexport const DISCLOSURE: readonly string[] = [\n \"What leaves this machine: the bounded text of each prompt, each native search query or URL (and, when one came back short, its status, size or error), each task handed to a subagent, and each question your assistant asks you with your answers, sent to Tenjin for the free routing gate, beside this session's id. When the gate offers free library docs for a search, that search query also goes to Tenjin's docs lookup, which asks Context7.\",\n 'What is kept when a lookup is paid: the capability chosen, a hash of the contract, a hash of the arguments, and your wallet address. No prompt text, no arguments, no hint text.',\n 'What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere.',\n];\n\nexport interface RouterInstallArgs {\n /** Write into this project's `.claude/settings.json` instead of your home one. */\n project?: boolean;\n /**\n * Bring the entries this machine ALREADY has up to the running build, and\n * add nothing: no config write, no MCP registration, and a refusal when\n * nothing of ours is here. `tenjin update` spawns exactly this after it swaps\n * the binary, so the flag's name and meaning are a compatibility contract.\n */\n refresh?: boolean;\n /**\n * Accept the limits the question shows instead of asking: the selector's\n * \"Use these limits\", for an agent running the user's yes.\n */\n yes?: boolean;\n /**\n * What to do about Claude Code's `statusLine`. Absent is the default path:\n * write ours when the key is free, and print the composition line when it is\n * not. `compose` wraps the status line already there and appends ours;\n * `skip` leaves the key alone entirely.\n */\n statusLine?: StatusLineMode;\n /** Create no wallet, for CI and scripted machines. */\n noWallet?: boolean;\n}\n\nexport interface RouterInstallDeps extends WalletDeps {\n /** This user's running `tenjin mcp` processes; tests inject them. */\n listMcpProcesses?: ListMcpProcesses;\n /** When this build was installed; tests inject it. */\n installedAt?: InstalledAt;\n homeDir?: string;\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** PATH probe for the `claude` binary. */\n which?: (bin: string) => boolean;\n /** Runs `claude mcp add`; tests inject it so no binary is spawned. The scope\n * and the working directory are passed, because project scope is decided by\n * where the command runs as much as by the flag. */\n registerMcp?: (\n command: string,\n opts: { scope: 'user' | 'project'; cwd: string },\n ) => Promise<void>;\n /** Reads the registration the scope's own file holds; tests inject it. */\n readMcpEntry?: (\n scope: 'user' | 'project',\n cwd: string,\n home: string,\n ) => Promise<{ found: boolean; state: McpEntryState }>;\n /** Whether a person can answer the spend-limit question (a TTY on stdout and\n * stdin, no `--json`); injected in tests. */\n isInteractive?: boolean;\n /** The spend-limit selector; defaults to the clack list. */\n promptLimits?: (message: string) => Promise<LimitsChoice | null>;\n /** One amount question; defaults to the clack text input. */\n promptAmount?: (message: string, placeholder: string) => Promise<string | null>;\n /** The router reachability probe's transport; tests inject it. */\n fetchImpl?: typeof fetch;\n}\n\nexport type LimitsChoice = 'approve' | 'own';\n\nexport interface McpRegistration {\n name: string;\n registered: boolean;\n /** Which scope it went to, following the hook entries rather than the flag\n * being read twice. `project` writes `<project>/.mcp.json`. */\n scope: 'user' | 'project';\n /** The command to run by hand, when this run could not. */\n command: string;\n /**\n * WHAT THIS RUN ACTUALLY DID, which `registered` alone cannot say:\n * `already-registered` (the scope's file already launches `tenjin mcp`, and\n * nothing was spawned), `added`, `repaired` (a same-name entry launching\n * something else was removed and re-added, which only `uninstall` does now),\n * `unrepaired` (a registration this run KNOWS is wrong or unreadable and will\n * not touch) or `unavailable` (it is simply not there and this machine could\n * not add it, e.g. no `claude` on PATH). A refresh fails on `unrepaired`,\n * because reporting convergence over a registration that launches something\n * else is the thing to avoid; it still only prints the manual command for\n * `unavailable`.\n */\n reconciled: 'already-registered' | 'added' | 'repaired' | 'unrepaired' | 'unavailable';\n reason?: string;\n}\n\nasync function inferRefreshProject(\n cwd: string,\n home: string,\n dataDir: string,\n readRegistration: typeof readMcpEntry,\n): Promise<boolean> {\n const hooks = await probeOurEntries(routerSettingsPath({ project: true, cwd }), dataDir);\n if (hooks.state !== 'present') return false;\n const [cwdPath, homePath] = await Promise.all([\n realpath(cwd),\n realpath(home).catch((err: NodeJS.ErrnoException) => {\n // A missing home cannot alias this existing project. Do not require it\n // to exist (or create it) just to refresh the project's own settings.\n if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return null;\n throw err;\n }),\n ]);\n if (cwdPath !== homePath) return true;\n\n // Home shares one hooks file between scopes. Preserve a project-only install,\n // but prefer user scope when both registrations exist (including alpha.18's\n // accidental duplicate). With neither registration, the default is user.\n // Unreadable/conflicting entries stay in their scope so reconciliation refuses\n // them instead of silently creating a registration in the other scope.\n const user = await readRegistration('user', cwd, home);\n if (user.state !== 'absent') return false;\n const project = await readRegistration('project', cwd, home);\n return project.state !== 'absent';\n}\n\nexport async function runRouterInstall(\n args: RouterInstallArgs,\n ctx: CommandContext,\n deps: RouterInstallDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n if (!isAbsolute(home)) {\n throw new CliError('INTERNAL', 'The home directory is not an absolute path.', {\n fix: 'Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`.',\n });\n }\n const config = await loadRawConfig(ctx.dataDir); // Validate before any install writes; retired keys remain readable.\n const cwd = deps.cwd ?? process.cwd();\n // `tenjin update` runs from home, where the hooks file cannot prove scope.\n // An explicit --project still wins, including for a project rooted at home.\n const project =\n args.project ??\n (args.refresh === true &&\n (await inferRefreshProject(cwd, home, ctx.dataDir, deps.readMcpEntry ?? readMcpEntry)));\n const settingsPath = routerSettingsPath({\n ...(project ? { project: true } : {}),\n homeDir: home,\n cwd,\n });\n\n if (args.refresh === true) {\n const probe = await probeOurEntries(settingsPath, ctx.dataDir);\n // An unreadable file is not an absence, and telling someone to install over\n // it is the wrong instruction: the writer would refuse it too.\n if (probe.state === 'unreadable') {\n throw new CliError('CONFIG_INVALID', `Could not inspect ${settingsPath}: ${probe.reason}`, {\n fix: `Fix ${settingsPath}, then re-run: tenjin update`,\n });\n }\n if (probe.state === 'absent') {\n throw new CliError(\n 'REFUSED',\n `Nothing to refresh in ${settingsPath}: no Tenjin hook entries are registered here.`,\n { fix: 'Run `tenjin install` to set this machine up.' },\n );\n }\n }\n // The shelf install's gate: a refresh, `--json`, or a run with no terminal on\n // either side asks nothing. An agent's install is that run: its shell has no\n // terminal. Install then writes no spend limit at all, the same state a\n // person cancelling at the selector leaves, and its output hands the question\n // to whoever ran it (see {@link spendApproval}). Until someone answers, the\n // bare CLI's zero holds and doctor reports the question as pending.\n const humanOutput = ctx.flags.json === true ? false : (deps.isInteractive ?? ctx.io.isTTY);\n const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n // `--yes` is the selector's \"Use these limits\", answered ahead: the same\n // install, run again by an agent for the user's yes.\n const limits =\n args.refresh === true\n ? undefined\n : args.yes === true\n ? shownLimits(config)\n : canPrompt\n ? await approveLimits(config, deps)\n : {};\n const spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true, limits);\n const removedKeysLines =\n spend.removed.length > 0\n ? [\n `Removed retired settings: ${spend.removed.join(', ')}. Automatic router limits remain in effect; manual pay always requires consent.`,\n ]\n : [];\n const removedSkills = await removeRetiredSkills(home, project ? cwd : undefined);\n const hooks = await writeHooks({\n adapter: claudeAdapter,\n homeDir: home,\n dataDir: ctx.dataDir,\n env,\n plan: routerHookPlan(),\n settingsPath,\n });\n const permissions = await ensurePermissionRules(settingsPath);\n const statusLine = await ensureStatusLine(settingsPath, {\n ...(args.statusLine !== undefined ? { mode: args.statusLine } : {}),\n ...(args.refresh === true ? { refreshOnly: true } : {}),\n });\n const mcp = await registerMcpServer(deps, env, project, cwd, home);\n // After the hooks are written: a `tenjin mcp` that started before this\n // install runs the old build, so the new hooks fail there until it restarts.\n // Named, never killed.\n const servers = await readMcpServers(deps);\n const serverLines =\n servers.stale > 0\n ? [paint(ctx.io, 'yellow', `! ${servers.check.detail}. ${RECONNECT_FIX}`)]\n : [];\n if (args.refresh === true) {\n // The SAME writers, minus the one that decides anything: the entries are\n // rewritten in place by their ownership marker so an upgrade never\n // duplicates them, the rule and the registration are re-checked because a\n // new version can change either. Config cleanup only removes retired keys;\n // the wallet, current limits and `spend.json` are unchanged. Widening an agent's spend policy\n // during an unattended upgrade is not a convergence.\n // RECONCILED, not re-added: `claude mcp add` exits 1 on an existing entry,\n // so the registration is read first and only written when it is missing or\n // wrong (see {@link registerMcpServer}).\n // A registration this run KNOWS is wrong and could not repair is not a\n // converged install, and `tenjin update` reporting success over it is how\n // a machine keeps a stale `x402` server across upgrade after upgrade.\n if (mcp.reconciled === 'unrepaired') {\n throw new CliError(\n 'REFUSED',\n `The ${MCP_SERVER_NAME} MCP registration (${mcpScope(project)} scope) is not the router's and this run could not repair it: ${mcp.reason ?? 'unknown reason'}.`,\n { fix: `Run: ${mcp.command}`, details: { settingsPath, hooks, permissions, mcp } },\n );\n }\n return {\n data: {\n settingsPath,\n hooks,\n permissions,\n statusLine,\n mcp,\n refresh: true,\n spend,\n removedSkills,\n scope: mcpScope(project),\n mcpServer: servers.check,\n },\n humanLines: [\n ...refreshLines(ctx, problems(ctx, hooks, permissions, statusLine, mcp)),\n ...removedKeysLines,\n ...serverLines,\n ],\n };\n }\n // The shelf install's wallet step, unchanged except that it never asks: a\n // lookup cannot be paid without a wallet, so install makes one. A failure is\n // reported, never fatal; everything above is useful without it.\n const { resolveWallet } = await import('../commands/install-wallet');\n const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? 'flag' : undefined, false);\n // Read back AFTER the write: a machine that already carried its own caps\n // keeps them, and a readout quoting the defaults would describe limits this\n // run did not set.\n const effective = await resolveContextSettings(ctx);\n const approval =\n !canPrompt && args.yes !== true && !spend.kept.includes('maxAutoSpend')\n ? spendApproval(config, args)\n : undefined;\n // A warning, never a failure: everything above is written and correct, and\n // the network this machine is on now may not be the one it uses later.\n const router = await probeRouter(effective.baseUrl, {\n timeoutMs: ctx.flags.timeout,\n env,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n const data = {\n settingsPath,\n hooks,\n permissions,\n statusLine,\n spend: {\n ...spend,\n effective: effectiveLimits(effective.policy),\n ...(approval !== undefined ? { approval } : {}),\n },\n mcp,\n wallet,\n router: {\n status: router.status === 'ok' ? 'ok' : 'warn',\n detail: router.detail,\n ...(router.fix !== undefined ? { fix: router.fix } : {}),\n },\n disclosure: DISCLOSURE,\n removedSkills,\n mcpServer: servers.check,\n };\n return {\n data,\n humanLines: [\n ...lines(ctx, {\n project,\n hooks,\n permissions,\n statusLine,\n mcp,\n wallet,\n policy: effective.policy,\n ...(approval !== undefined ? { approval } : {}),\n router,\n }),\n ...removedKeysLines,\n ...serverLines,\n ],\n };\n}\n\n/** What turns automatic payment on after an install that left it at zero. */\nconst AUTO_SPEND_FIX = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;\nconst DECLINED =\n 'the router then pays for nothing on its own, and the question stays open until `tenjin install` in a terminal or `tenjin config set` answers it';\n\n/** The spend question an install that could not ask hands to its caller. */\nexport interface SpendApproval {\n /** For the agent to put to the user as written: the limits and the routing fee. */\n question: string;\n /** The limits the question shows, in USD, as the selector shows them. */\n limits: { maxAutoSpend: string; sessionBudget: string };\n /** The routing fee's terms, which a yes also approves. */\n routingFee: string;\n /** What the agent does with each answer. */\n next: string;\n /** The one command for a yes: this install again with `--yes`, as the selector's \"Use these limits\". */\n approve: string;\n /** The commands for limits of the user's own. */\n own: string;\n}\n\n/**\n * An agent runs install with `--json` or in a shell with no terminal, so the\n * CLI cannot ask. The agent can: this is what the selector would have shown\n * (the limits and the routing fee) and what to run for each answer, the same\n * shape as the `request` tool's `needs_input` step. A script or CI ignores\n * it, and the zero holds.\n */\nfunction spendApproval(config: PartialConfig, args: RouterInstallArgs): SpendApproval {\n const limits = shownLimits(config);\n const approve = yesCommand(args);\n return {\n question: spendQuestion(limits),\n limits: limitsUsd(limits),\n routingFee: ROUTING_FEE_TERMS,\n next: `In this session, show the user these limits and ask this question before you change any limit. If they say yes, run the same install again with --yes: \\`${approve}\\`. If they give other amounts, run ${OWN_LIMITS_COMMANDS}. If they say no, run nothing: ${DECLINED}.`,\n approve,\n own: OWN_LIMITS_COMMANDS.replaceAll('`', ''),\n };\n}\n\n/** The install this run was, with `--yes`: what an agent runs for the user's yes. */\nfunction yesCommand(args: RouterInstallArgs): string {\n return [\n 'tenjin install',\n ...(args.project === true ? ['--project'] : []),\n ...(args.noWallet === true ? ['--no-wallet'] : []),\n ...(args.statusLine !== undefined ? [`--status-line ${args.statusLine}`] : []),\n '--yes',\n ].join(' ');\n}\n\n/**\n * The one question install asks, before anything is written: approve the\n * automatic spend limits or set your own. Only a key the file does not already\n * name is asked for, because the write fills absent keys and keeps the rest.\n * The question names the routing fee and its deposits too, and either answer\n * approves it. Cancelling at any step writes nothing.\n */\nasync function approveLimits(\n config: PartialConfig,\n deps: RouterInstallDeps,\n): Promise<RouterLimits | undefined> {\n const shown = shownLimits(config);\n const askCall = config.maxAutoSpend === undefined;\n const askDay = config.sessionBudget === undefined;\n if (!askCall && !askDay) return undefined;\n const daily =\n shown.sessionBudget === 'none'\n ? 'no daily limit'\n : `$${toMoney(shown.sessionBudget).usd} a day`;\n const fee = `\\n${ROUTING_FEE_TERMS}\\n${FEE_APPROVAL}`;\n const choice = await (deps.promptLimits ?? promptLimits)(\n `The router pays for tool calls without asking, up to:\\n $${toMoney(shown.maxAutoSpend).usd} a call, ${daily}${fee}`,\n );\n if (choice === null) throw installCancelled();\n if (choice === 'approve') return shown;\n const ask = deps.promptAmount ?? promptAmount;\n return {\n maxAutoSpend: askCall\n ? await askLimit(ask, 'Most the router may pay for one call, in USD', '0.25', false)\n : shown.maxAutoSpend,\n sessionBudget: askDay\n ? await askLimit(ask, 'Most it may pay in a day, in USD, or none', '5', true)\n : shown.sessionBudget,\n };\n}\n\n/** Asks until the answer is a positive amount (or `none` for the daily limit). */\nasync function askLimit(\n ask: NonNullable<RouterInstallDeps['promptAmount']>,\n question: string,\n placeholder: string,\n allowNone: boolean,\n): Promise<string> {\n let message = question;\n for (;;) {\n const answer = await ask(message, placeholder);\n if (answer === null) throw installCancelled();\n const parsed = parseLimit(answer, allowNone);\n if (!('refusal' in parsed)) return parsed.value;\n message = `${parsed.refusal} ${question}`;\n }\n}\n\n/** Zero is refused: a zero per-call limit means the router can never pay, and\n * `router.enabled false` is how to turn it off. */\nfunction parseLimit(answer: string, allowNone: boolean): { value: string } | { refusal: string } {\n const trimmed = answer.trim();\n if (allowNone && trimmed === 'none') return { value: 'none' };\n let atomic: string;\n try {\n atomic = parseUsdToAtomic(trimmed);\n } catch (err) {\n if (err instanceof CliError) return { refusal: `${err.message}.` };\n throw err;\n }\n if (atomic === '0') return { refusal: 'The limit must be more than zero.' };\n return { value: atomic };\n}\n\nfunction installCancelled(): CliError {\n return new CliError('REFUSED', 'Install cancelled before anything was written.', {\n fix: 'Re-run `tenjin install` and choose the spend limits.',\n });\n}\n\nfunction promptLimits(message: string): Promise<LimitsChoice | null> {\n return selectOne<LimitsChoice>({\n message,\n choices: [\n { value: 'approve', label: 'Use these limits' },\n { value: 'own', label: 'Choose my own' },\n ],\n initialValue: 'approve',\n });\n}\n\nfunction promptAmount(message: string, placeholder: string): Promise<string | null> {\n return askText({ message, placeholder });\n}\n\nexport interface AllowRuleResult {\n path: string;\n rule: string;\n added: boolean;\n /** {@link DENY_RULE}, written to `permissions.deny` beside the allow rule. */\n denyRule: string;\n denyAdded: boolean;\n /** Set when the file could not be written; the rules are then not in force. */\n warning?: string;\n}\n\n/**\n * The two permission rules, through the shared allowlist writer rather than a\n * third hand-rolled one: it resolves a symlinked settings.json before the\n * rename, refuses a file it cannot parse, and compares the bytes it read before\n * committing, none of which a local copy of the merge would have. Each adds\n * only its own rule and keeps every other entry in the list.\n */\nasync function ensurePermissionRules(path: string): Promise<AllowRuleResult> {\n const allow = await appendAllowlistRules(path, [ALLOW_RULE]);\n const deny = await appendAllowlistRules(path, [DENY_RULE], 'deny');\n const warning = writerWarning(allow) ?? writerWarning(deny);\n return {\n path: allow.path,\n rule: ALLOW_RULE,\n added: allow.added.length > 0,\n denyRule: DENY_RULE,\n denyAdded: deny.added.length > 0,\n ...(warning !== undefined ? { warning } : {}),\n };\n}\n\nfunction writerWarning(result: AppendAllowlistResult): string | undefined {\n return (\n result.warning ??\n (result.skipped !== undefined\n ? `${result.path} was left untouched (${result.skipped}).`\n : undefined)\n );\n}\n\n/**\n * RECONCILE, do not re-add blindly. `claude mcp add` is not idempotent: Claude\n * Code 2.1.280 exits 1 on a second identical add with \"MCP server x402 already\n * exists in .mcp.json\". Running it unconditionally therefore reported a\n * perfectly healthy machine as an unregistered one and printed a repair command\n * that would fail the same way, while a same-name entry launching something\n * else never converged, because `add` refuses to overwrite it.\n *\n * So the scope's own file is read first: an entry that already launches\n * `tenjin mcp` is the goal state and nothing is spawned, and a file that cannot\n * be read is refused out loud rather than written over.\n *\n * AN `x402` ENTRY THAT LAUNCHES SOMETHING ELSE IS SOMEBODY ELSE'S. This command\n * will not delete it. It may be another tool of the user's that happens to\n * share the name, and an installer that removes a registration nobody asked it\n * to touch has destroyed configuration to make its own output look tidy. The\n * conflict is reported with the exact two commands to run, and the user decides.\n */\nasync function registerMcpServer(\n deps: RouterInstallDeps,\n env: NodeJS.ProcessEnv,\n project: boolean,\n cwd: string,\n home: string,\n): Promise<McpRegistration> {\n const scope = mcpScope(project);\n const command = mcpAddCommand(project);\n const base = { name: MCP_SERVER_NAME, scope, command };\n const existing = await (deps.readMcpEntry ?? readMcpEntry)(scope, cwd, home);\n if (existing.state === 'ok') {\n return { ...base, registered: true, reconciled: 'already-registered' };\n }\n if (existing.state === 'unreadable') {\n return {\n ...base,\n registered: false,\n reconciled: 'unrepaired',\n reason: `the ${scope}-scope registration file could not be read, so nothing was written over it`,\n };\n }\n // REFUSED, NOT REPLACED. Nothing of the user's is removed to make room.\n if (existing.state === 'wrong-command') {\n return {\n ...base,\n registered: false,\n reconciled: 'unrepaired',\n command: `${mcpRemoveCommand(project)} && ${command}`,\n reason: `an MCP server named ${MCP_SERVER_NAME} is already registered at ${scope} scope and launches something else. This command will not remove a registration it did not write; run the two commands above if that entry is stale`,\n };\n }\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n if (!which('claude')) {\n return {\n ...base,\n registered: false,\n reconciled: 'unavailable',\n reason: 'the `claude` binary is not on PATH',\n };\n }\n try {\n await (deps.registerMcp ?? runClaudeMcpAdd)(command, { scope, cwd });\n return { ...base, registered: true, reconciled: 'added' };\n } catch (err) {\n return {\n ...base,\n registered: false,\n reconciled: 'unavailable',\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nexport type McpEntryState = 'ok' | 'absent' | 'wrong-command' | 'unreadable';\n\n/**\n * What an entry named `x402` actually launches. The name proves nothing: a\n * stale entry pointing at another binary would read as a working request tool.\n */\nexport function classifyMcpEntry(entry: unknown): McpEntryState {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return 'absent';\n const { command, args } = entry as { command?: unknown; args?: unknown };\n if (typeof command !== 'string' || command.length === 0) return 'wrong-command';\n // The basename, so `/opt/homebrew/bin/tenjin` and a bare `tenjin` both pass.\n const binary = command.split(/[\\\\/]/).pop();\n const runsRouter =\n binary === 'tenjin' && Array.isArray(args) && args.length === 1 && args[0] === 'mcp';\n return runsRouter ? 'ok' : 'wrong-command';\n}\n\n/**\n * The file each scope writes: the project's own `.mcp.json`, or the user's\n * `~/.claude.json`. Neither can inherit from the other. Shared by `install`,\n * which reconciles against it, and `doctor`, which reports it.\n */\nexport async function readMcpEntry(\n scope: 'user' | 'project',\n cwd: string,\n home: string,\n): Promise<{ found: boolean; state: McpEntryState }> {\n const path = scope === 'project' ? join(cwd, '.mcp.json') : join(home, '.claude.json');\n // ONLY \"it is not there\" is an absence. A permission or filesystem error on a\n // file that DOES exist says nothing about what is registered in it, and\n // treating it as missing sent the refresh on to `claude mcp add` over a\n // registration it had never read: a failed add then looked like a machine\n // that simply lacks the tooling, and `tenjin update` exited 0 over whatever\n // was actually in there.\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT' || code === 'ENOTDIR') return { found: false, state: 'absent' };\n return { found: true, state: 'unreadable' };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // NOT an absence: the harness's own file is there and unreadable to this\n // build, so neither \"register it\" nor \"it is missing\" is a true statement.\n return { found: true, state: 'unreadable' };\n }\n const servers = (parsed as { mcpServers?: unknown } | null)?.mcpServers;\n if (servers === undefined) return { found: true, state: 'absent' };\n if (servers === null || typeof servers !== 'object' || Array.isArray(servers)) {\n return { found: true, state: 'unreadable' };\n }\n const entry = (servers as Record<string, unknown>)[MCP_SERVER_NAME];\n if (entry === undefined) return { found: true, state: 'absent' };\n return { found: true, state: classifyMcpEntry(entry) };\n}\n\n/** Project scope is decided by the working directory as well as the flag:\n * `claude` writes `.mcp.json` beside the project it was run in. */\nasync function runClaudeMcpAdd(\n _command: string,\n opts: { scope: 'user' | 'project'; cwd: string },\n): Promise<void> {\n await exec('claude', ['mcp', 'add', MCP_SERVER_NAME, '-s', opts.scope, '--', 'tenjin', 'mcp'], {\n timeout: 20_000,\n cwd: opts.cwd,\n });\n}\n\ninterface EffectiveLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\nfunction effectiveLimits(policy: SpendPolicy): EffectiveLimits {\n return {\n maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,\n sessionBudget:\n policy.sessionBudgetAtomic === null\n ? 'no daily ceiling'\n : toMoney(policy.sessionBudgetAtomic.toString()).usd,\n };\n}\n\n/** Only the status-line state that needs the user: one this install would not\n * touch, with the command that adds the footer beside it. */\nexport function statusLineProblems(ctx: CommandContext, result: StatusLineResult): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (result.warning !== undefined) {\n return [warn(`The live status line was not registered (${result.warning})`)];\n }\n if (result.state !== 'foreign') return [];\n return [\n warn('You already have a status line, so it was left exactly as it is.'),\n ' To show the live x402 footer beside it, run:',\n ' tenjin install --status-line compose',\n ...(result.compose === undefined\n ? []\n : [' or set this command yourself:', ` ${result.compose}`]),\n ];\n}\n\n/**\n * A few lines a first-time user can read at a glance: it worked, here is your\n * wallet, here is the one thing to do next. The file paths, entry counts and\n * data-handling detail stay in `--json` and the docs; the terminal only grows\n * a line when something needs the user.\n */\nfunction lines(\n ctx: CommandContext,\n s: {\n project: boolean;\n hooks: HooksResult;\n permissions: AllowRuleResult;\n statusLine: StatusLineResult;\n mcp: McpRegistration;\n wallet: WalletOutcome;\n policy: SpendPolicy;\n approval?: SpendApproval;\n router: RouterCheck;\n },\n): string[] {\n const ok = paint(ctx.io, 'green', '✓');\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const limits = effectiveLimits(s.policy);\n const daily =\n s.policy.sessionBudgetAtomic === null ? 'no daily limit' : `$${limits.sessionBudget} a day`;\n const spend =\n s.approval !== undefined\n ? [\n warn('Automatic payments are off until the user approves a spend limit'),\n ` Ask the user in this session: ${s.approval.question}`,\n ` Yes: ${s.approval.approve}`,\n ` Other amounts: ${s.approval.own}`,\n ` No: run nothing, ${DECLINED.replaceAll('`', '')}`,\n ]\n : s.policy.maxAutoSpendAtomic === 0n\n ? [\n warn('Automatic payments are off: every paid lookup needs your approval'),\n ` To let the router pay without asking, run: ${AUTO_SPEND_FIX}`,\n ]\n : [` Automatic router: up to $${limits.maxAutoSpend} per call; daily limit ${daily}`];\n const router =\n s.router.status === 'ok'\n ? []\n : [\n warn(`The router did not answer: ${s.router.detail}`),\n ...(s.router.fix !== undefined ? [` ${s.router.fix}`] : []),\n ];\n // The first line only says \"set up\" when it is: a settings file this run\n // would not write to means nothing was set up, and hooks without the MCP\n // server point at a `request` tool that is not there.\n const blocked = s.hooks.skipped !== undefined;\n const needsMcp = !blocked && !s.mcp.registered;\n const where = s.project ? ' in this project' : '';\n const fund = paint(ctx.io, 'bold', 'tenjin wallet fund');\n return [\n blocked\n ? paint(ctx.io, 'yellow', `! Tenjin could not finish setting up Claude Code${where}`)\n : needsMcp\n ? paint(ctx.io, 'yellow', '! Almost done: Claude Code needs one command')\n : `${ok} Tenjin is set up for Claude Code${where}`,\n ...walletLines(ctx, ok, s.wallet),\n ...spend,\n ...(s.statusLine.state === 'ours' || s.statusLine.state === 'composed'\n ? [' Live status line on: each lookup names its provider while it runs']\n : []),\n ...problems(ctx, s.hooks, s.permissions, s.statusLine, s.mcp),\n ...router,\n '',\n blocked\n ? 'Next: fix the file above, then run tenjin install again'\n : needsMcp\n ? s.wallet.status === 'created'\n ? `Next: run the command above and ${fund}, then start a new Claude Code session so the hooks and the server load`\n : 'Next: run the command above, then start a new Claude Code session so the hooks and the server load'\n : s.wallet.status === 'created'\n ? `Next: ${fund}, then start a new Claude Code session so the hooks and the server load`\n : 'Next: start a new Claude Code session so the hooks and the server load',\n ];\n}\n\n/** \"Up to date\" only when nothing below it needs the user. */\nfunction refreshLines(ctx: CommandContext, issues: string[]): string[] {\n if (issues.length === 0) return [`${paint(ctx.io, 'green', '✓')} Tenjin is up to date`];\n return [paint(ctx.io, 'yellow', '! Tenjin is updated, but needs one fix'), ...issues];\n}\n\nfunction walletLines(ctx: CommandContext, ok: string, w: WalletOutcome): string[] {\n if (w.status === 'created') return [`${ok} Wallet created: ${w.address}`];\n if (w.status === 'existing') return [`${ok} Wallet: ${w.address}`];\n if (w.reason === 'flag') return [' No wallet yet. Create one with: tenjin wallet create'];\n return [\n paint(ctx.io, 'yellow', `! No wallet was created. ${w.warning ?? ''}`.trimEnd()),\n ` ${w.fix ?? 'Create one with: tenjin wallet create'}`,\n ];\n}\n\n/** Only what needs the user, each with the command that fixes it. */\nfunction problems(\n ctx: CommandContext,\n hooks: HooksResult,\n permissions: AllowRuleResult,\n statusLine: StatusLineResult,\n mcp: McpRegistration,\n): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const out: string[] = [];\n // The hooks and the permission rule share one settings file, so a file this\n // run would not touch is reported once, not once per writer.\n if (hooks.skipped !== undefined) {\n out.push(\n warn(\n hooks.warning ??\n `${hooks.path ?? 'Your Claude Code settings file'} was left untouched (${hooks.skipped}).`,\n ),\n );\n } else {\n if (hooks.warning !== undefined) out.push(warn(hooks.warning));\n if (permissions.warning !== undefined) out.push(warn(permissions.warning));\n }\n if (!mcp.registered) {\n // The reason stays in --json: raw exec output is noise here, the fix is not.\n out.push(warn('Could not add the request tool to Claude Code. Run:'));\n out.push(` ${mcp.command}`);\n }\n out.push(...statusLineProblems(ctx, statusLine));\n return out;\n}\n\n/**\n * THREE ANSWERS, NOT TWO. A settings file that cannot be read or parsed is not\n * a file without our entries, and collapsing the two let `refreshEveryInstall`\n * read a momentarily broken project settings file as confirmed absence and\n * strike the project off `install.routerProjects` for good: repairing the file\n * afterwards did not bring it back, so every later `tenjin update` from HOME\n * silently skipped it.\n */\ntype EntriesProbe =\n { state: 'present' } | { state: 'absent' } | { state: 'unreadable'; reason: string };\n\nasync function probeOurEntries(path: string, dataDir: string): Promise<EntriesProbe> {\n const found = await inspectHooksFile(path);\n if ('refusal' in found) {\n // `unreadable` here is the inspection's own vocabulary for \"the file exists\n // and this build could not use it\"; a file that is simply not there comes\n // back as an empty, readable inspection rather than a refusal.\n return { state: 'unreadable', reason: found.refusal.reason };\n }\n const present = Object.values(found.hooks).some((list) =>\n list.some((entry) => ownsHookEntry(entry, dataDir)),\n );\n return present ? { state: 'present' } : { state: 'absent' };\n}\n\n/** Shared with `uninstall`: the prune this module's writer already performs. */\nexport { pruneHooks };\n","import { lstatSync } from 'node:fs';\nimport { readdir, rm, rmdir } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport {\n CLI_SKILL_NAMES,\n readSkillFile,\n skillFrontmatterName,\n skillsDirsFor,\n} from './skill-wiring';\nimport { RETIRED_SKILL_NAMES, SHIPPED_SKILL_FILES } from './skills-source';\nimport { hasCode } from './errno';\n\nfunction isRealDirectory(path: string): boolean {\n try {\n return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n } catch (err) {\n // Linux reports ENOTDIR when an ancestor is a regular file. Nothing can\n // be installed below it, just as with an absent path. Do not follow symlinks.\n if (hasCode(err, 'ENOENT') || hasCode(err, 'ENOTDIR')) return false;\n throw err;\n }\n}\n\n/**\n * Remove only the files our named skill shipped (SKILL.md last, as the ownership\n * proof), then any directory they leave empty; preserve foreign skills and\n * adjacent user files.\n */\nexport async function removeOwnedSkill(\n name: string,\n skillsDir: string,\n): Promise<{ changed: boolean }> {\n if (!isRealDirectory(skillsDir)) {\n return { changed: false };\n }\n const skillDir = join(skillsDir, name);\n if (!isRealDirectory(skillDir)) {\n return { changed: false };\n }\n const path = join(skillDir, 'SKILL.md');\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return { changed: false };\n if (read.kind !== 'ok' || skillFrontmatterName(read.bytes.toString('utf8')) !== name) {\n return { changed: false }; // not ours to delete for sitting at our path\n }\n const shipped = (SHIPPED_SKILL_FILES as Record<string, readonly string[]>)[name] ?? [];\n const subdirs = new Set<string>();\n for (const rel of shipped) {\n if (rel === 'SKILL.md') continue;\n const file = join(skillDir, rel);\n // A symlinked `references/` would route the delete outside the skill.\n if (!isRealDirectory(dirname(file))) continue;\n subdirs.add(dirname(file));\n if (lstatSync(file, { throwIfNoEntry: false })?.isFile() === true) await rm(file);\n }\n await rm(path, { force: true });\n for (const dir of [...subdirs, skillDir].sort((a, b) => b.length - a.length)) {\n const rest = await readdir(dir).catch(() => null);\n if (rest !== null && rest.length === 0) await rmdir(dir).catch(() => undefined);\n }\n return { changed: true };\n}\n\n/**\n * Refresh retires obsolete skills without needing their old packaged source:\n * the retired names, and the shelf's CLI skills, whose `tenjin search` and\n * `tenjin publish` commands the router CLI does not ship.\n */\nexport async function removeRetiredSkills(home: string, project?: string): Promise<string[]> {\n const removed: string[] = [];\n const dirs = [...skillsDirsFor(home), ...(project ? skillsDirsFor(project) : [])];\n for (const dir of new Set(dirs)) {\n for (const name of [...RETIRED_SKILL_NAMES, ...CLI_SKILL_NAMES]) {\n if ((await removeOwnedSkill(name, dir)).changed) removed.push(join(dir, name));\n }\n }\n return removed;\n}\n","import { envProxySupported, proxyVariable } from '../lib/env-proxy';\nimport { httpRequest, type HttpResponse } from '../lib/http';\nimport { isSameDeployment, PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { ROUTER_PATH } from './decision';\n\nexport interface RouterCheck {\n name: string;\n status: 'ok' | 'warn' | 'fail';\n required: boolean;\n detail: string;\n fix?: string;\n}\n\n/**\n * One cheap request to the free decision route with an empty body. It checks\n * the route is reachable and enabled, not that it routes: a 400 is the route\n * refusing that body, and a 404 is the route switched off. Nothing is signed\n * and no Jev request is spent. `doctor` fails on it; `install` only warns.\n *\n * A refusal is blamed on the layer that sent it. A proxy, firewall or VPN that\n * blocks the host is not the origin asking for credentials, and on the\n * production base URL the fix is never \"set the base URL\", because that is the\n * one setting that is already right.\n */\nexport async function probeRouter(\n baseUrl: string,\n opts: {\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n env?: NodeJS.ProcessEnv;\n /** Test seam; production asks this Node whether it can use the proxy. */\n proxySupported?: boolean;\n },\n): Promise<RouterCheck> {\n const fail = (detail: string, fix: string): RouterCheck => ({\n name: 'router',\n status: 'fail',\n required: true,\n detail,\n fix,\n });\n // `TENJIN_BASE_URL` and `--base-url` reach here unvalidated. A throw would\n // fail an install that has already written everything else.\n let url: string;\n try {\n url = new URL(ROUTER_PATH, baseUrl).toString();\n } catch {\n return fail(\n `the base URL ${JSON.stringify(baseUrl)} is not a URL`,\n `Check TENJIN_BASE_URL, or set it with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n const host = new URL(url).host;\n const probe = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n blockRedirects: true,\n // A reachability check, not use: it must not count this machine as an install.\n anonymous: true,\n jsonBody: {},\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n });\n const production = isSameDeployment(new URL(url).origin, PRODUCTION_ORIGIN);\n const checkBase = production\n ? 'Try again later.'\n : 'Check that the configured base URL names the Tenjin router (`tenjin config get baseUrl`), then try again later.';\n const env = opts.env ?? process.env;\n const network = networkFix(host, env, production, opts.proxySupported ?? envProxySupported());\n const credentials = proxyCredentialsFix(env);\n // Off production, a host that does not resolve or answer is most likely a\n // typo or a dev server that is not running, not a blocked network.\n const unreached = production ? network : checkBase;\n if (!probe.ok) {\n const t = probe.transport;\n if (t?.layer === 'proxy' && t.proxyStatus === 407) {\n return fail(\n `a proxy between this machine and ${host} asked for its own credentials (407)`,\n credentials,\n );\n }\n if (t?.layer === 'proxy') {\n return fail(\n `a proxy refused the connection to ${host} (${t.proxyStatus}), so the router never answered`,\n unreached,\n );\n }\n if (t?.layer === 'dns') {\n return fail(`${host} did not resolve (${t.code}), so the router was not reached`, unreached);\n }\n if (t?.layer === 'tls') {\n return fail(\n `the TLS connection to ${host} failed (${t.code}). A proxy that inspects TLS causes this`,\n `If this network inspects TLS, set NODE_EXTRA_CA_CERTS to its CA certificate. ${unreached}`,\n );\n }\n if (t?.layer === 'connect') {\n return fail(`could not connect to ${host} (${t.code})`, unreached);\n }\n return fail(`the router at ${url} is unreachable or erroring (${probe.message})`, unreached);\n }\n // 429 is the route's own rate limit: proof the router is there.\n if (probe.status === 200 || probe.status === 400 || probe.status === 429) {\n return { name: 'router', status: 'ok', required: true, detail: `${url} is live` };\n }\n if (probe.status === 404) {\n return fail(`the router is not enabled at ${url}`, checkBase);\n }\n if (probe.status === 407) {\n return fail(\n `a proxy between this machine and ${host} asked for its own credentials (407)`,\n credentials,\n );\n }\n if (probe.status === 401 || probe.status === 403) {\n if (!fromDeployment(probe)) {\n return fail(\n `${host} answered ${probe.status} without the headers a Tenjin deployment sends, so a proxy, firewall or VPN on the way most likely refused the request`,\n network,\n );\n }\n if (production) {\n return fail(`${url} refused this machine (${probe.status})`, checkBase);\n }\n return fail(\n `${url} is not a Tenjin router (it asked for credentials)`,\n `Set the router URL with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n if (probe.status >= 500) {\n return fail(`the router at ${url} is unreachable or erroring (${probe.status})`, checkBase);\n }\n return fail(\n `${url} answered ${probe.status}, which a Tenjin router does not`,\n 'Check that the configured base URL names a Tenjin deployment (`tenjin config get baseUrl`).',\n );\n}\n\n/**\n * Did the origin send this, rather than something in front of it? Every Vercel\n * response carries `x-vercel-id` (its own access protection included), and\n * every Tenjin API route adds `x-request-id`. A block page from a proxy,\n * firewall or VPN carries neither.\n */\nfunction fromDeployment(probe: HttpResponse): boolean {\n return probe.header('x-vercel-id') !== undefined || probe.header('x-request-id') !== undefined;\n}\n\nfunction networkFix(\n host: string,\n env: NodeJS.ProcessEnv,\n production: boolean,\n proxySupported: boolean,\n): string {\n const proxy = proxyVariable(env);\n const config = production ? \" Tenjin's own config is correct and needs no change.\" : '';\n if (proxy !== undefined && !proxySupported) {\n return `This shell sets ${proxy}, but Node ${process.versions.node} cannot send Tenjin's requests through it. Upgrade to Node 24.14 or newer, or run from a network that reaches ${host} directly.${config}`;\n }\n const via = proxy !== undefined ? ` (this shell sets ${proxy})` : '';\n return `Allow ${host} through your proxy, firewall or VPN${via}, or run from a network that reaches it.${config}`;\n}\n\nfunction proxyCredentialsFix(env: NodeJS.ProcessEnv): string {\n const proxy = proxyVariable(env) ?? 'HTTPS_PROXY';\n return `Put the proxy's credentials in ${proxy} (\\`http://user:password@proxy:port\\`), then try again.`;\n}\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BAAwB,MAAM,OAAO;AAAA,MAC1F;AAAA,IACF;AAAA,EACF,OAAO;AACL,QAAI,MAAM,YAAY,OAAW,KAAI,KAAK,KAAK,MAAM,OAAO,CAAC;AAC7D,QAAI,YAAY,YAAY,OAAW,KAAI,KAAK,KAAK,YAAY,OAAO,CAAC;AAAA,EAC3E;AACA,MAAI,CAAC,IAAI,YAAY;AAEnB,QAAI,KAAK,KAAK,qDAAqD,CAAC;AACpE,QAAI,KAAK,KAAK,IAAI,OAAO,EAAE;AAAA,EAC7B;AACA,MAAI,KAAK,GAAG,mBAAmB,KAAK,UAAU,CAAC;AAC/C,SAAO;AACT;AAaA,eAAe,gBAAgB,MAAc,SAAwC;AACnF,QAAM,QAAQ,MAAM,iBAAiB,IAAI;AACzC,MAAI,aAAa,OAAO;AAItB,WAAO,EAAE,OAAO,cAAc,QAAQ,MAAM,QAAQ,OAAO;AAAA,EAC7D;AACA,QAAM,UAAU,OAAO,OAAO,MAAM,KAAK,EAAE;AAAA,IAAK,CAAC,SAC/C,KAAK,KAAK,CAAC,UAAU,cAAc,OAAO,OAAO,CAAC;AAAA,EACpD;AACA,SAAO,UAAU,EAAE,OAAO,UAAU,IAAI,EAAE,OAAO,SAAS;AAC5D;","names":["join","join"]}
|
|
1
|
+
{"version":3,"sources":["../src/router/install.ts","../src/lib/skill-placement.ts","../src/router/reachability.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, realpath } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { claudeAdapter } from '../adapters/claude';\nimport { persistRouterDefaults, ROUTER_DEFAULTS, type RouterLimits } from '../commands/config';\nimport { askText, selectOne } from '../lib/clack';\nimport { CliError } from '../lib/errors';\nimport {\n appendAllowlistRules,\n claudeSettingsPath,\n type AppendAllowlistResult,\n} from '../lib/harness-permissions';\nimport {\n inspectHooksFile,\n ownsHookEntry,\n pruneHooks,\n writeHooks,\n type HooksResult,\n} from '../lib/harness-hooks';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { paint } from '../lib/output';\nimport { resolveContextSettings } from '../lib/settings';\nimport type { SpendPolicy } from '../lib/policy';\nimport { removeRetiredSkills } from '../lib/skill-placement';\nimport { loadRawConfig, type PartialConfig } from '../lib/config';\nimport { onPath } from '../lib/skill-wiring';\nimport type { WalletDeps, WalletOutcome } from '../commands/install-wallet';\nimport type { CommandContext, CommandResult } from '../context';\nimport { HOOK_TOOL, hookToolInput, type HookKind } from './hook-tool';\nimport { MCP_SERVER_NAME, REQUEST_TOOL } from './names';\nimport { probeRouter, type RouterCheck } from './reachability';\nimport {\n readMcpServers,\n RECONNECT_FIX,\n type InstalledAt,\n type ListMcpProcesses,\n} from './mcp-processes';\nimport { ensureStatusLine, type StatusLineMode, type StatusLineResult } from './status-line-wiring';\nimport {\n FEE_APPROVAL,\n limitsUsd,\n OWN_LIMITS_COMMANDS,\n ROUTING_FEE_TERMS,\n shownLimits,\n spendQuestion,\n} from './spend-question';\n\n/**\n * `tenjin install` for the router product: seven hook entries, one MCP server,\n * one permission rule, the spend defaults, and a wallet when there is none.\n *\n * WHAT IT WRITES IS WHAT IT SAYS. There is no skill to materialize and no\n * daemon to start: each hook entry is a Claude Code `mcp_tool` hook that calls\n * the `hook` tool of the session's own router MCP server (`tenjin mcp`), which\n * runs the leg and holds the wallet, and every other key in the settings file\n * is preserved byte for byte. The one process a leg starts is the free docs\n * fetch beside a search, which exits within `PREFETCH_TIMEOUT_MS`.\n */\n\nconst exec = promisify(execFile);\n\n/**\n * The harness's kill budget for each routing leg: a stuck server never holds a\n * prompt longer than this. Every wait inside the leg is cut from it: the gate's\n * 3.5 s, which holds the paid path's 402, the reads before a deposit and the\n * paid request, with 500 ms left for the transcript read and the reply\n * (`wire.test.ts` pins the sum). A whole leg whose call carried a deposit took\n * 2.8 to 3.3 s on Base Sepolia, so it fits; a slower one (a wallet unlock, a\n * slow settlement) loses only that prompt's hint, and the SDK recovers the\n * channel on the next call.\n *\n * A machine carrying an older entry is converged by the writer, not by the\n * user: the entries are ours by marker, so `install`, `install --refresh` and\n * the refresh `tenjin update` spawns all rewrite them in place.\n */\nexport const ROUTE_HOOK_TIMEOUT_SECONDS = 5;\n/**\n * The after-call entries' kill budget, longer than the rest for the one wait\n * a leg makes: a search the pre-call leg is fetching free docs for waits up to\n * `AUGMENT_WAIT_MS` (9 s) for them, and when none came back and the search was\n * short, the gate's 3.5 s follow, with startup to spare (`wire.test.ts` pins\n * the sum). Every other after-call event\n * returns as fast as before, so the number is a ceiling, not a cost.\n */\nexport const AFTER_CALL_TIMEOUT_SECONDS = 15;\nexport { MCP_SERVER_NAME };\nexport const ALLOW_RULE = REQUEST_TOOL;\n/**\n * THE HOOK ENTRIES' TOOL IS DENIED TO THE MODEL. Its event fields are plain\n * arguments, so the model calling it could forge a routing leg. A deny rule\n * takes the tool out of the model's tool list in every permission mode,\n * bypass included, while Claude Code's own `mcp_tool` hook calls to it still\n * run (checked on Claude Code 2.1.289). The tool's transcript check\n * (`admitHookEvent`) stays for a settings file without the rule.\n */\nexport const DENY_RULE = `mcp__${MCP_SERVER_NAME}__${HOOK_TOOL}`;\n/**\n * The MCP registration follows the SAME SCOPE the hook entries do. A\n * `--project` install that wrote its hooks into the project and then registered\n * the server at user scope would reach into `~/.claude.json` on a run whose\n * whole point is to touch this project and nothing else, and `tenjin uninstall\n * --project` would leave that behind.\n *\n * Project scope writes `<project>/.mcp.json`, so the registration lives beside\n * the settings file that names the hooks and travels with the repository.\n */\nexport function mcpScope(project: boolean | undefined): 'user' | 'project' {\n return project === true ? 'project' : 'user';\n}\n\nexport function mcpAddCommand(project?: boolean): string {\n return `claude mcp add ${MCP_SERVER_NAME} -s ${mcpScope(project)} -- tenjin mcp`;\n}\n\nexport function mcpRemoveCommand(project?: boolean): string {\n return `claude mcp remove ${MCP_SERVER_NAME} -s ${mcpScope(project)}`;\n}\n\n/** The user-scope form, kept as the name the docs and the tests already use. */\nexport const MCP_ADD_COMMAND = mcpAddCommand();\n\n/**\n * Which settings file this machine's router wiring lives in, spelled once so\n * `install`, `uninstall` and `doctor` can never disagree about where to look.\n * A doctor reading the home file on a `--project` install reported a correctly\n * wired machine as unwired and exited 3.\n */\nexport function routerSettingsPath(\n opts: { project?: boolean; homeDir?: string; cwd?: string } = {},\n): string {\n if (opts.project === true) return join(opts.cwd ?? process.cwd(), '.claude', 'settings.json');\n return claudeSettingsPath(opts.homeDir ?? homedir());\n}\n\n/** The subagent tool, under its current name and its older one. */\nexport const DELEGATION_MATCHER = 'Agent|Task';\n\n/** The native tools both native arms watch. */\nexport const NATIVE_MATCHER = 'WebSearch|WebFetch';\n\n/** The host's question to the user, watched before it is asked and after. */\nexport const ASK_MATCHER = 'AskUserQuestion';\n\n/**\n * The seven entries, spelled once so `uninstall`, `doctor` and the tests read\n * the same list. The native tools are routed twice over one lookup: BEFORE the\n * call, as every release has, with a line pointing to a paid lookup when one\n * fits; and AFTER it, only when it came back short and nothing was said before,\n * or to add the free docs the pre-call arm fetched to a search's results. A\n * failed call fires PostToolUseFailure rather than PostToolUse, so the second\n * takes both. The host's question to the user is routed the same two ways:\n * before it is asked, when a service could stand in for what it asks for, and\n * after, with the user's answers read as their own words.\n */\nexport function routerHookPlan(): unknown[] {\n const leg = (kind: HookKind, timeout = ROUTE_HOOK_TIMEOUT_SECONDS) => [\n {\n type: 'mcp_tool',\n server: MCP_SERVER_NAME,\n tool: HOOK_TOOL,\n input: hookToolInput(kind),\n timeout,\n },\n ];\n const afterCall = () => leg('shortfall', AFTER_CALL_TIMEOUT_SECONDS);\n return [\n { event: 'UserPromptSubmit', hooks: leg('prompt') },\n { event: 'PreToolUse', matcher: NATIVE_MATCHER, hooks: leg('native') },\n { event: 'PreToolUse', matcher: DELEGATION_MATCHER, hooks: leg('agent') },\n { event: 'PostToolUse', matcher: NATIVE_MATCHER, hooks: afterCall() },\n { event: 'PostToolUseFailure', matcher: NATIVE_MATCHER, hooks: afterCall() },\n { event: 'PreToolUse', matcher: ASK_MATCHER, hooks: leg('ask') },\n { event: 'PostToolUse', matcher: ASK_MATCHER, hooks: leg('answer') },\n ];\n}\n\nexport const DISCLOSURE: readonly string[] = [\n \"What leaves this machine: the bounded text of each prompt, each native search query or URL (and, when one came back short, its status, size or error), each task handed to a subagent, and each question your assistant asks you with your answers, sent to Tenjin for the free routing gate, beside this session's id. When the gate offers free library docs for a search, that search query also goes to Tenjin's docs lookup, which asks Context7.\",\n 'What is kept when a lookup is paid: the capability chosen, a hash of the contract, a hash of the arguments, and your wallet address. No prompt text, no arguments, no hint text.',\n 'What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere.',\n];\n\nexport interface RouterInstallArgs {\n /** Write into this project's `.claude/settings.json` instead of your home one. */\n project?: boolean;\n /**\n * Bring the entries this machine ALREADY has up to the running build, and\n * add nothing: no config write, no MCP registration, and a refusal when\n * nothing of ours is here. `tenjin update` spawns exactly this after it swaps\n * the binary, so the flag's name and meaning are a compatibility contract.\n */\n refresh?: boolean;\n /**\n * Accept the limits the question shows instead of asking: the selector's\n * \"Use these limits\", for an agent running the user's yes.\n */\n yes?: boolean;\n /**\n * What to do about Claude Code's `statusLine`. Absent is the default path:\n * write ours when the key is free, and print the composition line when it is\n * not. `compose` wraps the status line already there and appends ours;\n * `skip` leaves the key alone entirely.\n */\n statusLine?: StatusLineMode;\n /** Create no wallet, for CI and scripted machines. */\n noWallet?: boolean;\n}\n\nexport interface RouterInstallDeps extends WalletDeps {\n /** This user's running `tenjin mcp` processes; tests inject them. */\n listMcpProcesses?: ListMcpProcesses;\n /** When this build was installed; tests inject it. */\n installedAt?: InstalledAt;\n homeDir?: string;\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** PATH probe for the `claude` binary. */\n which?: (bin: string) => boolean;\n /** Runs `claude mcp add`; tests inject it so no binary is spawned. The scope\n * and the working directory are passed, because project scope is decided by\n * where the command runs as much as by the flag. */\n registerMcp?: (\n command: string,\n opts: { scope: 'user' | 'project'; cwd: string },\n ) => Promise<void>;\n /** Reads the registration the scope's own file holds; tests inject it. */\n readMcpEntry?: (\n scope: 'user' | 'project',\n cwd: string,\n home: string,\n ) => Promise<{ found: boolean; state: McpEntryState }>;\n /** Whether a person can answer the spend-limit question (a TTY on stdout and\n * stdin, no `--json`); injected in tests. */\n isInteractive?: boolean;\n /** The spend-limit selector; defaults to the clack list. */\n promptLimits?: (message: string) => Promise<LimitsChoice | null>;\n /** One amount question; defaults to the clack text input. */\n promptAmount?: (message: string, placeholder: string) => Promise<string | null>;\n /** The router reachability probe's transport; tests inject it. */\n fetchImpl?: typeof fetch;\n}\n\nexport type LimitsChoice = 'approve' | 'own';\n\nexport interface McpRegistration {\n name: string;\n registered: boolean;\n /** Which scope it went to, following the hook entries rather than the flag\n * being read twice. `project` writes `<project>/.mcp.json`. */\n scope: 'user' | 'project';\n /** The command to run by hand, when this run could not. */\n command: string;\n /**\n * WHAT THIS RUN ACTUALLY DID, which `registered` alone cannot say:\n * `already-registered` (the scope's file already launches `tenjin mcp`, and\n * nothing was spawned), `added`, `repaired` (a same-name entry launching\n * something else was removed and re-added, which only `uninstall` does now),\n * `unrepaired` (a registration this run KNOWS is wrong or unreadable and will\n * not touch) or `unavailable` (it is simply not there and this machine could\n * not add it, e.g. no `claude` on PATH). A refresh fails on `unrepaired`,\n * because reporting convergence over a registration that launches something\n * else is the thing to avoid; it still only prints the manual command for\n * `unavailable`.\n */\n reconciled: 'already-registered' | 'added' | 'repaired' | 'unrepaired' | 'unavailable';\n reason?: string;\n}\n\nasync function inferRefreshProject(\n cwd: string,\n home: string,\n dataDir: string,\n readRegistration: typeof readMcpEntry,\n): Promise<boolean> {\n const hooks = await probeOurEntries(routerSettingsPath({ project: true, cwd }), dataDir);\n if (hooks.state !== 'present') return false;\n const [cwdPath, homePath] = await Promise.all([\n realpath(cwd),\n realpath(home).catch((err: NodeJS.ErrnoException) => {\n // A missing home cannot alias this existing project. Do not require it\n // to exist (or create it) just to refresh the project's own settings.\n if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return null;\n throw err;\n }),\n ]);\n if (cwdPath !== homePath) return true;\n\n // Home shares one hooks file between scopes. Preserve a project-only install,\n // but prefer user scope when both registrations exist (including alpha.18's\n // accidental duplicate). With neither registration, the default is user.\n // Unreadable/conflicting entries stay in their scope so reconciliation refuses\n // them instead of silently creating a registration in the other scope.\n const user = await readRegistration('user', cwd, home);\n if (user.state !== 'absent') return false;\n const project = await readRegistration('project', cwd, home);\n return project.state !== 'absent';\n}\n\nexport async function runRouterInstall(\n args: RouterInstallArgs,\n ctx: CommandContext,\n deps: RouterInstallDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n if (!isAbsolute(home)) {\n throw new CliError('INTERNAL', 'The home directory is not an absolute path.', {\n fix: 'Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`.',\n });\n }\n const config = await loadRawConfig(ctx.dataDir); // Validate before any install writes; retired keys remain readable.\n const cwd = deps.cwd ?? process.cwd();\n // `tenjin update` runs from home, where the hooks file cannot prove scope.\n // An explicit --project still wins, including for a project rooted at home.\n const project =\n args.project ??\n (args.refresh === true &&\n (await inferRefreshProject(cwd, home, ctx.dataDir, deps.readMcpEntry ?? readMcpEntry)));\n const settingsPath = routerSettingsPath({\n ...(project ? { project: true } : {}),\n homeDir: home,\n cwd,\n });\n\n if (args.refresh === true) {\n const probe = await probeOurEntries(settingsPath, ctx.dataDir);\n // An unreadable file is not an absence, and telling someone to install over\n // it is the wrong instruction: the writer would refuse it too.\n if (probe.state === 'unreadable') {\n throw new CliError('CONFIG_INVALID', `Could not inspect ${settingsPath}: ${probe.reason}`, {\n fix: `Fix ${settingsPath}, then re-run: tenjin update`,\n });\n }\n if (probe.state === 'absent') {\n throw new CliError(\n 'REFUSED',\n `Nothing to refresh in ${settingsPath}: no Tenjin hook entries are registered here.`,\n { fix: 'Run `tenjin install` to set this machine up.' },\n );\n }\n }\n // The shelf install's gate: a refresh, `--json`, or a run with no terminal on\n // either side asks nothing. An agent's install is that run: its shell has no\n // terminal. Install then writes no spend limit at all, the same state a\n // person cancelling at the selector leaves, and its output hands the question\n // to whoever ran it (see {@link spendApproval}). Until someone answers, the\n // bare CLI's zero holds and doctor reports the question as pending.\n const humanOutput = ctx.flags.json === true ? false : (deps.isInteractive ?? ctx.io.isTTY);\n const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n // `--yes` is the selector's \"Use these limits\", answered ahead: the same\n // install, run again by an agent for the user's yes.\n const limits =\n args.refresh === true\n ? undefined\n : args.yes === true\n ? shownLimits(config)\n : canPrompt\n ? await approveLimits(config, deps)\n : {};\n const spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true, limits);\n const removedKeysLines =\n spend.removed.length > 0\n ? [\n `Removed retired settings: ${spend.removed.join(', ')}. Automatic router limits remain in effect; manual pay always requires consent.`,\n ]\n : [];\n const removedSkills = await removeRetiredSkills(home, project ? cwd : undefined);\n const hooks = await writeHooks({\n adapter: claudeAdapter,\n homeDir: home,\n dataDir: ctx.dataDir,\n env,\n plan: routerHookPlan(),\n settingsPath,\n });\n const permissions = await ensurePermissionRules(settingsPath);\n const statusLine = await ensureStatusLine(settingsPath, {\n ...(args.statusLine !== undefined ? { mode: args.statusLine } : {}),\n ...(args.refresh === true ? { refreshOnly: true } : {}),\n });\n const mcp = await registerMcpServer(deps, env, project, cwd, home);\n // After the hooks are written: a `tenjin mcp` that started before this\n // install runs the old build, so the new hooks fail there until it restarts.\n // Named, never killed.\n const servers = await readMcpServers(deps);\n const serverLines =\n servers.stale > 0\n ? [paint(ctx.io, 'yellow', `! ${servers.check.detail}. ${RECONNECT_FIX}`)]\n : [];\n if (args.refresh === true) {\n // The SAME writers, minus the one that decides anything: the entries are\n // rewritten in place by their ownership marker so an upgrade never\n // duplicates them, the rule and the registration are re-checked because a\n // new version can change either. Config cleanup only removes retired keys;\n // the wallet, current limits and `spend.json` are unchanged. Widening an agent's spend policy\n // during an unattended upgrade is not a convergence.\n // RECONCILED, not re-added: `claude mcp add` exits 1 on an existing entry,\n // so the registration is read first and only written when it is missing or\n // wrong (see {@link registerMcpServer}).\n // A registration this run KNOWS is wrong and could not repair is not a\n // converged install, and `tenjin update` reporting success over it is how\n // a machine keeps a stale `x402` server across upgrade after upgrade.\n if (mcp.reconciled === 'unrepaired') {\n throw new CliError(\n 'REFUSED',\n `The ${MCP_SERVER_NAME} MCP registration (${mcpScope(project)} scope) is not the router's and this run could not repair it: ${mcp.reason ?? 'unknown reason'}.`,\n { fix: `Run: ${mcp.command}`, details: { settingsPath, hooks, permissions, mcp } },\n );\n }\n return {\n data: {\n settingsPath,\n hooks,\n permissions,\n statusLine,\n mcp,\n refresh: true,\n spend,\n removedSkills,\n scope: mcpScope(project),\n mcpServer: servers.check,\n },\n humanLines: [\n ...refreshLines(ctx, problems(ctx, hooks, permissions, statusLine, mcp)),\n ...removedKeysLines,\n ...serverLines,\n ],\n };\n }\n // The shelf install's wallet step, unchanged except that it never asks: a\n // lookup cannot be paid without a wallet, so install makes one. A failure is\n // reported, never fatal; everything above is useful without it.\n const { resolveWallet } = await import('../commands/install-wallet');\n const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? 'flag' : undefined, false);\n // Read back AFTER the write: a machine that already carried its own caps\n // keeps them, and a readout quoting the defaults would describe limits this\n // run did not set.\n const effective = await resolveContextSettings(ctx);\n const approval =\n !canPrompt && args.yes !== true && !spend.kept.includes('maxAutoSpend')\n ? spendApproval(config, args)\n : undefined;\n // A warning, never a failure: everything above is written and correct, and\n // the network this machine is on now may not be the one it uses later.\n const router = await probeRouter(effective.baseUrl, {\n timeoutMs: ctx.flags.timeout,\n env,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n const data = {\n settingsPath,\n hooks,\n permissions,\n statusLine,\n spend: {\n ...spend,\n effective: effectiveLimits(effective.policy),\n ...(approval !== undefined ? { approval } : {}),\n },\n mcp,\n wallet,\n router: {\n status: router.status === 'ok' ? 'ok' : 'warn',\n detail: router.detail,\n ...(router.fix !== undefined ? { fix: router.fix } : {}),\n },\n disclosure: DISCLOSURE,\n removedSkills,\n mcpServer: servers.check,\n };\n return {\n data,\n humanLines: [\n ...lines(ctx, {\n project,\n hooks,\n permissions,\n statusLine,\n mcp,\n wallet,\n policy: effective.policy,\n ...(approval !== undefined ? { approval } : {}),\n router,\n }),\n ...removedKeysLines,\n ...serverLines,\n ],\n };\n}\n\n/** What turns automatic payment on after an install that left it at zero. */\nconst AUTO_SPEND_FIX = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;\nconst DECLINED =\n 'the router then pays for nothing on its own, and the question stays open until `tenjin install` in a terminal or `tenjin config set` answers it';\n\n/** The spend question an install that could not ask hands to its caller. */\nexport interface SpendApproval {\n /** For the agent to put to the user as written: the limits and the routing fee. */\n question: string;\n /** The limits the question shows, in USD, as the selector shows them. */\n limits: { maxAutoSpend: string; sessionBudget: string };\n /** The routing fee's terms, which a yes also approves. */\n routingFee: string;\n /** What the agent does with each answer. */\n next: string;\n /** The one command for a yes: this install again with `--yes`, as the selector's \"Use these limits\". */\n approve: string;\n /** The commands for limits of the user's own. */\n own: string;\n}\n\n/**\n * An agent runs install with `--json` or in a shell with no terminal, so the\n * CLI cannot ask. The agent can: this is what the selector would have shown\n * (the limits and the routing fee) and what to run for each answer, the same\n * shape as the `request` tool's `needs_input` step. A script or CI ignores\n * it, and the zero holds.\n */\nfunction spendApproval(config: PartialConfig, args: RouterInstallArgs): SpendApproval {\n const limits = shownLimits(config);\n const approve = yesCommand(args);\n return {\n question: spendQuestion(limits),\n limits: limitsUsd(limits),\n routingFee: ROUTING_FEE_TERMS,\n next: `In this session, show the user these limits and ask this question before you change any limit. If they say yes, run the same install again with --yes: \\`${approve}\\`. If they give other amounts, run ${OWN_LIMITS_COMMANDS}. If they say no, run nothing: ${DECLINED}.`,\n approve,\n own: OWN_LIMITS_COMMANDS.replaceAll('`', ''),\n };\n}\n\n/** The install this run was, with `--yes`: what an agent runs for the user's yes. */\nfunction yesCommand(args: RouterInstallArgs): string {\n return [\n 'tenjin install',\n ...(args.project === true ? ['--project'] : []),\n ...(args.noWallet === true ? ['--no-wallet'] : []),\n ...(args.statusLine !== undefined ? [`--status-line ${args.statusLine}`] : []),\n '--yes',\n ].join(' ');\n}\n\n/**\n * The one question install asks, before anything is written: approve the\n * automatic spend limits or set your own. Only a key the file does not already\n * name is asked for, because the write fills absent keys and keeps the rest.\n * The question names the routing fee and its deposits too, and either answer\n * approves it. Cancelling at any step writes nothing.\n */\nasync function approveLimits(\n config: PartialConfig,\n deps: RouterInstallDeps,\n): Promise<RouterLimits | undefined> {\n const shown = shownLimits(config);\n const askCall = config.maxAutoSpend === undefined;\n const askDay = config.sessionBudget === undefined;\n if (!askCall && !askDay) return undefined;\n const daily =\n shown.sessionBudget === 'none'\n ? 'no daily limit'\n : `$${toMoney(shown.sessionBudget).usd} a day`;\n const fee = `\\n${ROUTING_FEE_TERMS}\\n${FEE_APPROVAL}`;\n const choice = await (deps.promptLimits ?? promptLimits)(\n `The router pays for tool calls without asking, up to:\\n $${toMoney(shown.maxAutoSpend).usd} a call, ${daily}${fee}`,\n );\n if (choice === null) throw installCancelled();\n if (choice === 'approve') return shown;\n const ask = deps.promptAmount ?? promptAmount;\n return {\n maxAutoSpend: askCall\n ? await askLimit(ask, 'Most the router may pay for one call, in USD', '0.25', false)\n : shown.maxAutoSpend,\n sessionBudget: askDay\n ? await askLimit(ask, 'Most it may pay in a day, in USD, or none', '5', true)\n : shown.sessionBudget,\n };\n}\n\n/** Asks until the answer is a positive amount (or `none` for the daily limit). */\nasync function askLimit(\n ask: NonNullable<RouterInstallDeps['promptAmount']>,\n question: string,\n placeholder: string,\n allowNone: boolean,\n): Promise<string> {\n let message = question;\n for (;;) {\n const answer = await ask(message, placeholder);\n if (answer === null) throw installCancelled();\n const parsed = parseLimit(answer, allowNone);\n if (!('refusal' in parsed)) return parsed.value;\n message = `${parsed.refusal} ${question}`;\n }\n}\n\n/** Zero is refused: a zero per-call limit means the router can never pay, and\n * `router.enabled false` is how to turn it off. */\nfunction parseLimit(answer: string, allowNone: boolean): { value: string } | { refusal: string } {\n const trimmed = answer.trim();\n if (allowNone && trimmed === 'none') return { value: 'none' };\n let atomic: string;\n try {\n atomic = parseUsdToAtomic(trimmed);\n } catch (err) {\n if (err instanceof CliError) return { refusal: `${err.message}.` };\n throw err;\n }\n if (atomic === '0') return { refusal: 'The limit must be more than zero.' };\n return { value: atomic };\n}\n\nfunction installCancelled(): CliError {\n return new CliError('REFUSED', 'Install cancelled before anything was written.', {\n fix: 'Re-run `tenjin install` and choose the spend limits.',\n });\n}\n\nfunction promptLimits(message: string): Promise<LimitsChoice | null> {\n return selectOne<LimitsChoice>({\n message,\n choices: [\n { value: 'approve', label: 'Use these limits' },\n { value: 'own', label: 'Choose my own' },\n ],\n initialValue: 'approve',\n });\n}\n\nfunction promptAmount(message: string, placeholder: string): Promise<string | null> {\n return askText({ message, placeholder });\n}\n\nexport interface AllowRuleResult {\n path: string;\n rule: string;\n added: boolean;\n /** {@link DENY_RULE}, written to `permissions.deny` beside the allow rule. */\n denyRule: string;\n denyAdded: boolean;\n /** Set when the file could not be written; the rules are then not in force. */\n warning?: string;\n}\n\n/**\n * The two permission rules, through the shared allowlist writer rather than a\n * third hand-rolled one: it resolves a symlinked settings.json before the\n * rename, refuses a file it cannot parse, and compares the bytes it read before\n * committing, none of which a local copy of the merge would have. Each adds\n * only its own rule and keeps every other entry in the list.\n */\nasync function ensurePermissionRules(path: string): Promise<AllowRuleResult> {\n const allow = await appendAllowlistRules(path, [ALLOW_RULE]);\n const deny = await appendAllowlistRules(path, [DENY_RULE], 'deny');\n const warning = writerWarning(allow) ?? writerWarning(deny);\n return {\n path: allow.path,\n rule: ALLOW_RULE,\n added: allow.added.length > 0,\n denyRule: DENY_RULE,\n denyAdded: deny.added.length > 0,\n ...(warning !== undefined ? { warning } : {}),\n };\n}\n\nfunction writerWarning(result: AppendAllowlistResult): string | undefined {\n return (\n result.warning ??\n (result.skipped !== undefined\n ? `${result.path} was left untouched (${result.skipped}).`\n : undefined)\n );\n}\n\n/**\n * RECONCILE, do not re-add blindly. `claude mcp add` is not idempotent: Claude\n * Code 2.1.280 exits 1 on a second identical add with \"MCP server x402 already\n * exists in .mcp.json\". Running it unconditionally therefore reported a\n * perfectly healthy machine as an unregistered one and printed a repair command\n * that would fail the same way, while a same-name entry launching something\n * else never converged, because `add` refuses to overwrite it.\n *\n * So the scope's own file is read first: an entry that already launches\n * `tenjin mcp` is the goal state and nothing is spawned, and a file that cannot\n * be read is refused out loud rather than written over.\n *\n * AN `x402` ENTRY THAT LAUNCHES SOMETHING ELSE IS SOMEBODY ELSE'S. This command\n * will not delete it. It may be another tool of the user's that happens to\n * share the name, and an installer that removes a registration nobody asked it\n * to touch has destroyed configuration to make its own output look tidy. The\n * conflict is reported with the exact two commands to run, and the user decides.\n */\nasync function registerMcpServer(\n deps: RouterInstallDeps,\n env: NodeJS.ProcessEnv,\n project: boolean,\n cwd: string,\n home: string,\n): Promise<McpRegistration> {\n const scope = mcpScope(project);\n const command = mcpAddCommand(project);\n const base = { name: MCP_SERVER_NAME, scope, command };\n const existing = await (deps.readMcpEntry ?? readMcpEntry)(scope, cwd, home);\n if (existing.state === 'ok') {\n return { ...base, registered: true, reconciled: 'already-registered' };\n }\n if (existing.state === 'unreadable') {\n return {\n ...base,\n registered: false,\n reconciled: 'unrepaired',\n reason: `the ${scope}-scope registration file could not be read, so nothing was written over it`,\n };\n }\n // REFUSED, NOT REPLACED. Nothing of the user's is removed to make room.\n if (existing.state === 'wrong-command') {\n return {\n ...base,\n registered: false,\n reconciled: 'unrepaired',\n command: `${mcpRemoveCommand(project)} && ${command}`,\n reason: `an MCP server named ${MCP_SERVER_NAME} is already registered at ${scope} scope and launches something else. This command will not remove a registration it did not write; run the two commands above if that entry is stale`,\n };\n }\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n if (!which('claude')) {\n return {\n ...base,\n registered: false,\n reconciled: 'unavailable',\n reason: 'the `claude` binary is not on PATH',\n };\n }\n try {\n await (deps.registerMcp ?? runClaudeMcpAdd)(command, { scope, cwd });\n return { ...base, registered: true, reconciled: 'added' };\n } catch (err) {\n return {\n ...base,\n registered: false,\n reconciled: 'unavailable',\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nexport type McpEntryState = 'ok' | 'absent' | 'wrong-command' | 'unreadable';\n\n/**\n * What an entry named `x402` actually launches. The name proves nothing: a\n * stale entry pointing at another binary would read as a working request tool.\n */\nexport function classifyMcpEntry(entry: unknown): McpEntryState {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return 'absent';\n const { command, args } = entry as { command?: unknown; args?: unknown };\n if (typeof command !== 'string' || command.length === 0) return 'wrong-command';\n // The basename, so `/opt/homebrew/bin/tenjin` and a bare `tenjin` both pass.\n const binary = command.split(/[\\\\/]/).pop();\n const runsRouter =\n binary === 'tenjin' && Array.isArray(args) && args.length === 1 && args[0] === 'mcp';\n return runsRouter ? 'ok' : 'wrong-command';\n}\n\n/**\n * The file each scope writes: the project's own `.mcp.json`, or the user's\n * `~/.claude.json`. Neither can inherit from the other. Shared by `install`,\n * which reconciles against it, and `doctor`, which reports it.\n */\nexport async function readMcpEntry(\n scope: 'user' | 'project',\n cwd: string,\n home: string,\n): Promise<{ found: boolean; state: McpEntryState }> {\n const path = scope === 'project' ? join(cwd, '.mcp.json') : join(home, '.claude.json');\n // ONLY \"it is not there\" is an absence. A permission or filesystem error on a\n // file that DOES exist says nothing about what is registered in it, and\n // treating it as missing sent the refresh on to `claude mcp add` over a\n // registration it had never read: a failed add then looked like a machine\n // that simply lacks the tooling, and `tenjin update` exited 0 over whatever\n // was actually in there.\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT' || code === 'ENOTDIR') return { found: false, state: 'absent' };\n return { found: true, state: 'unreadable' };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // NOT an absence: the harness's own file is there and unreadable to this\n // build, so neither \"register it\" nor \"it is missing\" is a true statement.\n return { found: true, state: 'unreadable' };\n }\n const servers = (parsed as { mcpServers?: unknown } | null)?.mcpServers;\n if (servers === undefined) return { found: true, state: 'absent' };\n if (servers === null || typeof servers !== 'object' || Array.isArray(servers)) {\n return { found: true, state: 'unreadable' };\n }\n const entry = (servers as Record<string, unknown>)[MCP_SERVER_NAME];\n if (entry === undefined) return { found: true, state: 'absent' };\n return { found: true, state: classifyMcpEntry(entry) };\n}\n\n/** Project scope is decided by the working directory as well as the flag:\n * `claude` writes `.mcp.json` beside the project it was run in. */\nasync function runClaudeMcpAdd(\n _command: string,\n opts: { scope: 'user' | 'project'; cwd: string },\n): Promise<void> {\n await exec('claude', ['mcp', 'add', MCP_SERVER_NAME, '-s', opts.scope, '--', 'tenjin', 'mcp'], {\n timeout: 20_000,\n cwd: opts.cwd,\n });\n}\n\ninterface EffectiveLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\nfunction effectiveLimits(policy: SpendPolicy): EffectiveLimits {\n return {\n maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,\n sessionBudget:\n policy.sessionBudgetAtomic === null\n ? 'no daily ceiling'\n : toMoney(policy.sessionBudgetAtomic.toString()).usd,\n };\n}\n\n/** Only the status-line state that needs the user: one this install would not\n * touch, with the command that adds the footer beside it. */\nexport function statusLineProblems(ctx: CommandContext, result: StatusLineResult): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (result.warning !== undefined) {\n return [warn(`The live status line was not registered (${result.warning})`)];\n }\n if (result.state !== 'foreign') return [];\n return [\n warn('You already have a status line, so it was left exactly as it is.'),\n ' To show the live x402 footer beside it, run:',\n ' tenjin install --status-line compose',\n ...(result.compose === undefined\n ? []\n : [' or set this command yourself:', ` ${result.compose}`]),\n ];\n}\n\n/**\n * A few lines a first-time user can read at a glance: it worked, here is your\n * wallet, here is the one thing to do next. The file paths, entry counts and\n * data-handling detail stay in `--json` and the docs; the terminal only grows\n * a line when something needs the user.\n */\nfunction lines(\n ctx: CommandContext,\n s: {\n project: boolean;\n hooks: HooksResult;\n permissions: AllowRuleResult;\n statusLine: StatusLineResult;\n mcp: McpRegistration;\n wallet: WalletOutcome;\n policy: SpendPolicy;\n approval?: SpendApproval;\n router: RouterCheck;\n },\n): string[] {\n const ok = paint(ctx.io, 'green', '✓');\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const limits = effectiveLimits(s.policy);\n const daily =\n s.policy.sessionBudgetAtomic === null ? 'no daily limit' : `$${limits.sessionBudget} a day`;\n const spend =\n s.approval !== undefined\n ? [\n warn('Automatic payments are off until the user approves a spend limit'),\n ` Ask the user in this session: ${s.approval.question}`,\n ` Yes: ${s.approval.approve}`,\n ` Other amounts: ${s.approval.own}`,\n ` No: run nothing, ${DECLINED.replaceAll('`', '')}`,\n ]\n : s.policy.maxAutoSpendAtomic === 0n\n ? [\n warn('Automatic payments are off: every paid lookup needs your approval'),\n ` To let the router pay without asking, run: ${AUTO_SPEND_FIX}`,\n ]\n : [` Automatic router: up to $${limits.maxAutoSpend} per call; daily limit ${daily}`];\n const router =\n s.router.status === 'ok'\n ? []\n : [\n warn(`The router did not answer: ${s.router.detail}`),\n ...(s.router.fix !== undefined ? [` ${s.router.fix}`] : []),\n ];\n // The first line only says \"set up\" when it is: a settings file this run\n // would not write to means nothing was set up, and hooks without the MCP\n // server point at a `request` tool that is not there.\n const blocked = s.hooks.skipped !== undefined;\n const needsMcp = !blocked && !s.mcp.registered;\n const where = s.project ? ' in this project' : '';\n const fund = paint(ctx.io, 'bold', 'tenjin wallet fund');\n return [\n blocked\n ? paint(ctx.io, 'yellow', `! Tenjin could not finish setting up Claude Code${where}`)\n : needsMcp\n ? paint(ctx.io, 'yellow', '! Almost done: Claude Code needs one command')\n : `${ok} Tenjin is set up for Claude Code${where}`,\n ...walletLines(ctx, ok, s.wallet),\n ...spend,\n ...(s.statusLine.state === 'ours' || s.statusLine.state === 'composed'\n ? [' Live status line on: each lookup names its provider while it runs']\n : []),\n ...problems(ctx, s.hooks, s.permissions, s.statusLine, s.mcp),\n ...router,\n '',\n blocked\n ? 'Next: fix the file above, then run tenjin install again'\n : needsMcp\n ? s.wallet.status === 'created'\n ? `Next: run the command above and ${fund}, then start a new Claude Code session so the hooks and the server load`\n : 'Next: run the command above, then start a new Claude Code session so the hooks and the server load'\n : s.wallet.status === 'created'\n ? `Next: ${fund}, then start a new Claude Code session so the hooks and the server load`\n : 'Next: start a new Claude Code session so the hooks and the server load',\n ];\n}\n\n/** \"Up to date\" only when nothing below it needs the user. */\nfunction refreshLines(ctx: CommandContext, issues: string[]): string[] {\n if (issues.length === 0) return [`${paint(ctx.io, 'green', '✓')} Tenjin is up to date`];\n return [paint(ctx.io, 'yellow', '! Tenjin is updated, but needs one fix'), ...issues];\n}\n\nfunction walletLines(ctx: CommandContext, ok: string, w: WalletOutcome): string[] {\n if (w.status === 'created') return [`${ok} Wallet created: ${w.address}`];\n if (w.status === 'existing') return [`${ok} Wallet: ${w.address}`];\n if (w.reason === 'flag') return [' No wallet yet. Create one with: tenjin wallet create'];\n return [\n paint(ctx.io, 'yellow', `! No wallet was created. ${w.warning ?? ''}`.trimEnd()),\n ` ${w.fix ?? 'Create one with: tenjin wallet create'}`,\n ];\n}\n\n/** Only what needs the user, each with the command that fixes it. */\nfunction problems(\n ctx: CommandContext,\n hooks: HooksResult,\n permissions: AllowRuleResult,\n statusLine: StatusLineResult,\n mcp: McpRegistration,\n): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const out: string[] = [];\n // The hooks and the permission rule share one settings file, so a file this\n // run would not touch is reported once, not once per writer.\n if (hooks.skipped !== undefined) {\n out.push(\n warn(\n hooks.warning ??\n `${hooks.path ?? 'Your Claude Code settings file'} was left untouched (${hooks.skipped}).`,\n ),\n );\n } else {\n if (hooks.warning !== undefined) out.push(warn(hooks.warning));\n if (permissions.warning !== undefined) out.push(warn(permissions.warning));\n }\n if (!mcp.registered) {\n // The reason stays in --json: raw exec output is noise here, the fix is not.\n out.push(warn('Could not add the request tool to Claude Code. Run:'));\n out.push(` ${mcp.command}`);\n }\n out.push(...statusLineProblems(ctx, statusLine));\n return out;\n}\n\n/**\n * THREE ANSWERS, NOT TWO. A settings file that cannot be read or parsed is not\n * a file without our entries, and collapsing the two let `refreshEveryInstall`\n * read a momentarily broken project settings file as confirmed absence and\n * strike the project off `install.routerProjects` for good: repairing the file\n * afterwards did not bring it back, so every later `tenjin update` from HOME\n * silently skipped it.\n */\ntype EntriesProbe =\n { state: 'present' } | { state: 'absent' } | { state: 'unreadable'; reason: string };\n\nasync function probeOurEntries(path: string, dataDir: string): Promise<EntriesProbe> {\n const found = await inspectHooksFile(path);\n if ('refusal' in found) {\n // `unreadable` here is the inspection's own vocabulary for \"the file exists\n // and this build could not use it\"; a file that is simply not there comes\n // back as an empty, readable inspection rather than a refusal.\n return { state: 'unreadable', reason: found.refusal.reason };\n }\n const present = Object.values(found.hooks).some((list) =>\n list.some((entry) => ownsHookEntry(entry, dataDir)),\n );\n return present ? { state: 'present' } : { state: 'absent' };\n}\n\n/** Shared with `uninstall`: the prune this module's writer already performs. */\nexport { pruneHooks };\n","import { lstatSync } from 'node:fs';\nimport { readdir, rm, rmdir } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport {\n CLI_SKILL_NAMES,\n readSkillFile,\n skillFrontmatterName,\n skillsDirsFor,\n} from './skill-wiring';\nimport { RETIRED_SKILL_NAMES, SHIPPED_SKILL_FILES } from './skills-source';\nimport { hasCode } from './errno';\n\nfunction isRealDirectory(path: string): boolean {\n try {\n return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n } catch (err) {\n // Linux reports ENOTDIR when an ancestor is a regular file. Nothing can\n // be installed below it, just as with an absent path. Do not follow symlinks.\n if (hasCode(err, 'ENOENT') || hasCode(err, 'ENOTDIR')) return false;\n throw err;\n }\n}\n\n/**\n * Remove only the files our named skill shipped (SKILL.md last, as the ownership\n * proof), then any directory they leave empty; preserve foreign skills and\n * adjacent user files.\n */\nexport async function removeOwnedSkill(\n name: string,\n skillsDir: string,\n): Promise<{ changed: boolean }> {\n if (!isRealDirectory(skillsDir)) {\n return { changed: false };\n }\n const skillDir = join(skillsDir, name);\n if (!isRealDirectory(skillDir)) {\n return { changed: false };\n }\n const path = join(skillDir, 'SKILL.md');\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return { changed: false };\n if (read.kind !== 'ok' || skillFrontmatterName(read.bytes.toString('utf8')) !== name) {\n return { changed: false }; // not ours to delete for sitting at our path\n }\n const shipped = (SHIPPED_SKILL_FILES as Record<string, readonly string[]>)[name] ?? [];\n const subdirs = new Set<string>();\n for (const rel of shipped) {\n if (rel === 'SKILL.md') continue;\n const file = join(skillDir, rel);\n // A symlinked `references/` would route the delete outside the skill.\n if (!isRealDirectory(dirname(file))) continue;\n subdirs.add(dirname(file));\n if (lstatSync(file, { throwIfNoEntry: false })?.isFile() === true) await rm(file);\n }\n await rm(path, { force: true });\n for (const dir of [...subdirs, skillDir].sort((a, b) => b.length - a.length)) {\n const rest = await readdir(dir).catch(() => null);\n if (rest !== null && rest.length === 0) await rmdir(dir).catch(() => undefined);\n }\n return { changed: true };\n}\n\n/**\n * Refresh retires obsolete skills without needing their old packaged source:\n * the retired names, and the shelf's CLI skills, whose `tenjin search` and\n * `tenjin publish` commands the router CLI does not ship.\n */\nexport async function removeRetiredSkills(home: string, project?: string): Promise<string[]> {\n const removed: string[] = [];\n const dirs = [...skillsDirsFor(home), ...(project ? skillsDirsFor(project) : [])];\n for (const dir of new Set(dirs)) {\n for (const name of [...RETIRED_SKILL_NAMES, ...CLI_SKILL_NAMES]) {\n if ((await removeOwnedSkill(name, dir)).changed) removed.push(join(dir, name));\n }\n }\n return removed;\n}\n","import { envProxySupported, proxyVariable } from '../lib/env-proxy';\nimport { httpRequest, type HttpResponse } from '../lib/http';\nimport { isSameDeployment, PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { ROUTER_PATH } from './decision';\n\nexport interface RouterCheck {\n name: string;\n status: 'ok' | 'warn' | 'fail';\n required: boolean;\n detail: string;\n fix?: string;\n}\n\n/**\n * One cheap request to the free decision route with an empty body. It checks\n * the route is reachable and enabled, not that it routes: a 400 is the route\n * refusing that body, and a 404 is the route switched off. Nothing is signed\n * and no Jev request is spent. `doctor` fails on it; `install` only warns.\n *\n * A refusal is blamed on the layer that sent it. A proxy, firewall or VPN that\n * blocks the host is not the origin asking for credentials, and on the\n * production base URL the fix is never \"set the base URL\", because that is the\n * one setting that is already right.\n */\nexport async function probeRouter(\n baseUrl: string,\n opts: {\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n env?: NodeJS.ProcessEnv;\n /** Test seam; production asks this Node whether it can use the proxy. */\n proxySupported?: boolean;\n },\n): Promise<RouterCheck> {\n const fail = (detail: string, fix: string): RouterCheck => ({\n name: 'router',\n status: 'fail',\n required: true,\n detail,\n fix,\n });\n // `TENJIN_BASE_URL` and `--base-url` reach here unvalidated. A throw would\n // fail an install that has already written everything else.\n let url: string;\n try {\n url = new URL(ROUTER_PATH, baseUrl).toString();\n } catch {\n return fail(\n `the base URL ${JSON.stringify(baseUrl)} is not a URL`,\n `Check TENJIN_BASE_URL, or set it with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n const host = new URL(url).host;\n const probe = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n blockRedirects: true,\n // A reachability check, not use: it must not count this machine as an install.\n anonymous: true,\n jsonBody: {},\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n });\n const production = isSameDeployment(new URL(url).origin, PRODUCTION_ORIGIN);\n const checkBase = production\n ? 'Try again later.'\n : 'Check that the configured base URL names the Tenjin router (`tenjin config get baseUrl`), then try again later.';\n const env = opts.env ?? process.env;\n const network = networkFix(host, env, production, opts.proxySupported ?? envProxySupported());\n const credentials = proxyCredentialsFix(env);\n // Off production, a host that does not resolve or answer is most likely a\n // typo or a dev server that is not running, not a blocked network.\n const unreached = production ? network : checkBase;\n if (!probe.ok) {\n const t = probe.transport;\n if (t?.layer === 'proxy' && t.proxyStatus === 407) {\n return fail(\n `a proxy between this machine and ${host} asked for its own credentials (407)`,\n credentials,\n );\n }\n if (t?.layer === 'proxy') {\n return fail(\n `a proxy refused the connection to ${host} (${t.proxyStatus}), so the router never answered`,\n unreached,\n );\n }\n if (t?.layer === 'dns') {\n return fail(`${host} did not resolve (${t.code}), so the router was not reached`, unreached);\n }\n if (t?.layer === 'tls') {\n return fail(\n `the TLS connection to ${host} failed (${t.code}). A proxy that inspects TLS causes this`,\n `If this network inspects TLS, set NODE_EXTRA_CA_CERTS to its CA certificate. ${unreached}`,\n );\n }\n if (t?.layer === 'connect') {\n return fail(`could not connect to ${host} (${t.code})`, unreached);\n }\n return fail(`the router at ${url} is unreachable or erroring (${probe.message})`, unreached);\n }\n // 429 is the route's own rate limit: proof the router is there.\n if (probe.status === 200 || probe.status === 400 || probe.status === 429) {\n return { name: 'router', status: 'ok', required: true, detail: `${url} is live` };\n }\n if (probe.status === 404) {\n return fail(`the router is not enabled at ${url}`, checkBase);\n }\n if (probe.status === 407) {\n return fail(\n `a proxy between this machine and ${host} asked for its own credentials (407)`,\n credentials,\n );\n }\n if (probe.status === 401 || probe.status === 403) {\n if (!fromDeployment(probe)) {\n return fail(\n `${host} answered ${probe.status} without the headers a Tenjin deployment sends, so a proxy, firewall or VPN on the way most likely refused the request`,\n network,\n );\n }\n if (production) {\n return fail(`${url} refused this machine (${probe.status})`, checkBase);\n }\n return fail(\n `${url} is not a Tenjin router (it asked for credentials)`,\n `Set the router URL with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n if (probe.status >= 500) {\n return fail(`the router at ${url} is unreachable or erroring (${probe.status})`, checkBase);\n }\n return fail(\n `${url} answered ${probe.status}, which a Tenjin router does not`,\n 'Check that the configured base URL names a Tenjin deployment (`tenjin config get baseUrl`).',\n );\n}\n\n/**\n * Did the origin send this, rather than something in front of it? Every Vercel\n * response carries `x-vercel-id` (its own access protection included), and\n * every Tenjin API route adds `x-request-id`. A block page from a proxy,\n * firewall or VPN carries neither.\n */\nfunction fromDeployment(probe: HttpResponse): boolean {\n return probe.header('x-vercel-id') !== undefined || probe.header('x-request-id') !== undefined;\n}\n\nfunction networkFix(\n host: string,\n env: NodeJS.ProcessEnv,\n production: boolean,\n proxySupported: boolean,\n): string {\n const proxy = proxyVariable(env);\n const config = production ? \" Tenjin's own config is correct and needs no change.\" : '';\n if (proxy !== undefined && !proxySupported) {\n return `This shell sets ${proxy}, but Node ${process.versions.node} cannot send Tenjin's requests through it. Upgrade to Node 24.14 or newer, or run from a network that reaches ${host} directly.${config}`;\n }\n const via = proxy !== undefined ? ` (this shell sets ${proxy})` : '';\n return `Allow ${host} through your proxy, firewall or VPN${via}, or run from a network that reaches it.${config}`;\n}\n\nfunction proxyCredentialsFix(env: NodeJS.ProcessEnv): string {\n const proxy = proxyVariable(env) ?? 'HTTPS_PROXY';\n return `Put the proxy's credentials in ${proxy} (\\`http://user:password@proxy:port\\`), then try again.`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,gBAAgB;AACnC,SAAS,eAAe;AACxB,SAAS,YAAY,QAAAA,aAAY;AACjC,SAAS,iBAAiB;;;ACJ1B,SAAS,iBAAiB;AAC1B,SAAS,SAAS,IAAI,aAAa;AACnC,SAAS,SAAS,YAAY;AAU9B,SAAS,gBAAgB,MAAuB;AAC9C,MAAI;AACF,WAAO,UAAU,MAAM,EAAE,gBAAgB,MAAM,CAAC,GAAG,YA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A,eAAe,gBAAgB,MAAc,SAAwC;AACnF,QAAM,QAAQ,MAAM,iBAAiB,IAAI;AACzC,MAAI,aAAa,OAAO;AAItB,WAAO,EAAE,OAAO,cAAc,QAAQ,MAAM,QAAQ,OAAO;AAAA,EAC7D;AACA,QAAM,UAAU,OAAO,OAAO,MAAM,KAAK,EAAE;AAAA,IAAK,CAAC,SAC/C,KAAK,KAAK,CAAC,UAAU,cAAc,OAAO,OAAO,CAAC;AAAA,EACpD;AACA,SAAO,UAAU,EAAE,OAAO,UAAU,IAAI,EAAE,OAAO,SAAS;AAC5D;","names":["join","join"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/env-proxy.ts"],"sourcesContent":["import * as http from 'node:http';\n\n/** Named, never quoted: a proxy URL can carry its own credentials. */\nexport const PROXY_VARIABLES = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'] as const;\n\ntype SetGlobalProxy = (env: NodeJS.ProcessEnv) => () => void;\n\n/** Node 24.14 added it. `engines` admits 22.0, where it is absent. */\nconst nodeSetGlobalProxy = (http as { setGlobalProxyFromEnv?: SetGlobalProxy })\n .setGlobalProxyFromEnv;\n\n/** The first proxy variable this environment sets, or undefined. */\nexport function proxyVariable(env: NodeJS.ProcessEnv): string | undefined {\n return PROXY_VARIABLES.find((name) => (env[name] ?? '') !== '');\n}\n\n/** Can this Node route `fetch` through the proxy the environment names? */\nexport function envProxySupported(setGlobal: unknown = nodeSetGlobalProxy): boolean {\n return typeof setGlobal === 'function';\n}\n\nexport type EnvProxyResult = 'none' | 'set' | 'unsupported' | 'invalid';\n\n/**\n * Send `fetch` and `https.request` through the proxy the environment names.\n * Node's `fetch` ignores HTTPS_PROXY, HTTP_PROXY and NO_PROXY unless\n * NODE_USE_ENV_PROXY=1, so on a network where the proxy is the only way out the\n * harness reaches the internet and Tenjin does not. Called once by the bin\n * entry, so the CLI, the hooks and `tenjin mcp` all get it. Never throws: a\n * proxy URL Node cannot parse leaves the transport as it was.\n */\nexport function useEnvProxy(\n env: NodeJS.ProcessEnv,\n setGlobal: SetGlobalProxy | null = nodeSetGlobalProxy ?? null,\n): EnvProxyResult {\n if (proxyVariable(env) === undefined) return 'none';\n if (typeof setGlobal !== 'function') return 'unsupported';\n try {\n setGlobal(env);\n return 'set';\n } catch {\n return 'invalid';\n }\n}\n"],"mappings":";;;AAAA,YAAY,UAAU;AAGf,IAAM,kBAAkB,CAAC,eAAe,eAAe,cAAc,YAAY;AAKxF,IAAM,qBACH;AAGI,SAAS,cAAc,KAA4C;AACxE,SAAO,gBAAgB,KAAK,CAAC,UAAU,IAAI,IAAI,KAAK,QAAQ,EAAE;AAChE;AAGO,SAAS,kBAAkB,YAAqB,oBAA6B;AAClF,SAAO,OAAO,cAAc;AAC9B;AAYO,SAAS,YACd,KACA,YAAmC,sBAAsB,MACzC;AAChB,MAAI,cAAc,GAAG,MAAM,OAAW,QAAO;AAC7C,MAAI,OAAO,cAAc,WAAY,QAAO;AAC5C,MAAI;AACF,cAAU,GAAG;AACb,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
setTenjinIdentity
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-OHZYNZSD.js";
|
|
5
5
|
import {
|
|
6
6
|
hasCode
|
|
7
7
|
} from "./chunk-2I4QTOLB.js";
|
|
8
8
|
import {
|
|
9
9
|
isTeamModeConfig
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-G4AM2SOL.js";
|
|
11
11
|
import {
|
|
12
12
|
knownDeploymentOrigins,
|
|
13
13
|
loadRawConfig,
|
|
14
14
|
resolveSettings
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-VIOUZW7Z.js";
|
|
16
16
|
import {
|
|
17
17
|
writeFileAtomicExclusive
|
|
18
18
|
} from "./chunk-JLEF5WHM.js";
|
|
@@ -109,4 +109,4 @@ export {
|
|
|
109
109
|
enableCliIdentity,
|
|
110
110
|
enableDaemonIdentity
|
|
111
111
|
};
|
|
112
|
-
//# sourceMappingURL=chunk-
|
|
112
|
+
//# sourceMappingURL=chunk-SKQQOEWH.js.map
|
|
@@ -15135,47 +15135,6 @@ function isNotFound(err) {
|
|
|
15135
15135
|
return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
|
|
15136
15136
|
}
|
|
15137
15137
|
|
|
15138
|
-
// src/lib/money.ts
|
|
15139
|
-
var USDC_DECIMALS = 6;
|
|
15140
|
-
function parseUsdToAtomic(input) {
|
|
15141
|
-
const trimmed = input.trim();
|
|
15142
|
-
if (!/^\d+(\.\d+)?$/.test(trimmed)) {
|
|
15143
|
-
throw new CliError("USAGE", `Invalid USD amount: ${JSON.stringify(input)}`, {
|
|
15144
|
-
fix: "Pass a non-negative decimal like 0.25 or 5."
|
|
15145
|
-
});
|
|
15146
|
-
}
|
|
15147
|
-
const [whole, frac = ""] = trimmed.split(".");
|
|
15148
|
-
if (frac.length > USDC_DECIMALS) {
|
|
15149
|
-
throw new CliError(
|
|
15150
|
-
"USAGE",
|
|
15151
|
-
`USD amount ${JSON.stringify(input)} has more than 6 decimal places`,
|
|
15152
|
-
{
|
|
15153
|
-
fix: "USDC supports at most 6 decimal places (micro-dollars)."
|
|
15154
|
-
}
|
|
15155
|
-
);
|
|
15156
|
-
}
|
|
15157
|
-
const atomic = BigInt(`${whole}${frac.padEnd(USDC_DECIMALS, "0")}`);
|
|
15158
|
-
return atomic.toString();
|
|
15159
|
-
}
|
|
15160
|
-
function atomicToUsd(atomic) {
|
|
15161
|
-
const trimmed = atomic.trim();
|
|
15162
|
-
if (!/^\d+$/.test(trimmed)) {
|
|
15163
|
-
throw new CliError("INTERNAL", `Malformed atomic amount: ${JSON.stringify(atomic)}`);
|
|
15164
|
-
}
|
|
15165
|
-
const value = BigInt(trimmed);
|
|
15166
|
-
const base = 10n ** BigInt(USDC_DECIMALS);
|
|
15167
|
-
const whole = value / base;
|
|
15168
|
-
const frac = (value % base).toString().padStart(USDC_DECIMALS, "0").replace(/0+$/, "");
|
|
15169
|
-
return frac.length > 0 ? `${whole}.${frac}` : whole.toString();
|
|
15170
|
-
}
|
|
15171
|
-
function toMoney(atomic) {
|
|
15172
|
-
return { atomic, usd: atomicToUsd(atomic) };
|
|
15173
|
-
}
|
|
15174
|
-
function formatUsdDisplay(atomic) {
|
|
15175
|
-
const [whole, frac = ""] = atomicToUsd(atomic).split(".");
|
|
15176
|
-
return `${whole}.${frac.padEnd(2, "0")}`;
|
|
15177
|
-
}
|
|
15178
|
-
|
|
15179
15138
|
export {
|
|
15180
15139
|
$constructor,
|
|
15181
15140
|
defineLazy,
|
|
@@ -15238,9 +15197,6 @@ export {
|
|
|
15238
15197
|
loadRawConfig,
|
|
15239
15198
|
loadConfig,
|
|
15240
15199
|
resolveSettings,
|
|
15241
|
-
resolveExperimentalBazaar
|
|
15242
|
-
parseUsdToAtomic,
|
|
15243
|
-
toMoney,
|
|
15244
|
-
formatUsdDisplay
|
|
15200
|
+
resolveExperimentalBazaar
|
|
15245
15201
|
};
|
|
15246
|
-
//# sourceMappingURL=chunk-
|
|
15202
|
+
//# sourceMappingURL=chunk-VIOUZW7Z.js.map
|