tenjin-cli 0.1.0-alpha.26 → 0.1.0-alpha.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -20
- package/dist/alive-3J3CHOQP.js +21 -0
- package/dist/{chunk-WT7DHJNJ.js → chunk-3QJREVMX.js} +5 -7
- package/dist/{chunk-WT7DHJNJ.js.map → chunk-3QJREVMX.js.map} +1 -1
- package/dist/{chunk-BOAI23CX.js → chunk-6KA4HFX5.js} +21 -15
- package/dist/chunk-6KA4HFX5.js.map +1 -0
- package/dist/chunk-6W5GYG3W.js +128 -0
- package/dist/chunk-6W5GYG3W.js.map +1 -0
- package/dist/{chunk-W36HL4TB.js → chunk-7H3RN4WJ.js} +7 -9
- package/dist/{chunk-W36HL4TB.js.map → chunk-7H3RN4WJ.js.map} +1 -1
- package/dist/{chunk-4HAV6IFE.js → chunk-7R37M6WV.js} +5 -7
- package/dist/{chunk-4HAV6IFE.js.map → chunk-7R37M6WV.js.map} +1 -1
- package/dist/{chunk-LAIZ2AQA.js → chunk-A5H3E5QA.js} +2 -2
- package/dist/{update-QXVH2DE7.js → chunk-AO54FM4H.js} +147 -35
- package/dist/chunk-AO54FM4H.js.map +1 -0
- package/dist/{chunk-XMIVHQ35.js → chunk-B2L53TMK.js} +17 -2
- package/dist/{chunk-XMIVHQ35.js.map → chunk-B2L53TMK.js.map} +1 -1
- package/dist/{chunk-YTM7OURD.js → chunk-BRHREK7E.js} +2 -2
- package/dist/{chunk-YLCWI6ZR.js → chunk-DJYAPACT.js} +79 -36
- package/dist/chunk-DJYAPACT.js.map +1 -0
- package/dist/{chunk-OBPZ36HG.js → chunk-DYSDQE7S.js} +92 -5
- package/dist/chunk-DYSDQE7S.js.map +1 -0
- package/dist/{chunk-EJXIK6WY.js → chunk-FQ6DHINU.js} +80 -48
- package/dist/chunk-FQ6DHINU.js.map +1 -0
- package/dist/chunk-FZTSGQVK.js +52 -0
- package/dist/chunk-FZTSGQVK.js.map +1 -0
- package/dist/{chunk-QF4SSCQV.js → chunk-KAMRYUK2.js} +5 -4
- package/dist/chunk-KAMRYUK2.js.map +1 -0
- package/dist/{chunk-ALJRB7NG.js → chunk-MNTQMZJB.js} +8 -8
- package/dist/{chunk-XICKN3CH.js → chunk-QTND6XWJ.js} +160 -80
- package/dist/chunk-QTND6XWJ.js.map +1 -0
- package/dist/chunk-RLPLYUME.js +115 -0
- package/dist/chunk-RLPLYUME.js.map +1 -0
- package/dist/{chunk-ZLD6MJVJ.js → chunk-S4SAZ7OD.js} +1 -1
- package/dist/chunk-S4SAZ7OD.js.map +1 -0
- package/dist/{chunk-5HS54CLI.js → chunk-UEOWNDQG.js} +8 -10
- package/dist/{chunk-5HS54CLI.js.map → chunk-UEOWNDQG.js.map} +1 -1
- package/dist/{chunk-5INS5ZZF.js → chunk-UOW5JXYY.js} +5 -7
- package/dist/{chunk-5INS5ZZF.js.map → chunk-UOW5JXYY.js.map} +1 -1
- package/dist/chunk-VSUHGRVB.js +1455 -0
- package/dist/chunk-VSUHGRVB.js.map +1 -0
- package/dist/{chunk-Z7R2QDX2.js → chunk-W6JX4LYF.js} +50 -7
- package/dist/chunk-W6JX4LYF.js.map +1 -0
- package/dist/{chunk-UDWGT4FX.js → chunk-XVTD7UWR.js} +14 -8
- package/dist/chunk-XVTD7UWR.js.map +1 -0
- package/dist/{chunk-6JIYGYRB.js → chunk-YFJJYHVG.js} +2 -2
- package/dist/{chunk-DI7WHXOZ.js → chunk-ZG6ZZLO7.js} +898 -521
- package/dist/chunk-ZG6ZZLO7.js.map +1 -0
- package/dist/{chunk-OZ3LWLCI.js → chunk-ZO3X5NPG.js} +4 -6
- package/dist/{chunk-OZ3LWLCI.js.map → chunk-ZO3X5NPG.js.map} +1 -1
- package/dist/{chunk-5NUF4BHR.js → chunk-ZP5PV3JB.js} +4 -4
- package/dist/{chunk-HII5HOQV.js → chunk-ZP7AHN7Z.js} +6 -6
- package/dist/{cli-2U5JB7OQ.js → cli-234DNHN6.js} +53 -51
- package/dist/{cli-2U5JB7OQ.js.map → cli-234DNHN6.js.map} +1 -1
- package/dist/{config-44EGO636.js → config-IY2OJCAK.js} +11 -13
- package/dist/{doctor-BD42BBEG.js → doctor-2UZZF44A.js} +275 -250
- package/dist/doctor-2UZZF44A.js.map +1 -0
- package/dist/{env-proxy-KEGEMWKX.js → env-proxy-XL4P73MZ.js} +2 -2
- package/dist/{fund-WQOOUESE.js → fund-RZ2QFULK.js} +92 -36
- package/dist/{fund-WQOOUESE.js.map → fund-RZ2QFULK.js.map} +1 -1
- package/dist/hook-command-PZHKS7ES.js +31 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
- package/dist/hosts/claude/tenjin/.mcp.json +11 -0
- package/dist/hosts/claude/tenjin/hooks/hooks.json +206 -0
- package/dist/index.js +15 -6
- package/dist/index.js.map +1 -1
- package/dist/install-O5FJ5EP3.js +48 -0
- package/dist/{install-identity-4RDWTLJ2.js → install-identity-QM44IQ6Z.js} +7 -7
- package/dist/{install-wallet-USHWL7AX.js → install-wallet-Z52EDLPB.js} +14 -14
- package/dist/{mcp-T5SYCLP7.js → mcp-33HAADDF.js} +557 -118
- package/dist/mcp-33HAADDF.js.map +1 -0
- package/dist/package-RT24HTTP.js +37 -0
- package/dist/{pay-276DSSYG.js → pay-IR2V76FX.js} +16 -16
- package/dist/{payments-TZYLJXK3.js → payments-GFV4HU5R.js} +10 -10
- package/dist/{send-YHDKZPED.js → send-PI4NUA7I.js} +13 -13
- package/dist/{status-X2INT6VD.js → status-ZUHTJK46.js} +10 -9
- package/dist/{status-X2INT6VD.js.map → status-ZUHTJK46.js.map} +1 -1
- package/dist/{status-line-QKDJYZGV.js → status-line-2G5JPQAE.js} +6 -6
- package/dist/uninstall-THKUH5ZT.js +136 -0
- package/dist/uninstall-THKUH5ZT.js.map +1 -0
- package/dist/update-NPZDP24E.js +18 -0
- package/dist/update-NPZDP24E.js.map +1 -0
- package/dist/{wallet-CKKB23D5.js → wallet-53EFH4M5.js} +11 -11
- package/dist/wallet-53EFH4M5.js.map +1 -0
- package/docs/agent-permissions.md +32 -21
- package/package.json +3 -3
- package/dist/chunk-65EJJVT3.js +0 -172
- package/dist/chunk-65EJJVT3.js.map +0 -1
- package/dist/chunk-BOAI23CX.js.map +0 -1
- package/dist/chunk-DI7WHXOZ.js.map +0 -1
- package/dist/chunk-EJXIK6WY.js.map +0 -1
- package/dist/chunk-GHR4BTNJ.js +0 -87
- package/dist/chunk-GHR4BTNJ.js.map +0 -1
- package/dist/chunk-H4BOQLWW.js +0 -99
- package/dist/chunk-H4BOQLWW.js.map +0 -1
- package/dist/chunk-JLEF5WHM.js +0 -132
- package/dist/chunk-JLEF5WHM.js.map +0 -1
- package/dist/chunk-OBPZ36HG.js.map +0 -1
- package/dist/chunk-PM2MOXJ3.js +0 -66
- package/dist/chunk-PM2MOXJ3.js.map +0 -1
- package/dist/chunk-QF4SSCQV.js.map +0 -1
- package/dist/chunk-TGLKKLQG.js +0 -11
- package/dist/chunk-TGLKKLQG.js.map +0 -1
- package/dist/chunk-UDWGT4FX.js.map +0 -1
- package/dist/chunk-VNT3CQFV.js +0 -940
- package/dist/chunk-VNT3CQFV.js.map +0 -1
- package/dist/chunk-XICKN3CH.js.map +0 -1
- package/dist/chunk-YHWBDCGS.js +0 -753
- package/dist/chunk-YHWBDCGS.js.map +0 -1
- package/dist/chunk-YLCWI6ZR.js.map +0 -1
- package/dist/chunk-Z7R2QDX2.js.map +0 -1
- package/dist/chunk-ZLD6MJVJ.js.map +0 -1
- package/dist/doctor-BD42BBEG.js.map +0 -1
- package/dist/hook-command-23LC5NRN.js +0 -32
- package/dist/install-REPLHNU7.js +0 -72
- package/dist/mcp-T5SYCLP7.js.map +0 -1
- package/dist/status-line-wiring-LW4HFRHB.js +0 -31
- package/dist/uninstall-NVTGU7JD.js +0 -175
- package/dist/uninstall-NVTGU7JD.js.map +0 -1
- package/dist/update-QXVH2DE7.js.map +0 -1
- /package/dist/{config-44EGO636.js.map → alive-3J3CHOQP.js.map} +0 -0
- /package/dist/{chunk-LAIZ2AQA.js.map → chunk-A5H3E5QA.js.map} +0 -0
- /package/dist/{chunk-YTM7OURD.js.map → chunk-BRHREK7E.js.map} +0 -0
- /package/dist/{chunk-ALJRB7NG.js.map → chunk-MNTQMZJB.js.map} +0 -0
- /package/dist/{chunk-6JIYGYRB.js.map → chunk-YFJJYHVG.js.map} +0 -0
- /package/dist/{chunk-5NUF4BHR.js.map → chunk-ZP5PV3JB.js.map} +0 -0
- /package/dist/{chunk-HII5HOQV.js.map → chunk-ZP7AHN7Z.js.map} +0 -0
- /package/dist/{env-proxy-KEGEMWKX.js.map → config-IY2OJCAK.js.map} +0 -0
- /package/dist/{hook-command-23LC5NRN.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
- /package/dist/{install-REPLHNU7.js.map → hook-command-PZHKS7ES.js.map} +0 -0
- /package/dist/{install-identity-4RDWTLJ2.js.map → install-O5FJ5EP3.js.map} +0 -0
- /package/dist/{pay-276DSSYG.js.map → install-identity-QM44IQ6Z.js.map} +0 -0
- /package/dist/{install-wallet-USHWL7AX.js.map → install-wallet-Z52EDLPB.js.map} +0 -0
- /package/dist/{status-line-wiring-LW4HFRHB.js.map → package-RT24HTTP.js.map} +0 -0
- /package/dist/{wallet-CKKB23D5.js.map → pay-IR2V76FX.js.map} +0 -0
- /package/dist/{payments-TZYLJXK3.js.map → payments-GFV4HU5R.js.map} +0 -0
- /package/dist/{send-YHDKZPED.js.map → send-PI4NUA7I.js.map} +0 -0
- /package/dist/{status-line-QKDJYZGV.js.map → status-line-2G5JPQAE.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
CliError
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-QTND6XWJ.js";
|
|
5
5
|
|
|
6
6
|
// src/lib/destination.ts
|
|
7
7
|
import { lookup } from "node:dns/promises";
|
|
@@ -104,4 +104,4 @@ export {
|
|
|
104
104
|
assertPublicDestination,
|
|
105
105
|
resolvePublicDestination
|
|
106
106
|
};
|
|
107
|
-
//# sourceMappingURL=chunk-
|
|
107
|
+
//# sourceMappingURL=chunk-A5H3E5QA.js.map
|
|
@@ -5,40 +5,27 @@ import {
|
|
|
5
5
|
fetchDistTags,
|
|
6
6
|
isNewer,
|
|
7
7
|
resolveTarget
|
|
8
|
-
} from "./chunk-
|
|
9
|
-
import {
|
|
10
|
-
RECONNECT_FIX,
|
|
11
|
-
readMcpServers
|
|
12
|
-
} from "./chunk-H4BOQLWW.js";
|
|
8
|
+
} from "./chunk-7H3RN4WJ.js";
|
|
13
9
|
import {
|
|
14
10
|
emitWriteNotice,
|
|
15
11
|
sanitizeForTerminal
|
|
16
|
-
} from "./chunk-
|
|
17
|
-
import {
|
|
18
|
-
CHANNEL_DEPOSIT_ATOMIC,
|
|
19
|
-
ROUTING_FEE_ATOMIC,
|
|
20
|
-
usd
|
|
21
|
-
} from "./chunk-OBPZ36HG.js";
|
|
22
|
-
import "./chunk-XMIVHQ35.js";
|
|
23
|
-
import {
|
|
24
|
-
package_default
|
|
25
|
-
} from "./chunk-GHR4BTNJ.js";
|
|
26
|
-
import "./chunk-2I4QTOLB.js";
|
|
27
|
-
import "./chunk-XICKN3CH.js";
|
|
12
|
+
} from "./chunk-XVTD7UWR.js";
|
|
28
13
|
import {
|
|
29
14
|
CliError
|
|
30
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-QTND6XWJ.js";
|
|
31
16
|
import {
|
|
32
17
|
defaultDataDir
|
|
33
18
|
} from "./chunk-K6AXXYCG.js";
|
|
34
|
-
import
|
|
19
|
+
import {
|
|
20
|
+
package_default
|
|
21
|
+
} from "./chunk-RLPLYUME.js";
|
|
35
22
|
|
|
36
23
|
// src/commands/update.ts
|
|
37
24
|
import { spawn } from "node:child_process";
|
|
38
25
|
import { existsSync as existsSync2, statSync as statSync2 } from "node:fs";
|
|
39
26
|
import { homedir } from "node:os";
|
|
40
27
|
import { resolve, sep as sep2 } from "node:path";
|
|
41
|
-
import { fileURLToPath } from "node:url";
|
|
28
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
42
29
|
|
|
43
30
|
// src/lib/install-location.ts
|
|
44
31
|
import { existsSync, realpathSync, statSync } from "node:fs";
|
|
@@ -192,6 +179,97 @@ function realpathOrNull(p) {
|
|
|
192
179
|
}
|
|
193
180
|
}
|
|
194
181
|
|
|
182
|
+
// src/router/mcp-processes.ts
|
|
183
|
+
import { execFile } from "node:child_process";
|
|
184
|
+
import { stat } from "node:fs/promises";
|
|
185
|
+
import { dirname as dirname2, join as join2 } from "node:path";
|
|
186
|
+
import { fileURLToPath } from "node:url";
|
|
187
|
+
import { promisify } from "node:util";
|
|
188
|
+
var exec = promisify(execFile);
|
|
189
|
+
var listMcpProcesses = async () => {
|
|
190
|
+
if (process.platform === "win32" || typeof process.getuid !== "function") return null;
|
|
191
|
+
try {
|
|
192
|
+
const { stdout } = await exec(
|
|
193
|
+
"ps",
|
|
194
|
+
["-U", String(process.getuid()), "-o", "pid=,lstart=,args="],
|
|
195
|
+
{ timeout: 5e3, env: { ...process.env, LC_ALL: "C" }, maxBuffer: 4 * 1024 * 1024 }
|
|
196
|
+
);
|
|
197
|
+
return parsePs(stdout, process.pid);
|
|
198
|
+
} catch {
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
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+(.*)$/;
|
|
203
|
+
function parsePs(stdout, selfPid) {
|
|
204
|
+
const found = [];
|
|
205
|
+
for (const line of stdout.split("\n")) {
|
|
206
|
+
const m = PS_LINE.exec(line);
|
|
207
|
+
if (m === null) continue;
|
|
208
|
+
const pid = Number(m[1]);
|
|
209
|
+
if (pid === selfPid || !isTenjinMcp(m[3])) continue;
|
|
210
|
+
const startedAt = Date.parse(m[2].replace(/\s+/g, " "));
|
|
211
|
+
found.push({ pid, startedAt: Number.isNaN(startedAt) ? null : startedAt });
|
|
212
|
+
}
|
|
213
|
+
return found;
|
|
214
|
+
}
|
|
215
|
+
function isTenjinMcp(args) {
|
|
216
|
+
const tokens = args.trim().split(/\s+/);
|
|
217
|
+
const bin = tokens.findIndex(
|
|
218
|
+
(t) => /(^|[/\\])tenjin(\.js|\.cmd)?$/.test(t) || /[/\\]tenjin-cli[/\\]/.test(t)
|
|
219
|
+
);
|
|
220
|
+
return bin >= 0 && tokens[bin + 1] === "mcp";
|
|
221
|
+
}
|
|
222
|
+
var installedAt = async () => {
|
|
223
|
+
let dir = dirname2(fileURLToPath(import.meta.url));
|
|
224
|
+
for (let i = 0; i < 6; i += 1) {
|
|
225
|
+
try {
|
|
226
|
+
const st = await stat(join2(dir, "package.json"));
|
|
227
|
+
return Math.max(st.ctimeMs, st.mtimeMs);
|
|
228
|
+
} catch {
|
|
229
|
+
dir = dirname2(dir);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return null;
|
|
233
|
+
};
|
|
234
|
+
var RECONNECT_FIX = "Type /reload-plugins in this Claude Code session, or start a new session.";
|
|
235
|
+
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.";
|
|
236
|
+
function mcpServersState(procs, installed, version = package_default.version, fix = RECONNECT_FIX) {
|
|
237
|
+
const check = (detail) => ({
|
|
238
|
+
stale: 0,
|
|
239
|
+
check: { name: "mcp server", status: "ok", required: false, detail }
|
|
240
|
+
});
|
|
241
|
+
if (procs === null) {
|
|
242
|
+
return check("unknown: running `tenjin mcp` processes cannot be listed on this platform");
|
|
243
|
+
}
|
|
244
|
+
if (procs.length === 0) return check("none running (starts with the next session)");
|
|
245
|
+
if (installed === null) {
|
|
246
|
+
return check(`${procs.length} running; when this build was installed is unknown`);
|
|
247
|
+
}
|
|
248
|
+
const stale = procs.filter((p) => p.startedAt !== null && p.startedAt < installed).length;
|
|
249
|
+
if (stale === 0) {
|
|
250
|
+
return check(`${procs.length} running, all started after this install`);
|
|
251
|
+
}
|
|
252
|
+
const which = stale === 1 ? "process" : "processes";
|
|
253
|
+
return {
|
|
254
|
+
stale,
|
|
255
|
+
check: {
|
|
256
|
+
name: "mcp server",
|
|
257
|
+
status: "warn",
|
|
258
|
+
required: false,
|
|
259
|
+
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"`,
|
|
260
|
+
fix
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
async function readMcpServers(deps = {}, opts = {}) {
|
|
265
|
+
const [procs, installed] = await Promise.all([
|
|
266
|
+
(deps.listMcpProcesses ?? listMcpProcesses)().catch(() => null),
|
|
267
|
+
(deps.installedAt ?? installedAt)().catch(() => null)
|
|
268
|
+
]);
|
|
269
|
+
const fix = opts.settingsInstallPending === true ? NEW_SESSION_FIX : RECONNECT_FIX;
|
|
270
|
+
return mcpServersState(procs, installed, package_default.version, fix);
|
|
271
|
+
}
|
|
272
|
+
|
|
195
273
|
// src/commands/update.ts
|
|
196
274
|
var INSTALL_TIMEOUT_MS = 3e5;
|
|
197
275
|
function resolveManager(manager, deps) {
|
|
@@ -201,7 +279,7 @@ function resolveManager(manager, deps) {
|
|
|
201
279
|
async function runUpdate(opts, ctx, deps = {}) {
|
|
202
280
|
const current = deps.currentVersion ?? package_default.version;
|
|
203
281
|
const channel = channelTag(current);
|
|
204
|
-
const moduleDir = deps.moduleDir ??
|
|
282
|
+
const moduleDir = deps.moduleDir ?? fileURLToPath2(new URL(".", import.meta.url));
|
|
205
283
|
if (channel === null) {
|
|
206
284
|
throw new CliError("REFUSED", `tenjin-cli reports an unrecognizable version (${current})`, {
|
|
207
285
|
fix: "Reinstall a published build: npm i -g tenjin-cli"
|
|
@@ -298,18 +376,19 @@ async function runUpdate(opts, ctx, deps = {}) {
|
|
|
298
376
|
`tenjin update: replaced the global tenjin-cli with ${latest} via ${manager}`
|
|
299
377
|
);
|
|
300
378
|
const refresh = await refreshProfiles(ctx, deps);
|
|
301
|
-
const servers = await readMcpServers(deps
|
|
379
|
+
const servers = await readMcpServers(deps, {
|
|
380
|
+
settingsInstallPending: refresh.settingsInstallPending
|
|
381
|
+
});
|
|
302
382
|
return {
|
|
303
383
|
data: { ...data(true), refresh, mcpServer: servers.check },
|
|
304
384
|
humanLines: [
|
|
305
385
|
`Updated tenjin-cli ${current} -> ${latest}.`,
|
|
306
386
|
...refreshLines(refresh),
|
|
307
|
-
...
|
|
308
|
-
|
|
387
|
+
...refresh.notices,
|
|
388
|
+
...servers.stale > 0 ? [`! ${servers.check.detail}. ${servers.check.fix ?? ""}`.trim()] : []
|
|
309
389
|
]
|
|
310
390
|
};
|
|
311
391
|
}
|
|
312
|
-
var ROUTING_FEE_LINE = `Routing costs $${usd(ROUTING_FEE_ATOMIC)} a call once Tenjin's server turns the fee on, paid from deposits of up to $${usd(CHANNEL_DEPOSIT_ATOMIC)} that count against your spend limits (\`tenjin config get maxAutoSpend\`, \`tenjin config get sessionBudget\`).`;
|
|
313
392
|
var REFRESH_TIMEOUT_MS = 6e4;
|
|
314
393
|
async function refreshProfiles(ctx, deps) {
|
|
315
394
|
const home = deps.homeDir ?? homedir();
|
|
@@ -326,10 +405,14 @@ async function refreshProfiles(ctx, deps) {
|
|
|
326
405
|
const reason = "This build has no entry the update could safely re-execute.";
|
|
327
406
|
return {
|
|
328
407
|
profiles: [],
|
|
329
|
-
failed: candidates.map((d) => ({ dataDir: d, reason, fix: fixFor(d) }))
|
|
408
|
+
failed: candidates.map((d) => ({ dataDir: d, reason, fix: fixFor(d) })),
|
|
409
|
+
notices: [],
|
|
410
|
+
settingsInstallPending: false
|
|
330
411
|
};
|
|
331
412
|
}
|
|
332
413
|
const failed = [...unrun];
|
|
414
|
+
const notices = [];
|
|
415
|
+
let settingsInstallPending = false;
|
|
333
416
|
for (const dataDir of profiles) {
|
|
334
417
|
let tail = "";
|
|
335
418
|
const outcome = await (deps.spawnImpl ?? spawnCapture)(
|
|
@@ -348,11 +431,38 @@ async function refreshProfiles(ctx, deps) {
|
|
|
348
431
|
);
|
|
349
432
|
if (outcome.kind !== "exit" || outcome.code !== 0) {
|
|
350
433
|
failed.push({ dataDir, reason: refreshReason(outcome, tail), fix: fixFor(dataDir) });
|
|
434
|
+
continue;
|
|
435
|
+
}
|
|
436
|
+
const reported = envelopeData(tail);
|
|
437
|
+
for (const notice of noticesOf(reported)) if (!notices.includes(notice)) notices.push(notice);
|
|
438
|
+
const migration = reported?.migration;
|
|
439
|
+
if (migration?.state === "pending" || migration?.state === "blocked") {
|
|
440
|
+
settingsInstallPending = true;
|
|
351
441
|
}
|
|
352
442
|
}
|
|
353
|
-
return { profiles, failed };
|
|
443
|
+
return { profiles, failed, notices, settingsInstallPending };
|
|
354
444
|
}
|
|
355
|
-
|
|
445
|
+
function envelopeData(output) {
|
|
446
|
+
const lines = output.split("\n");
|
|
447
|
+
for (let i = lines.length - 1; i >= 0; i -= 1) {
|
|
448
|
+
if (lines[i]?.trim() !== "{" && !lines[i]?.trim().startsWith('{"')) continue;
|
|
449
|
+
try {
|
|
450
|
+
const parsed = JSON.parse(lines.slice(i).join("\n"));
|
|
451
|
+
if (parsed?.ok === true && parsed.data !== null && typeof parsed.data === "object") {
|
|
452
|
+
return parsed.data;
|
|
453
|
+
}
|
|
454
|
+
} catch {
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
return null;
|
|
459
|
+
}
|
|
460
|
+
function noticesOf(data) {
|
|
461
|
+
const raw = data?.notices;
|
|
462
|
+
if (!Array.isArray(raw)) return [];
|
|
463
|
+
return raw.filter((n) => typeof n === "string").map((n) => sanitizeForTerminal(n).trim().slice(0, REASON_LIMIT)).filter((n) => n.length > 0).slice(0, 5);
|
|
464
|
+
}
|
|
465
|
+
var REFRESH_TAIL_LIMIT = 64e3;
|
|
356
466
|
var REASON_LIMIT = 300;
|
|
357
467
|
function refreshReason(outcome, output) {
|
|
358
468
|
const reported = envelopeMessage(output);
|
|
@@ -384,7 +494,7 @@ function isExistingDir(path) {
|
|
|
384
494
|
function manualFix(dataDir, home, invoking) {
|
|
385
495
|
const bare = resolve(dataDir) === resolve(defaultDataDir(home)) && resolve(dataDir) === resolve(invoking);
|
|
386
496
|
const command = bare ? "tenjin install" : `TENJIN_DATA_DIR=${dataDir} tenjin install`;
|
|
387
|
-
return `Run \`${command}\` to bring the
|
|
497
|
+
return `Run \`${command}\` to bring the Claude Code plugin up to this version.`;
|
|
388
498
|
}
|
|
389
499
|
function versionFreeEntry(entry) {
|
|
390
500
|
if (entry === void 0 || entry.length === 0) return null;
|
|
@@ -401,14 +511,14 @@ function refreshLines(refresh) {
|
|
|
401
511
|
const done = refresh.profiles.filter((p) => !failedDirs.has(p));
|
|
402
512
|
if (refresh.failed.length === 0) {
|
|
403
513
|
return [
|
|
404
|
-
done.length > 1 ? `Refreshed the
|
|
514
|
+
done.length > 1 ? `Refreshed the Claude Code plugin for ${done.length} profiles: ${done.join(", ")}.` : `Refreshed the Claude Code plugin for ${done[0]}.`
|
|
405
515
|
];
|
|
406
516
|
}
|
|
407
517
|
const total = done.length + refresh.failed.length;
|
|
408
518
|
const lines = done.length > 0 ? [
|
|
409
|
-
`Refreshed the
|
|
519
|
+
`Refreshed the Claude Code plugin for ${done.length} of ${total} profiles: ${done.join(", ")}.`
|
|
410
520
|
] : [];
|
|
411
|
-
lines.push(`Could not refresh the
|
|
521
|
+
lines.push(`Could not refresh the Claude Code plugin for ${refresh.failed.length}:`);
|
|
412
522
|
lines.push(...refresh.failed.map((f) => `- ${f.dataDir}: ${f.reason} ${f.fix}`));
|
|
413
523
|
return lines;
|
|
414
524
|
}
|
|
@@ -443,9 +553,11 @@ var spawnCapture = (cmd, args, opts, onOutput) => new Promise((res) => {
|
|
|
443
553
|
res(timedOut ? { kind: "timeout" } : { kind: "exit", code: code ?? 1 });
|
|
444
554
|
});
|
|
445
555
|
});
|
|
556
|
+
|
|
446
557
|
export {
|
|
558
|
+
readMcpServers,
|
|
447
559
|
runUpdate,
|
|
448
|
-
|
|
449
|
-
|
|
560
|
+
versionFreeEntry,
|
|
561
|
+
spawnCapture
|
|
450
562
|
};
|
|
451
|
-
//# sourceMappingURL=
|
|
563
|
+
//# sourceMappingURL=chunk-AO54FM4H.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/update.ts","../src/lib/install-location.ts","../src/router/mcp-processes.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { existsSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport pkg from '../../package.json';\nimport { CliError } from '../lib/errors';\nimport { MANAGERS, classifyManager, refuse, resolveManagerScript } from '../lib/install-location';\nimport type { Delegable } from '../lib/install-location';\nimport { emitWriteNotice, sanitizeForTerminal } from '../lib/output';\nimport {\n NUDGE_OPT_OUT,\n channelTag,\n fetchDistTags,\n isNewer,\n resolveTarget,\n} from '../lib/update-check';\nimport { defaultDataDir } from '../lib/paths';\nimport type { CommandContext, CommandResult } from '../context';\nimport { readMcpServers, type InstalledAt, type ListMcpProcesses } from '../router/mcp-processes';\n\n/**\n * `tenjin update`: replace this install with the newest version npm offers it,\n * by spawning the package manager that OWNS the install rather than\n * reimplementing one. Four invariants:\n *\n * - The argv pins the EXACT version the registry just named, never the tag, so\n * the check and the install cannot disagree about what ships, and the version\n * string is certified parseable by the same `isNewer` gate the nudge trusts\n * before it goes anywhere near an argv.\n * - The owner performs the install. npm, pnpm and bun are each driven with their\n * own global-add command, because the PATH race that makes a second install\n * dangerous comes from CROSS-manager writes, not from asking the owner to do\n * what it already owns. What cannot be driven is refused instead of guessed\n * at: a source checkout updates by git, an npx run has nothing installed to\n * replace, a project-local copy updates where it is declared, and yarn's\n * global install exists only in yarn 1. See lib/install-location.\n * - The child is a binary or `node <script>`, never a shell. That is what makes\n * the pinned argv worth pinning, and it is the only form that works on win32.\n * - The manager's chatter goes to stderr (live, human mode only, sanitized) and\n * its failure into the error envelope; stdout stays the one envelope every\n * command emits.\n */\n\n/** How long the npm child gets before it is killed. npm's own retry budget runs\n * into minutes, and an agent's turn should not hang on a wedged registry. */\nconst INSTALL_TIMEOUT_MS = 300_000;\n\nexport interface UpdateOptions {\n /** Report whether a newer version exists; never install. */\n check: boolean;\n}\n\n/**\n * How the child ended. Never rejects: all three outcomes are envelope-shaped\n * facts the caller reports, not exceptions, and each is separately testable.\n */\nexport type SpawnResult =\n { kind: 'exit'; code: number } | { kind: 'start-failed'; cause: unknown } | { kind: 'timeout' };\n\nexport type UpdateSpawn = (\n cmd: string,\n args: string[],\n opts: {\n cwd: string;\n timeoutMs: number;\n /** Variables layered ONTO this process's environment, for the per-profile\n * `TENJIN_DATA_DIR` the refresh pass sets. Absent means inherit unchanged. */\n env?: Record<string, string>;\n },\n onOutput: (chunk: string) => void,\n) => Promise<SpawnResult>;\n\n/** What to spawn for one manager: a command and any argv that must precede its own. */\ninterface ResolvedManager {\n cmd: string;\n prefix: readonly string[];\n}\n\n/**\n * Turn a manager into a spawnable command. A resolved script runs under THIS\n * node, keeping `shell` unset on every platform; otherwise the bare binary name\n * is used, which is correct for a native binary and fails closed on win32 for a\n * `.cmd` shim.\n */\nfunction resolveManager(manager: Delegable, deps: UpdateDeps): ResolvedManager {\n const script =\n deps.managerScript !== undefined\n ? deps.managerScript\n : resolveManagerScript(manager, process.execPath);\n return script === null\n ? { cmd: MANAGERS[manager].bin, prefix: [] }\n : { cmd: process.execPath, prefix: [script] };\n}\n\nexport interface UpdateDeps {\n fetchImpl?: typeof fetch;\n spawnImpl?: UpdateSpawn;\n /** Where this build's code lives on disk; tests point it at fixture trees. */\n moduleDir?: string;\n /** The running version; defaults to this build's. Injectable for tests. */\n currentVersion?: string;\n /** The owning manager's entry script, or null when it has none to find.\n * Injectable so the argv shape is asserted without depending on the runner. */\n managerScript?: string | null;\n /** Home whose manual-fix command the report names. Defaults to os.homedir(). */\n homeDir?: string;\n /**\n * The CLI entry the refresh child runs. Defaults to `process.argv[1]`, which\n * after the swap resolves to the NEWLY installed script — that is the whole\n * point of spawning rather than calling.\n */\n refreshCommand?: string;\n /** This user's running `tenjin mcp` processes; tests inject them. */\n listMcpProcesses?: ListMcpProcesses;\n /** When the new build was installed; tests inject it. */\n installedAt?: InstalledAt;\n}\n\ninterface UpdateData {\n current: string;\n latest: string;\n updateAvailable: boolean;\n updated: boolean;\n}\n\nexport async function runUpdate(\n opts: UpdateOptions,\n ctx: CommandContext,\n deps: UpdateDeps = {},\n): Promise<CommandResult> {\n const current = deps.currentVersion ?? pkg.version;\n const channel = channelTag(current);\n const moduleDir = deps.moduleDir ?? fileURLToPath(new URL('.', import.meta.url));\n\n // Refused, not defaulted to a channel: a build whose version this package\n // cannot parse has no release line to compare against, and guessing one is how\n // a foreign build gets told it is up to date forever.\n if (channel === null) {\n throw new CliError('REFUSED', `tenjin-cli reports an unrecognizable version (${current})`, {\n fix: 'Reinstall a published build: npm i -g tenjin-cli',\n });\n }\n\n // First stage: everything whose fix string does not need a resolved version,\n // so it answers without the network. An offline contributor in a checkout is\n // told they are in a checkout, not told to go debug their registry access.\n refuse(moduleDir, { check: opts.check, spec: null });\n\n const tags = await fetchDistTags({\n fetchImpl: deps.fetchImpl,\n timeoutMs: ctx.flags.timeout,\n });\n if (tags === null) {\n throw new CliError('NETWORK_ERROR', 'Could not read tenjin-cli dist-tags from npm', {\n fix: 'Check access to registry.npmjs.org and retry',\n });\n }\n const latest = resolveTarget(current, tags);\n // Not a NETWORK_ERROR: nothing about the connection is wrong, and telling the\n // user to check their access sends them after a fault that is not there.\n if (latest === null) {\n const raw = tags[channel];\n throw raw === undefined\n ? new CliError('RESOURCE_NOT_FOUND', 'npm has no published tenjin-cli on the latest tag', {\n fix: 'Pick a version yourself: npm view tenjin-cli versions',\n })\n : new CliError(\n 'RESOURCE_NOT_FOUND',\n // Registry-controlled: bounded here, escaped by the error emitter.\n `npm's latest tenjin-cli (${raw.slice(0, 40)}) is not a version this build can read`,\n {\n fix: 'Install it by name: npm i -g tenjin-cli@<version> (npm view tenjin-cli versions)',\n },\n );\n }\n\n const updateAvailable = isNewer(latest, current);\n const data = (updated: boolean): UpdateData => ({\n current,\n latest,\n updateAvailable,\n updated,\n });\n\n if (!updateAvailable) {\n return {\n data: data(false),\n humanLines: [`tenjin-cli ${current} is up to date`],\n };\n }\n if (opts.check) {\n return {\n data: data(false),\n humanLines: [\n `tenjin-cli ${latest} is available (you have ${current}).`,\n 'Run tenjin update to install it.',\n ],\n };\n }\n\n // `latest` is argv-safe here: isNewer returned true, so it matched VERSION_RE.\n const spec = `tenjin-cli@${latest}`;\n\n // Second stage: the entries whose fix strings name the version just resolved.\n // Reached only on the install path, since --check has already returned.\n refuse(moduleDir, { check: false, spec });\n\n // Live chatter is a human courtesy only; the tail rides in the error envelope\n // so a piped failure is still diagnosable. Sanitized per line, because npm\n // relays publisher-controlled text (deprecation notices) and a line break is\n // the one control character this stream must keep.\n const human = ctx.io.isTTY && !ctx.flags.json;\n let tail = '';\n const onOutput = (chunk: string): void => {\n tail = (tail + chunk).slice(-2000);\n if (human) ctx.io.stderr.write(chunk.split('\\n').map(sanitizeForTerminal).join('\\n'));\n };\n\n // Whoever owns the install performs it. The PATH-race objection that used to\n // make this a refusal only applies to CROSS-manager writes; invoking the owner\n // is exactly what the refusal used to tell the user to type by hand.\n //\n // The cast is sound only because `refuse` ran directly above and yarn is one\n // of its entries, so the one non-delegable manager has already thrown. Move\n // this line above that call and it becomes a lie.\n const manager = classifyManager(moduleDir) as Delegable;\n const plan = MANAGERS[manager];\n // --ignore-scripts where the manager has it (tenjin-cli has no runtime\n // dependencies and no registry install runs its own `prepare`), and cwd is the\n // home directory so the child never reads a project's config by accident.\n const args = plan.args(spec);\n const resolved = resolveManager(manager, deps);\n const manual = `Run it yourself: ${plan.manual(spec)}`;\n\n const outcome = await (deps.spawnImpl ?? spawnCapture)(\n resolved.cmd,\n [...resolved.prefix, ...args],\n { cwd: homedir(), timeoutMs: INSTALL_TIMEOUT_MS },\n onOutput,\n );\n if (outcome.kind === 'start-failed') {\n throw new CliError('UPDATE_FAILED', `Could not start ${manager}`, {\n fix: manual,\n cause: outcome.cause,\n });\n }\n if (outcome.kind === 'timeout') {\n throw new CliError(\n 'UPDATE_FAILED',\n `${manager} did not finish in ${INSTALL_TIMEOUT_MS / 1000}s`,\n { fix: manual, details: { output: tail } },\n );\n }\n if (outcome.code !== 0) {\n throw new CliError('UPDATE_FAILED', `${manager} ${args.join(' ')} exited ${outcome.code}`, {\n // EACCES on a root-owned global prefix is the common cause; the operator\n // fixing that themselves beats this CLI ever escalating.\n fix: manual,\n details: { output: tail },\n });\n }\n\n emitWriteNotice(\n ctx.io,\n `tenjin update: replaced the global tenjin-cli with ${latest} via ${manager}`,\n );\n\n const refresh = await refreshProfiles(ctx, deps);\n // The refresh child's output is captured, so the warning it would print about\n // a `tenjin mcp` still running the old build is checked again here, with the\n // fix the child's migration state calls for.\n const servers = await readMcpServers(deps, {\n settingsInstallPending: refresh.settingsInstallPending,\n });\n return {\n data: { ...data(true), refresh, mcpServer: servers.check },\n humanLines: [\n `Updated tenjin-cli ${current} -> ${latest}.`,\n ...refreshLines(refresh),\n ...refresh.notices,\n ...(servers.stale > 0\n ? [`! ${servers.check.detail}. ${servers.check.fix ?? ''}`.trim()]\n : []),\n ],\n };\n}\n\n/** How long one `install --refresh` child gets. Local file writes only, no\n * registry: a minute is already generous, and `update` must not hang a turn. */\nconst REFRESH_TIMEOUT_MS = 60_000;\n\n/** One profile this update did not bring up to date, and why. */\nexport interface RefreshFailure {\n /** The profile's data dir. */\n dataDir: string;\n /**\n * Why it is not up to date, in the words of whoever decided that: the child's\n * own `error.message` when it printed a failure envelope, this pass's own\n * account when the child was never run or never got that far. Always present,\n * because a failure whose four causes render identically is the reason this\n * field exists.\n */\n reason: string;\n /** The command that converges THIS profile; see {@link manualFix}. */\n fix: string;\n}\n\n/** What the post-swap re-materialize did, per profile. */\nexport interface RefreshOutcome {\n /** Data dirs a refresh was run for, whether or not it succeeded. */\n profiles: string[];\n /**\n * Profiles this update did not bring up to date, each with its reason and the\n * manual command to finish it. Both halves land here: a refresh that ran and\n * did not report success, and one that was never run at all (no entry to\n * re-exec, a data dir that is not a directory).\n */\n failed: RefreshFailure[];\n /**\n * What a refresh that succeeded said the person must know (the child's\n * `data.notices`): a plugin left for a newer Claude Code, a status line the\n * migration took out. Printed as given, one line each.\n */\n notices: string[];\n /** A refreshed profile still carries an earlier release's settings install. */\n settingsInstallPending: boolean;\n}\n\n/**\n * Re-materialize what the swap left stale, on the NEW binary.\n *\n * `update` replaces the package and nothing else, but `install` bakes this\n * build's identity into files: the generated hook scripts carry a version, and\n * the wired skills carry this release's instructions. Until something rewrites\n * them the highest-volume request path keeps reporting the previous version and\n * agents keep reading the previous release's guidance (tenjin-agent#171).\n *\n * SPAWNED, NOT CALLED. This process is the OLD build; it cannot render the new\n * version's copies, and re-exec is the only way to reach code that can. The\n * child is the freshly installed entry, and what it runs is\n * `install --refresh` — a mode that converges existing surfaces and creates\n * none, which is the only kind of write an unattended upgrade may make.\n *\n * ONCE PER HOOK-OWNER PROFILE. `install` bakes its data dir into the scripts it\n * generates, so a machine whose hooks were installed under `TENJIN_DATA_DIR`\n * has hooks belonging to THAT profile while a bare `tenjin update` resolves the\n * default one. Refreshing only the invoking profile there would leave the\n * registered scripts — the ones the harness actually fires — stale forever,\n * which is exactly the shelf runbook's manual re-install step. So the detector\n * reads the harness settings and each profile it names is refreshed with\n * `TENJIN_DATA_DIR` set to it. A machine with no registered hooks has no other\n * profile to find, and gets one refresh for the invoking one.\n *\n * NEVER FAILS THE UPDATE. The swap already happened and is the thing the\n * operator asked for. A refusal, a run with nothing to converge, a crash, a\n * timeout, or an older-binary \"unknown option --refresh\" all land here as a warn\n * naming the manual command.\n *\n * EACH FAILURE CARRIES ITS OWN REASON AND ITS OWN FIX. The four ways a profile\n * misses are not interchangeable — a dir that is not a directory, a settings\n * file that changed underneath, a machine that never ran `install`, and a\n * timeout each want a different next move — so the child's output is collected\n * and its `error.message` reported per profile rather than collapsed into one\n * parent line.\n */\nasync function refreshProfiles(ctx: CommandContext, deps: UpdateDeps): Promise<RefreshOutcome> {\n const home = deps.homeDir ?? homedir();\n // THE INVOKING PROFILE, AND ONLY IT. The pre-daemon installer baked its data\n // dir into eight generated scripts, so an upgrade had to find every profile\n // registered in settings.json and refresh each one's bodies. Nothing is baked\n // any more: the two bundles are the same bytes for every profile, and a\n // profile's daemon picks up the new build the next time its own `tenjin`\n // command runs. So there is nothing left to hunt for, and a detector reading\n // paths out of somebody's settings file is not worth keeping to say so.\n const candidates = [ctx.dataDir];\n const fixFor = (dataDir: string): string => manualFix(dataDir, home, ctx.dataDir);\n\n // The child would CREATE a data dir that is not there: `install --refresh`\n // converges surfaces rather than materializing them, but the process around it\n // mkdirs the tree for the update cache on its way out. So a path that is not\n // already a directory is reported unrefreshed instead of visited.\n const profiles: string[] = [];\n const unrun: RefreshFailure[] = [];\n for (const dataDir of candidates) {\n if (isExistingDir(dataDir)) profiles.push(dataDir);\n else unrun.push({ dataDir, reason: 'It is not a directory.', fix: fixFor(dataDir) });\n }\n\n const entry = versionFreeEntry(deps.refreshCommand ?? process.argv[1]);\n // Nothing safe to re-exec: no argv (an embedder, a stripped argv), or a path\n // that names the version being replaced (see versionFreeEntry). Report the\n // profiles as unrefreshed rather than guessing, since guessing is how a hook\n // script gets rewritten by the wrong binary — and a refresh that ran the OLD\n // build would report success while writing the bytes the update just left.\n if (entry === null) {\n const reason = 'This build has no entry the update could safely re-execute.';\n return {\n profiles: [],\n failed: candidates.map((d) => ({ dataDir: d, reason, fix: fixFor(d) })),\n notices: [],\n settingsInstallPending: false,\n };\n }\n\n const failed = [...unrun];\n const notices: string[] = [];\n let settingsInstallPending = false;\n for (const dataDir of profiles) {\n // A BOUNDED COLLECTOR, not the manager's live echo. npm's chatter is minutes\n // of progress a human wants to see; this child emits one envelope on a pipe,\n // and painting that JSON into the human's stderr is noise. It is still kept,\n // because the envelope is where the child says WHICH refusal this was.\n let tail = '';\n const outcome = await (deps.spawnImpl ?? spawnCapture)(\n process.execPath,\n [entry, 'install', '--refresh'],\n {\n cwd: homedir(),\n timeoutMs: REFRESH_TIMEOUT_MS,\n // TENJIN_DATA_DIR aims the child at this profile; the nudge opt-out is\n // what keeps it from touching any other file in there (lib/update-check).\n env: { TENJIN_DATA_DIR: dataDir, [NUDGE_OPT_OUT]: '1' },\n },\n (chunk) => {\n tail = (tail + chunk).slice(-REFRESH_TAIL_LIMIT);\n },\n );\n // The child's exit code IS the verdict: `install --refresh` exits non-zero\n // when it refused or found nothing to converge, so a machine that never ran\n // `install` warns here instead of being told its hooks were refreshed. The\n // envelope on the pipe is what turns that verdict into a reason.\n if (outcome.kind !== 'exit' || outcome.code !== 0) {\n failed.push({ dataDir, reason: refreshReason(outcome, tail), fix: fixFor(dataDir) });\n continue;\n }\n const reported = envelopeData(tail);\n for (const notice of noticesOf(reported)) if (!notices.includes(notice)) notices.push(notice);\n const migration = reported?.migration as { state?: unknown } | undefined;\n if (migration?.state === 'pending' || migration?.state === 'blocked') {\n settingsInstallPending = true;\n }\n }\n return { profiles, failed, notices, settingsInstallPending };\n}\n\n/** The `data` of the one success envelope the child printed, or null. */\nfunction envelopeData(output: string): Record<string, unknown> | null {\n const lines = output.split('\\n');\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n if (lines[i]?.trim() !== '{' && !lines[i]?.trim().startsWith('{\"')) continue;\n try {\n const parsed = JSON.parse(lines.slice(i).join('\\n')) as { ok?: unknown; data?: unknown };\n if (parsed?.ok === true && parsed.data !== null && typeof parsed.data === 'object') {\n return parsed.data as Record<string, unknown>;\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n\n/**\n * The child's notices, each bounded and sanitized: the child is the build\n * this update just installed, but its text still reaches a terminal.\n */\nfunction noticesOf(data: Record<string, unknown> | null): string[] {\n const raw = data?.notices;\n if (!Array.isArray(raw)) return [];\n return raw\n .filter((n): n is string => typeof n === 'string')\n .map((n) => sanitizeForTerminal(n).trim().slice(0, REASON_LIMIT))\n .filter((n) => n.length > 0)\n .slice(0, 5);\n}\n\n/** How much of one refresh child's output is kept. It prints a single envelope,\n * not a build log, so this is headroom rather than a budget. */\nconst REFRESH_TAIL_LIMIT = 64_000;\n\n/** How much of a child's own message reaches the parent's report. Long enough\n * for every message `install --refresh` can produce, short enough that a child\n * which somehow printed prose cannot own the operator's terminal. */\nconst REASON_LIMIT = 300;\n\n/**\n * Why this profile is not up to date, preferring the child's own account.\n *\n * The exit code separates success from failure and nothing else, so the four\n * refusals `install --refresh` can reach would otherwise reach the operator as\n * one line that names none of them. The envelope on the pipe carries the\n * distinction; the outcome kind covers the deaths that never printed one.\n */\nfunction refreshReason(outcome: SpawnResult, output: string): string {\n const reported = envelopeMessage(output);\n if (reported !== undefined) return reported;\n if (outcome.kind === 'timeout') return `It did not finish in ${REFRESH_TIMEOUT_MS / 1000}s.`;\n if (outcome.kind === 'start-failed') return 'The refresh could not be started.';\n // An older binary rejecting `--refresh` is the expected shape here: commander\n // writes its own usage error and exits without an envelope of ours.\n return `The refresh exited ${outcome.code} without reporting a reason.`;\n}\n\n/**\n * The `error.message` out of the one failure envelope the child printed.\n *\n * Read from the LAST envelope because stdout carries exactly one while stderr\n * may carry notices ahead of it, and the two pipes are merged here.\n *\n * `writeJson` PRETTY-PRINTS, so the envelope spans many lines and its only line\n * starting with `{` is a bare `{` that does not parse alone. So scan backwards\n * for an opening line and parse from there to the end; a compact single line\n * still parses through the same path, which keeps an older child readable.\n *\n * Sanitized because this text is bound for a human's terminal and the child\n * relays paths and parse errors it did not author.\n */\nfunction envelopeMessage(output: string): string | undefined {\n const lines = output.split('\\n');\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n const line = lines[i]?.trim();\n if (line === undefined || !line.startsWith('{')) continue;\n let parsed: { ok?: unknown; error?: { message?: unknown } };\n try {\n parsed = JSON.parse(lines.slice(i).join('\\n')) as typeof parsed;\n } catch {\n continue;\n }\n if (parsed?.ok !== false || typeof parsed.error?.message !== 'string') continue;\n const message = sanitizeForTerminal(parsed.error.message).trim();\n if (message.length > 0) return message.slice(0, REASON_LIMIT);\n }\n return undefined;\n}\n\n/** A path that already exists AND is a directory. Follows links on purpose: a\n * data dir behind a symlink is an ordinary machine layout, an absent one is not\n * a profile this command may create. */\nfunction isExistingDir(path: string): boolean {\n return statSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n}\n\n/**\n * The manual command that converges THIS profile.\n *\n * A bare `tenjin install` resolves one data dir, so handing it to an operator\n * whose failed profile is a shelf — the case the per-profile loop exists for —\n * is advice that cannot repair the thing it names. The bare form is emitted only\n * for a dir that is the default under this home AND the one this invocation\n * itself resolved, so it is right under either reading of \"what a bare install\n * would do next\"; every other profile gets the explicit env prefix, which is the\n * same form the shelf runbook uses and is right unconditionally.\n */\nfunction manualFix(dataDir: string, home: string, invoking: string): string {\n const bare =\n resolve(dataDir) === resolve(defaultDataDir(home)) && resolve(dataDir) === resolve(invoking);\n const command = bare ? 'tenjin install' : `TENJIN_DATA_DIR=${dataDir} tenjin install`;\n return `Run \\`${command}\\` to bring the Claude Code plugin up to this version.`;\n}\n\n/**\n * The entry to re-exec, or null when there is none this code may trust.\n *\n * `process.argv[1]` is the path Node RESOLVED, symlinks and all (see\n * `classifyManager`, which reads the manager off exactly that property). Under\n * npm and bun that path carries no version, so after the swap it is already the\n * new build. Under pnpm it points into the virtual store, whose directory names\n * PIN A VERSION: `.../node_modules/.pnpm/tenjin-cli@<version>/node_modules/tenjin-cli/dist/index.js`.\n * Re-executing that is the worst available outcome — it runs the build the\n * update just replaced and reports a successful refresh over the previous\n * version's bytes, which is the exact staleness this whole command exists to\n * end (tenjin-agent#171).\n *\n * The virtual store keeps the version-free link one level out, beside `.pnpm`,\n * and the swap repoints it, so the same path with the store segments removed is\n * the new build. It is derived rather than assumed: if the result is not on\n * disk, this returns null and the caller warns instead of running anything.\n */\nexport function versionFreeEntry(entry: string | undefined): string | null {\n if (entry === undefined || entry.length === 0) return null;\n const segs = entry.split(sep);\n const store = segs.indexOf('.pnpm');\n if (store === -1) return segs.join(sep);\n // `.pnpm/<name>@<version>/node_modules/<name>/...`: everything from the second\n // `node_modules` on is the package's own path within the global tree.\n const inner = segs.indexOf('node_modules', store);\n if (inner === -1) return null;\n const derived = [...segs.slice(0, store), ...segs.slice(inner + 1)].join(sep);\n return existsSync(derived) ? derived : null;\n}\n\n/**\n * What the refresh actually did, as lines.\n *\n * It replaces \"New builds pick it up immediately\", which was true of the binary\n * and false of everything install had written — so it read as reassurance about\n * precisely the thing that was NOT handled (tenjin-agent#171).\n *\n * The successes are reported ALONGSIDE the failures rather than instead of them:\n * a machine where 8 of 12 profiles converged is not a machine where the refresh\n * did nothing, and one line per failure is what lets its own reason and its own\n * command travel with it.\n */\nfunction refreshLines(refresh: RefreshOutcome): string[] {\n const failedDirs = new Set(refresh.failed.map((f) => f.dataDir));\n const done = refresh.profiles.filter((p) => !failedDirs.has(p));\n if (refresh.failed.length === 0) {\n return [\n done.length > 1\n ? `Refreshed the Claude Code plugin for ${done.length} profiles: ${done.join(', ')}.`\n : `Refreshed the Claude Code plugin for ${done[0]}.`,\n ];\n }\n const total = done.length + refresh.failed.length;\n const lines =\n done.length > 0\n ? [\n `Refreshed the Claude Code plugin for ${done.length} of ${total} profiles: ${done.join(', ')}.`,\n ]\n : [];\n lines.push(`Could not refresh the Claude Code plugin for ${refresh.failed.length}:`);\n lines.push(...refresh.failed.map((f) => `- ${f.dataDir}: ${f.reason} ${f.fix}`));\n return lines;\n}\n\n/**\n * Default spawn: merged stdout+stderr chunks out, an outcome back, no shell.\n * Bounded by its own timer rather than Node's `timeout` option so that a kill\n * this code ordered is distinguishable from any other death by signal.\n */\nexport const spawnCapture: UpdateSpawn = (cmd, args, opts, onOutput) =>\n new Promise((res) => {\n let child;\n try {\n child = spawn(cmd, args, {\n stdio: ['ignore', 'pipe', 'pipe'],\n cwd: opts.cwd,\n // Layered onto this process's environment rather than replacing it: the\n // child is a Node CLI that needs PATH and HOME, and only the keys named\n // here are being decided.\n ...(opts.env !== undefined ? { env: { ...process.env, ...opts.env } } : {}),\n });\n } catch (cause) {\n // An argv or option Node rejects outright throws here; ENOENT arrives on\n // the 'error' event instead. Both mean the same thing to the caller.\n res({ kind: 'start-failed', cause });\n return;\n }\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill('SIGKILL');\n }, opts.timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => onOutput(chunk.toString()));\n child.stderr?.on('data', (chunk: Buffer) => onOutput(chunk.toString()));\n child.on('error', (cause) => {\n clearTimeout(timer);\n res({ kind: 'start-failed', cause });\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n res(timedOut ? { kind: 'timeout' } : { kind: 'exit', code: code ?? 1 });\n });\n });\n","import { existsSync, realpathSync, statSync } from 'node:fs';\nimport { delimiter, dirname, join, sep } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * WHERE this build is installed, and what that implies about replacing it.\n *\n * Its own module because it answers a different question from the command that\n * uses it: \"what IS this install\" rather than \"how do I replace it\". The\n * refusal set is the load-bearing part, and it got re-cut in three consecutive\n * reviews while it was expressed positionally inside the command body.\n */\n\n/** Managers a global install can be handed back to. yarn is deliberately absent\n * from the delegable set: see the yarn entry in REFUSALS. */\nexport type Delegable = 'npm' | 'pnpm' | 'bun';\n\n/**\n * One reason `npm install -g` would not actually replace THIS build.\n *\n * Each entry carries the three properties that decide WHEN it is evaluated,\n * because expressing them by where the line sat is what made this set get\n * re-cut three times: a missing entry, then a copy on the wrong side of the\n * fetch, then a duplicate that could not run. Declaring them means adding a\n * refusal is a matter of answering three questions, not of guessing a position.\n */\ninterface Refusal {\n /** Does this install location refuse? Pure filesystem, never the network. */\n test: (moduleDir: string) => boolean;\n error: (spec: string, moduleDir: string) => CliError;\n /**\n * Does the fix string name the version the registry just resolved? This is\n * also what decides whether the entry may run BEFORE the fetch: one that does\n * not need a version is evaluated first, so an offline user in a checkout is\n * told they are in a checkout rather than told to go debug their network.\n */\n needsVersion: boolean;\n /**\n * Does it apply to `--check`? Everything here is a reason not to WRITE, and\n * `--check` only reports, so today nothing does. An entry that ever answers\n * yes is one whose test says the REPORT would be wrong, not the install.\n */\n appliesToCheck: boolean;\n}\n\n/**\n * Ordered most-specific first: a checkout and an npx cache are recognizable\n * before any question of which manager or which tree, and the manager entry\n * precedes the global/local one because a pnpm or bun store has its own layout\n * that `isGlobalTree` is not written for.\n */\nexport const REFUSALS: readonly Refusal[] = [\n {\n test: isSourceCheckout,\n error: () =>\n new CliError('REFUSED', 'tenjin-cli is running from a source checkout, not an install', {\n fix: 'Update the checkout instead: git pull && pnpm install',\n }),\n needsVersion: false,\n appliesToCheck: false,\n },\n {\n test: (moduleDir) => moduleDir.split(sep).includes('_npx'),\n error: (spec) =>\n new CliError('REFUSED', 'tenjin-cli is running from the npx cache, not an install', {\n // Writing a global here would \"succeed\" and change nothing: the next\n // `npx tenjin` still resolves its own cached copy.\n fix: `npx fetches its own copy every time. To keep one: npm i -g ${spec}`,\n }),\n needsVersion: true,\n appliesToCheck: false,\n },\n {\n // The ONLY manager still refused. `yarn global add` is yarn-1 only, and\n // berry dropped global installs altogether, so there is no one command this\n // can drive across the versions a user might have. Every other manager is\n // delegated to rather than refused (see MANAGERS).\n test: (moduleDir) => classifyManager(moduleDir) === 'yarn',\n error: (spec) =>\n new CliError(\n 'REFUSED',\n 'This tenjin-cli was installed with yarn, whose global install exists only in yarn 1',\n { fix: `yarn global add ${spec}` },\n ),\n needsVersion: true,\n appliesToCheck: false,\n },\n {\n // Scoped to npm on purpose: the prefix-vs-project-root test is written for\n // npm's layout. pnpm's global store and bun's global dir both keep a\n // package.json beside `node_modules`, so an unscoped test would read either\n // as a project-local install and refuse the very case we now delegate.\n test: (moduleDir) => classifyManager(moduleDir) === 'npm' && !isGlobalTree(moduleDir),\n error: (spec) =>\n new CliError(\n 'REFUSED',\n 'This tenjin-cli is a project-local dependency, not a global install',\n {\n fix: `Update it where it is declared: npm i ${spec}`,\n },\n ),\n needsVersion: true,\n appliesToCheck: false,\n },\n];\n\n/**\n * Evaluate the refusal set, once per stage. `spec` is null before the registry\n * has been asked and the resolved `tenjin-cli@<version>` after, which is what\n * selects the eligible entries: every entry runs in exactly one stage, so no\n * refusal can be reached twice or, as in round three, be written twice and\n * reached once.\n */\nexport function refuse(moduleDir: string, opts: { check: boolean; spec: string | null }): void {\n for (const entry of REFUSALS) {\n if (opts.check && !entry.appliesToCheck) continue;\n if (entry.needsVersion !== (opts.spec !== null)) continue;\n if (entry.test(moduleDir)) throw entry.error(opts.spec ?? '', moduleDir);\n }\n}\n\n/**\n * The published package ships `dist/`, `docs/`, and `skills/` with no `src/`\n * beside them (the `files` array), so a `src/` next to the nearest package.json\n * means a checkout, whose version number says nothing about what HEAD holds.\n * Same test skill-heal uses to keep its hands off working-tree skills.\n */\nexport function isSourceCheckout(moduleDir: string): boolean {\n let dir = moduleDir;\n for (let i = 0; i < 8; i += 1) {\n if (existsSync(join(dir, 'package.json'))) return existsSync(join(dir, 'src'));\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return false;\n}\n\n/**\n * Is this a GLOBAL npm tree? A global install sits under a prefix directory that\n * is not itself a package (`<prefix>/lib/node_modules/tenjin-cli` on POSIX,\n * `<prefix>\\node_modules\\tenjin-cli` on win32), while a project-local one sits\n * under the project root, which by definition has a package.json. That parent is\n * the whole test, which is why it holds for homebrew, nvm, volta and a\n * user-set `npm config prefix` alike without this code enumerating any of them.\n */\nexport function isGlobalTree(moduleDir: string): boolean {\n const segs = moduleDir.split(sep);\n const i = segs.lastIndexOf('node_modules');\n if (i <= 0) return false;\n return !existsSync(join(segs.slice(0, i).join(sep), 'package.json'));\n}\n\n/**\n * Which package manager owns this install, read off the on-disk path. Node\n * resolved the bin symlink before loading us, so the segments name the real\n * store: pnpm's virtual store keeps a literal `.pnpm` segment (or\n * `pnpm/global` for older layouts), bun installs under `.bun`, yarn under\n * `.yarn` or `yarn/global`. Everything else is treated as npm's tree; that\n * covers nvm and volta, both of which route `npm i -g` correctly.\n */\nexport function classifyManager(moduleDir: string): Delegable | 'yarn' {\n const segs = moduleDir.split(sep);\n const pair = (a: string, b: string): boolean => segs.includes(a) && segs.includes(b);\n if (segs.includes('.pnpm') || pair('pnpm', 'global')) return 'pnpm';\n if (segs.includes('.bun')) return 'bun';\n if (segs.includes('.yarn') || pair('yarn', 'global')) return 'yarn';\n return 'npm';\n}\n\n/**\n * How to perform a global install with each manager we delegate to.\n *\n * `scriptSuffixes` is what a PATH shim may resolve to that Node can run\n * directly, which is how win32 is served without a shell: npm and pnpm ship as\n * JS, so the child becomes `node <script>`. An empty list means the binary is\n * native (bun), where spawning it by name already works on every platform.\n */\nexport const MANAGERS: Record<\n Delegable,\n {\n bin: string;\n scriptSuffixes: readonly string[];\n /** Ships beside the running node, as npm does inside the Node distribution. */\n besideNode: boolean;\n args: (spec: string) => string[];\n manual: (spec: string) => string;\n }\n> = {\n npm: {\n bin: 'npm',\n scriptSuffixes: ['npm-cli.js'],\n besideNode: true,\n args: (spec) => ['install', '-g', '--ignore-scripts', spec],\n manual: (spec) => `npm i -g ${spec}`,\n },\n pnpm: {\n bin: 'pnpm',\n // corepack's shim resolves to `pnpm.js`, a standalone install to `pnpm.cjs`.\n scriptSuffixes: ['.cjs', '.js'],\n besideNode: false,\n args: (spec) => ['add', '-g', '--ignore-scripts', spec],\n manual: (spec) => `pnpm add -g ${spec}`,\n },\n bun: {\n bin: 'bun',\n scriptSuffixes: [],\n besideNode: false,\n // No --ignore-scripts: bun's flag surface for it is not stable across the\n // versions in the wild, and an unknown flag would fail the install outright.\n args: (spec) => ['add', '-g', spec],\n manual: (spec) => `bun add -g ${spec}`,\n },\n};\n\n/**\n * npm's own entry script, so the child can be `node npm-cli.js` rather than the\n * `npm` shim.\n *\n * On win32 the shim is `npm.cmd`, which Node refuses to spawn without\n * `shell: true`, and `shell: true` is exactly what this command must not do —\n * it would hand back the argv safety the pinned version buys.\n *\n * Deliberately NOT \"npm ships inside the Node distribution\". That is a property\n * of the installer, not of Node: Homebrew's plain `node` formula keeps only\n * corepack in the keg and puts npm at the brew prefix, so a probe relative to\n * `process.execPath` alone returns null on one of the most common macOS setups.\n * So the layout is searched, not assumed — beside the running binary first\n * (official tarball and installer, nvm, volta, versioned brew kegs), then off\n * PATH, where on POSIX the `npm` shim is itself a symlink to `npm-cli.js` and on\n * win32 `npm.cmd` has `node_modules` beside it. Still null when npm cannot be\n * found at all; the caller then falls back to the bare shim, which works\n * everywhere but win32 and fails closed there into UPDATE_FAILED carrying the\n * manual command.\n */\nexport function resolveNpmCli(\n execPath: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n return resolveManagerScript('npm', execPath, env);\n}\n\n/**\n * The JS entry script for `manager`, or null when it has none to find (a native\n * binary, or a shim this cannot see through). Null means \"spawn the bare name\",\n * which works everywhere but win32 and fails closed there.\n */\nexport function resolveManagerScript(\n manager: Delegable,\n execPath: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n const plan = MANAGERS[manager];\n if (plan.scriptSuffixes.length === 0) return null;\n const beside = plan.besideNode ? scriptNear(dirname(execPath), plan.bin) : null;\n return beside ?? scriptOnPath(plan.bin, plan.scriptSuffixes, env);\n}\n\n/** A manager's script relative to a directory holding `node` or its own shim. */\nfunction scriptNear(dir: string, bin: string): string | null {\n const candidates = [\n join(dir, 'node_modules', bin, 'bin', `${bin}-cli.js`),\n join(dir, '..', 'lib', 'node_modules', bin, 'bin', `${bin}-cli.js`),\n ];\n return candidates.find(isFile) ?? null;\n}\n\n/**\n * Walk PATH for the manager's shim and turn it into its script. Probes the\n * PATHEXT extensions on win32 for the same reason `onPath` in skill-wiring.ts\n * does: the real file there is `npm.cmd`, never a bare `npm`.\n */\nfunction scriptOnPath(\n bin: string,\n suffixes: readonly string[],\n env: NodeJS.ProcessEnv,\n): string | null {\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of (env.PATH ?? '').split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (!isFile(join(part, `${bin}${ext}`))) continue;\n // POSIX package managers link the shim straight at the script, which is\n // what makes this layout-independent rather than a longer guess list.\n //\n // The endsWith is a CORRECTNESS check, not a security guard: it asks \"did\n // this symlink land on npm's script or on something else\", and a shim\n // pointed elsewhere returns null, which falls back to spawning that same\n // retargeted shim anyway. PATH poisoning is out of scope by construction —\n // an attacker ahead of npm on PATH owns every tool the user runs, and the\n // pre-existing fallback `spawn('npm', ...)` resolved through the same PATH.\n const real = realpathOrNull(join(part, `${bin}${ext}`));\n if (real !== null && suffixes.some((suffix) => real.endsWith(suffix))) return real;\n const near = scriptNear(part, bin);\n if (near !== null) return near;\n }\n }\n return null;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\nfunction realpathOrNull(p: string): string | null {\n try {\n return realpathSync(p);\n } catch {\n return null;\n }\n}\n","import { execFile } from 'node:child_process';\nimport { stat } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { promisify } from 'node:util';\nimport pkg from '../../package.json';\nimport type { RouterCheck } from './reachability';\n\n/**\n * A `tenjin mcp` STARTED BEFORE THIS INSTALL still runs the code it started\n * with. Claude Code keeps its MCP servers for the life of a session, so after\n * an update the hooks the new install wrote can call a tool the old process\n * does not have (\"Tool hook not found\"), while every file on disk reads as\n * correct. This finds this user's running `tenjin mcp` processes and compares\n * each start time with the installed package's own `package.json`.\n */\n\nexport interface McpProcess {\n pid: number;\n /** Start time in epoch ms, or null when `ps` gave none this could read. */\n startedAt: number | null;\n}\n\n/** This user's running `tenjin mcp` processes, or null where they cannot be listed. */\nexport type ListMcpProcesses = () => Promise<McpProcess[] | null>;\n\n/** When the installed package was written, in epoch ms, or null. */\nexport type InstalledAt = () => Promise<number | null>;\n\nconst exec = promisify(execFile);\n\n/** `ps` on macOS and Linux; null on Windows or when `ps` fails, which is \"unknown\". */\nexport const listMcpProcesses: ListMcpProcesses = async () => {\n if (process.platform === 'win32' || typeof process.getuid !== 'function') return null;\n try {\n const { stdout } = await exec(\n 'ps',\n ['-U', String(process.getuid()), '-o', 'pid=,lstart=,args='],\n { timeout: 5_000, env: { ...process.env, LC_ALL: 'C' }, maxBuffer: 4 * 1024 * 1024 },\n );\n return parsePs(stdout, process.pid);\n } catch {\n return null;\n }\n};\n\nconst 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+(.*)$/;\n\n/** The `tenjin mcp` lines of `ps -o pid=,lstart=,args=`, this process left out. */\nexport function parsePs(stdout: string, selfPid: number): McpProcess[] {\n const found: McpProcess[] = [];\n for (const line of stdout.split('\\n')) {\n const m = PS_LINE.exec(line);\n if (m === null) continue;\n const pid = Number(m[1]);\n if (pid === selfPid || !isTenjinMcp(m[3]!)) continue;\n const startedAt = Date.parse(m[2]!.replace(/\\s+/g, ' '));\n found.push({ pid, startedAt: Number.isNaN(startedAt) ? null : startedAt });\n }\n return found;\n}\n\n/** `tenjin mcp`, however the bin was invoked: `node /path/bin/tenjin mcp`, `tenjin mcp`. */\nfunction isTenjinMcp(args: string): boolean {\n const tokens = args.trim().split(/\\s+/);\n const bin = tokens.findIndex(\n (t) => /(^|[/\\\\])tenjin(\\.js|\\.cmd)?$/.test(t) || /[/\\\\]tenjin-cli[/\\\\]/.test(t),\n );\n return bin >= 0 && tokens[bin + 1] === 'mcp';\n}\n\n/**\n * When this build's `package.json`, the nearest one above this module, was\n * written. Its ctime, not its mtime: npm extracts a package with the\n * tarball's fixed 1985 mtimes, and setting them is what moves the ctime to\n * the moment of the install.\n */\nexport const installedAt: InstalledAt = async () => {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 6; i += 1) {\n try {\n const st = await stat(join(dir, 'package.json'));\n return Math.max(st.ctimeMs, st.mtimeMs);\n } catch {\n dir = dirname(dir);\n }\n }\n return null;\n};\n\n/** How many running servers predate the install, and what doctor says about it. */\nexport interface McpServersState {\n stale: number;\n check: RouterCheck;\n}\n\n/** Worded for the session the person is in: a slash command there, never a terminal. */\nexport const RECONNECT_FIX =\n 'Type /reload-plugins in this Claude Code session, or start a new session.';\n/**\n * WHILE A SETTINGS INSTALL IS STILL HERE, only a new session. `/reload-plugins`\n * reconnects plugin servers alone, so the plugin would load beside a\n * pre-upgrade `x402` server that does not know to stay silent, and every\n * event would route twice for the rest of that session.\n */\nexport const NEW_SESSION_FIX =\n 'Start a new Claude Code session: the earlier Tenjin setup is still in this one, and /reload-plugins would run both.';\n\n/** The `mcp server` check from a process list and the install time. Never a failure. */\nexport function mcpServersState(\n procs: McpProcess[] | null,\n installed: number | null,\n version: string = pkg.version,\n fix: string = RECONNECT_FIX,\n): McpServersState {\n const check = (detail: string): McpServersState => ({\n stale: 0,\n check: { name: 'mcp server', status: 'ok', required: false, detail },\n });\n if (procs === null) {\n return check('unknown: running `tenjin mcp` processes cannot be listed on this platform');\n }\n if (procs.length === 0) return check('none running (starts with the next session)');\n if (installed === null) {\n return check(`${procs.length} running; when this build was installed is unknown`);\n }\n const stale = procs.filter((p) => p.startedAt !== null && p.startedAt < installed).length;\n if (stale === 0) {\n return check(`${procs.length} running, all started after this install`);\n }\n const which = stale === 1 ? 'process' : 'processes';\n return {\n stale,\n check: {\n name: 'mcp server',\n status: 'warn',\n required: false,\n 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\"`,\n fix,\n },\n };\n}\n\n/** The check, read from this machine (or the injected sources). */\nexport async function readMcpServers(\n deps: { listMcpProcesses?: ListMcpProcesses; installedAt?: InstalledAt } = {},\n opts: { settingsInstallPending?: boolean } = {},\n): Promise<McpServersState> {\n const [procs, installed] = await Promise.all([\n (deps.listMcpProcesses ?? listMcpProcesses)().catch(() => null),\n (deps.installedAt ?? installedAt)().catch(() => null),\n ]);\n const fix = opts.settingsInstallPending === true ? NEW_SESSION_FIX : RECONNECT_FIX;\n return mcpServersState(procs, installed, pkg.version, fix);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,cAAAA,aAAY,YAAAC,iBAAgB;AACrC,SAAS,eAAe;AACxB,SAAS,SAAS,OAAAC,YAAW;AAC7B,SAAS,iBAAAC,sBAAqB;;;ACJ9B,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,WAAW,SAAS,MAAM,WAAW;AAkDvC,IAAM,WAA+B;AAAA,EAC1C;AAAA,IACE,MAAM;AAAA,IACN,OAAO,MACL,IAAI,SAAS,WAAW,gEAAgE;AAAA,MACtF,KAAK;AAAA,IACP,CAAC;AAAA,IACH,cAAc;AAAA,IACd,gBAAgB;AAAA,EAClB;AAAA,EACA;AAAA,IACE,MAAM,CAAC,cAAc,UAAU,MAAM,GAAG,EAAE,SAAS,MAAM;AAAA,IACzD,OAAO,CAAC,SACN,IAAI,SAAS,WAAW,4DAA4D;AAAA;AAAA;AAAA,MAGlF,KAAK,8DAA8D,IAAI;AAAA,IACzE,CAAC;AAAA,IACH,cAAc;AAAA,IACd,gBAAgB;AAAA,EAClB;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKE,MAAM,CAAC,cAAc,gBAAgB,SAAS,MAAM;AAAA,IACpD,OAAO,CAAC,SACN,IAAI;AAAA,MACF;AAAA,MACA;AAAA,MACA,EAAE,KAAK,mBAAmB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3E,CAAC;AAAA,EACH,SAAS,OAAO;AAGd,QAAI,EAAE,MAAM,gBAAgB,MAAM,CAAC;AACnC;AAAA,EACF;AACA,MAAI,WAAW;AACf,QAAM,QAAQ,WAAW,MAAM;AAC7B,eAAW;AACX,UAAM,KAAK,SAAS;AAAA,EACtB,GAAG,KAAK,SAAS;AACjB,QAAM,QAAQ,GAAG,QAAQ,CAAC,UAAkB,SAAS,MAAM,SAAS,CAAC,CAAC;AACtE,QAAM,QAAQ,GAAG,QAAQ,CAAC,UAAkB,SAAS,MAAM,SAAS,CAAC,CAAC;AACtE,QAAM,GAAG,SAAS,CAAC,UAAU;AAC3B,iBAAa,KAAK;AAClB,QAAI,EAAE,MAAM,gBAAgB,MAAM,CAAC;AAAA,EACrC,CAAC;AACD,QAAM,GAAG,SAAS,CAAC,SAAS;AAC1B,iBAAa,KAAK;AAClB,QAAI,WAAW,EAAE,MAAM,UAAU,IAAI,EAAE,MAAM,QAAQ,MAAM,QAAQ,EAAE,CAAC;AAAA,EACxE,CAAC;AACH,CAAC;","names":["existsSync","statSync","sep","fileURLToPath","dirname","join","dirname","join","fileURLToPath","statSync","sep","existsSync"]}
|
|
@@ -48,8 +48,23 @@ function evaluateSpendPolicy(policy, req) {
|
|
|
48
48
|
}
|
|
49
49
|
return { decision: "allow", reason: "within_policy", message: "within spend policy" };
|
|
50
50
|
}
|
|
51
|
+
function policyCoversSet(policy, steps, sessionSpentAtomic) {
|
|
52
|
+
let spent = sessionSpentAtomic;
|
|
53
|
+
for (const step of steps) {
|
|
54
|
+
const evaluation = evaluateSpendPolicy(policy, {
|
|
55
|
+
mode: "automatic",
|
|
56
|
+
amountAtomic: step.amountAtomic,
|
|
57
|
+
creator: step.creator,
|
|
58
|
+
sessionSpentAtomic: spent
|
|
59
|
+
});
|
|
60
|
+
if (evaluation.decision !== "allow") return evaluation;
|
|
61
|
+
spent += step.amountAtomic;
|
|
62
|
+
}
|
|
63
|
+
return { decision: "allow", reason: "within_policy", message: "within spend policy" };
|
|
64
|
+
}
|
|
51
65
|
|
|
52
66
|
export {
|
|
53
|
-
evaluateSpendPolicy
|
|
67
|
+
evaluateSpendPolicy,
|
|
68
|
+
policyCoversSet
|
|
54
69
|
};
|
|
55
|
-
//# sourceMappingURL=chunk-
|
|
70
|
+
//# sourceMappingURL=chunk-B2L53TMK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/policy.ts"],"sourcesContent":["/**\n * Spend-policy evaluation, pure and provider-agnostic. The wallet provider layer\n * (lib/wallet/spend.ts) owns the ledger and calls this; a future hosted provider\n * (Privy, B5) reuses the same decision rules, so the knobs live in exactly one\n * place. Nothing here does IO, the caller supplies the already-spent total and\n * decides how to satisfy a `confirm` decision (a `--yes`, a TTY prompt, or a\n * non-interactive refusal).\n */\n\nexport type PaymentMode = 'automatic' | 'manual';\n\nexport interface SpendPolicy {\n /** Automatic per-call ceiling; zero blocks positive automatic payments. */\n maxAutoSpendAtomic: bigint;\n /** Rolling ceiling on automatic exposure. null = no ceiling; zero blocks positive automatic payments. */\n sessionBudgetAtomic: bigint | null;\n /** Creators (handle or 0x-address, lowercased) all payments are restricted to.\n * Empty = no restriction. A non-empty list is a hard gate: a non-member is\n * denied even with `--yes`. */\n allowlistCreators: string[];\n}\n\nexport interface SpendRequest {\n /** Omitted by legacy consumers: conservatively automatic. */\n mode?: PaymentMode;\n amountAtomic: bigint;\n /** Creator identity from the 402 preview / candidate, handle or 0x address. */\n creator: string;\n /** The caller's `--max-price` cap, if given. A hard ceiling, never bypassable. */\n maxPriceAtomic?: bigint;\n /** Cumulative spend already recorded in this rolling session window. */\n sessionSpentAtomic: bigint;\n}\n\n/**\n * `allow`: within policy, proceed silently. `confirm`: an approval is required ,\n * the caller satisfies it with `--yes`, an interactive prompt, or refuses. `deny`:\n * a hard gate blocked it (price cap, allowlist, session budget); NOT satisfiable\n * by `--yes` or a prompt.\n */\nexport type SpendDecision = 'allow' | 'confirm' | 'deny';\n\n/**\n * `duplicate_in_flight` is the one reason this pure evaluator never returns: it\n * is a fact about the ledger (an identical request already holds a reservation\n * in this turn), so the authorizer raises it. It lives in the union because\n * every caller renders a decision's reason from one vocabulary.\n */\nexport type PolicyReason =\n | 'within_policy'\n | 'duplicate_in_flight'\n | 'price_cap_exceeded'\n | 'not_allowlisted'\n | 'session_budget_exceeded'\n | 'above_auto_spend'\n | 'confirm_always';\n\nexport interface PolicyEvaluation {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n}\n\n/** Normalize a creator identity for allowlist comparison (case-insensitive; a\n * word-handle and a 0x address are both single tokens). */\nfunction normCreator(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/** Hard price/creator checks apply in both modes. Manual payments require consent;\n * automatic payments must fit both configured ceilings without prompting. */\nexport function evaluateSpendPolicy(policy: SpendPolicy, req: SpendRequest): PolicyEvaluation {\n if (req.maxPriceAtomic !== undefined && req.amountAtomic > req.maxPriceAtomic) {\n return {\n decision: 'deny',\n reason: 'price_cap_exceeded',\n message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`,\n };\n }\n\n if (policy.allowlistCreators.length > 0) {\n const allowed = policy.allowlistCreators.map(normCreator);\n if (!allowed.includes(normCreator(req.creator))) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${req.creator}\" is not in allowlistCreators.`,\n };\n }\n }\n\n if (req.mode === 'manual') {\n return req.amountAtomic > 0n\n ? {\n decision: 'confirm',\n reason: 'confirm_always',\n message: 'Manual payment requires explicit consent.',\n }\n : { decision: 'allow', reason: 'within_policy', message: 'No payment required.' };\n }\n\n if (policy.sessionBudgetAtomic !== null) {\n const projected = req.sessionSpentAtomic + req.amountAtomic;\n if (projected > policy.sessionBudgetAtomic) {\n return {\n decision: 'deny',\n reason: 'session_budget_exceeded',\n message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`,\n };\n }\n }\n\n if (req.amountAtomic > policy.maxAutoSpendAtomic) {\n return {\n decision: 'deny',\n reason: 'above_auto_spend',\n message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; automatic payment refused.`,\n };\n }\n\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n"],"mappings":";;;AAiEA,SAAS,YAAY,OAAuB;AAC1C,SAAO,MAAM,KAAK,EAAE,YAAY;AAClC;AAIO,SAAS,oBAAoB,QAAqB,KAAqC;AAC5F,MAAI,IAAI,mBAAmB,UAAa,IAAI,eAAe,IAAI,gBAAgB;AAC7E,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,gCAAgC,IAAI,cAAc;AAAA,IACtF;AAAA,EACF;AAEA,MAAI,OAAO,kBAAkB,SAAS,GAAG;AACvC,UAAM,UAAU,OAAO,kBAAkB,IAAI,WAAW;AACxD,QAAI,CAAC,QAAQ,SAAS,YAAY,IAAI,OAAO,CAAC,GAAG;AAC/C,aAAO;AAAA,QACL,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,SAAS,YAAY,IAAI,OAAO;AAAA,MAClC;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,SAAS,UAAU;AACzB,WAAO,IAAI,eAAe,KACtB;AAAA,MACE,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS;AAAA,IACX,IACA,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,uBAAuB;AAAA,EACpF;AAEA,MAAI,OAAO,wBAAwB,MAAM;AACvC,UAAM,YAAY,IAAI,qBAAqB,IAAI;AAC/C,QAAI,YAAY,OAAO,qBAAqB;AAC1C,aAAO;AAAA,QACL,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,SAAS,+CAA+C,SAAS,wBAAwB,OAAO,mBAAmB;AAAA,MACrH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,oBAAoB;AAChD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,0BAA0B,OAAO,kBAAkB;AAAA,IACvF;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,sBAAsB;AACtF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/lib/policy.ts"],"sourcesContent":["/**\n * Spend-policy evaluation, pure and provider-agnostic. The wallet provider layer\n * (lib/wallet/spend.ts) owns the ledger and calls this; a future hosted provider\n * (Privy, B5) reuses the same decision rules, so the knobs live in exactly one\n * place. Nothing here does IO, the caller supplies the already-spent total and\n * decides how to satisfy a `confirm` decision (a `--yes`, a TTY prompt, or a\n * non-interactive refusal).\n */\n\nexport type PaymentMode = 'automatic' | 'manual';\n\nexport interface SpendPolicy {\n /** Automatic per-call ceiling; zero blocks positive automatic payments. */\n maxAutoSpendAtomic: bigint;\n /** Rolling ceiling on automatic exposure. null = no ceiling; zero blocks positive automatic payments. */\n sessionBudgetAtomic: bigint | null;\n /** Creators (handle or 0x-address, lowercased) all payments are restricted to.\n * Empty = no restriction. A non-empty list is a hard gate: a non-member is\n * denied even with `--yes`. */\n allowlistCreators: string[];\n}\n\nexport interface SpendRequest {\n /** Omitted by legacy consumers: conservatively automatic. */\n mode?: PaymentMode;\n amountAtomic: bigint;\n /** Creator identity from the 402 preview / candidate, handle or 0x address. */\n creator: string;\n /** The caller's `--max-price` cap, if given. A hard ceiling, never bypassable. */\n maxPriceAtomic?: bigint;\n /** Cumulative spend already recorded in this rolling session window. */\n sessionSpentAtomic: bigint;\n}\n\n/**\n * `allow`: within policy, proceed silently. `confirm`: an approval is required ,\n * the caller satisfies it with `--yes`, an interactive prompt, or refuses. `deny`:\n * a hard gate blocked it (price cap, allowlist, session budget); NOT satisfiable\n * by `--yes` or a prompt.\n */\nexport type SpendDecision = 'allow' | 'confirm' | 'deny';\n\n/**\n * `duplicate_in_flight` is the one reason this pure evaluator never returns: it\n * is a fact about the ledger (an identical request already holds a reservation\n * in this turn), so the authorizer raises it. It lives in the union because\n * every caller renders a decision's reason from one vocabulary.\n */\nexport type PolicyReason =\n | 'within_policy'\n | 'duplicate_in_flight'\n | 'price_cap_exceeded'\n | 'not_allowlisted'\n | 'session_budget_exceeded'\n | 'above_auto_spend'\n | 'confirm_always';\n\nexport interface PolicyEvaluation {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n}\n\n/** Normalize a creator identity for allowlist comparison (case-insensitive; a\n * word-handle and a 0x address are both single tokens). */\nfunction normCreator(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/** Hard price/creator checks apply in both modes. Manual payments require consent;\n * automatic payments must fit both configured ceilings without prompting. */\nexport function evaluateSpendPolicy(policy: SpendPolicy, req: SpendRequest): PolicyEvaluation {\n if (req.maxPriceAtomic !== undefined && req.amountAtomic > req.maxPriceAtomic) {\n return {\n decision: 'deny',\n reason: 'price_cap_exceeded',\n message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`,\n };\n }\n\n if (policy.allowlistCreators.length > 0) {\n const allowed = policy.allowlistCreators.map(normCreator);\n if (!allowed.includes(normCreator(req.creator))) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${req.creator}\" is not in allowlistCreators.`,\n };\n }\n }\n\n if (req.mode === 'manual') {\n return req.amountAtomic > 0n\n ? {\n decision: 'confirm',\n reason: 'confirm_always',\n message: 'Manual payment requires explicit consent.',\n }\n : { decision: 'allow', reason: 'within_policy', message: 'No payment required.' };\n }\n\n if (policy.sessionBudgetAtomic !== null) {\n const projected = req.sessionSpentAtomic + req.amountAtomic;\n if (projected > policy.sessionBudgetAtomic) {\n return {\n decision: 'deny',\n reason: 'session_budget_exceeded',\n message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`,\n };\n }\n }\n\n if (req.amountAtomic > policy.maxAutoSpendAtomic) {\n return {\n decision: 'deny',\n reason: 'above_auto_spend',\n message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; automatic payment refused.`,\n };\n }\n\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n\n/**\n * WHETHER A SET OF AUTOMATIC PAYMENTS FITS, all of them, before any is signed.\n * Each one meets {@link evaluateSpendPolicy} exactly as it would alone, with\n * the ones before it already counted against the session: so every step is\n * held to the per-call cap on its own and the set's total to the budget. The\n * first refusal is the answer; each payment still meets the gate when it is\n * signed.\n */\nexport function policyCoversSet(\n policy: SpendPolicy,\n steps: readonly { amountAtomic: bigint; creator: string }[],\n sessionSpentAtomic: bigint,\n): PolicyEvaluation {\n let spent = sessionSpentAtomic;\n for (const step of steps) {\n const evaluation = evaluateSpendPolicy(policy, {\n mode: 'automatic',\n amountAtomic: step.amountAtomic,\n creator: step.creator,\n sessionSpentAtomic: spent,\n });\n if (evaluation.decision !== 'allow') return evaluation;\n spent += step.amountAtomic;\n }\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n"],"mappings":";;;AAiEA,SAAS,YAAY,OAAuB;AAC1C,SAAO,MAAM,KAAK,EAAE,YAAY;AAClC;AAIO,SAAS,oBAAoB,QAAqB,KAAqC;AAC5F,MAAI,IAAI,mBAAmB,UAAa,IAAI,eAAe,IAAI,gBAAgB;AAC7E,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,gCAAgC,IAAI,cAAc;AAAA,IACtF;AAAA,EACF;AAEA,MAAI,OAAO,kBAAkB,SAAS,GAAG;AACvC,UAAM,UAAU,OAAO,kBAAkB,IAAI,WAAW;AACxD,QAAI,CAAC,QAAQ,SAAS,YAAY,IAAI,OAAO,CAAC,GAAG;AAC/C,aAAO;AAAA,QACL,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,SAAS,YAAY,IAAI,OAAO;AAAA,MAClC;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,SAAS,UAAU;AACzB,WAAO,IAAI,eAAe,KACtB;AAAA,MACE,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS;AAAA,IACX,IACA,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,uBAAuB;AAAA,EACpF;AAEA,MAAI,OAAO,wBAAwB,MAAM;AACvC,UAAM,YAAY,IAAI,qBAAqB,IAAI;AAC/C,QAAI,YAAY,OAAO,qBAAqB;AAC1C,aAAO;AAAA,QACL,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,SAAS,+CAA+C,SAAS,wBAAwB,OAAO,mBAAmB;AAAA,MACrH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,oBAAoB;AAChD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,0BAA0B,OAAO,kBAAkB;AAAA,IACvF;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,sBAAsB;AACtF;AAUO,SAAS,gBACd,QACA,OACA,oBACkB;AAClB,MAAI,QAAQ;AACZ,aAAW,QAAQ,OAAO;AACxB,UAAM,aAAa,oBAAoB,QAAQ;AAAA,MAC7C,MAAM;AAAA,MACN,cAAc,KAAK;AAAA,MACnB,SAAS,KAAK;AAAA,MACd,oBAAoB;AAAA,IACtB,CAAC;AACD,QAAI,WAAW,aAAa,QAAS,QAAO;AAC5C,aAAS,KAAK;AAAA,EAChB;AACA,SAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,sBAAsB;AACtF;","names":[]}
|
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
} from "./chunk-EGELTSPU.js";
|
|
28
28
|
import {
|
|
29
29
|
USDC_ADDRESS
|
|
30
|
-
} from "./chunk-
|
|
30
|
+
} from "./chunk-QTND6XWJ.js";
|
|
31
31
|
|
|
32
32
|
// node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/op-stack/contracts.js
|
|
33
33
|
var contracts = {
|
|
@@ -318,4 +318,4 @@ export {
|
|
|
318
318
|
prepareUsdcSend,
|
|
319
319
|
broadcastUsdcSend
|
|
320
320
|
};
|
|
321
|
-
//# sourceMappingURL=chunk-
|
|
321
|
+
//# sourceMappingURL=chunk-BRHREK7E.js.map
|