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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +13 -10
  2. package/dist/{chunk-ZG6ZZLO7.js → chunk-25GGN553.js} +9 -11
  3. package/dist/{chunk-ZG6ZZLO7.js.map → chunk-25GGN553.js.map} +1 -1
  4. package/dist/{chunk-B2L53TMK.js → chunk-2SNUOHAT.js} +28 -23
  5. package/dist/chunk-2SNUOHAT.js.map +1 -0
  6. package/dist/{chunk-UEOWNDQG.js → chunk-3FY5HG7R.js} +82 -13
  7. package/dist/chunk-3FY5HG7R.js.map +1 -0
  8. package/dist/{chunk-DJYAPACT.js → chunk-4FYMDRD3.js} +32 -24
  9. package/dist/chunk-4FYMDRD3.js.map +1 -0
  10. package/dist/{chunk-ZP7AHN7Z.js → chunk-AMEUXNJT.js} +3 -5
  11. package/dist/{chunk-ZP7AHN7Z.js.map → chunk-AMEUXNJT.js.map} +1 -1
  12. package/dist/chunk-EWLU46J6.js +100 -0
  13. package/dist/chunk-EWLU46J6.js.map +1 -0
  14. package/dist/{chunk-RLPLYUME.js → chunk-LRCJ2IZ5.js} +3 -3
  15. package/dist/{chunk-RLPLYUME.js.map → chunk-LRCJ2IZ5.js.map} +1 -1
  16. package/dist/{chunk-YFJJYHVG.js → chunk-LX5OT4TQ.js} +3 -3
  17. package/dist/{chunk-YFJJYHVG.js.map → chunk-LX5OT4TQ.js.map} +1 -1
  18. package/dist/{chunk-ZO3X5NPG.js → chunk-MG3G644T.js} +4 -4
  19. package/dist/{chunk-6KA4HFX5.js → chunk-MOG7PB3A.js} +3 -3
  20. package/dist/{chunk-DYSDQE7S.js → chunk-MRUPDSUM.js} +14 -93
  21. package/dist/chunk-MRUPDSUM.js.map +1 -0
  22. package/dist/{chunk-KAMRYUK2.js → chunk-OOSRB3OF.js} +2 -2
  23. package/dist/{chunk-PZ5N6BAL.js → chunk-ORWL5BSN.js} +5 -4
  24. package/dist/chunk-ORWL5BSN.js.map +1 -0
  25. package/dist/chunk-P4LVLFO4.js +29 -0
  26. package/dist/chunk-P4LVLFO4.js.map +1 -0
  27. package/dist/{chunk-ZP5PV3JB.js → chunk-QTGUDCIR.js} +5 -5
  28. package/dist/{chunk-FQ6DHINU.js → chunk-R4AO7GC2.js} +437 -78
  29. package/dist/chunk-R4AO7GC2.js.map +1 -0
  30. package/dist/{chunk-UOW5JXYY.js → chunk-RJEPZMYY.js} +10 -4
  31. package/dist/chunk-RJEPZMYY.js.map +1 -0
  32. package/dist/{chunk-VSUHGRVB.js → chunk-SBL4THYT.js} +712 -93
  33. package/dist/chunk-SBL4THYT.js.map +1 -0
  34. package/dist/{chunk-BRHREK7E.js → chunk-SFEQGENI.js} +2 -2
  35. package/dist/{chunk-K6AXXYCG.js → chunk-SJLTEINJ.js} +10 -2
  36. package/dist/{chunk-K6AXXYCG.js.map → chunk-SJLTEINJ.js.map} +1 -1
  37. package/dist/{chunk-XVTD7UWR.js → chunk-TROZ6HL4.js} +2 -2
  38. package/dist/{chunk-3QJREVMX.js → chunk-USOLCBKC.js} +5 -5
  39. package/dist/{chunk-W6JX4LYF.js → chunk-VKQXVCZR.js} +46 -5
  40. package/dist/chunk-VKQXVCZR.js.map +1 -0
  41. package/dist/{chunk-QTND6XWJ.js → chunk-VVAHFCX2.js} +51 -3
  42. package/dist/chunk-VVAHFCX2.js.map +1 -0
  43. package/dist/{chunk-7H3RN4WJ.js → chunk-WM7TJEBP.js} +5 -5
  44. package/dist/{chunk-MNTQMZJB.js → chunk-XDYKZRLN.js} +22 -13
  45. package/dist/chunk-XDYKZRLN.js.map +1 -0
  46. package/dist/{chunk-A5H3E5QA.js → chunk-XJQ6CH7X.js} +3 -2
  47. package/dist/{chunk-7R37M6WV.js → chunk-ZQNGTLOC.js} +5 -5
  48. package/dist/{cli-234DNHN6.js → cli-JPTDHGRX.js} +38 -33
  49. package/dist/{cli-234DNHN6.js.map → cli-JPTDHGRX.js.map} +1 -1
  50. package/dist/{config-IY2OJCAK.js → config-YYKDH2TH.js} +11 -11
  51. package/dist/{doctor-2UZZF44A.js → doctor-SSTXGCHX.js} +60 -56
  52. package/dist/doctor-SSTXGCHX.js.map +1 -0
  53. package/dist/{fund-RZ2QFULK.js → fund-QWVWRVDK.js} +14 -16
  54. package/dist/{fund-RZ2QFULK.js.map → fund-QWVWRVDK.js.map} +1 -1
  55. package/dist/hook-command-VWJXRT7H.js +31 -0
  56. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  57. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  58. package/dist/hosts/claude/tenjin/.mcp.json +2 -1
  59. package/dist/hosts/claude/tenjin/hooks/hooks.json +18 -3
  60. package/dist/index.js +6 -6
  61. package/dist/{install-O5FJ5EP3.js → install-2GXXD4DK.js} +19 -16
  62. package/dist/{install-identity-QM44IQ6Z.js → install-identity-FK3YF227.js} +7 -8
  63. package/dist/{install-wallet-Z52EDLPB.js → install-wallet-TC22U52X.js} +17 -12
  64. package/dist/{install-wallet-Z52EDLPB.js.map → install-wallet-TC22U52X.js.map} +1 -1
  65. package/dist/{mcp-33HAADDF.js → mcp-42H2F4NY.js} +2091 -348
  66. package/dist/mcp-42H2F4NY.js.map +1 -0
  67. package/dist/{package-RT24HTTP.js → package-6DJA3Y2O.js} +2 -2
  68. package/dist/{paths-MUXHUOCM.js → paths-POPTXJO6.js} +6 -2
  69. package/dist/{pay-IR2V76FX.js → pay-LSDJBIAZ.js} +18 -15
  70. package/dist/payments-SPECLBRQ.js +105 -0
  71. package/dist/payments-SPECLBRQ.js.map +1 -0
  72. package/dist/{send-PI4NUA7I.js → send-MHAOLPK3.js} +12 -14
  73. package/dist/{send-PI4NUA7I.js.map → send-MHAOLPK3.js.map} +1 -1
  74. package/dist/status-O2RWLPS5.js +114 -0
  75. package/dist/status-O2RWLPS5.js.map +1 -0
  76. package/dist/{status-line-2G5JPQAE.js → status-line-45TVCRM3.js} +7 -8
  77. package/dist/{status-line-2G5JPQAE.js.map → status-line-45TVCRM3.js.map} +1 -1
  78. package/dist/{uninstall-THKUH5ZT.js → uninstall-VOK2Z5M4.js} +27 -17
  79. package/dist/uninstall-VOK2Z5M4.js.map +1 -0
  80. package/dist/update-FGP3HNLD.js +33 -0
  81. package/dist/{wallet-53EFH4M5.js → wallet-DA7OFNEW.js} +17 -12
  82. package/docs/agent-permissions.md +11 -8
  83. package/docs/safety-model.md +3 -1
  84. package/package.json +2 -2
  85. package/dist/chunk-AO54FM4H.js +0 -563
  86. package/dist/chunk-AO54FM4H.js.map +0 -1
  87. package/dist/chunk-B2L53TMK.js.map +0 -1
  88. package/dist/chunk-DJYAPACT.js.map +0 -1
  89. package/dist/chunk-DYSDQE7S.js.map +0 -1
  90. package/dist/chunk-FQ6DHINU.js.map +0 -1
  91. package/dist/chunk-FZTSGQVK.js +0 -52
  92. package/dist/chunk-FZTSGQVK.js.map +0 -1
  93. package/dist/chunk-MNTQMZJB.js.map +0 -1
  94. package/dist/chunk-PZ5N6BAL.js.map +0 -1
  95. package/dist/chunk-QTND6XWJ.js.map +0 -1
  96. package/dist/chunk-UEOWNDQG.js.map +0 -1
  97. package/dist/chunk-UOW5JXYY.js.map +0 -1
  98. package/dist/chunk-VSUHGRVB.js.map +0 -1
  99. package/dist/chunk-W6JX4LYF.js.map +0 -1
  100. package/dist/doctor-2UZZF44A.js.map +0 -1
  101. package/dist/hook-command-PZHKS7ES.js +0 -31
  102. package/dist/mcp-33HAADDF.js.map +0 -1
  103. package/dist/payments-GFV4HU5R.js +0 -47
  104. package/dist/payments-GFV4HU5R.js.map +0 -1
  105. package/dist/status-ZUHTJK46.js +0 -71
  106. package/dist/status-ZUHTJK46.js.map +0 -1
  107. package/dist/uninstall-THKUH5ZT.js.map +0 -1
  108. package/dist/update-NPZDP24E.js +0 -18
  109. /package/dist/{chunk-ZO3X5NPG.js.map → chunk-MG3G644T.js.map} +0 -0
  110. /package/dist/{chunk-6KA4HFX5.js.map → chunk-MOG7PB3A.js.map} +0 -0
  111. /package/dist/{chunk-KAMRYUK2.js.map → chunk-OOSRB3OF.js.map} +0 -0
  112. /package/dist/{chunk-ZP5PV3JB.js.map → chunk-QTGUDCIR.js.map} +0 -0
  113. /package/dist/{chunk-BRHREK7E.js.map → chunk-SFEQGENI.js.map} +0 -0
  114. /package/dist/{chunk-XVTD7UWR.js.map → chunk-TROZ6HL4.js.map} +0 -0
  115. /package/dist/{chunk-3QJREVMX.js.map → chunk-USOLCBKC.js.map} +0 -0
  116. /package/dist/{chunk-7H3RN4WJ.js.map → chunk-WM7TJEBP.js.map} +0 -0
  117. /package/dist/{chunk-A5H3E5QA.js.map → chunk-XJQ6CH7X.js.map} +0 -0
  118. /package/dist/{chunk-7R37M6WV.js.map → chunk-ZQNGTLOC.js.map} +0 -0
  119. /package/dist/{config-IY2OJCAK.js.map → config-YYKDH2TH.js.map} +0 -0
  120. /package/dist/{hook-command-PZHKS7ES.js.map → hook-command-VWJXRT7H.js.map} +0 -0
  121. /package/dist/{install-O5FJ5EP3.js.map → install-2GXXD4DK.js.map} +0 -0
  122. /package/dist/{install-identity-QM44IQ6Z.js.map → install-identity-FK3YF227.js.map} +0 -0
  123. /package/dist/{package-RT24HTTP.js.map → package-6DJA3Y2O.js.map} +0 -0
  124. /package/dist/{paths-MUXHUOCM.js.map → paths-POPTXJO6.js.map} +0 -0
  125. /package/dist/{pay-IR2V76FX.js.map → pay-LSDJBIAZ.js.map} +0 -0
  126. /package/dist/{update-NPZDP24E.js.map → update-FGP3HNLD.js.map} +0 -0
  127. /package/dist/{wallet-53EFH4M5.js.map → wallet-DA7OFNEW.js.map} +0 -0
@@ -1,17 +1,25 @@
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-W6JX4LYF.js";
4
+ } from "./chunk-VKQXVCZR.js";
5
+ import {
6
+ NUDGE_OPT_OUT,
7
+ channelTag,
8
+ fetchDistTags,
9
+ isNewer,
10
+ resolveTarget
11
+ } from "./chunk-WM7TJEBP.js";
5
12
  import {
6
13
  CLI_SKILL_NAMES,
7
14
  RETIRED_SKILL_NAMES,
8
15
  SHIPPED_SKILL_FILES,
9
16
  inspectHooksFile,
10
17
  persistRouterDefaults,
18
+ persistRouterProject,
11
19
  readSkillFile,
12
20
  skillFrontmatterName,
13
21
  skillsDirsFor
14
- } from "./chunk-ZG6ZZLO7.js";
22
+ } from "./chunk-25GGN553.js";
15
23
  import {
16
24
  HOOK_TOOL,
17
25
  hookToolInput
@@ -35,18 +43,16 @@ import {
35
43
  limitsUsd,
36
44
  shownLimits,
37
45
  spendQuestion
38
- } from "./chunk-DYSDQE7S.js";
46
+ } from "./chunk-EWLU46J6.js";
39
47
  import {
40
48
  askText,
41
49
  selectOne
42
50
  } from "./chunk-P7LABKCW.js";
43
51
  import {
44
- readMcpServers,
45
- versionFreeEntry
46
- } from "./chunk-AO54FM4H.js";
47
- import {
48
- paint
49
- } from "./chunk-XVTD7UWR.js";
52
+ emitWriteNotice,
53
+ paint,
54
+ sanitizeForTerminal
55
+ } from "./chunk-TROZ6HL4.js";
50
56
  import {
51
57
  readAliveStamp
52
58
  } from "./chunk-6W5GYG3W.js";
@@ -56,37 +62,197 @@ import {
56
62
  } from "./chunk-S4SAZ7OD.js";
57
63
  import {
58
64
  httpRequest
59
- } from "./chunk-UOW5JXYY.js";
65
+ } from "./chunk-RJEPZMYY.js";
60
66
  import {
61
67
  hasCode
62
68
  } from "./chunk-2I4QTOLB.js";
63
69
  import {
64
70
  resolveContextSettings
65
- } from "./chunk-ZP7AHN7Z.js";
66
- import {
67
- parseUsdToAtomic,
68
- toMoney
69
- } from "./chunk-FZTSGQVK.js";
71
+ } from "./chunk-AMEUXNJT.js";
70
72
  import {
71
73
  CliError,
72
74
  PRODUCTION_ORIGIN,
73
75
  isSameDeployment,
74
76
  loadRawConfig,
77
+ parseUsdToAtomic,
78
+ toMoney,
75
79
  writeFileAtomic
76
- } from "./chunk-QTND6XWJ.js";
80
+ } from "./chunk-VVAHFCX2.js";
81
+ import {
82
+ defaultDataDir
83
+ } from "./chunk-SJLTEINJ.js";
77
84
  import {
78
85
  package_default
79
- } from "./chunk-RLPLYUME.js";
86
+ } from "./chunk-LRCJ2IZ5.js";
87
+
88
+ // src/commands/update.ts
89
+ import { spawn } from "node:child_process";
90
+ import { existsSync as existsSync2, statSync as statSync3 } from "node:fs";
91
+ import { homedir as homedir3 } from "node:os";
92
+ import { resolve, sep as sep3 } from "node:path";
93
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
94
+
95
+ // src/lib/install-location.ts
96
+ import { existsSync, realpathSync, statSync } from "node:fs";
97
+ import { delimiter, dirname, join, sep } from "node:path";
98
+ var REFUSALS = [
99
+ {
100
+ test: isSourceCheckout,
101
+ error: () => new CliError("REFUSED", "tenjin-cli is running from a source checkout, not an install", {
102
+ fix: "Update the checkout instead: git pull && pnpm install"
103
+ }),
104
+ needsVersion: false,
105
+ appliesToCheck: false
106
+ },
107
+ {
108
+ test: (moduleDir) => moduleDir.split(sep).includes("_npx"),
109
+ error: (spec) => new CliError("REFUSED", "tenjin-cli is running from the npx cache, not an install", {
110
+ // Writing a global here would "succeed" and change nothing: the next
111
+ // `npx tenjin` still resolves its own cached copy.
112
+ fix: `npx fetches its own copy every time. To keep one: npm i -g ${spec}`
113
+ }),
114
+ needsVersion: true,
115
+ appliesToCheck: false
116
+ },
117
+ {
118
+ // The ONLY manager still refused. `yarn global add` is yarn-1 only, and
119
+ // berry dropped global installs altogether, so there is no one command this
120
+ // can drive across the versions a user might have. Every other manager is
121
+ // delegated to rather than refused (see MANAGERS).
122
+ test: (moduleDir) => classifyManager(moduleDir) === "yarn",
123
+ error: (spec) => new CliError(
124
+ "REFUSED",
125
+ "This tenjin-cli was installed with yarn, whose global install exists only in yarn 1",
126
+ { fix: `yarn global add ${spec}` }
127
+ ),
128
+ needsVersion: true,
129
+ appliesToCheck: false
130
+ },
131
+ {
132
+ // Scoped to npm on purpose: the prefix-vs-project-root test is written for
133
+ // npm's layout. pnpm's global store and bun's global dir both keep a
134
+ // package.json beside `node_modules`, so an unscoped test would read either
135
+ // as a project-local install and refuse the very case we now delegate.
136
+ test: (moduleDir) => classifyManager(moduleDir) === "npm" && !isGlobalTree(moduleDir),
137
+ error: (spec) => new CliError(
138
+ "REFUSED",
139
+ "This tenjin-cli is a project-local dependency, not a global install",
140
+ {
141
+ fix: `Update it where it is declared: npm i ${spec}`
142
+ }
143
+ ),
144
+ needsVersion: true,
145
+ appliesToCheck: false
146
+ }
147
+ ];
148
+ function refuse(moduleDir, opts) {
149
+ for (const entry of REFUSALS) {
150
+ if (opts.check && !entry.appliesToCheck) continue;
151
+ if (entry.needsVersion !== (opts.spec !== null)) continue;
152
+ if (entry.test(moduleDir)) throw entry.error(opts.spec ?? "", moduleDir);
153
+ }
154
+ }
155
+ function isSourceCheckout(moduleDir) {
156
+ let dir = moduleDir;
157
+ for (let i = 0; i < 8; i += 1) {
158
+ if (existsSync(join(dir, "package.json"))) return existsSync(join(dir, "src"));
159
+ const parent = dirname(dir);
160
+ if (parent === dir) break;
161
+ dir = parent;
162
+ }
163
+ return false;
164
+ }
165
+ function isGlobalTree(moduleDir) {
166
+ const segs = moduleDir.split(sep);
167
+ const i = segs.lastIndexOf("node_modules");
168
+ if (i <= 0) return false;
169
+ return !existsSync(join(segs.slice(0, i).join(sep), "package.json"));
170
+ }
171
+ function classifyManager(moduleDir) {
172
+ const segs = moduleDir.split(sep);
173
+ const pair = (a, b) => segs.includes(a) && segs.includes(b);
174
+ if (segs.includes(".pnpm") || pair("pnpm", "global")) return "pnpm";
175
+ if (segs.includes(".bun")) return "bun";
176
+ if (segs.includes(".yarn") || pair("yarn", "global")) return "yarn";
177
+ return "npm";
178
+ }
179
+ var MANAGERS = {
180
+ npm: {
181
+ bin: "npm",
182
+ scriptSuffixes: ["npm-cli.js"],
183
+ besideNode: true,
184
+ args: (spec) => ["install", "-g", "--ignore-scripts", spec],
185
+ manual: (spec) => `npm i -g ${spec}`
186
+ },
187
+ pnpm: {
188
+ bin: "pnpm",
189
+ // corepack's shim resolves to `pnpm.js`, a standalone install to `pnpm.cjs`.
190
+ scriptSuffixes: [".cjs", ".js"],
191
+ besideNode: false,
192
+ args: (spec) => ["add", "-g", "--ignore-scripts", spec],
193
+ manual: (spec) => `pnpm add -g ${spec}`
194
+ },
195
+ bun: {
196
+ bin: "bun",
197
+ scriptSuffixes: [],
198
+ besideNode: false,
199
+ // No --ignore-scripts: bun's flag surface for it is not stable across the
200
+ // versions in the wild, and an unknown flag would fail the install outright.
201
+ args: (spec) => ["add", "-g", spec],
202
+ manual: (spec) => `bun add -g ${spec}`
203
+ }
204
+ };
205
+ function resolveManagerScript(manager, execPath, env = process.env) {
206
+ const plan = MANAGERS[manager];
207
+ if (plan.scriptSuffixes.length === 0) return null;
208
+ const beside = plan.besideNode ? scriptNear(dirname(execPath), plan.bin) : null;
209
+ return beside ?? scriptOnPath(plan.bin, plan.scriptSuffixes, env);
210
+ }
211
+ function scriptNear(dir, bin) {
212
+ const candidates = [
213
+ join(dir, "node_modules", bin, "bin", `${bin}-cli.js`),
214
+ join(dir, "..", "lib", "node_modules", bin, "bin", `${bin}-cli.js`)
215
+ ];
216
+ return candidates.find(isFile) ?? null;
217
+ }
218
+ function scriptOnPath(bin, suffixes, env) {
219
+ const exts = process.platform === "win32" ? ["", ...(env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter((e) => e.length > 0)] : [""];
220
+ for (const part of (env.PATH ?? "").split(delimiter)) {
221
+ if (part.length === 0) continue;
222
+ for (const ext of exts) {
223
+ if (!isFile(join(part, `${bin}${ext}`))) continue;
224
+ const real = realpathOrNull(join(part, `${bin}${ext}`));
225
+ if (real !== null && suffixes.some((suffix) => real.endsWith(suffix))) return real;
226
+ const near = scriptNear(part, bin);
227
+ if (near !== null) return near;
228
+ }
229
+ }
230
+ return null;
231
+ }
232
+ function isFile(p) {
233
+ try {
234
+ return statSync(p).isFile();
235
+ } catch {
236
+ return false;
237
+ }
238
+ }
239
+ function realpathOrNull(p) {
240
+ try {
241
+ return realpathSync(p);
242
+ } catch {
243
+ return null;
244
+ }
245
+ }
80
246
 
81
247
  // src/router/install.ts
82
248
  import { readFile as readFile4, realpath } from "node:fs/promises";
83
249
  import { homedir as homedir2 } from "node:os";
84
- import { isAbsolute as isAbsolute2, join as join6 } from "node:path";
250
+ import { isAbsolute as isAbsolute2, join as join8 } from "node:path";
85
251
 
86
252
  // src/lib/skill-placement.ts
87
253
  import { lstatSync } from "node:fs";
88
254
  import { readdir, rm, rmdir } from "node:fs/promises";
89
- import { dirname, join } from "node:path";
255
+ import { dirname as dirname2, join as join2 } from "node:path";
90
256
  function isRealDirectory(path) {
91
257
  try {
92
258
  return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;
@@ -99,11 +265,11 @@ async function removeOwnedSkill(name, skillsDir) {
99
265
  if (!isRealDirectory(skillsDir)) {
100
266
  return { changed: false };
101
267
  }
102
- const skillDir = join(skillsDir, name);
268
+ const skillDir = join2(skillsDir, name);
103
269
  if (!isRealDirectory(skillDir)) {
104
270
  return { changed: false };
105
271
  }
106
- const path = join(skillDir, "SKILL.md");
272
+ const path = join2(skillDir, "SKILL.md");
107
273
  const read = await readSkillFile(path);
108
274
  if (read.kind === "absent") return { changed: false };
109
275
  if (read.kind !== "ok" || skillFrontmatterName(read.bytes.toString("utf8")) !== name) {
@@ -113,9 +279,9 @@ async function removeOwnedSkill(name, skillsDir) {
113
279
  const subdirs = /* @__PURE__ */ new Set();
114
280
  for (const rel of shipped) {
115
281
  if (rel === "SKILL.md") continue;
116
- const file = join(skillDir, rel);
117
- if (!isRealDirectory(dirname(file))) continue;
118
- subdirs.add(dirname(file));
282
+ const file = join2(skillDir, rel);
283
+ if (!isRealDirectory(dirname2(file))) continue;
284
+ subdirs.add(dirname2(file));
119
285
  if (lstatSync(file, { throwIfNoEntry: false })?.isFile() === true) await rm(file);
120
286
  }
121
287
  await rm(path, { force: true });
@@ -130,7 +296,7 @@ async function removeRetiredSkills(home, project) {
130
296
  const dirs = [...skillsDirsFor(home), ...project ? skillsDirsFor(project) : []];
131
297
  for (const dir of new Set(dirs)) {
132
298
  for (const name of [...RETIRED_SKILL_NAMES, ...CLI_SKILL_NAMES]) {
133
- if ((await removeOwnedSkill(name, dir)).changed) removed.push(join(dir, name));
299
+ if ((await removeOwnedSkill(name, dir)).changed) removed.push(join2(dir, name));
134
300
  }
135
301
  }
136
302
  return removed;
@@ -138,45 +304,45 @@ async function removeRetiredSkills(home, project) {
138
304
 
139
305
  // src/router/claude-cli.ts
140
306
  import { execFile } from "node:child_process";
141
- import { statSync } from "node:fs";
307
+ import { statSync as statSync2 } from "node:fs";
142
308
  import { homedir } from "node:os";
143
- import { delimiter, isAbsolute, join as join2 } from "node:path";
309
+ import { delimiter as delimiter2, isAbsolute, join as join3 } from "node:path";
144
310
  var CLAUDE_CODE_FLOOR = "2.1.287";
145
311
  function claudeConfigDir(env, home = homedir()) {
146
312
  const dir = env.CLAUDE_CONFIG_DIR;
147
- return dir !== void 0 && dir.length > 0 ? dir : join2(home, ".claude");
313
+ return dir !== void 0 && dir.length > 0 ? dir : join3(home, ".claude");
148
314
  }
149
315
  function userSettingsPath(env, home = homedir()) {
150
- return join2(claudeConfigDir(env, home), "settings.json");
316
+ return join3(claudeConfigDir(env, home), "settings.json");
151
317
  }
152
318
  function userMcpFile(env, home = homedir()) {
153
319
  const dir = env.CLAUDE_CONFIG_DIR;
154
- return dir !== void 0 && dir.length > 0 ? join2(dir, ".claude.json") : join2(home, ".claude.json");
320
+ return dir !== void 0 && dir.length > 0 ? join3(dir, ".claude.json") : join3(home, ".claude.json");
155
321
  }
156
- function isFile(path) {
322
+ function isFile2(path) {
157
323
  try {
158
- return statSync(path).isFile();
324
+ return statSync2(path).isFile();
159
325
  } catch {
160
326
  return false;
161
327
  }
162
328
  }
163
329
  function findClaudeBinary(env) {
164
330
  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)) {
331
+ for (const part of (env.PATH ?? "").split(delimiter2)) {
166
332
  if (part.length === 0) continue;
167
333
  for (const ext of exts) {
168
- const candidate = join2(part, `claude${ext}`);
169
- if (isFile(candidate)) return { path: candidate, source: "path" };
334
+ const candidate = join3(part, `claude${ext}`);
335
+ if (isFile2(candidate)) return { path: candidate, source: "path" };
170
336
  }
171
337
  }
172
- const exec = env.CLAUDE_CODE_EXECPATH;
173
- if (exec !== void 0 && isAbsolute(exec) && isFile(exec)) {
174
- return { path: exec, source: "execpath" };
338
+ const exec2 = env.CLAUDE_CODE_EXECPATH;
339
+ if (exec2 !== void 0 && isAbsolute(exec2) && isFile2(exec2)) {
340
+ return { path: exec2, source: "execpath" };
175
341
  }
176
342
  return null;
177
343
  }
178
344
  function runClaude(bin, args, opts) {
179
- return new Promise((resolve) => {
345
+ return new Promise((resolve2) => {
180
346
  execFile(
181
347
  bin.path,
182
348
  args,
@@ -189,7 +355,7 @@ function runClaude(bin, args, opts) {
189
355
  },
190
356
  (err, stdout, stderr) => {
191
357
  const code = err === null ? 0 : typeof err.code === "number" ? err.code : null;
192
- resolve({ code, stdout: String(stdout), stderr: String(stderr) });
358
+ resolve2({ code, stdout: String(stdout), stderr: String(stderr) });
193
359
  }
194
360
  );
195
361
  });
@@ -252,7 +418,7 @@ async function readClaudeCode(env, cwd, find = findClaudeBinary) {
252
418
 
253
419
  // src/router/legacy-install.ts
254
420
  import { readFile, stat } from "node:fs/promises";
255
- import { join as join3 } from "node:path";
421
+ import { join as join4 } from "node:path";
256
422
 
257
423
  // src/router/status-line-wiring.ts
258
424
  var STATUS_LINE_COMMAND = "tenjin status-line";
@@ -484,12 +650,12 @@ async function removeMcpEntry(opts, out) {
484
650
  }
485
651
  }
486
652
  function projectMcpFile(cwd) {
487
- return join3(cwd, ".mcp.json");
653
+ return join4(cwd, ".mcp.json");
488
654
  }
489
655
 
490
656
  // src/router/plugin-registration.ts
491
657
  import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
492
- import { dirname as dirname3, join as join5 } from "node:path";
658
+ import { dirname as dirname4, join as join6 } from "node:path";
493
659
  import { fileURLToPath } from "node:url";
494
660
 
495
661
  // src/router/plugin-files.ts
@@ -499,7 +665,11 @@ var LOCAL_HOOK_TIMEOUT_SECONDS = 5;
499
665
  var DELEGATION_MATCHER = "Agent|Task";
500
666
  var NATIVE_MATCHER = "WebSearch|WebFetch";
501
667
  var ASK_MATCHER = "AskUserQuestion";
502
- var ALIVE_COMMAND = "tenjin hook alive";
668
+ var PLUGIN_ROOT_ENTRY = "${CLAUDE_PLUGIN_ROOT}/../../../index.js";
669
+ function cliLaunch(args, entry = PLUGIN_ROOT_ENTRY) {
670
+ return { command: "node", args: [entry, ...args] };
671
+ }
672
+ var ALIVE_ARGS = ["hook", "alive"];
503
673
  function permissionAnswer(decision, reason) {
504
674
  return JSON.stringify({
505
675
  hookSpecificOutput: {
@@ -509,11 +679,17 @@ function permissionAnswer(decision, reason) {
509
679
  }
510
680
  });
511
681
  }
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")}'`;
682
+ var PRINT_ARGUMENT = "process.stdout.write(process.argv[1])";
683
+ function printed(answer) {
684
+ return { command: "node", args: ["-e", PRINT_ARGUMENT, answer] };
685
+ }
686
+ var DENY_HOOK = printed(
687
+ permissionAnswer(
688
+ "deny",
689
+ `Only the Tenjin hooks call this tool. To make a lookup, call ${REQUEST_TOOL}.`
690
+ )
691
+ );
692
+ var ALLOW_HOOK = printed(permissionAnswer("allow", "Tenjin lookup"));
517
693
  function leg(kind, timeout = ROUTE_HOOK_TIMEOUT_SECONDS) {
518
694
  return [
519
695
  {
@@ -525,8 +701,8 @@ function leg(kind, timeout = ROUTE_HOOK_TIMEOUT_SECONDS) {
525
701
  }
526
702
  ];
527
703
  }
528
- function command(text) {
529
- return [{ type: "command", command: text, timeout: LOCAL_HOOK_TIMEOUT_SECONDS }];
704
+ function command(launch) {
705
+ return [{ type: "command", ...launch, timeout: LOCAL_HOOK_TIMEOUT_SECONDS }];
530
706
  }
531
707
  function routerHookPlan() {
532
708
  const afterCall = () => leg("shortfall", AFTER_CALL_TIMEOUT_SECONDS);
@@ -540,12 +716,12 @@ function routerHookPlan() {
540
716
  { event: "PostToolUse", matcher: ASK_MATCHER, hooks: leg("answer") }
541
717
  ];
542
718
  }
543
- function renderPluginHooks() {
719
+ function renderPluginHooks(entry = PLUGIN_ROOT_ENTRY) {
544
720
  const plan = [
545
- { event: "SessionStart", hooks: command(ALIVE_COMMAND) },
721
+ { event: "SessionStart", hooks: command(cliLaunch(ALIVE_ARGS, entry)) },
546
722
  ...routerHookPlan(),
547
- { event: "PreToolUse", matcher: PLUGIN_HOOK_TOOL, hooks: command(DENY_HOOK_COMMAND) },
548
- { event: "PreToolUse", matcher: REQUEST_TOOL, hooks: command(ALLOW_HOOK_COMMAND) }
723
+ { event: "PreToolUse", matcher: PLUGIN_HOOK_TOOL, hooks: command(DENY_HOOK) },
724
+ { event: "PreToolUse", matcher: REQUEST_TOOL, hooks: command(ALLOW_HOOK) }
549
725
  ];
550
726
  const hooks = {};
551
727
  for (const { event, hooks: handlers, ...rest } of plan) {
@@ -554,8 +730,8 @@ function renderPluginHooks() {
554
730
  return { hooks };
555
731
  }
556
732
  var PLUGIN_MCP_ARGS = ["mcp", "--plugin"];
557
- function renderPluginMcp() {
558
- return { mcpServers: { [MCP_SERVER_NAME]: { command: "tenjin", args: [...PLUGIN_MCP_ARGS] } } };
733
+ function renderPluginMcp(entry = PLUGIN_ROOT_ENTRY) {
734
+ return { mcpServers: { [MCP_SERVER_NAME]: cliLaunch(PLUGIN_MCP_ARGS, entry) } };
559
735
  }
560
736
  var OWNER_MARKER = "tenjin-cli";
561
737
  var UNBUILT = "source";
@@ -579,20 +755,20 @@ var PLUGIN_FILES = [
579
755
  ];
580
756
  var json = (value) => `${JSON.stringify(value, null, 2)}
581
757
  `;
582
- function renderPluginFiles(version) {
758
+ function renderPluginFiles(version, entry) {
583
759
  return {
584
- ".mcp.json": json(renderPluginMcp()),
585
- "hooks/hooks.json": json(renderPluginHooks()),
760
+ ".mcp.json": json(renderPluginMcp(entry)),
761
+ "hooks/hooks.json": json(renderPluginHooks(entry)),
586
762
  ".claude-plugin/plugin.json": json(renderPluginManifest(version))
587
763
  };
588
764
  }
589
765
 
590
766
  // src/router/plugin-folder.ts
591
767
  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";
768
+ import { dirname as dirname3, join as join5, relative, sep as sep2 } from "node:path";
593
769
  var FOLDER_NAME = "tenjin-router";
594
770
  function pluginFolderPath(base) {
595
- return join4(base, "skills", FOLDER_NAME);
771
+ return join5(base, "skills", FOLDER_NAME);
596
772
  }
597
773
  async function inspectPluginFolder(dir) {
598
774
  const entry = await lstat(dir).catch(() => null);
@@ -600,7 +776,7 @@ async function inspectPluginFolder(dir) {
600
776
  if (!entry.isDirectory() || entry.isSymbolicLink()) return "foreign";
601
777
  try {
602
778
  const manifest = JSON.parse(
603
- await readFile2(join4(dir, ".claude-plugin", "plugin.json"), "utf8")
779
+ await readFile2(join5(dir, ".claude-plugin", "plugin.json"), "utf8")
604
780
  );
605
781
  const marked = manifest.metadata !== null && typeof manifest.metadata === "object" && OWNER_MARKER in manifest.metadata;
606
782
  return manifest.name === PLUGIN_NAME && marked ? "ours" : "foreign";
@@ -621,7 +797,7 @@ async function writePluginFolder(dir, files) {
621
797
  for (const path of PLUGIN_FILES) {
622
798
  const body = files[path];
623
799
  if (body === void 0) continue;
624
- await writeFileAtomic(join4(dir, path), body);
800
+ await writeFileAtomic(join5(dir, path), body);
625
801
  }
626
802
  } catch (err) {
627
803
  return {
@@ -643,11 +819,11 @@ async function removePluginFolder(dir) {
643
819
  reason: `${dir} is not a folder this CLI wrote, so nothing in it was removed`
644
820
  };
645
821
  }
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(
822
+ for (const path of PLUGIN_FILES) await rm2(join5(dir, path), { force: true });
823
+ const subdirs = [...new Set(PLUGIN_FILES.map((p) => dirname3(p)).filter((d) => d !== "."))].sort(
648
824
  (a, b) => b.split("/").length - a.split("/").length
649
825
  );
650
- for (const sub of subdirs) await rmdir2(join4(dir, sub)).catch(() => void 0);
826
+ for (const sub of subdirs) await rmdir2(join5(dir, sub)).catch(() => void 0);
651
827
  const left = await listFiles(dir);
652
828
  if (left.length === 0) await rmdir2(dir).catch(() => void 0);
653
829
  return { path: dir, removed: true, left };
@@ -656,9 +832,9 @@ async function listFiles(dir) {
656
832
  const out = [];
657
833
  const walk = async (current) => {
658
834
  for (const entry of await readdir2(current, { withFileTypes: true }).catch(() => [])) {
659
- const path = join4(current, entry.name);
835
+ const path = join5(current, entry.name);
660
836
  if (entry.isDirectory()) await walk(path);
661
- else out.push(relative(dir, path).split(sep).join("/"));
837
+ else out.push(relative(dir, path).split(sep2).join("/"));
662
838
  }
663
839
  };
664
840
  await walk(dir);
@@ -667,7 +843,7 @@ async function listFiles(dir) {
667
843
 
668
844
  // src/router/plugin-registration.ts
669
845
  function folderFor(scope, env, home, cwd) {
670
- return pluginFolderPath(scope === "local" ? join5(cwd, ".claude") : claudeConfigDir(env, home));
846
+ return pluginFolderPath(scope === "local" ? join6(cwd, ".claude") : claudeConfigDir(env, home));
671
847
  }
672
848
  async function registerPlugin(opts) {
673
849
  const folder = folderFor(opts.scope, opts.env, opts.home, opts.cwd);
@@ -720,7 +896,10 @@ async function registerPlugin(opts) {
720
896
  };
721
897
  }
722
898
  }
723
- const written = await writePluginFolder(folder, renderPluginFiles(opts.version));
899
+ const written = await writePluginFolder(
900
+ folder,
901
+ renderPluginFiles(opts.version, opts.cliEntry ?? packageCliEntry())
902
+ );
724
903
  if (written.state === "written") {
725
904
  return {
726
905
  method: "skills-dir",
@@ -807,7 +986,7 @@ async function ownMarketplace(row) {
807
986
  if (await stat2(path).catch(() => null) === null) {
808
987
  return /tenjin-cli[\\/]dist[\\/]hosts[\\/]claude$/.test(path);
809
988
  }
810
- return await inspectPluginFolder(join5(path, PLUGIN_DIR)) === "ours";
989
+ return await inspectPluginFolder(join6(path, PLUGIN_DIR)) === "ours";
811
990
  }
812
991
  async function existingCopy(binary, env, home, cwd) {
813
992
  const out = await runClaude(binary, ["plugin", "list", "--json"], { env, cwd });
@@ -821,7 +1000,7 @@ async function existingCopy(binary, env, home, cwd) {
821
1000
  async function installedThroughCommands(env, home) {
822
1001
  try {
823
1002
  const raw = await readFile3(
824
- join5(claudeConfigDir(env, home), "plugins", "installed_plugins.json"),
1003
+ join6(claudeConfigDir(env, home), "plugins", "installed_plugins.json"),
825
1004
  "utf8"
826
1005
  );
827
1006
  const plugins = JSON.parse(raw).plugins;
@@ -830,11 +1009,15 @@ async function installedThroughCommands(env, home) {
830
1009
  return false;
831
1010
  }
832
1011
  }
833
- async function packageHostsDir(moduleDir = dirname3(fileURLToPath(import.meta.url))) {
834
- const catalog = join5(moduleDir, "hosts", "claude", ".claude-plugin", "marketplace.json");
1012
+ async function packageHostsDir(moduleDir = dirname4(fileURLToPath(import.meta.url))) {
1013
+ const catalog = join6(moduleDir, "hosts", "claude", ".claude-plugin", "marketplace.json");
835
1014
  const stable = versionFreeEntry(catalog) ?? catalog;
836
1015
  if ((await stat2(stable).catch(() => null))?.isFile() !== true) return null;
837
- return dirname3(dirname3(stable));
1016
+ return dirname4(dirname4(stable));
1017
+ }
1018
+ function packageCliEntry(moduleDir = dirname4(fileURLToPath(import.meta.url))) {
1019
+ const entry = join6(moduleDir, "index.js");
1020
+ return versionFreeEntry(entry) ?? entry;
838
1021
  }
839
1022
  async function readPluginListing(binary, env, cwd) {
840
1023
  const out = await runClaude(binary, ["plugin", "list", "--json"], { env, cwd });
@@ -968,6 +1151,97 @@ function proxyCredentialsFix(env) {
968
1151
  return `Put the proxy's credentials in ${proxy} (\`http://user:password@proxy:port\`), then try again.`;
969
1152
  }
970
1153
 
1154
+ // src/router/mcp-processes.ts
1155
+ import { execFile as execFile2 } from "node:child_process";
1156
+ import { stat as stat3 } from "node:fs/promises";
1157
+ import { dirname as dirname5, join as join7 } from "node:path";
1158
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
1159
+ import { promisify } from "node:util";
1160
+ var exec = promisify(execFile2);
1161
+ var listMcpProcesses = async () => {
1162
+ if (process.platform === "win32" || typeof process.getuid !== "function") return null;
1163
+ try {
1164
+ const { stdout } = await exec(
1165
+ "ps",
1166
+ ["-U", String(process.getuid()), "-o", "pid=,lstart=,args="],
1167
+ { timeout: 5e3, env: { ...process.env, LC_ALL: "C" }, maxBuffer: 4 * 1024 * 1024 }
1168
+ );
1169
+ return parsePs(stdout, process.pid);
1170
+ } catch {
1171
+ return null;
1172
+ }
1173
+ };
1174
+ var PS_LINE = /^\s*(\d+)\s+(\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.*)$/;
1175
+ function parsePs(stdout, selfPid) {
1176
+ const found = [];
1177
+ for (const line of stdout.split("\n")) {
1178
+ const m = PS_LINE.exec(line);
1179
+ if (m === null) continue;
1180
+ const pid = Number(m[1]);
1181
+ if (pid === selfPid || !isTenjinMcp(m[3])) continue;
1182
+ const startedAt = Date.parse(m[2].replace(/\s+/g, " "));
1183
+ found.push({ pid, startedAt: Number.isNaN(startedAt) ? null : startedAt });
1184
+ }
1185
+ return found;
1186
+ }
1187
+ function isTenjinMcp(args) {
1188
+ const tokens = args.trim().split(/\s+/);
1189
+ const bin = tokens.findIndex(
1190
+ (t) => /(^|[/\\])tenjin(\.js|\.cmd)?$/.test(t) || /[/\\]tenjin-cli[/\\]/.test(t) || /[/\\]hosts[/\\]claude[/\\]tenjin[/\\]\.\.[/\\]\.\.[/\\]\.\.[/\\]index\.js$/.test(t)
1191
+ );
1192
+ return bin >= 0 && tokens[bin + 1] === "mcp";
1193
+ }
1194
+ var installedAt = async () => {
1195
+ let dir = dirname5(fileURLToPath2(import.meta.url));
1196
+ for (let i = 0; i < 6; i += 1) {
1197
+ try {
1198
+ const st = await stat3(join7(dir, "package.json"));
1199
+ return Math.max(st.ctimeMs, st.mtimeMs);
1200
+ } catch {
1201
+ dir = dirname5(dir);
1202
+ }
1203
+ }
1204
+ return null;
1205
+ };
1206
+ var RECONNECT_FIX = "Type /reload-plugins in this Claude Code session, or start a new session.";
1207
+ var NEW_SESSION_FIX = "Start a new Claude Code session: the earlier Tenjin setup is still in this one, and /reload-plugins would run both.";
1208
+ function mcpServersState(procs, installed, version = package_default.version, fix = RECONNECT_FIX) {
1209
+ const check = (detail) => ({
1210
+ stale: 0,
1211
+ check: { name: "mcp server", status: "ok", required: false, detail }
1212
+ });
1213
+ if (procs === null) {
1214
+ return check("unknown: running `tenjin mcp` processes cannot be listed on this platform");
1215
+ }
1216
+ if (procs.length === 0) return check("none running (starts with the next session)");
1217
+ if (installed === null) {
1218
+ return check(`${procs.length} running; when this build was installed is unknown`);
1219
+ }
1220
+ const stale = procs.filter((p) => p.startedAt !== null && p.startedAt < installed).length;
1221
+ if (stale === 0) {
1222
+ return check(`${procs.length} running, all started after this install`);
1223
+ }
1224
+ const which = stale === 1 ? "process" : "processes";
1225
+ return {
1226
+ stale,
1227
+ check: {
1228
+ name: "mcp server",
1229
+ status: "warn",
1230
+ required: false,
1231
+ detail: `${stale} running \`tenjin mcp\` ${which} started before this install (${version}), so ${stale === 1 ? "it runs" : "they run"} the older build, where the hooks can fail with "Tool hook not found"`,
1232
+ fix
1233
+ }
1234
+ };
1235
+ }
1236
+ async function readMcpServers(deps = {}, opts = {}) {
1237
+ const [procs, installed] = await Promise.all([
1238
+ (deps.listMcpProcesses ?? listMcpProcesses)().catch(() => null),
1239
+ (deps.installedAt ?? installedAt)().catch(() => null)
1240
+ ]);
1241
+ const fix = opts.settingsInstallPending === true ? NEW_SESSION_FIX : RECONNECT_FIX;
1242
+ return mcpServersState(procs, installed, package_default.version, fix);
1243
+ }
1244
+
971
1245
  // src/router/install.ts
972
1246
  var DISCLOSURE = [
973
1247
  "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.",
@@ -981,7 +1255,7 @@ function loadStep(settingsInstallPresent) {
981
1255
  }
982
1256
  function settingsInstallPaths(project, env, home, cwd) {
983
1257
  return project ? {
984
- settingsPath: join6(cwd, ".claude", "settings.json"),
1258
+ settingsPath: join8(cwd, ".claude", "settings.json"),
985
1259
  mcpFile: projectMcpFile(cwd),
986
1260
  mcpScope: "project"
987
1261
  } : {
@@ -1025,18 +1299,25 @@ async function migrateSettingsInstall(legacy, claude, opts) {
1025
1299
  });
1026
1300
  return { state: "done", settingsPath: legacy.settingsPath, removed };
1027
1301
  }
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);
1302
+ async function projectInstallHere(cwd, home, env) {
1303
+ if (await isHome(cwd, home)) return false;
1304
+ return projectInstallAt(cwd, home, env);
1305
+ }
1306
+ async function projectInstallAt(dir, home, env) {
1307
+ const local = await readFile4(join8(dir, ".claude", "settings.local.json"), "utf8").then((raw) => JSON.parse(raw)).catch(() => null);
1035
1308
  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);
1309
+ if (await isHome(dir, home)) return false;
1310
+ if ((await folderState("local", env, home, dir)).state === "ours") return true;
1311
+ const paths = settingsInstallPaths(true, env, home, dir);
1038
1312
  return (await inspectLegacyInstall(paths.settingsPath, paths.mcpFile)).events.length > 0;
1039
1313
  }
1314
+ async function isHome(dir, home) {
1315
+ const [dirPath, homePath] = await Promise.all([
1316
+ realpath(dir).catch(() => dir),
1317
+ realpath(home).catch(() => home)
1318
+ ]);
1319
+ return dirPath === homePath;
1320
+ }
1040
1321
  async function somethingToRefresh(claude, scope, legacy, env, home, cwd) {
1041
1322
  if (legacy.present) return true;
1042
1323
  if ((await folderState(scope, env, home, cwd)).state === "ours") return true;
@@ -1056,7 +1337,7 @@ async function runRouterInstall(args, ctx, deps = {}) {
1056
1337
  }
1057
1338
  const config = await loadRawConfig(ctx.dataDir);
1058
1339
  const cwd = deps.cwd ?? process.cwd();
1059
- const project = args.project ?? (args.refresh === true && await inferRefreshProject(cwd, home, env));
1340
+ const project = args.project ?? (args.refresh === true && await projectInstallHere(cwd, home, env));
1060
1341
  const scope = project ? "local" : "user";
1061
1342
  const claude = await readClaudeCode(env, cwd, deps.findClaude ?? findClaudeBinary);
1062
1343
  const paths = settingsInstallPaths(project, env, home, cwd);
@@ -1083,8 +1364,12 @@ async function runRouterInstall(args, ctx, deps = {}) {
1083
1364
  env,
1084
1365
  home,
1085
1366
  cwd,
1086
- ...deps.hostsDir !== void 0 ? { hostsDir: deps.hostsDir } : {}
1367
+ ...deps.hostsDir !== void 0 ? { hostsDir: deps.hostsDir } : {},
1368
+ ...deps.cliEntry !== void 0 ? { cliEntry: deps.cliEntry } : {}
1087
1369
  });
1370
+ if (project && plugin.state !== "failed") {
1371
+ await persistRouterProject(ctx.dataDir, cwd).catch(() => void 0);
1372
+ }
1088
1373
  const migration = legacy.unreadable !== void 0 && !legacy.present ? { state: "blocked", settingsPath: paths.settingsPath, reason: legacy.unreadable } : await migrateSettingsInstall(legacy, claude, {
1089
1374
  dataDir: ctx.dataDir,
1090
1375
  env,
@@ -1123,7 +1408,7 @@ async function runRouterInstall(args, ctx, deps = {}) {
1123
1408
  ]
1124
1409
  };
1125
1410
  }
1126
- const { resolveWallet } = await import("./install-wallet-Z52EDLPB.js");
1411
+ const { resolveWallet } = await import("./install-wallet-TC22U52X.js");
1127
1412
  const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? "flag" : void 0, false);
1128
1413
  const effective = await resolveContextSettings(ctx);
1129
1414
  const approval = !canPrompt && args.yes !== true && !spend.kept.includes("maxAutoSpend") ? spendApproval(config, args) : void 0;
@@ -1137,6 +1422,9 @@ async function runRouterInstall(args, ctx, deps = {}) {
1137
1422
  claudeCode,
1138
1423
  migration,
1139
1424
  next: nextStep(plugin, claude, wallet, migration),
1425
+ // The check for this scope, said outright; a bare doctor in the project
1426
+ // also finds it from what the project holds.
1427
+ ...project ? { doctor: "tenjin doctor --project" } : {},
1140
1428
  spend: {
1141
1429
  ...spend,
1142
1430
  effective: effectiveLimits(effective.policy),
@@ -1179,13 +1467,14 @@ function claudeCodeData(claude) {
1179
1467
  };
1180
1468
  }
1181
1469
  function registrationFix(plugin) {
1470
+ const flag = plugin.scope === "local" ? " --project" : "";
1182
1471
  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.`;
1472
+ return `${plugin.id} keeps serving this machine at the version Claude Code has; run \`tenjin install${flag}\` again to retry.`;
1184
1473
  }
1185
1474
  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.`;
1475
+ return `Move ${plugin.path} aside, then run \`tenjin install${flag}\` again.`;
1187
1476
  }
1188
- return "Run `tenjin doctor` to see the cause, then run `tenjin install` again.";
1477
+ return `Run \`tenjin doctor${flag}\` to see the cause, then run \`tenjin install${flag}\` again.`;
1189
1478
  }
1190
1479
  function nextStep(plugin, claude, wallet, migration) {
1191
1480
  if (plugin.state === "failed") return registrationFix(plugin);
@@ -1405,6 +1694,7 @@ function lines(ctx, s) {
1405
1694
  ];
1406
1695
  return [
1407
1696
  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})`,
1697
+ ...s.plugin.scope === "local" && s.plugin.state !== "failed" ? [" For this project only; check it with: tenjin doctor --project"] : [],
1408
1698
  ...walletLines(ctx, ok, s.wallet),
1409
1699
  ...spend,
1410
1700
  ...pluginLines(ctx, s.plugin),
@@ -1425,6 +1715,329 @@ function refreshLines(ctx, plugin, claude, migration) {
1425
1715
  return [head, ...issues];
1426
1716
  }
1427
1717
 
1718
+ // src/commands/update.ts
1719
+ var INSTALL_TIMEOUT_MS = 3e5;
1720
+ function resolveManager(manager, deps) {
1721
+ const script = deps.managerScript !== void 0 ? deps.managerScript : resolveManagerScript(manager, process.execPath);
1722
+ return script === null ? { cmd: MANAGERS[manager].bin, prefix: [] } : { cmd: process.execPath, prefix: [script] };
1723
+ }
1724
+ async function runUpdate(opts, ctx, deps = {}) {
1725
+ const current = deps.currentVersion ?? package_default.version;
1726
+ const channel = channelTag(current);
1727
+ const moduleDir = deps.moduleDir ?? fileURLToPath3(new URL(".", import.meta.url));
1728
+ if (channel === null) {
1729
+ throw new CliError("REFUSED", `tenjin-cli reports an unrecognizable version (${current})`, {
1730
+ fix: "Reinstall a published build: npm i -g tenjin-cli"
1731
+ });
1732
+ }
1733
+ refuse(moduleDir, { check: opts.check, spec: null });
1734
+ const tags = await fetchDistTags({
1735
+ fetchImpl: deps.fetchImpl,
1736
+ timeoutMs: ctx.flags.timeout
1737
+ });
1738
+ if (tags === null) {
1739
+ throw new CliError("NETWORK_ERROR", "Could not read tenjin-cli dist-tags from npm", {
1740
+ fix: "Check access to registry.npmjs.org and retry"
1741
+ });
1742
+ }
1743
+ const latest = resolveTarget(current, tags);
1744
+ if (latest === null) {
1745
+ const raw = tags[channel];
1746
+ throw raw === void 0 ? new CliError("RESOURCE_NOT_FOUND", "npm has no published tenjin-cli on the latest tag", {
1747
+ fix: "Pick a version yourself: npm view tenjin-cli versions"
1748
+ }) : new CliError(
1749
+ "RESOURCE_NOT_FOUND",
1750
+ // Registry-controlled: bounded here, escaped by the error emitter.
1751
+ `npm's latest tenjin-cli (${raw.slice(0, 40)}) is not a version this build can read`,
1752
+ {
1753
+ fix: "Install it by name: npm i -g tenjin-cli@<version> (npm view tenjin-cli versions)"
1754
+ }
1755
+ );
1756
+ }
1757
+ const updateAvailable = isNewer(latest, current);
1758
+ const data = (updated) => ({
1759
+ current,
1760
+ latest,
1761
+ updateAvailable,
1762
+ updated
1763
+ });
1764
+ if (!updateAvailable) {
1765
+ return {
1766
+ data: data(false),
1767
+ humanLines: [`tenjin-cli ${current} is up to date`]
1768
+ };
1769
+ }
1770
+ if (opts.check) {
1771
+ return {
1772
+ data: data(false),
1773
+ humanLines: [
1774
+ `tenjin-cli ${latest} is available (you have ${current}).`,
1775
+ "Run tenjin update to install it."
1776
+ ]
1777
+ };
1778
+ }
1779
+ const spec = `tenjin-cli@${latest}`;
1780
+ refuse(moduleDir, { check: false, spec });
1781
+ const human = ctx.io.isTTY && !ctx.flags.json;
1782
+ let tail = "";
1783
+ const onOutput = (chunk) => {
1784
+ tail = (tail + chunk).slice(-2e3);
1785
+ if (human) ctx.io.stderr.write(chunk.split("\n").map(sanitizeForTerminal).join("\n"));
1786
+ };
1787
+ const manager = classifyManager(moduleDir);
1788
+ const plan = MANAGERS[manager];
1789
+ const args = plan.args(spec);
1790
+ const resolved = resolveManager(manager, deps);
1791
+ const manual = `Run it yourself: ${plan.manual(spec)}`;
1792
+ const outcome = await (deps.spawnImpl ?? spawnCapture)(
1793
+ resolved.cmd,
1794
+ [...resolved.prefix, ...args],
1795
+ { cwd: homedir3(), timeoutMs: INSTALL_TIMEOUT_MS },
1796
+ onOutput
1797
+ );
1798
+ if (outcome.kind === "start-failed") {
1799
+ throw new CliError("UPDATE_FAILED", `Could not start ${manager}`, {
1800
+ fix: manual,
1801
+ cause: outcome.cause
1802
+ });
1803
+ }
1804
+ if (outcome.kind === "timeout") {
1805
+ throw new CliError(
1806
+ "UPDATE_FAILED",
1807
+ `${manager} did not finish in ${INSTALL_TIMEOUT_MS / 1e3}s`,
1808
+ { fix: manual, details: { output: tail } }
1809
+ );
1810
+ }
1811
+ if (outcome.code !== 0) {
1812
+ throw new CliError("UPDATE_FAILED", `${manager} ${args.join(" ")} exited ${outcome.code}`, {
1813
+ // EACCES on a root-owned global prefix is the common cause; the operator
1814
+ // fixing that themselves beats this CLI ever escalating.
1815
+ fix: manual,
1816
+ details: { output: tail }
1817
+ });
1818
+ }
1819
+ emitWriteNotice(
1820
+ ctx.io,
1821
+ `tenjin update: replaced the global tenjin-cli with ${latest} via ${manager}`
1822
+ );
1823
+ const refresh = await refreshProfiles(ctx, deps);
1824
+ const servers = await readMcpServers(deps, {
1825
+ settingsInstallPending: refresh.settingsInstallPending
1826
+ });
1827
+ return {
1828
+ data: { ...data(true), refresh, mcpServer: servers.check },
1829
+ humanLines: [
1830
+ `Updated tenjin-cli ${current} -> ${latest}.`,
1831
+ ...refreshLines2(refresh),
1832
+ ...projectLines(refresh),
1833
+ ...refresh.notices,
1834
+ ...servers.stale > 0 ? [`! ${servers.check.detail}. ${servers.check.fix ?? ""}`.trim()] : []
1835
+ ]
1836
+ };
1837
+ }
1838
+ var REFRESH_TIMEOUT_MS = 6e4;
1839
+ async function refreshProfiles(ctx, deps) {
1840
+ const home = deps.homeDir ?? homedir3();
1841
+ const candidates = [ctx.dataDir];
1842
+ const fixFor = (dataDir) => manualFix(dataDir, home, ctx.dataDir);
1843
+ const profiles = [];
1844
+ const unrun = [];
1845
+ for (const dataDir of candidates) {
1846
+ if (isExistingDir(dataDir)) profiles.push(dataDir);
1847
+ else unrun.push({ dataDir, reason: "It is not a directory.", fix: fixFor(dataDir) });
1848
+ }
1849
+ const entry = versionFreeEntry(deps.refreshCommand ?? process.argv[1]);
1850
+ if (entry === null) {
1851
+ const reason = "This build has no entry the update could safely re-execute.";
1852
+ return {
1853
+ profiles: [],
1854
+ failed: candidates.map((d) => ({ dataDir: d, reason, fix: fixFor(d) })),
1855
+ notices: [],
1856
+ settingsInstallPending: false,
1857
+ projects: [],
1858
+ projectsFailed: []
1859
+ };
1860
+ }
1861
+ const failed = [...unrun];
1862
+ const notices = [];
1863
+ let settingsInstallPending = false;
1864
+ const heard = (reported) => {
1865
+ for (const notice of noticesOf(reported)) if (!notices.includes(notice)) notices.push(notice);
1866
+ const migration = reported?.migration;
1867
+ if (migration?.state === "pending" || migration?.state === "blocked") {
1868
+ settingsInstallPending = true;
1869
+ }
1870
+ };
1871
+ for (const dataDir of profiles) {
1872
+ const { outcome, tail } = await refreshChild(entry, homedir3(), dataDir, deps);
1873
+ if (outcome.kind !== "exit" || outcome.code !== 0) {
1874
+ failed.push({ dataDir, reason: refreshReason(outcome, tail), fix: fixFor(dataDir) });
1875
+ continue;
1876
+ }
1877
+ heard(envelopeData(tail));
1878
+ }
1879
+ const projects = [];
1880
+ const projectsFailed = [];
1881
+ const recorded = profiles.includes(ctx.dataDir) ? (await loadRawConfig(ctx.dataDir).catch(() => null))?.install?.routerProjects ?? [] : [];
1882
+ for (const project of recorded) {
1883
+ const forget = () => persistRouterProject(ctx.dataDir, project, false).catch(() => void 0);
1884
+ if (!isExistingDir(project) || !await projectInstallAt(project, home, process.env)) {
1885
+ await forget();
1886
+ continue;
1887
+ }
1888
+ const { outcome, tail } = await refreshChild(entry, project, ctx.dataDir, deps, ["--project"]);
1889
+ if (outcome.kind !== "exit" || outcome.code !== 0) {
1890
+ projectsFailed.push({
1891
+ project,
1892
+ reason: refreshReason(outcome, tail),
1893
+ fix: `Run \`tenjin install --project\` in ${project}.`
1894
+ });
1895
+ continue;
1896
+ }
1897
+ projects.push(project);
1898
+ heard(envelopeData(tail));
1899
+ }
1900
+ return { profiles, failed, notices, settingsInstallPending, projects, projectsFailed };
1901
+ }
1902
+ async function refreshChild(entry, cwd, dataDir, deps, flags = []) {
1903
+ let tail = "";
1904
+ const outcome = await (deps.spawnImpl ?? spawnCapture)(
1905
+ process.execPath,
1906
+ [entry, "install", "--refresh", ...flags],
1907
+ {
1908
+ cwd,
1909
+ timeoutMs: REFRESH_TIMEOUT_MS,
1910
+ // TENJIN_DATA_DIR aims the child at this profile; the nudge opt-out is
1911
+ // what keeps it from touching any other file in there (lib/update-check).
1912
+ env: { TENJIN_DATA_DIR: dataDir, [NUDGE_OPT_OUT]: "1" }
1913
+ },
1914
+ (chunk) => {
1915
+ tail = (tail + chunk).slice(-REFRESH_TAIL_LIMIT);
1916
+ }
1917
+ );
1918
+ return { outcome, tail };
1919
+ }
1920
+ function envelopeData(output) {
1921
+ const lines2 = output.split("\n");
1922
+ for (let i = lines2.length - 1; i >= 0; i -= 1) {
1923
+ if (lines2[i]?.trim() !== "{" && !lines2[i]?.trim().startsWith('{"')) continue;
1924
+ try {
1925
+ const parsed = JSON.parse(lines2.slice(i).join("\n"));
1926
+ if (parsed?.ok === true && parsed.data !== null && typeof parsed.data === "object") {
1927
+ return parsed.data;
1928
+ }
1929
+ } catch {
1930
+ continue;
1931
+ }
1932
+ }
1933
+ return null;
1934
+ }
1935
+ function noticesOf(data) {
1936
+ const raw = data?.notices;
1937
+ if (!Array.isArray(raw)) return [];
1938
+ return raw.filter((n) => typeof n === "string").map((n) => sanitizeForTerminal(n).trim().slice(0, REASON_LIMIT)).filter((n) => n.length > 0).slice(0, 5);
1939
+ }
1940
+ var REFRESH_TAIL_LIMIT = 64e3;
1941
+ var REASON_LIMIT = 300;
1942
+ function refreshReason(outcome, output) {
1943
+ const reported = envelopeMessage(output);
1944
+ if (reported !== void 0) return reported;
1945
+ if (outcome.kind === "timeout") return `It did not finish in ${REFRESH_TIMEOUT_MS / 1e3}s.`;
1946
+ if (outcome.kind === "start-failed") return "The refresh could not be started.";
1947
+ return `The refresh exited ${outcome.code} without reporting a reason.`;
1948
+ }
1949
+ function envelopeMessage(output) {
1950
+ const lines2 = output.split("\n");
1951
+ for (let i = lines2.length - 1; i >= 0; i -= 1) {
1952
+ const line = lines2[i]?.trim();
1953
+ if (line === void 0 || !line.startsWith("{")) continue;
1954
+ let parsed;
1955
+ try {
1956
+ parsed = JSON.parse(lines2.slice(i).join("\n"));
1957
+ } catch {
1958
+ continue;
1959
+ }
1960
+ if (parsed?.ok !== false || typeof parsed.error?.message !== "string") continue;
1961
+ const message = sanitizeForTerminal(parsed.error.message).trim();
1962
+ if (message.length > 0) return message.slice(0, REASON_LIMIT);
1963
+ }
1964
+ return void 0;
1965
+ }
1966
+ function isExistingDir(path) {
1967
+ return statSync3(path, { throwIfNoEntry: false })?.isDirectory() === true;
1968
+ }
1969
+ function manualFix(dataDir, home, invoking) {
1970
+ const bare = resolve(dataDir) === resolve(defaultDataDir(home)) && resolve(dataDir) === resolve(invoking);
1971
+ const command2 = bare ? "tenjin install" : `TENJIN_DATA_DIR=${dataDir} tenjin install`;
1972
+ return `Run \`${command2}\` to bring the Claude Code plugin up to this version.`;
1973
+ }
1974
+ function versionFreeEntry(entry) {
1975
+ if (entry === void 0 || entry.length === 0) return null;
1976
+ const segs = entry.split(sep3);
1977
+ const store = segs.indexOf(".pnpm");
1978
+ if (store === -1) return segs.join(sep3);
1979
+ const inner = segs.indexOf("node_modules", store);
1980
+ if (inner === -1) return null;
1981
+ const derived = [...segs.slice(0, store), ...segs.slice(inner + 1)].join(sep3);
1982
+ return existsSync2(derived) ? derived : null;
1983
+ }
1984
+ function refreshLines2(refresh) {
1985
+ const failedDirs = new Set(refresh.failed.map((f) => f.dataDir));
1986
+ const done = refresh.profiles.filter((p) => !failedDirs.has(p));
1987
+ if (refresh.failed.length === 0) {
1988
+ return [
1989
+ done.length > 1 ? `Refreshed the Claude Code plugin for ${done.length} profiles: ${done.join(", ")}.` : `Refreshed the Claude Code plugin for ${done[0]}.`
1990
+ ];
1991
+ }
1992
+ const total = done.length + refresh.failed.length;
1993
+ const lines2 = done.length > 0 ? [
1994
+ `Refreshed the Claude Code plugin for ${done.length} of ${total} profiles: ${done.join(", ")}.`
1995
+ ] : [];
1996
+ lines2.push(`Could not refresh the Claude Code plugin for ${refresh.failed.length}:`);
1997
+ lines2.push(...refresh.failed.map((f) => `- ${f.dataDir}: ${f.reason} ${f.fix}`));
1998
+ return lines2;
1999
+ }
2000
+ function projectLines(refresh) {
2001
+ return [
2002
+ ...refresh.projects.length > 0 ? [`Refreshed the project install in ${refresh.projects.join(", ")}.`] : [],
2003
+ ...refresh.projectsFailed.length > 0 ? [
2004
+ `Could not refresh the project install in ${refresh.projectsFailed.length}:`,
2005
+ ...refresh.projectsFailed.map((p) => `- ${p.project}: ${p.reason} ${p.fix}`)
2006
+ ] : []
2007
+ ];
2008
+ }
2009
+ var spawnCapture = (cmd, args, opts, onOutput) => new Promise((res) => {
2010
+ let child;
2011
+ try {
2012
+ child = spawn(cmd, args, {
2013
+ stdio: ["ignore", "pipe", "pipe"],
2014
+ cwd: opts.cwd,
2015
+ // Layered onto this process's environment rather than replacing it: the
2016
+ // child is a Node CLI that needs PATH and HOME, and only the keys named
2017
+ // here are being decided.
2018
+ ...opts.env !== void 0 ? { env: { ...process.env, ...opts.env } } : {}
2019
+ });
2020
+ } catch (cause) {
2021
+ res({ kind: "start-failed", cause });
2022
+ return;
2023
+ }
2024
+ let timedOut = false;
2025
+ const timer = setTimeout(() => {
2026
+ timedOut = true;
2027
+ child.kill("SIGKILL");
2028
+ }, opts.timeoutMs);
2029
+ child.stdout?.on("data", (chunk) => onOutput(chunk.toString()));
2030
+ child.stderr?.on("data", (chunk) => onOutput(chunk.toString()));
2031
+ child.on("error", (cause) => {
2032
+ clearTimeout(timer);
2033
+ res({ kind: "start-failed", cause });
2034
+ });
2035
+ child.on("close", (code) => {
2036
+ clearTimeout(timer);
2037
+ res(timedOut ? { kind: "timeout" } : { kind: "exit", code: code ?? 1 });
2038
+ });
2039
+ });
2040
+
1428
2041
  export {
1429
2042
  CLAUDE_CODE_FLOOR,
1430
2043
  claudeConfigDir,
@@ -1435,6 +2048,10 @@ export {
1435
2048
  readClaudeCode,
1436
2049
  inspectLegacyInstall,
1437
2050
  removeLegacyInstall,
2051
+ readMcpServers,
2052
+ runUpdate,
2053
+ versionFreeEntry,
2054
+ spawnCapture,
1438
2055
  ROUTE_HOOK_TIMEOUT_SECONDS,
1439
2056
  AFTER_CALL_TIMEOUT_SECONDS,
1440
2057
  removePluginFolder,
@@ -1450,6 +2067,8 @@ export {
1450
2067
  settingsInstallPaths,
1451
2068
  pluginProof,
1452
2069
  migrateSettingsInstall,
2070
+ projectInstallHere,
2071
+ projectInstallAt,
1453
2072
  runRouterInstall
1454
2073
  };
1455
- //# sourceMappingURL=chunk-VSUHGRVB.js.map
2074
+ //# sourceMappingURL=chunk-SBL4THYT.js.map