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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +9 -20
  2. package/dist/alive-3J3CHOQP.js +21 -0
  3. package/dist/{chunk-WT7DHJNJ.js → chunk-3QJREVMX.js} +5 -7
  4. package/dist/{chunk-WT7DHJNJ.js.map → chunk-3QJREVMX.js.map} +1 -1
  5. package/dist/{chunk-BOAI23CX.js → chunk-6KA4HFX5.js} +21 -15
  6. package/dist/chunk-6KA4HFX5.js.map +1 -0
  7. package/dist/chunk-6W5GYG3W.js +128 -0
  8. package/dist/chunk-6W5GYG3W.js.map +1 -0
  9. package/dist/{chunk-W36HL4TB.js → chunk-7H3RN4WJ.js} +7 -9
  10. package/dist/{chunk-W36HL4TB.js.map → chunk-7H3RN4WJ.js.map} +1 -1
  11. package/dist/{chunk-4HAV6IFE.js → chunk-7R37M6WV.js} +5 -7
  12. package/dist/{chunk-4HAV6IFE.js.map → chunk-7R37M6WV.js.map} +1 -1
  13. package/dist/{chunk-LAIZ2AQA.js → chunk-A5H3E5QA.js} +2 -2
  14. package/dist/{update-QXVH2DE7.js → chunk-AO54FM4H.js} +147 -35
  15. package/dist/chunk-AO54FM4H.js.map +1 -0
  16. package/dist/{chunk-XMIVHQ35.js → chunk-B2L53TMK.js} +17 -2
  17. package/dist/{chunk-XMIVHQ35.js.map → chunk-B2L53TMK.js.map} +1 -1
  18. package/dist/{chunk-YTM7OURD.js → chunk-BRHREK7E.js} +2 -2
  19. package/dist/{chunk-YLCWI6ZR.js → chunk-DJYAPACT.js} +79 -36
  20. package/dist/chunk-DJYAPACT.js.map +1 -0
  21. package/dist/{chunk-OBPZ36HG.js → chunk-DYSDQE7S.js} +92 -5
  22. package/dist/chunk-DYSDQE7S.js.map +1 -0
  23. package/dist/{chunk-EJXIK6WY.js → chunk-FQ6DHINU.js} +80 -48
  24. package/dist/chunk-FQ6DHINU.js.map +1 -0
  25. package/dist/chunk-FZTSGQVK.js +52 -0
  26. package/dist/chunk-FZTSGQVK.js.map +1 -0
  27. package/dist/{chunk-QF4SSCQV.js → chunk-KAMRYUK2.js} +5 -4
  28. package/dist/chunk-KAMRYUK2.js.map +1 -0
  29. package/dist/{chunk-ALJRB7NG.js → chunk-MNTQMZJB.js} +8 -8
  30. package/dist/{chunk-XICKN3CH.js → chunk-QTND6XWJ.js} +160 -80
  31. package/dist/chunk-QTND6XWJ.js.map +1 -0
  32. package/dist/chunk-RLPLYUME.js +115 -0
  33. package/dist/chunk-RLPLYUME.js.map +1 -0
  34. package/dist/{chunk-ZLD6MJVJ.js → chunk-S4SAZ7OD.js} +1 -1
  35. package/dist/chunk-S4SAZ7OD.js.map +1 -0
  36. package/dist/{chunk-5HS54CLI.js → chunk-UEOWNDQG.js} +8 -10
  37. package/dist/{chunk-5HS54CLI.js.map → chunk-UEOWNDQG.js.map} +1 -1
  38. package/dist/{chunk-5INS5ZZF.js → chunk-UOW5JXYY.js} +5 -7
  39. package/dist/{chunk-5INS5ZZF.js.map → chunk-UOW5JXYY.js.map} +1 -1
  40. package/dist/chunk-VSUHGRVB.js +1455 -0
  41. package/dist/chunk-VSUHGRVB.js.map +1 -0
  42. package/dist/{chunk-Z7R2QDX2.js → chunk-W6JX4LYF.js} +50 -7
  43. package/dist/chunk-W6JX4LYF.js.map +1 -0
  44. package/dist/{chunk-UDWGT4FX.js → chunk-XVTD7UWR.js} +14 -8
  45. package/dist/chunk-XVTD7UWR.js.map +1 -0
  46. package/dist/{chunk-6JIYGYRB.js → chunk-YFJJYHVG.js} +2 -2
  47. package/dist/{chunk-DI7WHXOZ.js → chunk-ZG6ZZLO7.js} +898 -521
  48. package/dist/chunk-ZG6ZZLO7.js.map +1 -0
  49. package/dist/{chunk-OZ3LWLCI.js → chunk-ZO3X5NPG.js} +4 -6
  50. package/dist/{chunk-OZ3LWLCI.js.map → chunk-ZO3X5NPG.js.map} +1 -1
  51. package/dist/{chunk-5NUF4BHR.js → chunk-ZP5PV3JB.js} +4 -4
  52. package/dist/{chunk-HII5HOQV.js → chunk-ZP7AHN7Z.js} +6 -6
  53. package/dist/{cli-2U5JB7OQ.js → cli-234DNHN6.js} +53 -51
  54. package/dist/{cli-2U5JB7OQ.js.map → cli-234DNHN6.js.map} +1 -1
  55. package/dist/{config-44EGO636.js → config-IY2OJCAK.js} +11 -13
  56. package/dist/{doctor-BD42BBEG.js → doctor-2UZZF44A.js} +275 -250
  57. package/dist/doctor-2UZZF44A.js.map +1 -0
  58. package/dist/{env-proxy-KEGEMWKX.js → env-proxy-XL4P73MZ.js} +2 -2
  59. package/dist/{fund-WQOOUESE.js → fund-RZ2QFULK.js} +92 -36
  60. package/dist/{fund-WQOOUESE.js.map → fund-RZ2QFULK.js.map} +1 -1
  61. package/dist/hook-command-PZHKS7ES.js +31 -0
  62. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  63. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
  64. package/dist/hosts/claude/tenjin/.mcp.json +11 -0
  65. package/dist/hosts/claude/tenjin/hooks/hooks.json +206 -0
  66. package/dist/index.js +15 -6
  67. package/dist/index.js.map +1 -1
  68. package/dist/install-O5FJ5EP3.js +48 -0
  69. package/dist/{install-identity-4RDWTLJ2.js → install-identity-QM44IQ6Z.js} +7 -7
  70. package/dist/{install-wallet-USHWL7AX.js → install-wallet-Z52EDLPB.js} +14 -14
  71. package/dist/{mcp-T5SYCLP7.js → mcp-33HAADDF.js} +557 -118
  72. package/dist/mcp-33HAADDF.js.map +1 -0
  73. package/dist/package-RT24HTTP.js +37 -0
  74. package/dist/{pay-276DSSYG.js → pay-IR2V76FX.js} +16 -16
  75. package/dist/{payments-TZYLJXK3.js → payments-GFV4HU5R.js} +10 -10
  76. package/dist/{send-YHDKZPED.js → send-PI4NUA7I.js} +13 -13
  77. package/dist/{status-X2INT6VD.js → status-ZUHTJK46.js} +10 -9
  78. package/dist/{status-X2INT6VD.js.map → status-ZUHTJK46.js.map} +1 -1
  79. package/dist/{status-line-QKDJYZGV.js → status-line-2G5JPQAE.js} +6 -6
  80. package/dist/uninstall-THKUH5ZT.js +136 -0
  81. package/dist/uninstall-THKUH5ZT.js.map +1 -0
  82. package/dist/update-NPZDP24E.js +18 -0
  83. package/dist/update-NPZDP24E.js.map +1 -0
  84. package/dist/{wallet-CKKB23D5.js → wallet-53EFH4M5.js} +11 -11
  85. package/dist/wallet-53EFH4M5.js.map +1 -0
  86. package/docs/agent-permissions.md +32 -21
  87. package/package.json +3 -3
  88. package/dist/chunk-65EJJVT3.js +0 -172
  89. package/dist/chunk-65EJJVT3.js.map +0 -1
  90. package/dist/chunk-BOAI23CX.js.map +0 -1
  91. package/dist/chunk-DI7WHXOZ.js.map +0 -1
  92. package/dist/chunk-EJXIK6WY.js.map +0 -1
  93. package/dist/chunk-GHR4BTNJ.js +0 -87
  94. package/dist/chunk-GHR4BTNJ.js.map +0 -1
  95. package/dist/chunk-H4BOQLWW.js +0 -99
  96. package/dist/chunk-H4BOQLWW.js.map +0 -1
  97. package/dist/chunk-JLEF5WHM.js +0 -132
  98. package/dist/chunk-JLEF5WHM.js.map +0 -1
  99. package/dist/chunk-OBPZ36HG.js.map +0 -1
  100. package/dist/chunk-PM2MOXJ3.js +0 -66
  101. package/dist/chunk-PM2MOXJ3.js.map +0 -1
  102. package/dist/chunk-QF4SSCQV.js.map +0 -1
  103. package/dist/chunk-TGLKKLQG.js +0 -11
  104. package/dist/chunk-TGLKKLQG.js.map +0 -1
  105. package/dist/chunk-UDWGT4FX.js.map +0 -1
  106. package/dist/chunk-VNT3CQFV.js +0 -940
  107. package/dist/chunk-VNT3CQFV.js.map +0 -1
  108. package/dist/chunk-XICKN3CH.js.map +0 -1
  109. package/dist/chunk-YHWBDCGS.js +0 -753
  110. package/dist/chunk-YHWBDCGS.js.map +0 -1
  111. package/dist/chunk-YLCWI6ZR.js.map +0 -1
  112. package/dist/chunk-Z7R2QDX2.js.map +0 -1
  113. package/dist/chunk-ZLD6MJVJ.js.map +0 -1
  114. package/dist/doctor-BD42BBEG.js.map +0 -1
  115. package/dist/hook-command-23LC5NRN.js +0 -32
  116. package/dist/install-REPLHNU7.js +0 -72
  117. package/dist/mcp-T5SYCLP7.js.map +0 -1
  118. package/dist/status-line-wiring-LW4HFRHB.js +0 -31
  119. package/dist/uninstall-NVTGU7JD.js +0 -175
  120. package/dist/uninstall-NVTGU7JD.js.map +0 -1
  121. package/dist/update-QXVH2DE7.js.map +0 -1
  122. /package/dist/{config-44EGO636.js.map → alive-3J3CHOQP.js.map} +0 -0
  123. /package/dist/{chunk-LAIZ2AQA.js.map → chunk-A5H3E5QA.js.map} +0 -0
  124. /package/dist/{chunk-YTM7OURD.js.map → chunk-BRHREK7E.js.map} +0 -0
  125. /package/dist/{chunk-ALJRB7NG.js.map → chunk-MNTQMZJB.js.map} +0 -0
  126. /package/dist/{chunk-6JIYGYRB.js.map → chunk-YFJJYHVG.js.map} +0 -0
  127. /package/dist/{chunk-5NUF4BHR.js.map → chunk-ZP5PV3JB.js.map} +0 -0
  128. /package/dist/{chunk-HII5HOQV.js.map → chunk-ZP7AHN7Z.js.map} +0 -0
  129. /package/dist/{env-proxy-KEGEMWKX.js.map → config-IY2OJCAK.js.map} +0 -0
  130. /package/dist/{hook-command-23LC5NRN.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
  131. /package/dist/{install-REPLHNU7.js.map → hook-command-PZHKS7ES.js.map} +0 -0
  132. /package/dist/{install-identity-4RDWTLJ2.js.map → install-O5FJ5EP3.js.map} +0 -0
  133. /package/dist/{pay-276DSSYG.js.map → install-identity-QM44IQ6Z.js.map} +0 -0
  134. /package/dist/{install-wallet-USHWL7AX.js.map → install-wallet-Z52EDLPB.js.map} +0 -0
  135. /package/dist/{status-line-wiring-LW4HFRHB.js.map → package-RT24HTTP.js.map} +0 -0
  136. /package/dist/{wallet-CKKB23D5.js.map → pay-IR2V76FX.js.map} +0 -0
  137. /package/dist/{payments-TZYLJXK3.js.map → payments-GFV4HU5R.js.map} +0 -0
  138. /package/dist/{send-YHDKZPED.js.map → send-PI4NUA7I.js.map} +0 -0
  139. /package/dist/{status-line-QKDJYZGV.js.map → status-line-2G5JPQAE.js.map} +0 -0
@@ -0,0 +1,1455 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ ROUTER_PATH
4
+ } from "./chunk-W6JX4LYF.js";
5
+ import {
6
+ CLI_SKILL_NAMES,
7
+ RETIRED_SKILL_NAMES,
8
+ SHIPPED_SKILL_FILES,
9
+ inspectHooksFile,
10
+ persistRouterDefaults,
11
+ readSkillFile,
12
+ skillFrontmatterName,
13
+ skillsDirsFor
14
+ } from "./chunk-ZG6ZZLO7.js";
15
+ import {
16
+ HOOK_TOOL,
17
+ hookToolInput
18
+ } from "./chunk-AKWGE6JQ.js";
19
+ import {
20
+ FEE_APPROVAL,
21
+ LEGACY_HOOK_TOOL,
22
+ LEGACY_MCP_SERVER_NAME,
23
+ LEGACY_REQUEST_TOOL,
24
+ MARKETPLACE_NAME,
25
+ MCP_SERVER_NAME,
26
+ OWN_LIMITS_COMMANDS,
27
+ PLUGIN_HOOK_TOOL,
28
+ PLUGIN_ID,
29
+ PLUGIN_NAME,
30
+ PLUGIN_SERVER,
31
+ REQUEST_TOOL,
32
+ ROUTER_DEFAULTS,
33
+ ROUTING_FEE_TERMS,
34
+ SKILLS_DIR_PLUGIN_ID,
35
+ limitsUsd,
36
+ shownLimits,
37
+ spendQuestion
38
+ } from "./chunk-DYSDQE7S.js";
39
+ import {
40
+ askText,
41
+ selectOne
42
+ } from "./chunk-P7LABKCW.js";
43
+ import {
44
+ readMcpServers,
45
+ versionFreeEntry
46
+ } from "./chunk-AO54FM4H.js";
47
+ import {
48
+ paint
49
+ } from "./chunk-XVTD7UWR.js";
50
+ import {
51
+ readAliveStamp
52
+ } from "./chunk-6W5GYG3W.js";
53
+ import {
54
+ envProxySupported,
55
+ proxyVariable
56
+ } from "./chunk-S4SAZ7OD.js";
57
+ import {
58
+ httpRequest
59
+ } from "./chunk-UOW5JXYY.js";
60
+ import {
61
+ hasCode
62
+ } from "./chunk-2I4QTOLB.js";
63
+ import {
64
+ resolveContextSettings
65
+ } from "./chunk-ZP7AHN7Z.js";
66
+ import {
67
+ parseUsdToAtomic,
68
+ toMoney
69
+ } from "./chunk-FZTSGQVK.js";
70
+ import {
71
+ CliError,
72
+ PRODUCTION_ORIGIN,
73
+ isSameDeployment,
74
+ loadRawConfig,
75
+ writeFileAtomic
76
+ } from "./chunk-QTND6XWJ.js";
77
+ import {
78
+ package_default
79
+ } from "./chunk-RLPLYUME.js";
80
+
81
+ // src/router/install.ts
82
+ import { readFile as readFile4, realpath } from "node:fs/promises";
83
+ import { homedir as homedir2 } from "node:os";
84
+ import { isAbsolute as isAbsolute2, join as join6 } from "node:path";
85
+
86
+ // src/lib/skill-placement.ts
87
+ import { lstatSync } from "node:fs";
88
+ import { readdir, rm, rmdir } from "node:fs/promises";
89
+ import { dirname, join } from "node:path";
90
+ function isRealDirectory(path) {
91
+ try {
92
+ return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;
93
+ } catch (err) {
94
+ if (hasCode(err, "ENOENT") || hasCode(err, "ENOTDIR")) return false;
95
+ throw err;
96
+ }
97
+ }
98
+ async function removeOwnedSkill(name, skillsDir) {
99
+ if (!isRealDirectory(skillsDir)) {
100
+ return { changed: false };
101
+ }
102
+ const skillDir = join(skillsDir, name);
103
+ if (!isRealDirectory(skillDir)) {
104
+ return { changed: false };
105
+ }
106
+ const path = join(skillDir, "SKILL.md");
107
+ const read = await readSkillFile(path);
108
+ if (read.kind === "absent") return { changed: false };
109
+ if (read.kind !== "ok" || skillFrontmatterName(read.bytes.toString("utf8")) !== name) {
110
+ return { changed: false };
111
+ }
112
+ const shipped = SHIPPED_SKILL_FILES[name] ?? [];
113
+ const subdirs = /* @__PURE__ */ new Set();
114
+ for (const rel of shipped) {
115
+ if (rel === "SKILL.md") continue;
116
+ const file = join(skillDir, rel);
117
+ if (!isRealDirectory(dirname(file))) continue;
118
+ subdirs.add(dirname(file));
119
+ if (lstatSync(file, { throwIfNoEntry: false })?.isFile() === true) await rm(file);
120
+ }
121
+ await rm(path, { force: true });
122
+ for (const dir of [...subdirs, skillDir].sort((a, b) => b.length - a.length)) {
123
+ const rest = await readdir(dir).catch(() => null);
124
+ if (rest !== null && rest.length === 0) await rmdir(dir).catch(() => void 0);
125
+ }
126
+ return { changed: true };
127
+ }
128
+ async function removeRetiredSkills(home, project) {
129
+ const removed = [];
130
+ const dirs = [...skillsDirsFor(home), ...project ? skillsDirsFor(project) : []];
131
+ for (const dir of new Set(dirs)) {
132
+ for (const name of [...RETIRED_SKILL_NAMES, ...CLI_SKILL_NAMES]) {
133
+ if ((await removeOwnedSkill(name, dir)).changed) removed.push(join(dir, name));
134
+ }
135
+ }
136
+ return removed;
137
+ }
138
+
139
+ // src/router/claude-cli.ts
140
+ import { execFile } from "node:child_process";
141
+ import { statSync } from "node:fs";
142
+ import { homedir } from "node:os";
143
+ import { delimiter, isAbsolute, join as join2 } from "node:path";
144
+ var CLAUDE_CODE_FLOOR = "2.1.287";
145
+ function claudeConfigDir(env, home = homedir()) {
146
+ const dir = env.CLAUDE_CONFIG_DIR;
147
+ return dir !== void 0 && dir.length > 0 ? dir : join2(home, ".claude");
148
+ }
149
+ function userSettingsPath(env, home = homedir()) {
150
+ return join2(claudeConfigDir(env, home), "settings.json");
151
+ }
152
+ function userMcpFile(env, home = homedir()) {
153
+ const dir = env.CLAUDE_CONFIG_DIR;
154
+ return dir !== void 0 && dir.length > 0 ? join2(dir, ".claude.json") : join2(home, ".claude.json");
155
+ }
156
+ function isFile(path) {
157
+ try {
158
+ return statSync(path).isFile();
159
+ } catch {
160
+ return false;
161
+ }
162
+ }
163
+ function findClaudeBinary(env) {
164
+ const exts = process.platform === "win32" ? ["", ...(env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter((e) => e.length > 0)] : [""];
165
+ for (const part of (env.PATH ?? "").split(delimiter)) {
166
+ if (part.length === 0) continue;
167
+ for (const ext of exts) {
168
+ const candidate = join2(part, `claude${ext}`);
169
+ if (isFile(candidate)) return { path: candidate, source: "path" };
170
+ }
171
+ }
172
+ const exec = env.CLAUDE_CODE_EXECPATH;
173
+ if (exec !== void 0 && isAbsolute(exec) && isFile(exec)) {
174
+ return { path: exec, source: "execpath" };
175
+ }
176
+ return null;
177
+ }
178
+ function runClaude(bin, args, opts) {
179
+ return new Promise((resolve) => {
180
+ execFile(
181
+ bin.path,
182
+ args,
183
+ {
184
+ env: opts.env,
185
+ cwd: opts.cwd,
186
+ timeout: opts.timeoutMs ?? 3e4,
187
+ maxBuffer: 4 * 1024 * 1024,
188
+ windowsHide: true
189
+ },
190
+ (err, stdout, stderr) => {
191
+ const code = err === null ? 0 : typeof err.code === "number" ? err.code : null;
192
+ resolve({ code, stdout: String(stdout), stderr: String(stderr) });
193
+ }
194
+ );
195
+ });
196
+ }
197
+ function jsonResult(stdout) {
198
+ const lines2 = stdout.split("\n").map((l) => l.trim());
199
+ for (let i = lines2.length - 1; i >= 0; i -= 1) {
200
+ const line = lines2[i];
201
+ if (!line.startsWith("{")) continue;
202
+ try {
203
+ const parsed = JSON.parse(line);
204
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
205
+ return parsed;
206
+ }
207
+ } catch {
208
+ continue;
209
+ }
210
+ }
211
+ return null;
212
+ }
213
+ function jsonList(stdout) {
214
+ const start = stdout.indexOf("[");
215
+ if (start === -1) return null;
216
+ try {
217
+ const parsed = JSON.parse(stdout.slice(start));
218
+ return Array.isArray(parsed) ? parsed.filter(
219
+ (row) => row !== null && typeof row === "object" && !Array.isArray(row)
220
+ ) : null;
221
+ } catch {
222
+ return null;
223
+ }
224
+ }
225
+ function parseClaudeVersion(text) {
226
+ return /(\d+)\.(\d+)\.(\d+)/.exec(text)?.[0] ?? null;
227
+ }
228
+ function meetsFloor(version, floor = CLAUDE_CODE_FLOOR) {
229
+ const a = version.split(".").map(Number);
230
+ const b = floor.split(".").map(Number);
231
+ for (let i = 0; i < 3; i += 1) {
232
+ const x = a[i] ?? 0;
233
+ const y = b[i] ?? 0;
234
+ if (x !== y) return x > y;
235
+ }
236
+ return true;
237
+ }
238
+ var CLAUDE_UPDATE_FIX = "Run `claude update` in this session, then start a new Claude Code session so the newer version loads.";
239
+ async function readClaudeCode(env, cwd, find = findClaudeBinary) {
240
+ const binary = find(env);
241
+ if (binary === null) return { binary, version: null, meetsFloor: true };
242
+ const run = await runClaude(binary, ["--version"], { env, cwd, timeoutMs: 15e3 });
243
+ const version = run.code === 0 ? parseClaudeVersion(run.stdout) : null;
244
+ const ok = version === null || meetsFloor(version);
245
+ return {
246
+ binary,
247
+ version,
248
+ meetsFloor: ok,
249
+ ...ok ? {} : { fix: CLAUDE_UPDATE_FIX }
250
+ };
251
+ }
252
+
253
+ // src/router/legacy-install.ts
254
+ import { readFile, stat } from "node:fs/promises";
255
+ import { join as join3 } from "node:path";
256
+
257
+ // src/router/status-line-wiring.ts
258
+ var STATUS_LINE_COMMAND = "tenjin status-line";
259
+ var OUR_MARKER = STATUS_LINE_COMMAND;
260
+ function classifyStatusLine(value) {
261
+ if (value === null || value === void 0) return "absent";
262
+ const command2 = typeof value === "string" ? value : typeof value === "object" && !Array.isArray(value) ? value.command : void 0;
263
+ if (typeof command2 !== "string" || command2.trim().length === 0) return "foreign";
264
+ if (command2.trim() === OUR_MARKER) return "ours";
265
+ return command2.includes(OUR_MARKER) ? "composed" : "foreign";
266
+ }
267
+ var shUnquote = (value) => value.replaceAll(String.raw`'\''`, "'");
268
+ function composedScript(existing) {
269
+ return [
270
+ "event=$(cat)",
271
+ `yours=$(printf %s "$event" | ${existing})`,
272
+ `tenjin=$(printf %s "$event" | ${STATUS_LINE_COMMAND})`,
273
+ 'printf %s "$yours${tenjin:+ \xB7 $tenjin}"'
274
+ ].join("; ");
275
+ }
276
+ function decomposeCommand(command2) {
277
+ const trimmed = command2.trim();
278
+ if (!trimmed.startsWith("sh -c '") || !trimmed.endsWith("'")) return null;
279
+ const script = shUnquote(trimmed.slice("sh -c '".length, -1));
280
+ const prefix = 'event=$(cat); yours=$(printf %s "$event" | ';
281
+ if (!script.startsWith(prefix)) return null;
282
+ const rest = script.slice(prefix.length);
283
+ const suffix = `); tenjin=$(printf %s "$event" | ${STATUS_LINE_COMMAND}); printf %s "$yours\${tenjin:+ \xB7 $tenjin}"`;
284
+ if (!rest.endsWith(suffix)) return null;
285
+ const existing = rest.slice(0, -suffix.length);
286
+ return existing.length > 0 && composedScript(existing) === script ? existing : null;
287
+ }
288
+
289
+ // src/router/legacy-install.ts
290
+ var LEGACY_COMMAND_RE = /^(\S*\/)?tenjin hook [a-z]+$/;
291
+ function isPlainObject(value) {
292
+ return typeof value === "object" && value !== null && !Array.isArray(value);
293
+ }
294
+ function ownsLegacyHandler(handler) {
295
+ if (!isPlainObject(handler)) return false;
296
+ if (handler.type === "mcp_tool") {
297
+ return handler.server === LEGACY_MCP_SERVER_NAME && handler.tool === "hook";
298
+ }
299
+ const command2 = handler.command;
300
+ return typeof command2 === "string" && LEGACY_COMMAND_RE.test(command2.trim());
301
+ }
302
+ function lookalike(handler) {
303
+ if (!isPlainObject(handler) || ownsLegacyHandler(handler)) return null;
304
+ const command2 = handler.command;
305
+ return typeof command2 === "string" && command2.includes("tenjin hook") ? command2 : null;
306
+ }
307
+ function classifyMcpEntry(entry) {
308
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return "absent";
309
+ const { command: command2, args } = entry;
310
+ if (typeof command2 !== "string" || command2.length === 0) return "wrong-command";
311
+ const binary = command2.split(/[\\/]/).pop();
312
+ const runsRouter = binary === "tenjin" && Array.isArray(args) && args.length === 1 && args[0] === "mcp";
313
+ return runsRouter ? "ok" : "wrong-command";
314
+ }
315
+ async function readLegacyMcpEntry(path) {
316
+ let raw;
317
+ try {
318
+ raw = await readFile(path, "utf8");
319
+ } catch (err) {
320
+ const code = err.code;
321
+ return code === "ENOENT" || code === "ENOTDIR" ? "absent" : "unreadable";
322
+ }
323
+ let parsed;
324
+ try {
325
+ parsed = JSON.parse(raw);
326
+ } catch {
327
+ return "unreadable";
328
+ }
329
+ const servers = parsed?.mcpServers;
330
+ if (servers === void 0) return "absent";
331
+ if (!isPlainObject(servers)) return "unreadable";
332
+ const entry = servers[LEGACY_MCP_SERVER_NAME];
333
+ return entry === void 0 ? "absent" : classifyMcpEntry(entry);
334
+ }
335
+ async function inspectLegacyInstall(settingsPath, mcpFile) {
336
+ const mcp = await readLegacyMcpEntry(mcpFile);
337
+ const base = {
338
+ settingsPath,
339
+ mcpFile,
340
+ events: [],
341
+ allowRule: false,
342
+ denyRule: false,
343
+ statusLine: "absent",
344
+ mcp,
345
+ lookalikes: []
346
+ };
347
+ const found = await inspectHooksFile(settingsPath);
348
+ if ("refusal" in found) {
349
+ return { ...base, present: mcp === "ok", unreadable: found.refusal.message };
350
+ }
351
+ const events = Object.entries(found.hooks).filter(([, list]) => list.some((entry) => handlersOf(entry).some(ownsLegacyHandler))).map(([event]) => event);
352
+ const lookalikes = Object.values(found.hooks).flatMap(
353
+ (list) => list.flatMap(
354
+ (entry) => handlersOf(entry).map(lookalike).filter((c) => c !== null)
355
+ )
356
+ );
357
+ const rulesOurs = mcp === "ok" || mcp === "absent" && events.length > 0;
358
+ const allowRule = rulesOurs && listOf(found.settings, "allow").includes(LEGACY_REQUEST_TOOL);
359
+ const denyRule = rulesOurs && listOf(found.settings, "deny").includes(LEGACY_HOOK_TOOL);
360
+ const statusLine = events.length > 0 ? classifyStatusLine(found.settings.statusLine) : "absent";
361
+ const statusOurs = statusLine === "ours" || statusLine === "composed";
362
+ return {
363
+ ...base,
364
+ present: events.length > 0 || allowRule || denyRule || statusOurs || mcp === "ok",
365
+ events,
366
+ allowRule,
367
+ denyRule,
368
+ statusLine,
369
+ lookalikes
370
+ };
371
+ }
372
+ function handlersOf(entry) {
373
+ return isPlainObject(entry) && Array.isArray(entry.hooks) ? entry.hooks : [];
374
+ }
375
+ function listOf(settings, key) {
376
+ const permissions = settings.permissions;
377
+ if (!isPlainObject(permissions)) return [];
378
+ const list = permissions[key];
379
+ return Array.isArray(list) ? list : [];
380
+ }
381
+ async function removeLegacyInstall(found, opts) {
382
+ const out = {
383
+ events: [],
384
+ allowRule: false,
385
+ denyRule: false,
386
+ statusLine: "kept",
387
+ mcp: found.mcp === "absent" ? "absent" : "kept",
388
+ wroteSettings: false,
389
+ warnings: []
390
+ };
391
+ if (found.unreadable === void 0) await removeFromSettings(found, out);
392
+ else out.warnings.push(found.unreadable);
393
+ if (found.mcp === "ok") await removeMcpEntry(opts, out);
394
+ else if (found.mcp === "wrong-command") {
395
+ out.warnings.push(
396
+ `an MCP server named ${LEGACY_MCP_SERVER_NAME} launches something else, so it is not Tenjin's and was left in place`
397
+ );
398
+ } else if (found.mcp === "unreadable") {
399
+ out.warnings.push(`${found.mcpFile} could not be read, so nothing was removed from it`);
400
+ }
401
+ return out;
402
+ }
403
+ async function removeFromSettings(found, out) {
404
+ const read = await inspectHooksFile(found.settingsPath);
405
+ if ("refusal" in read) {
406
+ out.warnings.push(read.refusal.message);
407
+ return;
408
+ }
409
+ if (read.raw === null) return;
410
+ const next = { ...read.settings };
411
+ if (isPlainObject(read.settings.hooks)) {
412
+ const hooks = {};
413
+ for (const [event, list] of Object.entries(read.hooks)) {
414
+ const kept = [];
415
+ for (const entry of list) {
416
+ const handlers = handlersOf(entry);
417
+ const left = handlers.filter((h) => !ownsLegacyHandler(h));
418
+ if (left.length === handlers.length) kept.push(entry);
419
+ else if (left.length > 0) kept.push({ ...entry, hooks: left });
420
+ }
421
+ if (kept.length !== list.length || kept.some((e, i) => e !== list[i])) out.events.push(event);
422
+ if (kept.length > 0 || list.length === 0) hooks[event] = kept;
423
+ }
424
+ next.hooks = hooks;
425
+ }
426
+ if ((found.allowRule || found.denyRule) && isPlainObject(read.settings.permissions)) {
427
+ const permissions = { ...read.settings.permissions };
428
+ if (found.allowRule && Array.isArray(permissions.allow)) {
429
+ permissions.allow = permissions.allow.filter((r) => r !== LEGACY_REQUEST_TOOL);
430
+ out.allowRule = true;
431
+ }
432
+ if (found.denyRule && Array.isArray(permissions.deny)) {
433
+ permissions.deny = permissions.deny.filter((r) => r !== LEGACY_HOOK_TOOL);
434
+ out.denyRule = true;
435
+ }
436
+ next.permissions = permissions;
437
+ }
438
+ if (found.statusLine === "ours") {
439
+ delete next.statusLine;
440
+ out.statusLine = "removed";
441
+ } else if (found.statusLine === "composed" && isPlainObject(read.settings.statusLine)) {
442
+ const command2 = read.settings.statusLine.command;
443
+ const original = typeof command2 === "string" ? decomposeCommand(command2) : null;
444
+ if (original !== null) {
445
+ next.statusLine = { ...read.settings.statusLine, command: original };
446
+ out.statusLine = "restored";
447
+ }
448
+ }
449
+ const removed = out.events.length > 0 || out.allowRule || out.denyRule || out.statusLine !== "kept";
450
+ if (!removed) return;
451
+ const body = `${JSON.stringify(next, null, 2)}
452
+ `;
453
+ const mode = await stat(read.path).then((s) => ({ mode: s.mode & 511 })).catch(() => ({}));
454
+ if (await readFile(read.path, "utf8").catch(() => null) !== read.raw) {
455
+ out.warnings.push(`${read.path} changed while it was read, so it was left as it is`);
456
+ Object.assign(out, { events: [], allowRule: false, denyRule: false, statusLine: "kept" });
457
+ return;
458
+ }
459
+ try {
460
+ await writeFileAtomic(read.path, body, mode);
461
+ out.wroteSettings = true;
462
+ } catch (err) {
463
+ out.warnings.push(err instanceof Error ? err.message : String(err));
464
+ Object.assign(out, { events: [], allowRule: false, denyRule: false, statusLine: "kept" });
465
+ }
466
+ }
467
+ async function removeMcpEntry(opts, out) {
468
+ if (opts.binary === null) {
469
+ out.warnings.push(
470
+ `the ${LEGACY_MCP_SERVER_NAME} MCP registration stays until a run with the claude binary removes it`
471
+ );
472
+ return;
473
+ }
474
+ const run = await runClaude(
475
+ opts.binary,
476
+ ["mcp", "remove", LEGACY_MCP_SERVER_NAME, "-s", opts.mcpScope],
477
+ { env: opts.env, cwd: opts.cwd }
478
+ );
479
+ if (run.code === 0) out.mcp = "removed";
480
+ else {
481
+ out.warnings.push(
482
+ `claude mcp remove ${LEGACY_MCP_SERVER_NAME} did not succeed: ${(run.stderr || run.stdout).trim().slice(0, 200) || "no output"}`
483
+ );
484
+ }
485
+ }
486
+ function projectMcpFile(cwd) {
487
+ return join3(cwd, ".mcp.json");
488
+ }
489
+
490
+ // src/router/plugin-registration.ts
491
+ import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
492
+ import { dirname as dirname3, join as join5 } from "node:path";
493
+ import { fileURLToPath } from "node:url";
494
+
495
+ // src/router/plugin-files.ts
496
+ var ROUTE_HOOK_TIMEOUT_SECONDS = 5;
497
+ var AFTER_CALL_TIMEOUT_SECONDS = 15;
498
+ var LOCAL_HOOK_TIMEOUT_SECONDS = 5;
499
+ var DELEGATION_MATCHER = "Agent|Task";
500
+ var NATIVE_MATCHER = "WebSearch|WebFetch";
501
+ var ASK_MATCHER = "AskUserQuestion";
502
+ var ALIVE_COMMAND = "tenjin hook alive";
503
+ function permissionAnswer(decision, reason) {
504
+ return JSON.stringify({
505
+ hookSpecificOutput: {
506
+ hookEventName: "PreToolUse",
507
+ permissionDecision: decision,
508
+ permissionDecisionReason: reason
509
+ }
510
+ });
511
+ }
512
+ var DENY_HOOK_COMMAND = `echo '${permissionAnswer(
513
+ "deny",
514
+ `Only the Tenjin hooks call this tool. To make a lookup, call ${REQUEST_TOOL}.`
515
+ )}'`;
516
+ var ALLOW_HOOK_COMMAND = `echo '${permissionAnswer("allow", "Tenjin lookup")}'`;
517
+ function leg(kind, timeout = ROUTE_HOOK_TIMEOUT_SECONDS) {
518
+ return [
519
+ {
520
+ type: "mcp_tool",
521
+ server: PLUGIN_SERVER,
522
+ tool: HOOK_TOOL,
523
+ input: hookToolInput(kind),
524
+ timeout
525
+ }
526
+ ];
527
+ }
528
+ function command(text) {
529
+ return [{ type: "command", command: text, timeout: LOCAL_HOOK_TIMEOUT_SECONDS }];
530
+ }
531
+ function routerHookPlan() {
532
+ const afterCall = () => leg("shortfall", AFTER_CALL_TIMEOUT_SECONDS);
533
+ return [
534
+ { event: "UserPromptSubmit", hooks: leg("prompt") },
535
+ { event: "PreToolUse", matcher: NATIVE_MATCHER, hooks: leg("native") },
536
+ { event: "PreToolUse", matcher: DELEGATION_MATCHER, hooks: leg("agent") },
537
+ { event: "PostToolUse", matcher: NATIVE_MATCHER, hooks: afterCall() },
538
+ { event: "PostToolUseFailure", matcher: NATIVE_MATCHER, hooks: afterCall() },
539
+ { event: "PreToolUse", matcher: ASK_MATCHER, hooks: leg("ask") },
540
+ { event: "PostToolUse", matcher: ASK_MATCHER, hooks: leg("answer") }
541
+ ];
542
+ }
543
+ function renderPluginHooks() {
544
+ const plan = [
545
+ { event: "SessionStart", hooks: command(ALIVE_COMMAND) },
546
+ ...routerHookPlan(),
547
+ { event: "PreToolUse", matcher: PLUGIN_HOOK_TOOL, hooks: command(DENY_HOOK_COMMAND) },
548
+ { event: "PreToolUse", matcher: REQUEST_TOOL, hooks: command(ALLOW_HOOK_COMMAND) }
549
+ ];
550
+ const hooks = {};
551
+ for (const { event, hooks: handlers, ...rest } of plan) {
552
+ (hooks[event] ??= []).push({ ...rest, hooks: handlers });
553
+ }
554
+ return { hooks };
555
+ }
556
+ var PLUGIN_MCP_ARGS = ["mcp", "--plugin"];
557
+ function renderPluginMcp() {
558
+ return { mcpServers: { [MCP_SERVER_NAME]: { command: "tenjin", args: [...PLUGIN_MCP_ARGS] } } };
559
+ }
560
+ var OWNER_MARKER = "tenjin-cli";
561
+ var UNBUILT = "source";
562
+ var DESCRIPTION = "Tenjin picks the right tool when your agent needs one, and one wallet on this machine pays for every call.";
563
+ function renderPluginManifest(version) {
564
+ return {
565
+ name: PLUGIN_NAME,
566
+ ...version !== void 0 ? { version } : {},
567
+ description: DESCRIPTION,
568
+ author: { name: "Tenjin", url: PRODUCTION_ORIGIN },
569
+ homepage: `${PRODUCTION_ORIGIN}/agents`,
570
+ repository: "https://github.com/BackTrackCo/tenjin-agent",
571
+ metadata: { [OWNER_MARKER]: version ?? UNBUILT }
572
+ };
573
+ }
574
+ var PLUGIN_DIR = PLUGIN_NAME;
575
+ var PLUGIN_FILES = [
576
+ ".mcp.json",
577
+ "hooks/hooks.json",
578
+ ".claude-plugin/plugin.json"
579
+ ];
580
+ var json = (value) => `${JSON.stringify(value, null, 2)}
581
+ `;
582
+ function renderPluginFiles(version) {
583
+ return {
584
+ ".mcp.json": json(renderPluginMcp()),
585
+ "hooks/hooks.json": json(renderPluginHooks()),
586
+ ".claude-plugin/plugin.json": json(renderPluginManifest(version))
587
+ };
588
+ }
589
+
590
+ // src/router/plugin-folder.ts
591
+ import { lstat, readdir as readdir2, readFile as readFile2, rm as rm2, rmdir as rmdir2 } from "node:fs/promises";
592
+ import { dirname as dirname2, join as join4, relative, sep } from "node:path";
593
+ var FOLDER_NAME = "tenjin-router";
594
+ function pluginFolderPath(base) {
595
+ return join4(base, "skills", FOLDER_NAME);
596
+ }
597
+ async function inspectPluginFolder(dir) {
598
+ const entry = await lstat(dir).catch(() => null);
599
+ if (entry === null) return "absent";
600
+ if (!entry.isDirectory() || entry.isSymbolicLink()) return "foreign";
601
+ try {
602
+ const manifest = JSON.parse(
603
+ await readFile2(join4(dir, ".claude-plugin", "plugin.json"), "utf8")
604
+ );
605
+ const marked = manifest.metadata !== null && typeof manifest.metadata === "object" && OWNER_MARKER in manifest.metadata;
606
+ return manifest.name === PLUGIN_NAME && marked ? "ours" : "foreign";
607
+ } catch {
608
+ return "foreign";
609
+ }
610
+ }
611
+ async function writePluginFolder(dir, files) {
612
+ const state = await inspectPluginFolder(dir);
613
+ if (state === "foreign") {
614
+ return {
615
+ path: dir,
616
+ state: "refused",
617
+ reason: `${dir} exists and is not a folder this CLI wrote, so it was left as it is`
618
+ };
619
+ }
620
+ try {
621
+ for (const path of PLUGIN_FILES) {
622
+ const body = files[path];
623
+ if (body === void 0) continue;
624
+ await writeFileAtomic(join4(dir, path), body);
625
+ }
626
+ } catch (err) {
627
+ return {
628
+ path: dir,
629
+ state: "refused",
630
+ reason: err instanceof Error ? err.message : String(err)
631
+ };
632
+ }
633
+ return { path: dir, state: "written" };
634
+ }
635
+ async function removePluginFolder(dir) {
636
+ const state = await inspectPluginFolder(dir);
637
+ if (state === "absent") return { path: dir, removed: false, left: [] };
638
+ if (state === "foreign") {
639
+ return {
640
+ path: dir,
641
+ removed: false,
642
+ left: [],
643
+ reason: `${dir} is not a folder this CLI wrote, so nothing in it was removed`
644
+ };
645
+ }
646
+ for (const path of PLUGIN_FILES) await rm2(join4(dir, path), { force: true });
647
+ const subdirs = [...new Set(PLUGIN_FILES.map((p) => dirname2(p)).filter((d) => d !== "."))].sort(
648
+ (a, b) => b.split("/").length - a.split("/").length
649
+ );
650
+ for (const sub of subdirs) await rmdir2(join4(dir, sub)).catch(() => void 0);
651
+ const left = await listFiles(dir);
652
+ if (left.length === 0) await rmdir2(dir).catch(() => void 0);
653
+ return { path: dir, removed: true, left };
654
+ }
655
+ async function listFiles(dir) {
656
+ const out = [];
657
+ const walk = async (current) => {
658
+ for (const entry of await readdir2(current, { withFileTypes: true }).catch(() => [])) {
659
+ const path = join4(current, entry.name);
660
+ if (entry.isDirectory()) await walk(path);
661
+ else out.push(relative(dir, path).split(sep).join("/"));
662
+ }
663
+ };
664
+ await walk(dir);
665
+ return out.sort();
666
+ }
667
+
668
+ // src/router/plugin-registration.ts
669
+ function folderFor(scope, env, home, cwd) {
670
+ return pluginFolderPath(scope === "local" ? join5(cwd, ".claude") : claudeConfigDir(env, home));
671
+ }
672
+ async function registerPlugin(opts) {
673
+ const folder = folderFor(opts.scope, opts.env, opts.home, opts.cwd);
674
+ const steps = [];
675
+ let fallbackReason;
676
+ if (opts.binary !== null) {
677
+ const hosts = opts.hostsDir === void 0 ? await packageHostsDir() : opts.hostsDir;
678
+ if (hosts === null) {
679
+ fallbackReason = "this build carries no plugin marketplace folder (dist/hosts/claude)";
680
+ } else {
681
+ const done = await viaPluginCommands(opts.binary, hosts, opts, steps);
682
+ if (done.ok) {
683
+ const superseded = await removePluginFolder(folder);
684
+ return {
685
+ method: "plugin",
686
+ id: PLUGIN_ID,
687
+ scope: opts.scope,
688
+ state: done.state,
689
+ path: hosts,
690
+ version: opts.version,
691
+ steps,
692
+ ...superseded.removed ? { supersededFolder: superseded } : {}
693
+ };
694
+ }
695
+ fallbackReason = done.reason;
696
+ }
697
+ const existing = await existingCopy(opts.binary, opts.env, opts.home, opts.cwd);
698
+ if (existing !== null) {
699
+ return {
700
+ method: "none",
701
+ id: existing,
702
+ scope: opts.scope,
703
+ state: "failed",
704
+ version: opts.version,
705
+ steps,
706
+ reason: `${fallbackReason}; ${existing} is already in Claude Code and was left as it is, so no second copy was written`
707
+ };
708
+ }
709
+ } else {
710
+ fallbackReason = "no claude binary on PATH or in CLAUDE_CODE_EXECPATH";
711
+ if (await installedThroughCommands(opts.env, opts.home)) {
712
+ return {
713
+ method: "plugin",
714
+ id: PLUGIN_ID,
715
+ scope: opts.scope,
716
+ state: "current",
717
+ version: opts.version,
718
+ steps,
719
+ fallbackReason: `${fallbackReason}; ${PLUGIN_ID} is already registered, so it was left as it is`
720
+ };
721
+ }
722
+ }
723
+ const written = await writePluginFolder(folder, renderPluginFiles(opts.version));
724
+ if (written.state === "written") {
725
+ return {
726
+ method: "skills-dir",
727
+ id: SKILLS_DIR_PLUGIN_ID,
728
+ scope: opts.scope,
729
+ state: "written",
730
+ path: folder,
731
+ version: opts.version,
732
+ steps,
733
+ fallbackReason
734
+ };
735
+ }
736
+ return {
737
+ method: "none",
738
+ id: null,
739
+ scope: opts.scope,
740
+ state: "failed",
741
+ path: folder,
742
+ version: opts.version,
743
+ steps,
744
+ fallbackReason,
745
+ reason: written.reason ?? "the plugin folder could not be written"
746
+ };
747
+ }
748
+ async function viaPluginCommands(binary, hosts, opts, steps) {
749
+ const run = (args) => runClaude(binary, args, { env: opts.env, cwd: opts.cwd });
750
+ const scopeArgs = ["--scope", opts.scope];
751
+ const marketplaceScope = opts.scope === "user" ? [] : scopeArgs;
752
+ const known = await run(["plugin", "marketplace", "list", "--json"]);
753
+ const listed = known.code === 0 ? jsonList(known.stdout) : null;
754
+ steps.push({
755
+ command: "claude plugin marketplace list --json",
756
+ ok: listed !== null,
757
+ ...listed === null ? { detail: commandDetail(known) } : {}
758
+ });
759
+ if (listed === null) {
760
+ return {
761
+ ok: false,
762
+ reason: `claude plugin marketplace list could not be read (${commandDetail(known)}), so no marketplace was added or repointed`
763
+ };
764
+ }
765
+ const existing = listed.find((m) => m.name === MARKETPLACE_NAME);
766
+ if (existing !== void 0 && !await ownMarketplace(existing)) {
767
+ return {
768
+ ok: false,
769
+ reason: `a marketplace named ${MARKETPLACE_NAME} that this CLI did not add is already configured, so it was left as it is`
770
+ };
771
+ }
772
+ const add = await step(
773
+ steps,
774
+ ["plugin", "marketplace", "add", hosts, "--json", ...marketplaceScope],
775
+ run
776
+ );
777
+ if (!add.ok) return { ok: false, reason: `claude plugin marketplace add failed: ${add.detail}` };
778
+ const install = await step(steps, ["plugin", "install", PLUGIN_ID, ...scopeArgs, "--json"], run);
779
+ if (!install.ok) return { ok: false, reason: `claude plugin install failed: ${install.detail}` };
780
+ const installed = install.result?.installedVersion;
781
+ const available = install.result?.availableVersion;
782
+ if (typeof installed !== "string" || typeof available !== "string") {
783
+ return { ok: true, state: "installed" };
784
+ }
785
+ if (installed === available) return { ok: true, state: "current" };
786
+ const update = await step(steps, ["plugin", "update", PLUGIN_ID, ...scopeArgs, "--json"], run);
787
+ if (!update.ok) return { ok: false, reason: `claude plugin update failed: ${update.detail}` };
788
+ return { ok: true, state: "updated" };
789
+ }
790
+ async function step(steps, args, run) {
791
+ const out = await run(args);
792
+ const result = jsonResult(out.stdout);
793
+ const ok = out.code === 0 && (result === null || result.outcome === void 0 || result.outcome === "ok");
794
+ const detail = commandDetail(out, result);
795
+ steps.push({ command: `claude ${args.join(" ")}`, ok, ...ok ? {} : { detail } });
796
+ return { ok, detail, result };
797
+ }
798
+ function commandDetail(out, result = null) {
799
+ if (typeof result?.message === "string") return result.message;
800
+ const text = (out.stderr || out.stdout).trim().slice(0, 300);
801
+ if (text.length > 0) return text;
802
+ return out.code === null ? "the command could not be run" : `exit ${out.code}`;
803
+ }
804
+ async function ownMarketplace(row) {
805
+ const path = typeof row.path === "string" ? row.path : void 0;
806
+ if (row.source !== "directory" || path === void 0) return false;
807
+ if (await stat2(path).catch(() => null) === null) {
808
+ return /tenjin-cli[\\/]dist[\\/]hosts[\\/]claude$/.test(path);
809
+ }
810
+ return await inspectPluginFolder(join5(path, PLUGIN_DIR)) === "ours";
811
+ }
812
+ async function existingCopy(binary, env, home, cwd) {
813
+ const out = await runClaude(binary, ["plugin", "list", "--json"], { env, cwd });
814
+ const listed = out.code === 0 ? jsonList(out.stdout) : null;
815
+ if (listed === null) return await installedThroughCommands(env, home) ? PLUGIN_ID : null;
816
+ const row = listed.find(
817
+ (p) => typeof p.id === "string" && p.id.startsWith(`${PLUGIN_NAME}@`) && p.id !== SKILLS_DIR_PLUGIN_ID && p.enabled === true
818
+ );
819
+ return typeof row?.id === "string" ? row.id : null;
820
+ }
821
+ async function installedThroughCommands(env, home) {
822
+ try {
823
+ const raw = await readFile3(
824
+ join5(claudeConfigDir(env, home), "plugins", "installed_plugins.json"),
825
+ "utf8"
826
+ );
827
+ const plugins = JSON.parse(raw).plugins;
828
+ return plugins !== null && typeof plugins === "object" && PLUGIN_ID in plugins;
829
+ } catch {
830
+ return false;
831
+ }
832
+ }
833
+ async function packageHostsDir(moduleDir = dirname3(fileURLToPath(import.meta.url))) {
834
+ const catalog = join5(moduleDir, "hosts", "claude", ".claude-plugin", "marketplace.json");
835
+ const stable = versionFreeEntry(catalog) ?? catalog;
836
+ if ((await stat2(stable).catch(() => null))?.isFile() !== true) return null;
837
+ return dirname3(dirname3(stable));
838
+ }
839
+ async function readPluginListing(binary, env, cwd) {
840
+ const out = await runClaude(binary, ["plugin", "list", "--json"], { env, cwd });
841
+ const rows = out.code === 0 ? jsonList(out.stdout) : null;
842
+ if (rows === null) return { id: null, enabled: false, version: null, read: false };
843
+ const row = rows.find((r) => r.id === PLUGIN_ID && r.enabled === true) ?? rows.find((r) => r.id === SKILLS_DIR_PLUGIN_ID && r.enabled === true) ?? rows.find((r) => r.id === PLUGIN_ID || r.id === SKILLS_DIR_PLUGIN_ID);
844
+ if (row === void 0) return { id: null, enabled: false, version: null, read: true };
845
+ return {
846
+ id: String(row.id),
847
+ enabled: row.enabled === true,
848
+ version: typeof row.version === "string" ? row.version : null,
849
+ read: true
850
+ };
851
+ }
852
+ async function folderState(scope, env, home, cwd) {
853
+ const path = folderFor(scope, env, home, cwd);
854
+ return { path, state: await inspectPluginFolder(path) };
855
+ }
856
+
857
+ // src/router/reachability.ts
858
+ async function probeRouter(baseUrl, opts) {
859
+ const fail = (detail, fix) => ({
860
+ name: "router",
861
+ status: "fail",
862
+ required: true,
863
+ detail,
864
+ fix
865
+ });
866
+ let url;
867
+ try {
868
+ url = new URL(ROUTER_PATH, baseUrl).toString();
869
+ } catch {
870
+ return fail(
871
+ `the base URL ${JSON.stringify(baseUrl)} is not a URL`,
872
+ `Check TENJIN_BASE_URL, or set it with \`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\`.`
873
+ );
874
+ }
875
+ const host = new URL(url).host;
876
+ const probe = await httpRequest(url, {
877
+ method: "POST",
878
+ timeoutMs: opts.timeoutMs,
879
+ blockRedirects: true,
880
+ // A reachability check, not use: it must not count this machine as an install.
881
+ anonymous: true,
882
+ jsonBody: {},
883
+ ...opts.fetchImpl !== void 0 ? { fetchImpl: opts.fetchImpl } : {}
884
+ });
885
+ const production = isSameDeployment(new URL(url).origin, PRODUCTION_ORIGIN);
886
+ const checkBase = production ? "Try again later." : "Check that the configured base URL names the Tenjin router (`tenjin config get baseUrl`), then try again later.";
887
+ const env = opts.env ?? process.env;
888
+ const network = networkFix(host, env, production, opts.proxySupported ?? envProxySupported());
889
+ const credentials = proxyCredentialsFix(env);
890
+ const unreached = production ? network : checkBase;
891
+ if (!probe.ok) {
892
+ const t = probe.transport;
893
+ if (t?.layer === "proxy" && t.proxyStatus === 407) {
894
+ return fail(
895
+ `a proxy between this machine and ${host} asked for its own credentials (407)`,
896
+ credentials
897
+ );
898
+ }
899
+ if (t?.layer === "proxy") {
900
+ return fail(
901
+ `a proxy refused the connection to ${host} (${t.proxyStatus}), so the router never answered`,
902
+ unreached
903
+ );
904
+ }
905
+ if (t?.layer === "dns") {
906
+ return fail(`${host} did not resolve (${t.code}), so the router was not reached`, unreached);
907
+ }
908
+ if (t?.layer === "tls") {
909
+ return fail(
910
+ `the TLS connection to ${host} failed (${t.code}). A proxy that inspects TLS causes this`,
911
+ `If this network inspects TLS, set NODE_EXTRA_CA_CERTS to its CA certificate. ${unreached}`
912
+ );
913
+ }
914
+ if (t?.layer === "connect") {
915
+ return fail(`could not connect to ${host} (${t.code})`, unreached);
916
+ }
917
+ return fail(`the router at ${url} is unreachable or erroring (${probe.message})`, unreached);
918
+ }
919
+ if (probe.status === 200 || probe.status === 400 || probe.status === 429) {
920
+ return { name: "router", status: "ok", required: true, detail: `${url} is live` };
921
+ }
922
+ if (probe.status === 404) {
923
+ return fail(`the router is not enabled at ${url}`, checkBase);
924
+ }
925
+ if (probe.status === 407) {
926
+ return fail(
927
+ `a proxy between this machine and ${host} asked for its own credentials (407)`,
928
+ credentials
929
+ );
930
+ }
931
+ if (probe.status === 401 || probe.status === 403) {
932
+ if (!fromDeployment(probe)) {
933
+ return fail(
934
+ `${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`,
935
+ network
936
+ );
937
+ }
938
+ if (production) {
939
+ return fail(`${url} refused this machine (${probe.status})`, checkBase);
940
+ }
941
+ return fail(
942
+ `${url} is not a Tenjin router (it asked for credentials)`,
943
+ `Set the router URL with \`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\`.`
944
+ );
945
+ }
946
+ if (probe.status >= 500) {
947
+ return fail(`the router at ${url} is unreachable or erroring (${probe.status})`, checkBase);
948
+ }
949
+ return fail(
950
+ `${url} answered ${probe.status}, which a Tenjin router does not`,
951
+ "Check that the configured base URL names a Tenjin deployment (`tenjin config get baseUrl`)."
952
+ );
953
+ }
954
+ function fromDeployment(probe) {
955
+ return probe.header("x-vercel-id") !== void 0 || probe.header("x-request-id") !== void 0;
956
+ }
957
+ function networkFix(host, env, production, proxySupported) {
958
+ const proxy = proxyVariable(env);
959
+ const config = production ? " Tenjin's own config is correct and needs no change." : "";
960
+ if (proxy !== void 0 && !proxySupported) {
961
+ 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}`;
962
+ }
963
+ const via = proxy !== void 0 ? ` (this shell sets ${proxy})` : "";
964
+ return `Allow ${host} through your proxy, firewall or VPN${via}, or run from a network that reaches it.${config}`;
965
+ }
966
+ function proxyCredentialsFix(env) {
967
+ const proxy = proxyVariable(env) ?? "HTTPS_PROXY";
968
+ return `Put the proxy's credentials in ${proxy} (\`http://user:password@proxy:port\`), then try again.`;
969
+ }
970
+
971
+ // src/router/install.ts
972
+ var DISCLOSURE = [
973
+ "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.",
974
+ "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.",
975
+ "What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere."
976
+ ];
977
+ var RELOAD_STEP = "type /reload-plugins in this Claude Code session, or start a new session, so Tenjin loads";
978
+ var NEW_SESSION_STEP = "start a new Claude Code session so Tenjin loads";
979
+ function loadStep(settingsInstallPresent) {
980
+ return settingsInstallPresent ? NEW_SESSION_STEP : RELOAD_STEP;
981
+ }
982
+ function settingsInstallPaths(project, env, home, cwd) {
983
+ return project ? {
984
+ settingsPath: join6(cwd, ".claude", "settings.json"),
985
+ mcpFile: projectMcpFile(cwd),
986
+ mcpScope: "project"
987
+ } : {
988
+ settingsPath: userSettingsPath(env, home),
989
+ mcpFile: userMcpFile(env, home),
990
+ mcpScope: "user"
991
+ };
992
+ }
993
+ async function pluginProof(claude, dataDir, env, cwd) {
994
+ if (claude.binary !== null && !claude.meetsFloor) {
995
+ return {
996
+ proven: false,
997
+ reason: `Claude Code ${claude.version ?? "(unknown)"} is older than the plugin needs`
998
+ };
999
+ }
1000
+ if (claude.binary !== null) {
1001
+ const listing = await readPluginListing(claude.binary, env, cwd);
1002
+ if (!listing.enabled) {
1003
+ return { proven: false, reason: "Claude Code does not list the plugin as enabled yet" };
1004
+ }
1005
+ }
1006
+ if (await readAliveStamp(dataDir) === null) {
1007
+ return {
1008
+ proven: false,
1009
+ reason: "the plugin has not loaded in a Claude Code session on this machine yet"
1010
+ };
1011
+ }
1012
+ return { proven: true };
1013
+ }
1014
+ async function migrateSettingsInstall(legacy, claude, opts) {
1015
+ if (!legacy.present) return { state: "none", settingsPath: legacy.settingsPath };
1016
+ const proof = await pluginProof(claude, opts.dataDir, opts.env, opts.cwd);
1017
+ if (!proof.proven) {
1018
+ return { state: "pending", settingsPath: legacy.settingsPath, reason: proof.reason };
1019
+ }
1020
+ const removed = await removeLegacyInstall(legacy, {
1021
+ binary: claude.binary,
1022
+ env: opts.env,
1023
+ cwd: opts.cwd,
1024
+ mcpScope: opts.mcpScope
1025
+ });
1026
+ return { state: "done", settingsPath: legacy.settingsPath, removed };
1027
+ }
1028
+ async function inferRefreshProject(cwd, home, env) {
1029
+ const [cwdPath, homePath] = await Promise.all([
1030
+ realpath(cwd).catch(() => cwd),
1031
+ realpath(home).catch(() => home)
1032
+ ]);
1033
+ if (cwdPath === homePath) return false;
1034
+ const local = await readFile4(join6(cwd, ".claude", "settings.local.json"), "utf8").then((raw) => JSON.parse(raw)).catch(() => null);
1035
+ if (local?.enabledPlugins?.[PLUGIN_ID] === true) return true;
1036
+ if ((await folderState("local", env, home, cwd)).state === "ours") return true;
1037
+ const paths = settingsInstallPaths(true, env, home, cwd);
1038
+ return (await inspectLegacyInstall(paths.settingsPath, paths.mcpFile)).events.length > 0;
1039
+ }
1040
+ async function somethingToRefresh(claude, scope, legacy, env, home, cwd) {
1041
+ if (legacy.present) return true;
1042
+ if ((await folderState(scope, env, home, cwd)).state === "ours") return true;
1043
+ if (claude.binary !== null) {
1044
+ const listing = await readPluginListing(claude.binary, env, cwd);
1045
+ if (listing.id === PLUGIN_ID) return true;
1046
+ }
1047
+ return false;
1048
+ }
1049
+ async function runRouterInstall(args, ctx, deps = {}) {
1050
+ const env = deps.env ?? process.env;
1051
+ const home = deps.homeDir ?? homedir2();
1052
+ if (!isAbsolute2(home)) {
1053
+ throw new CliError("INTERNAL", "The home directory is not an absolute path.", {
1054
+ fix: "Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`."
1055
+ });
1056
+ }
1057
+ const config = await loadRawConfig(ctx.dataDir);
1058
+ const cwd = deps.cwd ?? process.cwd();
1059
+ const project = args.project ?? (args.refresh === true && await inferRefreshProject(cwd, home, env));
1060
+ const scope = project ? "local" : "user";
1061
+ const claude = await readClaudeCode(env, cwd, deps.findClaude ?? findClaudeBinary);
1062
+ const paths = settingsInstallPaths(project, env, home, cwd);
1063
+ const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);
1064
+ if (args.refresh === true && !await somethingToRefresh(claude, scope, legacy, env, home, cwd)) {
1065
+ throw new CliError(
1066
+ "REFUSED",
1067
+ `Nothing to refresh: neither the ${PLUGIN_ID} plugin nor a settings install of Tenjin is registered here.`,
1068
+ { fix: "Run `tenjin install` to set this machine up." }
1069
+ );
1070
+ }
1071
+ const humanOutput = ctx.flags.json === true ? false : deps.isInteractive ?? ctx.io.isTTY;
1072
+ const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));
1073
+ const limits = args.refresh === true ? void 0 : args.yes === true ? shownLimits(config) : canPrompt ? await approveLimits(config, deps) : {};
1074
+ const spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true, limits);
1075
+ const removedKeysLines = spend.removed.length > 0 ? [
1076
+ `Removed retired settings: ${spend.removed.join(", ")}. Automatic router limits remain in effect; manual pay always requires consent.`
1077
+ ] : [];
1078
+ const removedSkills = await removeRetiredSkills(home, project ? cwd : void 0);
1079
+ const plugin = !claude.meetsFloor && legacy.present ? deferredRegistration(scope, claude) : await registerPlugin({
1080
+ binary: claude.binary,
1081
+ scope,
1082
+ version: package_default.version,
1083
+ env,
1084
+ home,
1085
+ cwd,
1086
+ ...deps.hostsDir !== void 0 ? { hostsDir: deps.hostsDir } : {}
1087
+ });
1088
+ const migration = legacy.unreadable !== void 0 && !legacy.present ? { state: "blocked", settingsPath: paths.settingsPath, reason: legacy.unreadable } : await migrateSettingsInstall(legacy, claude, {
1089
+ dataDir: ctx.dataDir,
1090
+ env,
1091
+ cwd,
1092
+ mcpScope: paths.mcpScope
1093
+ });
1094
+ const pending = settingsInstallStays(migration);
1095
+ const servers = await readMcpServers(deps, { settingsInstallPending: pending });
1096
+ const serverLines = servers.stale > 0 ? [paint(ctx.io, "yellow", `! ${servers.check.detail}. ${servers.check.fix ?? ""}`.trim())] : [];
1097
+ const claudeCode = claudeCodeData(claude);
1098
+ const notices = refreshNotices(plugin, claude, migration);
1099
+ if (args.refresh === true) {
1100
+ if (plugin.state === "failed" && migration.state !== "pending") {
1101
+ throw new CliError(
1102
+ "REFUSED",
1103
+ `The ${PLUGIN_ID} plugin could not be registered: ${plugin.reason ?? "unknown reason"}.`,
1104
+ { fix: registrationFix(plugin), details: { plugin, claudeCode, migration } }
1105
+ );
1106
+ }
1107
+ return {
1108
+ data: {
1109
+ plugin,
1110
+ claudeCode,
1111
+ migration,
1112
+ notices,
1113
+ refresh: true,
1114
+ spend,
1115
+ removedSkills,
1116
+ scope,
1117
+ mcpServer: servers.check
1118
+ },
1119
+ humanLines: [
1120
+ ...refreshLines(ctx, plugin, claude, migration),
1121
+ ...removedKeysLines,
1122
+ ...serverLines
1123
+ ]
1124
+ };
1125
+ }
1126
+ const { resolveWallet } = await import("./install-wallet-Z52EDLPB.js");
1127
+ const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? "flag" : void 0, false);
1128
+ const effective = await resolveContextSettings(ctx);
1129
+ const approval = !canPrompt && args.yes !== true && !spend.kept.includes("maxAutoSpend") ? spendApproval(config, args) : void 0;
1130
+ const router = await probeRouter(effective.baseUrl, {
1131
+ timeoutMs: ctx.flags.timeout,
1132
+ env,
1133
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
1134
+ });
1135
+ const data = {
1136
+ plugin,
1137
+ claudeCode,
1138
+ migration,
1139
+ next: nextStep(plugin, claude, wallet, migration),
1140
+ spend: {
1141
+ ...spend,
1142
+ effective: effectiveLimits(effective.policy),
1143
+ ...approval !== void 0 ? { approval } : {}
1144
+ },
1145
+ wallet,
1146
+ router: {
1147
+ status: router.status === "ok" ? "ok" : "warn",
1148
+ detail: router.detail,
1149
+ ...router.fix !== void 0 ? { fix: router.fix } : {}
1150
+ },
1151
+ disclosure: DISCLOSURE,
1152
+ removedSkills,
1153
+ mcpServer: servers.check
1154
+ };
1155
+ return {
1156
+ data,
1157
+ humanLines: [
1158
+ ...lines(ctx, {
1159
+ plugin,
1160
+ claude,
1161
+ migration,
1162
+ wallet,
1163
+ policy: effective.policy,
1164
+ ...approval !== void 0 ? { approval } : {},
1165
+ router
1166
+ }),
1167
+ ...removedKeysLines,
1168
+ ...serverLines
1169
+ ]
1170
+ };
1171
+ }
1172
+ function claudeCodeData(claude) {
1173
+ return {
1174
+ binary: claude.binary?.path ?? null,
1175
+ source: claude.binary?.source ?? null,
1176
+ version: claude.version,
1177
+ meetsFloor: claude.meetsFloor,
1178
+ ...claude.fix !== void 0 ? { fix: claude.fix } : {}
1179
+ };
1180
+ }
1181
+ function registrationFix(plugin) {
1182
+ if (plugin.id !== null && plugin.method === "none") {
1183
+ return `${plugin.id} keeps serving this machine at the version Claude Code has; run \`tenjin install\` again to retry.`;
1184
+ }
1185
+ if (plugin.path !== void 0 && plugin.reason?.includes("not a folder this CLI wrote") === true) {
1186
+ return `Move ${plugin.path} aside, then run \`tenjin install\` again.`;
1187
+ }
1188
+ return "Run `tenjin doctor` to see the cause, then run `tenjin install` again.";
1189
+ }
1190
+ function nextStep(plugin, claude, wallet, migration) {
1191
+ if (plugin.state === "failed") return registrationFix(plugin);
1192
+ const steps = [];
1193
+ if (wallet.status === "created") steps.push("fund the wallet with `tenjin wallet fund`");
1194
+ if (plugin.state === "deferred") {
1195
+ steps.unshift("run `claude update`");
1196
+ steps.push(
1197
+ "run `tenjin install` again; until then the earlier Tenjin setup keeps routing as before"
1198
+ );
1199
+ return steps.join(", then ");
1200
+ }
1201
+ if (!claude.meetsFloor) steps.unshift("run `claude update`");
1202
+ steps.push(loadStep(settingsInstallStays(migration)));
1203
+ return steps.join(", then ");
1204
+ }
1205
+ function settingsInstallStays(migration) {
1206
+ return migration.state === "pending" || migration.state === "blocked";
1207
+ }
1208
+ function deferredRegistration(scope, claude) {
1209
+ return {
1210
+ method: "none",
1211
+ id: null,
1212
+ scope,
1213
+ state: "deferred",
1214
+ version: package_default.version,
1215
+ steps: [],
1216
+ reason: `Claude Code ${claude.version ?? ""} is older than ${CLAUDE_CODE_FLOOR}, which the plugin needs, so it was not registered and the earlier settings setup keeps routing`
1217
+ };
1218
+ }
1219
+ function statusLineNotice(migration) {
1220
+ const status = migration.removed?.statusLine;
1221
+ if (status === "removed") {
1222
+ return "Removed the Tenjin status line (`tenjin status-line`) with the earlier settings setup; the plugin sets none. To keep it, set `tenjin status-line` as your Claude Code status line command.";
1223
+ }
1224
+ if (status === "restored") {
1225
+ return "Took the Tenjin footer out of your status line and put your own command back; the plugin sets none.";
1226
+ }
1227
+ return null;
1228
+ }
1229
+ function refreshNotices(plugin, claude, migration) {
1230
+ const out = [];
1231
+ if (plugin.state === "deferred") {
1232
+ out.push(
1233
+ `Claude Code ${claude.version ?? ""} is older than ${CLAUDE_CODE_FLOOR}, so the Tenjin plugin was not registered and the earlier settings setup keeps routing. Run \`claude update\`, then \`tenjin install\`.`
1234
+ );
1235
+ } else if (plugin.state !== "failed" && settingsInstallStays(migration)) {
1236
+ out.push(
1237
+ "Start a new Claude Code session so the Tenjin plugin loads; the earlier settings setup is removed by the next `tenjin update` or `tenjin install` after that."
1238
+ );
1239
+ }
1240
+ const status = statusLineNotice(migration);
1241
+ if (status !== null) out.push(status);
1242
+ return out;
1243
+ }
1244
+ var AUTO_SPEND_FIX = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;
1245
+ var DECLINED = "the router then pays for nothing on its own, and the question stays open until the user answers it";
1246
+ function spendApproval(config, args) {
1247
+ const limits = shownLimits(config);
1248
+ const approve = yesCommand(args);
1249
+ return {
1250
+ question: spendQuestion(limits),
1251
+ limits: limitsUsd(limits),
1252
+ routingFee: ROUTING_FEE_TERMS,
1253
+ 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}.`,
1254
+ approve,
1255
+ own: OWN_LIMITS_COMMANDS.replaceAll("`", "")
1256
+ };
1257
+ }
1258
+ function yesCommand(args) {
1259
+ return [
1260
+ "tenjin install",
1261
+ ...args.project === true ? ["--project"] : [],
1262
+ ...args.noWallet === true ? ["--no-wallet"] : [],
1263
+ "--yes"
1264
+ ].join(" ");
1265
+ }
1266
+ async function approveLimits(config, deps) {
1267
+ const shown = shownLimits(config);
1268
+ const askCall = config.maxAutoSpend === void 0;
1269
+ const askDay = config.sessionBudget === void 0;
1270
+ if (!askCall && !askDay) return void 0;
1271
+ const daily = shown.sessionBudget === "none" ? "no daily limit" : `$${toMoney(shown.sessionBudget).usd} a day`;
1272
+ const fee = `
1273
+ ${ROUTING_FEE_TERMS}
1274
+ ${FEE_APPROVAL}`;
1275
+ const choice = await (deps.promptLimits ?? promptLimits)(
1276
+ `The router pays for tool calls without asking, up to:
1277
+ $${toMoney(shown.maxAutoSpend).usd} a call, ${daily}${fee}`
1278
+ );
1279
+ if (choice === null) throw installCancelled();
1280
+ if (choice === "approve") return shown;
1281
+ const ask = deps.promptAmount ?? promptAmount;
1282
+ return {
1283
+ maxAutoSpend: askCall ? await askLimit(ask, "Most the router may pay for one call, in USD", "0.25", false) : shown.maxAutoSpend,
1284
+ sessionBudget: askDay ? await askLimit(ask, "Most it may pay in a day, in USD, or none", "5", true) : shown.sessionBudget
1285
+ };
1286
+ }
1287
+ async function askLimit(ask, question, placeholder, allowNone) {
1288
+ let message = question;
1289
+ for (; ; ) {
1290
+ const answer = await ask(message, placeholder);
1291
+ if (answer === null) throw installCancelled();
1292
+ const parsed = parseLimit(answer, allowNone);
1293
+ if (!("refusal" in parsed)) return parsed.value;
1294
+ message = `${parsed.refusal} ${question}`;
1295
+ }
1296
+ }
1297
+ function parseLimit(answer, allowNone) {
1298
+ const trimmed = answer.trim();
1299
+ if (allowNone && trimmed === "none") return { value: "none" };
1300
+ let atomic;
1301
+ try {
1302
+ atomic = parseUsdToAtomic(trimmed);
1303
+ } catch (err) {
1304
+ if (err instanceof CliError) return { refusal: `${err.message}.` };
1305
+ throw err;
1306
+ }
1307
+ if (atomic === "0") return { refusal: "The limit must be more than zero." };
1308
+ return { value: atomic };
1309
+ }
1310
+ function installCancelled() {
1311
+ return new CliError("REFUSED", "Install cancelled before anything was written.", {
1312
+ fix: "Re-run `tenjin install` and choose the spend limits."
1313
+ });
1314
+ }
1315
+ function promptLimits(message) {
1316
+ return selectOne({
1317
+ message,
1318
+ choices: [
1319
+ { value: "approve", label: "Use these limits" },
1320
+ { value: "own", label: "Choose my own" }
1321
+ ],
1322
+ initialValue: "approve"
1323
+ });
1324
+ }
1325
+ function promptAmount(message, placeholder) {
1326
+ return askText({ message, placeholder });
1327
+ }
1328
+ function effectiveLimits(policy) {
1329
+ return {
1330
+ maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,
1331
+ sessionBudget: policy.sessionBudgetAtomic === null ? "no daily ceiling" : toMoney(policy.sessionBudgetAtomic.toString()).usd
1332
+ };
1333
+ }
1334
+ function walletLines(ctx, ok, w) {
1335
+ if (w.status === "created") return [`${ok} Wallet created: ${w.address}`];
1336
+ if (w.status === "existing") return [`${ok} Wallet: ${w.address}`];
1337
+ if (w.reason === "flag") return [" No wallet yet. Create one with: tenjin wallet create"];
1338
+ return [
1339
+ paint(ctx.io, "yellow", `! No wallet was created. ${w.warning ?? ""}`.trimEnd()),
1340
+ ` ${w.fix ?? "Create one with: tenjin wallet create"}`
1341
+ ];
1342
+ }
1343
+ function pluginLines(ctx, plugin) {
1344
+ const warn = (text) => paint(ctx.io, "yellow", `! ${text}`);
1345
+ if (plugin.state === "deferred") return [warn(`${plugin.reason ?? ""}`)];
1346
+ if (plugin.state === "failed") {
1347
+ return [warn(`The Tenjin plugin was not registered: ${plugin.reason ?? "unknown reason"}`)];
1348
+ }
1349
+ if (plugin.method === "skills-dir") {
1350
+ return [
1351
+ ` Plugin ${plugin.id ?? ""} written to ${plugin.path ?? ""} (${plugin.fallbackReason ?? ""})`
1352
+ ];
1353
+ }
1354
+ return [];
1355
+ }
1356
+ function migrationLines(ctx, migration) {
1357
+ const warn = (text) => paint(ctx.io, "yellow", `! ${text}`);
1358
+ if (migration.state === "pending") {
1359
+ return [
1360
+ ` The settings install in ${migration.settingsPath} stays until the plugin has loaded (${migration.reason ?? ""}); \`tenjin update\` or \`tenjin install\` removes it then.`
1361
+ ];
1362
+ }
1363
+ if (migration.state === "blocked") {
1364
+ return [warn(`${migration.settingsPath} could not be read: ${migration.reason ?? ""}`)];
1365
+ }
1366
+ if (migration.state === "done") {
1367
+ const removed = migration.removed;
1368
+ const status = statusLineNotice(migration);
1369
+ return [
1370
+ ` Removed the earlier settings setup from ${migration.settingsPath}: the plugin carries its hooks, permissions and server`,
1371
+ ...status !== null ? [` ${status}`] : [],
1372
+ ...(removed?.warnings ?? []).map((w) => warn(w))
1373
+ ];
1374
+ }
1375
+ return [];
1376
+ }
1377
+ function claudeLines(ctx, claude) {
1378
+ if (claude.meetsFloor) return [];
1379
+ return [
1380
+ paint(
1381
+ ctx.io,
1382
+ "yellow",
1383
+ `! Claude Code ${claude.version ?? ""} is older than the plugin needs. ${claude.fix ?? ""}`.trim()
1384
+ )
1385
+ ];
1386
+ }
1387
+ function lines(ctx, s) {
1388
+ const ok = paint(ctx.io, "green", "\u2713");
1389
+ const warn = (text) => paint(ctx.io, "yellow", `! ${text}`);
1390
+ const limits = effectiveLimits(s.policy);
1391
+ const daily = s.policy.sessionBudgetAtomic === null ? "no daily limit" : `$${limits.sessionBudget} a day`;
1392
+ const spend = s.approval !== void 0 ? [
1393
+ warn("Automatic payments are off until the user approves a spend limit"),
1394
+ ` Ask the user in this session: ${s.approval.question}`,
1395
+ ` Yes: ${s.approval.approve}`,
1396
+ ` Other amounts: ${s.approval.own}`,
1397
+ ` No: run nothing, ${DECLINED.replaceAll("`", "")}`
1398
+ ] : s.policy.maxAutoSpendAtomic === 0n ? [
1399
+ warn("Automatic payments are off: every paid lookup needs your approval"),
1400
+ ` To let the router pay without asking, run: ${AUTO_SPEND_FIX}`
1401
+ ] : [` Automatic router: up to $${limits.maxAutoSpend} per call; daily limit ${daily}`];
1402
+ const router = s.router.status === "ok" ? [] : [
1403
+ warn(`The router did not answer: ${s.router.detail}`),
1404
+ ...s.router.fix !== void 0 ? [` ${s.router.fix}`] : []
1405
+ ];
1406
+ return [
1407
+ s.plugin.state === "failed" ? warn("Tenjin could not finish setting up Claude Code") : s.plugin.state === "deferred" ? warn("Tenjin keeps its earlier Claude Code setup until Claude Code is updated") : `${ok} Tenjin is set up for Claude Code (plugin ${s.plugin.id ?? PLUGIN_ID})`,
1408
+ ...walletLines(ctx, ok, s.wallet),
1409
+ ...spend,
1410
+ ...pluginLines(ctx, s.plugin),
1411
+ ...claudeLines(ctx, s.claude),
1412
+ ...migrationLines(ctx, s.migration),
1413
+ ...router,
1414
+ "",
1415
+ `Next: ${nextStep(s.plugin, s.claude, s.wallet, s.migration)}`
1416
+ ];
1417
+ }
1418
+ function refreshLines(ctx, plugin, claude, migration) {
1419
+ const issues = [
1420
+ ...pluginLines(ctx, plugin),
1421
+ ...claudeLines(ctx, claude),
1422
+ ...migrationLines(ctx, migration)
1423
+ ];
1424
+ const head = plugin.state === "failed" ? paint(ctx.io, "yellow", "! Tenjin is updated, but its plugin was not registered") : plugin.state === "deferred" ? paint(ctx.io, "yellow", "! Tenjin is updated; its plugin waits for a newer Claude Code") : `${paint(ctx.io, "green", "\u2713")} Tenjin is up to date (plugin ${plugin.id ?? PLUGIN_ID})`;
1425
+ return [head, ...issues];
1426
+ }
1427
+
1428
+ export {
1429
+ CLAUDE_CODE_FLOOR,
1430
+ claudeConfigDir,
1431
+ findClaudeBinary,
1432
+ runClaude,
1433
+ jsonResult,
1434
+ jsonList,
1435
+ readClaudeCode,
1436
+ inspectLegacyInstall,
1437
+ removeLegacyInstall,
1438
+ ROUTE_HOOK_TIMEOUT_SECONDS,
1439
+ AFTER_CALL_TIMEOUT_SECONDS,
1440
+ removePluginFolder,
1441
+ folderFor,
1442
+ ownMarketplace,
1443
+ readPluginListing,
1444
+ folderState,
1445
+ probeRouter,
1446
+ DISCLOSURE,
1447
+ RELOAD_STEP,
1448
+ NEW_SESSION_STEP,
1449
+ loadStep,
1450
+ settingsInstallPaths,
1451
+ pluginProof,
1452
+ migrateSettingsInstall,
1453
+ runRouterInstall
1454
+ };
1455
+ //# sourceMappingURL=chunk-VSUHGRVB.js.map