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
package/dist/chunk-GHR4BTNJ.js
DELETED
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
|
|
3
|
-
// package.json
|
|
4
|
-
var package_default = {
|
|
5
|
-
name: "tenjin-cli",
|
|
6
|
-
version: "0.1.0-alpha.26",
|
|
7
|
-
type: "module",
|
|
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
|
-
repository: {
|
|
10
|
-
type: "git",
|
|
11
|
-
url: "git+https://github.com/BackTrackCo/tenjin-agent.git"
|
|
12
|
-
},
|
|
13
|
-
homepage: "https://tenjin.sh/agents",
|
|
14
|
-
bugs: "https://github.com/BackTrackCo/tenjin-agent/issues",
|
|
15
|
-
keywords: [
|
|
16
|
-
"claude-code",
|
|
17
|
-
"coding-agents",
|
|
18
|
-
"tool-router",
|
|
19
|
-
"ai-agents",
|
|
20
|
-
"agent-tools",
|
|
21
|
-
"mcp",
|
|
22
|
-
"x402",
|
|
23
|
-
"usdc",
|
|
24
|
-
"base",
|
|
25
|
-
"micropayments",
|
|
26
|
-
"agent-payments",
|
|
27
|
-
"claude",
|
|
28
|
-
"codex",
|
|
29
|
-
"cli"
|
|
30
|
-
],
|
|
31
|
-
bin: {
|
|
32
|
-
tenjin: "dist/index.js"
|
|
33
|
-
},
|
|
34
|
-
engines: {
|
|
35
|
-
node: ">=24"
|
|
36
|
-
},
|
|
37
|
-
files: [
|
|
38
|
-
"dist",
|
|
39
|
-
"docs",
|
|
40
|
-
"NOTICE.md"
|
|
41
|
-
],
|
|
42
|
-
packageManager: "pnpm@11.11.0",
|
|
43
|
-
scripts: {
|
|
44
|
-
build: "rm -rf dist && tsup",
|
|
45
|
-
test: "vitest run",
|
|
46
|
-
typecheck: "tsc --noEmit",
|
|
47
|
-
lint: "eslint .",
|
|
48
|
-
format: "prettier --write .",
|
|
49
|
-
"format:check": "prettier --check .",
|
|
50
|
-
check: "pnpm run build && pnpm run test",
|
|
51
|
-
"sync:skill": "node scripts/sync-skill.mjs",
|
|
52
|
-
"pack-smoke": "bash scripts/pack-smoke.sh",
|
|
53
|
-
changeset: "changeset",
|
|
54
|
-
prepublishOnly: "pnpm run build",
|
|
55
|
-
githooks: "git config core.hooksPath .githooks"
|
|
56
|
-
},
|
|
57
|
-
devDependencies: {
|
|
58
|
-
"@changesets/cli": "^3.0.3",
|
|
59
|
-
"@clack/prompts": "^1.7.0",
|
|
60
|
-
"@eslint/js": "^10",
|
|
61
|
-
"@modelcontextprotocol/sdk": "1.31.0",
|
|
62
|
-
"@types/node": "^25",
|
|
63
|
-
"@x402/core": "2.28.0",
|
|
64
|
-
"@x402/evm": "2.28.0",
|
|
65
|
-
"@x402/extensions": "2.28.0",
|
|
66
|
-
"@x402/fetch": "2.28.0",
|
|
67
|
-
ajv: "^8.20.0",
|
|
68
|
-
"ajv-formats": "^3.0.1",
|
|
69
|
-
commander: "^14.0.1",
|
|
70
|
-
eslint: "^10",
|
|
71
|
-
"eslint-config-prettier": "^10",
|
|
72
|
-
"lean-qr": "^2.7.4",
|
|
73
|
-
ox: "0.14.30",
|
|
74
|
-
prettier: "^3",
|
|
75
|
-
tsup: "^8.5.0",
|
|
76
|
-
typescript: "^6",
|
|
77
|
-
"typescript-eslint": "^8",
|
|
78
|
-
viem: "^2.53.1",
|
|
79
|
-
vitest: "^4.1.9",
|
|
80
|
-
zod: "^4.4.3"
|
|
81
|
-
}
|
|
82
|
-
};
|
|
83
|
-
|
|
84
|
-
export {
|
|
85
|
-
package_default
|
|
86
|
-
};
|
|
87
|
-
//# sourceMappingURL=chunk-GHR4BTNJ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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,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.js
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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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OAAO,SAAS;AACzC;","names":[]}
|
package/dist/chunk-JLEF5WHM.js
DELETED
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
|
|
3
|
-
// src/lib/atomic-json.ts
|
|
4
|
-
import { chmod, link, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
|
|
5
|
-
import { randomBytes } from "node:crypto";
|
|
6
|
-
import { basename, dirname, join } from "node:path";
|
|
7
|
-
var isWindows = process.platform === "win32";
|
|
8
|
-
async function writeFileAtomic(targetPath, data, opts = {}) {
|
|
9
|
-
const dir = dirname(targetPath);
|
|
10
|
-
const fileMode = opts.mode ?? 420;
|
|
11
|
-
const dirMode = opts.dirMode ?? 493;
|
|
12
|
-
await mkdir(dir, { recursive: true, ...isWindows ? {} : { mode: dirMode } });
|
|
13
|
-
const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString("hex")}.tmp`);
|
|
14
|
-
try {
|
|
15
|
-
await writeFile(tmpPath, data, isWindows ? void 0 : { mode: fileMode });
|
|
16
|
-
if (!isWindows) await chmod(tmpPath, fileMode);
|
|
17
|
-
await rename(tmpPath, targetPath);
|
|
18
|
-
} catch (err) {
|
|
19
|
-
await rm(tmpPath, { force: true }).catch(() => void 0);
|
|
20
|
-
throw err;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
async function writeFileAtomicExclusive(targetPath, data, opts = {}) {
|
|
24
|
-
const dir = dirname(targetPath);
|
|
25
|
-
const fileMode = opts.mode ?? 420;
|
|
26
|
-
const dirMode = opts.dirMode ?? 493;
|
|
27
|
-
await mkdir(dir, { recursive: true, ...isWindows ? {} : { mode: dirMode } });
|
|
28
|
-
if (isWindows) {
|
|
29
|
-
const handle = await open(targetPath, "wx");
|
|
30
|
-
try {
|
|
31
|
-
await handle.writeFile(data);
|
|
32
|
-
await handle.sync();
|
|
33
|
-
} finally {
|
|
34
|
-
await handle.close();
|
|
35
|
-
}
|
|
36
|
-
return;
|
|
37
|
-
}
|
|
38
|
-
const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString("hex")}.tmp`);
|
|
39
|
-
try {
|
|
40
|
-
const handle = await open(tmpPath, "wx", fileMode);
|
|
41
|
-
try {
|
|
42
|
-
await handle.writeFile(data);
|
|
43
|
-
await handle.chmod(fileMode);
|
|
44
|
-
await handle.sync();
|
|
45
|
-
} finally {
|
|
46
|
-
await handle.close();
|
|
47
|
-
}
|
|
48
|
-
await link(tmpPath, targetPath);
|
|
49
|
-
await fsyncDir(dir);
|
|
50
|
-
} finally {
|
|
51
|
-
await rm(tmpPath, { force: true }).catch(() => void 0);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
async function fsyncDir(dir) {
|
|
55
|
-
const handle = await open(dir, "r");
|
|
56
|
-
try {
|
|
57
|
-
await handle.sync();
|
|
58
|
-
} finally {
|
|
59
|
-
await handle.close();
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// src/lib/errors.ts
|
|
64
|
-
var EXIT_BY_CODE = {
|
|
65
|
-
NODE_UNSUPPORTED: 1,
|
|
66
|
-
USAGE: 2,
|
|
67
|
-
CONFIG_INVALID: 2,
|
|
68
|
-
WALLET_EXISTS: 3,
|
|
69
|
-
WALLET_MISSING: 1,
|
|
70
|
-
WALLET_INVALID_KEY: 1,
|
|
71
|
-
PROVIDER_ERROR: 1,
|
|
72
|
-
RPC_ERROR: 1,
|
|
73
|
-
API_UNREACHABLE: 1,
|
|
74
|
-
CONTRACT_MISMATCH: 1,
|
|
75
|
-
REFUSED: 3,
|
|
76
|
-
NETWORK_ERROR: 1,
|
|
77
|
-
INTERNAL: 1,
|
|
78
|
-
NOT_IMPLEMENTED: 1,
|
|
79
|
-
POLICY_REFUSED: 3,
|
|
80
|
-
PAYMENT_FAILED: 4,
|
|
81
|
-
RESOURCE_NOT_FOUND: 1,
|
|
82
|
-
SEARCH_NOT_FOUND: 1,
|
|
83
|
-
RATE_LIMITED: 1,
|
|
84
|
-
// A publish awaiting confirmation or hard-blocked is understood-but-refused (3),
|
|
85
|
-
// the same posture as POLICY_REFUSED; a write that failed after approval is a
|
|
86
|
-
// settlement-class failure (4), like PAYMENT_FAILED.
|
|
87
|
-
NEEDS_CONFIRMATION: 3,
|
|
88
|
-
PUBLISH_BLOCKED: 3,
|
|
89
|
-
PUBLISH_FAILED: 4,
|
|
90
|
-
// A send that reverted or stalled AFTER the human approved it and it was
|
|
91
|
-
// broadcast: the post-decision failure class (4), like PAYMENT_FAILED.
|
|
92
|
-
SEND_FAILED: 4,
|
|
93
|
-
// A delete the operator confirmed and the server then refused: same class.
|
|
94
|
-
DELETE_FAILED: 4,
|
|
95
|
-
UPDATE_FAILED: 1,
|
|
96
|
-
// Refused BEFORE any signature existed: the Bazaar lane's fail-closed check.
|
|
97
|
-
REGISTRY_MISMATCH: 3,
|
|
98
|
-
// The seller's 402 challenge does not fit this process's header limit, so the
|
|
99
|
-
// terms could not be read and nothing was sent. Understood and refused (3),
|
|
100
|
-
// not a transport failure: the connection was fine and a retry changes
|
|
101
|
-
// nothing without an operator raising `--max-http-header-size`.
|
|
102
|
-
CHALLENGE_TOO_LARGE: 3
|
|
103
|
-
};
|
|
104
|
-
function exitCodeFor(code) {
|
|
105
|
-
return EXIT_BY_CODE[code];
|
|
106
|
-
}
|
|
107
|
-
var CliError = class extends Error {
|
|
108
|
-
code;
|
|
109
|
-
exitCode;
|
|
110
|
-
fix;
|
|
111
|
-
details;
|
|
112
|
-
constructor(code, message, opts = {}) {
|
|
113
|
-
super(message, opts.cause !== void 0 ? { cause: opts.cause } : void 0);
|
|
114
|
-
this.name = "CliError";
|
|
115
|
-
this.code = code;
|
|
116
|
-
this.exitCode = opts.exitCode ?? exitCodeFor(code);
|
|
117
|
-
this.fix = opts.fix;
|
|
118
|
-
this.details = opts.details;
|
|
119
|
-
}
|
|
120
|
-
};
|
|
121
|
-
|
|
122
|
-
// src/adapters/types.ts
|
|
123
|
-
var HARNESSES = ["claude", "codex"];
|
|
124
|
-
|
|
125
|
-
export {
|
|
126
|
-
writeFileAtomic,
|
|
127
|
-
writeFileAtomicExclusive,
|
|
128
|
-
fsyncDir,
|
|
129
|
-
CliError,
|
|
130
|
-
HARNESSES
|
|
131
|
-
};
|
|
132
|
-
//# sourceMappingURL=chunk-JLEF5WHM.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/atomic-json.ts","../src/lib/errors.ts","../src/adapters/types.ts"],"sourcesContent":["import { chmod, link, mkdir, open, rename, rm, writeFile } from 'node:fs/promises';\nimport { randomBytes } from 'node:crypto';\nimport { basename, dirname, join } from 'node:path';\n\n/** fs modes are no-ops on Windows; the 0600/0700 custody story does not apply. */\nconst isWindows = process.platform === 'win32';\n\nexport interface AtomicWriteOptions {\n /** Mode for the written file (ignored on win32). Default 0o644. */\n mode?: number;\n /** Mode for the parent dir when this call creates it (ignored on win32). Default 0o755. */\n dirMode?: number;\n}\n\n/**\n * Write `data` to `targetPath` atomically: a uniquely-named temp file is created\n * in the SAME directory (so the rename is atomic — a cross-filesystem rename is\n * not), given the final mode at open time, then renamed over the target. A\n * reader therefore sees either the old file or the fully-written new one, never\n * a partial write.\n *\n * The temp file is born with the caller's `mode` (0o600 for a wallet key) so the\n * bytes are never written through a world-readable descriptor; the follow-up\n * chmod only makes the mode exact under an unusual umask and only ever touches\n * the temp path, so the live target still appears atomically at its final mode.\n */\nexport async function writeFileAtomic(\n targetPath: string,\n data: string | Buffer,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n await writeFile(tmpPath, data, isWindows ? undefined : { mode: fileMode });\n if (!isWindows) await chmod(tmpPath, fileMode);\n await rename(tmpPath, targetPath);\n } catch (err) {\n await rm(tmpPath, { force: true }).catch(() => undefined);\n throw err;\n }\n}\n\n/**\n * Like {@link writeFileAtomic} but NO-CLOBBER and crash-durable: the commit fails\n * with `EEXIST` when `targetPath` already exists instead of replacing it, and the\n * new entry is fsynced before returning. This is what a wallet key needs — two\n * concurrent `create`/`import` runs must not both \"succeed\" and silently lose one\n * key; the loser gets a distinguishable EEXIST the wallet layer maps to\n * WALLET_EXISTS.\n *\n * The temp file is fsynced, then `link()` commits it — link is atomic and throws\n * EEXIST if the target already exists, so the check-then-write race is closed at\n * the filesystem, not by an earlier stat. The parent dir is then fsynced so the\n * new entry survives a crash. On win32, link semantics differ and a directory\n * cannot be fsynced, so we fall back to an exclusive `wx` open (still atomic\n * create-or-EEXIST, just not crash-durable — win32 has no 0600 custody story to\n * protect anyway).\n */\nexport async function writeFileAtomicExclusive(\n targetPath: string,\n data: string,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n if (isWindows) {\n const handle = await open(targetPath, 'wx');\n try {\n await handle.writeFile(data);\n await handle.sync();\n } finally {\n await handle.close();\n }\n return;\n }\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n const handle = await open(tmpPath, 'wx', fileMode);\n try {\n await handle.writeFile(data);\n await handle.chmod(fileMode); // exact mode even under an unusual umask\n await handle.sync();\n } finally {\n await handle.close();\n }\n await link(tmpPath, targetPath); // atomic; throws EEXIST when the target exists\n await fsyncDir(dir);\n } finally {\n // On success the temp is now a redundant link to the target; on EEXIST it is\n // the orphaned write. Either way remove it before returning/throwing.\n await rm(tmpPath, { force: true }).catch(() => undefined);\n }\n}\n\n/** fsync a directory so a freshly linked entry is durable. Never call on win32. */\nexport async function fsyncDir(dir: string): Promise<void> {\n const handle = await open(dir, 'r');\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n}\n","import type { ErrorCode } from '../schemas';\n\n/**\n * The process exit code is API (spec 10): 0 success, 1 runtime/network, 2 usage,\n * 3 understood-but-refused (policy refusal, publish confirmation/hard-block), 4 a\n * failure AFTER an approved spend or write (a settlement that failed, a publish\n * that failed post-consent).\n */\nexport type ExitCode = 1 | 2 | 3 | 4;\n\nexport interface CliErrorOptions {\n /** A copy-pasteable command or one-line remediation. */\n fix?: string;\n /** Structured detail for machine consumers; serialized into the envelope. */\n details?: unknown;\n /** Override the default exit code for this error's code. */\n exitCode?: ExitCode;\n /** Underlying cause, preserved on the Error but never serialized. */\n cause?: unknown;\n}\n\n/**\n * Default code -> exit-code mapping. USAGE/CONFIG_INVALID are malformed\n * invocations (2); WALLET_EXISTS/REFUSED are understood-but-refused (3);\n * everything else is a runtime/network failure (1). A CliError may override its\n * own exit code, but the table is the default every caller relies on.\n */\nconst EXIT_BY_CODE: Record<ErrorCode, ExitCode> = {\n NODE_UNSUPPORTED: 1,\n USAGE: 2,\n CONFIG_INVALID: 2,\n WALLET_EXISTS: 3,\n WALLET_MISSING: 1,\n WALLET_INVALID_KEY: 1,\n PROVIDER_ERROR: 1,\n RPC_ERROR: 1,\n API_UNREACHABLE: 1,\n CONTRACT_MISMATCH: 1,\n REFUSED: 3,\n NETWORK_ERROR: 1,\n INTERNAL: 1,\n NOT_IMPLEMENTED: 1,\n POLICY_REFUSED: 3,\n PAYMENT_FAILED: 4,\n RESOURCE_NOT_FOUND: 1,\n SEARCH_NOT_FOUND: 1,\n RATE_LIMITED: 1,\n // A publish awaiting confirmation or hard-blocked is understood-but-refused (3),\n // the same posture as POLICY_REFUSED; a write that failed after approval is a\n // settlement-class failure (4), like PAYMENT_FAILED.\n NEEDS_CONFIRMATION: 3,\n PUBLISH_BLOCKED: 3,\n PUBLISH_FAILED: 4,\n // A send that reverted or stalled AFTER the human approved it and it was\n // broadcast: the post-decision failure class (4), like PAYMENT_FAILED.\n SEND_FAILED: 4,\n // A delete the operator confirmed and the server then refused: same class.\n DELETE_FAILED: 4,\n UPDATE_FAILED: 1,\n // Refused BEFORE any signature existed: the Bazaar lane's fail-closed check.\n REGISTRY_MISMATCH: 3,\n // The seller's 402 challenge does not fit this process's header limit, so the\n // terms could not be read and nothing was sent. Understood and refused (3),\n // not a transport failure: the connection was fine and a retry changes\n // nothing without an operator raising `--max-http-header-size`.\n CHALLENGE_TOO_LARGE: 3,\n};\n\nexport function exitCodeFor(code: ErrorCode): ExitCode {\n return EXIT_BY_CODE[code];\n}\n\n/**\n * The one error type commands throw. It carries the machine `code`, the resolved\n * `exitCode`, and an optional `fix`/`details` that flow straight into the failure\n * envelope. Commands throw it; the CLI dispatcher catches, serializes, and exits.\n */\nexport class CliError extends Error {\n readonly code: ErrorCode;\n readonly exitCode: ExitCode;\n readonly fix?: string;\n readonly details?: unknown;\n\n constructor(code: ErrorCode, message: string, opts: CliErrorOptions = {}) {\n super(message, opts.cause !== undefined ? { cause: opts.cause } : undefined);\n this.name = 'CliError';\n this.code = code;\n this.exitCode = opts.exitCode ?? exitCodeFor(code);\n this.fix = opts.fix;\n this.details = opts.details;\n }\n}\n","/**\n * The harness adapter contract (tenjin-notes loop-redesign/04-harness-adapters.md).\n *\n * This and `error-markers.ts` (data both sides read) are the ONLY files the\n * kernel (`src/hooks/*`) imports from `src/adapters/`.\n * A harness is one module exporting a {@link HarnessAdapter}: a pure `decode`\n * from its native payload to {@link HookInput}, a pure `encode` from the\n * kernel's {@link Emit} to its native response, and a {@link Registrar} the\n * installer uses to write its hook entries. The daemon holds one adapter per\n * member of {@link Harness} and one route, `POST /hook/:harness`.\n *\n * Adding a harness is an adapter file plus a transport; nothing in `src/hooks`\n * or `src/daemon` changes. The union gains a member when an adapter lands, not\n * before.\n */\n\nimport type { PublishMode } from '../lib/config';\nimport type {\n CodexGrantResult,\n HarnessPermissions,\n PermissionsResult,\n} from '../lib/harness-permissions';\nimport type { CodexTrustReport, TrustProbeOptions, TrustResult } from '../lib/codex-trust';\n\n/** Harnesses with an adapter in this build. */\nexport type Harness = 'claude' | 'codex';\n\n/** The same union at run time: the installer's ownership predicate matches a\n * registered URL against `/hook/<harness>`, and a list it cannot iterate would\n * have to be spelled a second time. */\nexport const HARNESSES: readonly Harness[] = ['claude', 'codex'];\n\n/**\n * The canonical event vocabulary every adapter maps its native events onto.\n * `session.end` is deliberately absent: no arm registers on it and retention\n * never runs there (a daemon serves many sessions; one ending is not the\n * machine going quiet).\n */\nexport type Event =\n | 'session.start'\n | 'prompt'\n | 'tool.before'\n | 'tool.after'\n | 'agent.start'\n | 'agent.stop'\n | 'turn.end';\n\nexport const EVENTS: readonly Event[] = [\n 'session.start',\n 'prompt',\n 'tool.before',\n 'tool.after',\n 'agent.start',\n 'agent.stop',\n 'turn.end',\n];\n\n/**\n * What a tool IS to the arms. Anything unmatched is `'other'`, never a key.\n *\n * `web` and `fetch` are separate kinds because they are separate arms: a page\n * fetch and a real web search ask different questions, and one agent's six page\n * fetches must not spend the budget its search needed.\n */\nexport type ToolKind = 'web' | 'fetch' | 'dispatch' | 'shell' | 'edit' | 'read';\n\nexport interface ToolResult {\n stdout?: string;\n stderr?: string;\n error?: string;\n text?: string;\n}\n\ninterface ToolBase {\n /** The native tool name, verbatim. */\n name: string;\n callId?: string;\n /**\n * `tool.after` only, and DECIDED IN DECODE, never by an arm reading the\n * result text. `false` is a failure the harness stated or an error marker in\n * a shell's output; `true` is a completion the harness vouched for;\n * `undefined` is unknown, which is what a harness that reports no exit status\n * leaves behind. No marker never means success.\n */\n ok?: boolean;\n result?: ToolResult;\n interrupted?: boolean;\n}\n\n/**\n * The fields the arms read, canonical per kind. Native argument shapes (a\n * `file_path`, a patch body, a `message`) stop at the adapter; an arm never\n * reads a vendor field. One native invocation is one tool value, so an edit\n * that touches several files carries them all in `paths` and the context arm\n * marks every one in a single fire.\n */\nexport type HookTool = ToolBase &\n (\n | { kind: 'shell'; command: string }\n | { kind: 'edit'; paths: string[] }\n | { kind: 'read'; paths: string[] }\n | { kind: 'dispatch'; task: string; description?: string }\n | { kind: 'web'; query: string }\n | { kind: 'fetch'; url: string; prompt: string }\n | { kind: 'other' }\n );\n\n/** The normalized payload the kernel runs on. */\nexport interface HookInput {\n harness: Harness;\n event: Event;\n /** `hook_event_name` verbatim; `encode` stamps its response with it. */\n native: { event: string };\n /** The ROOT session as the harness names it: the id the lead and all its\n * children share. `actorOf` namespaces it by harness before anything is\n * stored, so equal native ids across harnesses never share state. */\n session: string;\n /** Child id; undefined = the lead. Present-but-invalid makes `decode` return null. */\n agent?: string;\n /** Required; '' is allowed and recorded. */\n cwd: string;\n /** Claude `prompt_id`, Codex `turn_id`. */\n turn?: string;\n tool?: HookTool;\n /** The prompt on `prompt`; the spawn prompt on `agent.start` when the harness has it. */\n prompt?: string;\n agentType?: string;\n lastMessage?: string;\n /** Claude/Codex `stop_hook_active`: this stop was raised by a hook's own\n * feedback rather than by the agent finishing. The capture arm reads it to\n * tell an ask turn from the answer turn after one. */\n stopFuse?: boolean;\n transcript?: { path?: string; agentPath?: string };\n /** `session.start` source (`startup`, `clear`, `compact`, `resume`). */\n source?: string;\n /** The native payload. Ledger `question` on error rows and tests only; never read by arms. */\n raw: unknown;\n}\n\n/**\n * What the kernel hands back to the harness. `null` is \"nothing to say\" (204).\n *\n * ONE CHANNEL. Everything an arm says is context beside the turn, including the\n * turn-end ask: on Stop and SubagentStop `additionalContext` keeps the\n * conversation going through the same loop protections a blocking decision\n * would, and shows in the transcript as hook feedback rather than a hook error.\n * A second channel with a red banner said the same words for a worse price.\n */\nexport interface Emit {\n context?: string;\n}\n\n/**\n * What the installer needs to register a harness, and nothing the daemon runs\n * on: `selectArm` reads the event and tool kind off the decoded input, so a\n * registrar carries no event or tool metadata that would claim an enforcement\n * nothing performs.\n */\nexport interface Registrar {\n /** The harness's own hooks file under `home`. */\n configPath(home: string, env?: NodeJS.ProcessEnv): string;\n /**\n * Entries the installer merges additively into that file, each\n * `{ event, matcher?, hooks }` in the harness's own JSON shape.\n */\n plan(target: { url: string; token: string; shimPath: string; timeoutSeconds: number }): unknown[];\n /**\n * The steps left to a PERSON once the file is written, for a harness that\n * gates entries it has not been told to trust. Takes the path actually\n * written, because a machine on `$CODEX_HOME` is not reading `~/.codex`.\n * One sentence was not enough: as a clause on the undo line, operators\n * finished an install reporting \"7 entries\" with a loop that never fired\n * (tenjin-agent#342).\n */\n activation?(hooksPath: string): string[];\n /** The harness-native persistent command grant, when this harness has one. */\n grant?: {\n path(home: string, env?: NodeJS.ProcessEnv): string;\n inspect(home: string, mode: PublishMode, env?: NodeJS.ProcessEnv): Promise<HarnessPermissions>;\n write(\n home: string,\n mode: PublishMode,\n env?: NodeJS.ProcessEnv,\n ): Promise<PermissionsResult | CodexGrantResult>;\n remove?(home: string, env?: NodeJS.ProcessEnv): Promise<{ path: string; removed: boolean }>;\n };\n /** A harness-native trust gate for registered hook handlers. */\n trust?: {\n ensure(\n home: string,\n keys: readonly string[],\n ownedBy: (row: { command?: unknown; sourcePath?: unknown }) => boolean,\n opts?: TrustProbeOptions,\n ): Promise<TrustResult>;\n read(\n home: string,\n keys: readonly string[],\n opts?: TrustProbeOptions,\n ): Promise<CodexTrustReport>;\n };\n}\n\nexport interface HarnessAdapter {\n id: Harness;\n /** Pure. `null` = drop the fire quietly (unknown event, invalid identity). */\n decode(raw: unknown): HookInput | null;\n /** Pure. `null` = respond 204 with no body. */\n encode(emit: Emit | null, input: HookInput): unknown;\n registrar: Registrar;\n}\n"],"mappings":";;;AAAA,SAAS,OAAO,MAAM,OAAO,MAAM,QAAQ,IAAI,iBAAiB;AAChE,SAAS,mBAAmB;AAC5B,SAAS,UAAU,SAAS,YAAY;AAGxC,IAAM,YAAY,QAAQ,aAAa;AAqBvC,eAAsB,gBACpB,YACA,MACA,OAA2B,CAAC,GACb;AACf,QAAM,MAAM,QAAQ,UAAU;AAC9B,QAA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AK,MAAM,IAAI,MAAS;AAC3E,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW,KAAK,YAAY,YAAY,IAAI;AACjD,SAAK,MAAM,KAAK;AAChB,SAAK,UAAU,KAAK;AAAA,EACtB;AACF;;;AC7DO,IAAM,YAAgC,CAAC,UAAU,OAAO;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/fee.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { mkdir, open, readFile, readdir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { hasCode } from '../lib/errno';\nimport { formatUsdDisplay } from '../lib/money';\nimport { evaluateSpendPolicy, type PolicyReason, type SpendPolicy } from '../lib/policy';\nimport type { DecisionRoute } from './decision';\n\n/**\n * THE ROUTING FEE, WITHOUT ANYTHING THAT PAYS. Every routing call on the paid\n * path pays $0.003 over x402 `batch-settlement`, and the stock SDK client in\n * `tenjin mcp` does all of it (`routing-payer.ts`). Everything else, `tenjin\n * hook` included, is the free path exactly as before this fee existed.\n *\n * Hook-safe: `tenjin hook` loads this module, and its chunk graph stays free\n * of the wallet and the x402 SDK (`dist-chunks.test.ts`).\n */\n\nexport const ROUTE_PAID_PATH = '/api/x402-router/route';\n\n/** The flat fee per routing call, atomic USDC ($0.003). */\nexport const ROUTING_FEE_ATOMIC = 3_000n;\n/** The largest channel deposit, atomic USDC ($0.25), made inline by the SDK\n * on the first paid call of a channel that cannot cover the next fee. */\nexport const CHANNEL_DEPOSIT_ATOMIC = 250_000n;\n/**\n * The smallest deposit worth signing: ten fees ($0.03). A per-call limit under\n * $0.25 sizes the deposit down to the limit while it still covers this many.\n */\nexport const MIN_DEPOSIT_ATOMIC = 10n * ROUTING_FEE_ATOMIC;\n\n/** A spend refusal, as the reason the call was not paid. */\nconst REFUSED: Partial<Record<PolicyReason, string>> = {\n not_allowlisted: 'not_allowlisted',\n session_budget_exceeded: 'budget_reached',\n above_auto_spend: 'limit_below_deposit',\n};\n\n/** The reason a spend refusal leaves a routing call unpaid. */\nexport function refusedWhy(reason: PolicyReason): string {\n return REFUSED[reason] ?? reason;\n}\n\n/**\n * THE DEPOSIT IS THE SPEND. It meets the whole policy once, the day's budget\n * included, when the SDK's `depositStrategy` reserves it. Each fee paid from\n * it then gets only the per-payment checks: the per-call limit, the creator\n * allowlist (the router's host) and an explicit zero daily limit. It is never\n * refused for the day's running total, which the deposit already consumed.\n * Null when those checks allow the fee.\n */\nexport function feeRefusal(policy: SpendPolicy, host: string): string | null {\n const evaluation = evaluateSpendPolicy(\n { ...policy, sessionBudgetAtomic: policy.sessionBudgetAtomic === 0n ? 0n : null },\n { mode: 'automatic', amountAtomic: ROUTING_FEE_ATOMIC, creator: host, sessionSpentAtomic: 0n },\n );\n return evaluation.decision === 'allow' ? null : refusedWhy(evaluation.reason);\n}\n\n/** The paid path for this call, or null for the free path. `tenjin mcp` passes\n * its payer's; absent, every call is free. */\nexport type RouteFor = (baseUrl: string) => Promise<DecisionRoute | null>;\n\n/** The free path's reason code once the server routes only paid calls. */\nexport const FEE_REQUIRED = 'fee_required';\n\n/** Whether a decision is the free path's `fee_required` answer. */\nexport function isFeeRequired(response: unknown): boolean {\n const decision = (response as { decision?: { action?: unknown; diagnostics?: unknown } })\n ?.decision;\n const diagnostics = decision?.diagnostics as { reasonCode?: unknown } | undefined;\n return decision?.action === 'native' && diagnostics?.reasonCode === FEE_REQUIRED;\n}\n\n/**\n * WHY A CALL WAS NOT PAID, for the user: the reason and the fix, keyed by the\n * payer's skip reason (or `fee_required`, when the free path answered it and\n * nothing else explains why). Null for a reason that is no fault and needs no\n * fix: another session's call on the channel, a server with no paid path, or\n * a call queued past its own budget, or a payment still out when the call's\n * budget ran out (it finishes in the background).\n */\nconst UNPAID: Record<string, { reason: string; fix: string }> = {\n wallet_low: {\n reason: `the wallet holds less than the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,\n fix: `Fund it with \\`tenjin wallet fund ${usd(CHANNEL_DEPOSIT_ATOMIC)}\\`.`,\n },\n wallet_locked: {\n reason: '`tenjin mcp` cannot unlock the wallet without a prompt',\n fix: 'Set TENJIN_WALLET_PASSPHRASE in the environment Claude Code starts from, then restart Claude Code.',\n },\n no_wallet: {\n reason: 'this machine has no wallet',\n fix: 'Run `tenjin doctor`.',\n },\n limit_below_deposit: {\n reason: `the per-call spend limit is below the smallest routing deposit ($${usd(MIN_DEPOSIT_ATOMIC)})`,\n fix: 'Run `tenjin doctor`.',\n },\n budget_reached: {\n reason: 'the daily spend limit has no room left for the routing fee or its deposit',\n fix: 'Run `tenjin doctor`.',\n },\n not_allowlisted: {\n reason: 'allowlistCreators does not include the router',\n fix: 'Run `tenjin doctor`.',\n },\n payment_failed: {\n reason: 'the routing payment failed',\n fix: 'Run `tenjin doctor`.',\n },\n [FEE_REQUIRED]: {\n reason: 'the router now charges it, and this session cannot pay it',\n fix: 'Run `tenjin doctor`.',\n },\n};\nconst NO_FAULT = new Set([\n 'channel_busy',\n 'paid_path_absent',\n 'busy',\n 'no_call',\n 'deadline_after_payment_sent',\n]);\n\n/** The reason and fix for an unpaid call, or null when it needs no word. */\nexport function unpaid(why: string): { reason: string; fix: string } | null {\n if (NO_FAULT.has(why)) return null;\n return UNPAID[why] ?? UNPAID['payment_failed']!;\n}\n\n/** The one line the user sees, once per session, when a call was not paid. */\nexport function unpaidSentence(why: string): string | null {\n const u = unpaid(why);\n if (u === null) return null;\n 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}`;\n}\n\nconst ADDRESS_RE = /^0x[0-9a-f]{40}$/;\n\n/** One wallet's folder: the SDK's file storage for its routing channel\n * (`client/<channelId>.json`). */\nexport function payerDir(dataDir: string, payer: string): string {\n const name = payer.toLowerCase();\n if (!ADDRESS_RE.test(name)) throw new Error(`not a wallet address: ${payer}`);\n return join(dataDir, 'router', 'fee', name);\n}\n\n/** Atomic USDC as dollars with at least two decimals, never a float. */\nexport function usd(atomic: bigint): string {\n return formatUsdDisplay(atomic.toString());\n}\n\n/** How long a session's notice marker is kept. */\nconst NOTICE_KEEP_MS = 7 * 86_400_000;\n\n/**\n * TRUE ONCE PER SESSION: the first caller for a session id creates its marker\n * and gets true; every later one gets false. Each marker holds the time it was\n * made, and those older than a week go on the way past, so the directory does\n * not grow with every session ever run.\n */\nexport async function firstNoticeFor(\n dataDir: string,\n sessionId: string,\n now: number,\n): Promise<boolean> {\n const dir = join(dataDir, 'router', 'notices');\n const name = createHash('sha256').update(sessionId).digest('hex').slice(0, 32);\n const created = await createExclusive(join(dir, name), String(now));\n if (created) {\n for (const entry of await readdir(dir).catch(() => [] as string[])) {\n const path = join(dir, entry);\n const at = Number(await readFile(path, 'utf8').catch(() => 'NaN'));\n if (!Number.isFinite(at) || now - at > NOTICE_KEEP_MS) await rm(path, { force: true });\n }\n }\n return created;\n}\n\nasync function createExclusive(path: string, body: string): Promise<boolean> {\n try {\n await mkdir(join(path, '..'), { recursive: true, mode: 0o700 });\n const handle = await open(path, 'wx', 0o600);\n try {\n await handle.writeFile(body);\n } finally {\n await handle.close();\n }\n return true;\n } catch (err) {\n if (hasCode(err, 'EEXIST')) return false;\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,MAAM,UAAU,SAAS,UAAU;AACnD,SAAS,YAAY;AAgBd,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;AAG3B,IAAM,yBAAyB;AAK/B,IAAM,qBAAqB,MAAM;AAGxC,IAAM,UAAiD;AAAA,EACrD,iBAAiB;AAAA,EACjB,yBAAyB;AAAA,EACzB,kBAAkB;AACpB;AAGO,SAAS,WAAW,QAA8B;AACvD,SAAO,QAAQ,MAAM,KAAK;AAC5B;AAUO,SAAS,WAAW,QAAqB,MAA6B;AAC3E,QAAM,aAAa;AAAA,IACjB,EAAE,GAAG,QAAQ,qBAAqB,OAAO,wBAAwB,KAAK,K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UAAE;AACA,YAAM,OAAO,MAAM;AAAA,IACrB;AACA,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,QAAQ,KAAK,QAAQ,EAAG,QAAO;AACnC,UAAM;AAAA,EACR;AACF;","names":[]}
|
package/dist/chunk-PM2MOXJ3.js
DELETED
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
CHANNEL_DEPOSIT_ATOMIC,
|
|
4
|
-
ROUTING_FEE_ATOMIC,
|
|
5
|
-
unpaidSentence,
|
|
6
|
-
usd
|
|
7
|
-
} from "./chunk-OBPZ36HG.js";
|
|
8
|
-
import {
|
|
9
|
-
toMoney
|
|
10
|
-
} from "./chunk-XICKN3CH.js";
|
|
11
|
-
|
|
12
|
-
// src/router/spend-question.ts
|
|
13
|
-
var ROUTER_DEFAULTS = {
|
|
14
|
-
maxAutoSpend: "250000",
|
|
15
|
-
sessionBudget: "5000000"
|
|
16
|
-
};
|
|
17
|
-
function shownLimits(config) {
|
|
18
|
-
return {
|
|
19
|
-
maxAutoSpend: config.maxAutoSpend ?? ROUTER_DEFAULTS.maxAutoSpend,
|
|
20
|
-
sessionBudget: config.sessionBudget ?? ROUTER_DEFAULTS.sessionBudget
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
function limitsUsd(limits) {
|
|
24
|
-
return {
|
|
25
|
-
maxAutoSpend: toMoney(limits.maxAutoSpend).usd,
|
|
26
|
-
sessionBudget: limits.sessionBudget === "none" ? "none" : toMoney(limits.sessionBudget).usd
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
function limitsPhrase(limits) {
|
|
30
|
-
const usdOf = limitsUsd(limits);
|
|
31
|
-
const daily = usdOf.sessionBudget === "none" ? "with no daily limit" : `and $${usdOf.sessionBudget} a day`;
|
|
32
|
-
return `up to $${usdOf.maxAutoSpend} a call ${daily}`;
|
|
33
|
-
}
|
|
34
|
-
var ROUTING_FEE_TERMS = `Routing costs $${usd(ROUTING_FEE_ATOMIC)} a call, paid from channel deposits of up to $${usd(CHANNEL_DEPOSIT_ATOMIC)} that stay yours until spent; each deposit counts against these limits.`;
|
|
35
|
-
var ACCEPT_COMMAND = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;
|
|
36
|
-
var OWN_LIMITS_COMMANDS = "`tenjin config set maxAutoSpend <usd>` and `tenjin config set sessionBudget <usd|none>`";
|
|
37
|
-
var FEE_APPROVAL = "Using these limits or choosing your own also approves the routing fee.";
|
|
38
|
-
function spendQuestion(limits) {
|
|
39
|
-
return `May Tenjin pay for tool calls without asking you each time, ${limitsPhrase(limits)}? ${ROUTING_FEE_TERMS} ${FEE_APPROVAL}`;
|
|
40
|
-
}
|
|
41
|
-
function unansweredNotice(limits, reader) {
|
|
42
|
-
const open = "Tenjin pays for nothing on its own yet: the spend limits are not answered.";
|
|
43
|
-
if (reader === "agent") {
|
|
44
|
-
return `${open} Ask the user: ${spendQuestion(limits)} For a yes, run \`${ACCEPT_COMMAND}\`; for other amounts, run ${OWN_LIMITS_COMMANDS}.`;
|
|
45
|
-
}
|
|
46
|
-
return `${open} It can pay for tool calls without asking you each time, ${limitsPhrase(limits)}. ${ROUTING_FEE_TERMS} ${FEE_APPROVAL} To use these limits, run \`${ACCEPT_COMMAND}\`; to choose your own, run ${OWN_LIMITS_COMMANDS}.`;
|
|
47
|
-
}
|
|
48
|
-
function unpaidNotice(why, config, reader) {
|
|
49
|
-
if (why === "limit_below_deposit" && config.maxAutoSpend === void 0) {
|
|
50
|
-
return unansweredNotice(shownLimits(config), reader);
|
|
51
|
-
}
|
|
52
|
-
return unpaidSentence(why);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export {
|
|
56
|
-
ROUTER_DEFAULTS,
|
|
57
|
-
shownLimits,
|
|
58
|
-
limitsUsd,
|
|
59
|
-
ROUTING_FEE_TERMS,
|
|
60
|
-
ACCEPT_COMMAND,
|
|
61
|
-
OWN_LIMITS_COMMANDS,
|
|
62
|
-
FEE_APPROVAL,
|
|
63
|
-
spendQuestion,
|
|
64
|
-
unpaidNotice
|
|
65
|
-
};
|
|
66
|
-
//# sourceMappingURL=chunk-PM2MOXJ3.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/spend-question.ts"],"sourcesContent":["import { toMoney } from '../lib/money';\nimport { CHANNEL_DEPOSIT_ATOMIC, ROUTING_FEE_ATOMIC, unpaidSentence, usd } from './fee';\n\n/**\n * THE SPEND QUESTION, ONE TEXT FOR EVERY PLACE THAT ASKS IT. The selector in a\n * terminal, the question an install that could not ask hands to its agent,\n * doctor's warning and the routing notice all show the same limits, the same\n * routing-fee terms and the same one-step yes, so the agent can put to the\n * user exactly what the selector would have.\n */\n\n/** Absent-only automatic router defaults, in atomic USDC. */\nexport const ROUTER_DEFAULTS = {\n maxAutoSpend: '250000',\n sessionBudget: '5000000',\n} as const;\n\n/** The automatic limits a fresh install fills in, in atomic USDC; `sessionBudget` may be `none`. */\nexport interface RouterLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\n/** What the question shows: the file's own value where it names one, else the default. */\nexport function shownLimits(config: {\n maxAutoSpend?: string | undefined;\n sessionBudget?: string | undefined;\n}): RouterLimits {\n return {\n maxAutoSpend: config.maxAutoSpend ?? ROUTER_DEFAULTS.maxAutoSpend,\n sessionBudget: config.sessionBudget ?? ROUTER_DEFAULTS.sessionBudget,\n };\n}\n\n/** The limits in USD, as the question shows them. */\nexport function limitsUsd(limits: RouterLimits): { maxAutoSpend: string; sessionBudget: string } {\n return {\n maxAutoSpend: toMoney(limits.maxAutoSpend).usd,\n sessionBudget: limits.sessionBudget === 'none' ? 'none' : toMoney(limits.sessionBudget).usd,\n };\n}\n\n/** \"up to $0.25 a call and $5 a day\" */\nexport function limitsPhrase(limits: RouterLimits): string {\n const usdOf = limitsUsd(limits);\n const daily =\n usdOf.sessionBudget === 'none' ? 'with no daily limit' : `and $${usdOf.sessionBudget} a day`;\n return `up to $${usdOf.maxAutoSpend} a call ${daily}`;\n}\n\n/** The routing fee's terms, as the selector names them. */\nexport const ROUTING_FEE_TERMS = `Routing costs $${usd(ROUTING_FEE_ATOMIC)} a call, paid from channel deposits of up to $${usd(CHANNEL_DEPOSIT_ATOMIC)} that stay yours until spent; each deposit counts against these limits.`;\n\n/**\n * The yes to the limits shown, where the command install ran is not known\n * (doctor, the routing notice, the request tool): the per-call limit only.\n * The daily limit already defaults to the one shown. A bare `install --yes`\n * here would undo a `--project`, `--no-wallet` or `--status-line skip`\n * install; install's own output names that command with its flags instead.\n */\nexport const ACCEPT_COMMAND = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;\n\n/** The commands for limits of the user's own, each in backticks. */\nexport const OWN_LIMITS_COMMANDS =\n '`tenjin config set maxAutoSpend <usd>` and `tenjin config set sessionBudget <usd|none>`';\n\n/** The selector's own line: either answer approves the fee. */\nexport const FEE_APPROVAL =\n 'Using these limits or choosing your own also approves the routing fee.';\n\n/** The question, for the agent to put to the user as written. */\nexport function spendQuestion(limits: RouterLimits): string {\n return `May Tenjin pay for tool calls without asking you each time, ${limitsPhrase(limits)}? ${ROUTING_FEE_TERMS} ${FEE_APPROVAL}`;\n}\n\n/** Who reads a notice: the user, in the hook's `systemMessage`, or the agent,\n * in the request tool's answer. */\nexport type NoticeReader = 'user' | 'agent';\n\n/**\n * The routing notice for a machine whose limits nobody has answered: the\n * question and the one-step yes, put to the user directly, or handed to the\n * agent to ask.\n */\nexport function unansweredNotice(limits: RouterLimits, reader: NoticeReader): string {\n const open = 'Tenjin pays for nothing on its own yet: the spend limits are not answered.';\n if (reader === 'agent') {\n return `${open} Ask the user: ${spendQuestion(limits)} For a yes, run \\`${ACCEPT_COMMAND}\\`; for other amounts, run ${OWN_LIMITS_COMMANDS}.`;\n }\n return `${open} It can pay for tool calls without asking you each time, ${limitsPhrase(limits)}. ${ROUTING_FEE_TERMS} ${FEE_APPROVAL} To use these limits, run \\`${ACCEPT_COMMAND}\\`; to choose your own, run ${OWN_LIMITS_COMMANDS}.`;\n}\n\n/**\n * The routing notice for a call that was not paid: the limits question when\n * the per-call limit is the code default's zero because nobody has answered\n * it, else the reason and fix for `why`.\n */\nexport function unpaidNotice(\n why: string,\n config: { maxAutoSpend?: string | undefined; sessionBudget?: string | undefined },\n reader: NoticeReader,\n): string | null {\n if (why === 'limit_below_deposit' && config.maxAutoSpend === undefined) {\n return unansweredNotice(shownLimits(config), reader);\n }\n return unpaidSentence(why);\n}\n"],"mappings":";;;;;;;;;;;;AAYO,IAAM,kBAAkB;AAAA,EAC7B,cAAc;AAAA,EACd,eAAe;AACjB;AASO,SAAS,YAAY,QAGX;AACf,SAAO;AAAA,IACL,cAAc,OAAO,gBAAgB,gBAAgB;AAAA,IACrD,eAAe,OAAO,iBAAiB,gBAAgB;AAAA,EACzD;AACF;AAGO,SAAS,UAAU,QAAuE;AAC/F,SAAO;AAAA,IACL,cAAc,QAAQ,OAAO,YAAY,EAAE;AAAA,IAC3C,eAAe,OAAO,kBAAkB,SAAS,SAAS,QAAQ,OAAO,aAAa,EAAE;AAAA,EAC1F;AACF;AAGO,SAAS,aAAa,QAA8B;AACzD,QAAM,QAAQ,UAAU,MAAM;AAC9B,QAAM,QACJ,MAAM,kBAAkB,SAAS,wBAAwB,QAAQ,MAAM,aAAa;AACtF,SAAO,UAAU,MAAM,YAAY,WAAW,KAAK;AACrD;AAGO,IAAM,oBAAoB,kBAAkB,IAAI,kBAAkB,CAAC,iDAAiD,IAAI,sBAAsB,CAAC;AAS/I,IAAM,iBAAiB,kCAAkC,QAAQ,gBAAgB,YAAY,EAAE,GAAG;AAGlG,IAAM,sBACX;AAGK,IAAM,eACX;AAGK,SAAS,cAAc,QAA8B;AAC1D,SAAO,+DAA+D,aAAa,MAAM,CAAC,KAAK,iBAAiB,IAAI,YAAY;AAClI;AAWO,SAAS,iBAAiB,QAAsB,QAA8B;AACnF,QAAM,OAAO;AACb,MAAI,WAAW,SAAS;AACtB,WAAO,GAAG,IAAI,kBAAkB,cAAc,MAAM,CAAC,qBAAqB,cAAc,8BAA8B,mBAAmB;AAAA,EAC3I;AACA,SAAO,GAAG,IAAI,4DAA4D,aAAa,MAAM,CAAC,KAAK,iBAAiB,IAAI,YAAY,+BAA+B,cAAc,+BAA+B,mBAAmB;AACrO;AAOO,SAAS,aACd,KACA,QACA,QACe;AACf,MAAI,QAAQ,yBAAyB,OAAO,iBAAiB,QAAW;AACtE,WAAO,iBAAiB,YAAY,MAAM,GAAG,MAAM;AAAA,EACrD;AACA,SAAO,eAAe,GAAG;AAC3B;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/progress.ts"],"sourcesContent":["import { createHash, randomUUID } from 'node:crypto';\nimport { constants } from 'node:fs';\nimport { lstat, open, opendir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic, writeFileAtomicExclusive } from '../lib/atomic-json';\n\n/**\n * The live status line's evidence: what this session is looking up right now,\n * which provider is actually being called, and what it cost.\n *\n * DISPLAY ONLY, AND STRICTLY DOWNSTREAM. Nothing here is read by the gate, the\n * decision, the spend policy or the paying leg; every write is best effort and\n * every failure is swallowed, so a full disk or a read-only data dir loses the\n * footer and changes no routing or payment outcome. That is the whole contract\n * this module has to keep. Two markers are read back by the hooks, the offer\n * mark and the redirect claims, and both only ever make a hook say less: losing\n * either routes a call exactly as a session with no record would, and a claim\n * that cannot be written denies nothing. The free-docs\n * records are the same kind: a lost augment marker is a search with no docs\n * added, and a lost query claim is one more free fetch.\n *\n * KEYED TO THE SESSION, NEVER GUESSED FROM IT. A record lives under the SHA-256\n * of the harness's own `session_id`, so the renderer for one session cannot see\n * another's. The hook knows that id; the tool, which runs inside the MCP server\n * process, does not, so it resolves the session in one of exactly two ways:\n *\n * - BY BINDING. An `execute` decision leaves an `id-<hash>.json` marker in the\n * session that produced it, and the model passes that id back on the tool\n * call. Resolving through the marker is proof, not inference.\n * - BY SOLE ACTIVITY. With no id, the request belongs to the only session that\n * has been active recently, and when two have been, it belongs to neither as\n * far as this module is concerned: {@link resolveProgressSession} returns\n * null and nothing is written. A missing footer is the correct failure;\n * showing one session's lookup in another session's terminal is not.\n */\n\nconst PROGRESS_DIR = 'progress';\n/** The binding marker's prefix, so it can never be read back as a call record. */\nconst BINDING_PREFIX = 'id-';\n/** A pre-call redirect's marker, keyed by the harness's `tool_use_id`. */\nconst OFFER_PREFIX = 'offer-';\n/** The session's own liveness touch, likewise outside the call-record pattern. */\nconst SESSION_FILE = 'session.json';\n/** A pre-call redirect, one file per agent and target in the session. */\nconst REDIRECT_PREFIX = 'redirect-';\n/** A search the pre-call hook is adding free docs to, keyed by its `tool_use_id`. */\nconst AUGMENT_PREFIX = 'augment-';\n/** What the docs prefetch got, beside its marker. The provider's text sets its\n * size, so it is never read as a record: it ages by its mtime. */\nconst AUGMENT_BODY_SUFFIX = '.docs';\n/** One agent's search query that was augmented, so the same one is not fetched twice. */\nconst QUERY_PREFIX = 'query-';\n/** Call records are named by a 64-hex digest and nothing else is read as one. */\nconst CALL_FILE_RE = /^[a-f0-9]{64}\\.json$/;\n\n/** An in-flight call older than this is shown as stale, never as running. */\nexport const STALE_AFTER_MS = 90_000;\n/**\n * How long a state stays on the footer once nothing has replaced it. The demo\n * holds each one for about ten seconds, which is what makes a decision that\n * takes a second readable at a one-second refresh; after that the line is\n * `x402 · ready` again.\n */\nexport const RECENT_MS = 10_000;\n/** Older than this and a record is ignored by the renderer and pruned on write. */\nexport const EXPIRY_MS = 10 * 60_000;\n/** How recently a session must have been touched to claim an id-less request. */\nexport const SESSION_ACTIVE_MS = 10 * 60_000;\n/** How long one agent's identical search is not given the same docs again. */\nexport const AUGMENT_REPEAT_MS = 5 * 60_000;\n/** Above this many files a session directory is reported rather than scanned. */\nconst MAX_RECORDS = 256;\n/** A ceiling on the root scan. {@link pruneSessions} keeps it far below this:\n * a directory is one LIVE session, not one session this machine ever had. */\nconst MAX_SESSIONS = 4_096;\n/** A record larger than this is damaged or not ours; it is skipped unread. */\nconst MAX_RECORD_BYTES = 4_096;\n\nexport type ProgressPhase = 'routing' | 'calling' | 'done';\n\n/** The two markers: a session's liveness touch and a decision-id binding. */\ninterface Stamp {\n version: 1;\n at: number;\n}\n\n/** What one call looks like on disk. Every string is already masked and bounded. */\ninterface SavedProgress extends Stamp {\n phase: ProgressPhase;\n /** The tool whose activity this is, as the footer names it. */\n operation: string;\n /** What the state SAYS: the outcome on `done`, and on an in-flight record the\n * stage, when it is not the tool's own `selecting service`. */\n outcome?: string;\n /** Host plus path of the provider actually called, without a scheme. */\n endpoint?: string;\n /** The call's parameters as compact JSON. */\n parameters?: string;\n /** What the provider was paid, as USD. */\n price?: string;\n}\n\n/** A search being given free docs, and whose docs they are. */\ninterface SavedAugment extends Stamp {\n provider: string;\n}\n\nexport interface ProgressStep {\n phase: ProgressPhase;\n operation?: string;\n outcome?: string;\n /** The executed provider's URL. It can differ from the hint's suggestion. */\n provider?: string;\n parameters?: unknown;\n price?: string;\n}\n\nconst digest = (value: string): string => createHash('sha256').update(value).digest('hex');\n\nfunction bounded(value: string, limit: number): string {\n const chars = Array.from(value);\n return chars.length <= limit ? value : `${chars.slice(0, limit - 1).join('')}…`;\n}\n\n/**\n * Provider text reaches a terminal here, so it is treated as hostile: control\n * characters, format characters and directional overrides are replaced before\n * anything is written, and again before anything is printed. A footer that can\n * be made to repaint the line above it is a spoofing surface, not a display.\n */\nexport function sanitize(value: string, limit: number): string {\n return bounded(\n value\n .replace(/[\\p{Cc}\\p{Cf}]/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim(),\n limit,\n );\n}\n\n/**\n * The CLI's own redaction, behind a dynamic import ON PURPOSE: the rule corpus\n * and the BIP-39 wordlist are a real parse cost, the renderer runs once a\n * second, and only the write path needs them. `dist-chunks.test.ts` pins it.\n */\nasync function clean(value: string, limit: number): Promise<string> {\n const { mask } = await import('../lib/redact');\n return sanitize(mask(value), limit);\n}\n\n/** Host plus path, which is what names a provider to a person watching. */\nasync function endpointOf(value: string): Promise<string> {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return 'invalid endpoint';\n }\n if (url.username !== '' || url.password !== '') return 'invalid endpoint';\n return clean(`${url.host}${url.pathname === '/' ? '' : url.pathname}`, 110);\n}\n\nasync function parametersOf(value: unknown): Promise<string | undefined> {\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n return undefined;\n }\n return json === undefined ? undefined : clean(json, 180);\n}\n\nexport function sessionDir(dataDir: string, sessionId: string): string {\n return join(dataDir, PROGRESS_DIR, digest(sessionId));\n}\n\n/** A fresh key for one call, so two overlapping lookups never share a record. */\nexport function newCallId(): string {\n return randomUUID();\n}\n\n/**\n * Mark this session live, so an id-less tool call made from it can be\n * attributed. Written on every hook event, including the ones that route\n * nothing: an open session has to be distinguishable from a closed one.\n */\nexport async function noteSession(\n dataDir: string,\n sessionId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), SESSION_FILE), { version: 1, at: now });\n}\n\n/** Record that this decision id was produced in this session. */\nexport async function bindDecision(\n dataDir: string,\n sessionId: string,\n decisionId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), `${BINDING_PREFIX}${digest(decisionId)}.json`), {\n version: 1,\n at: now,\n });\n}\n\n/**\n * ONE ROUTING ANSWER PER LOOKUP. The pre-call hook marks the native call it\n * redirected, by the harness's own `tool_use_id`, and the after-call hook reads\n * the mark before it asks again about the same call. Expires and is pruned like every\n * other record here.\n */\nexport async function markOffered(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), `${OFFER_PREFIX}${digest(toolUseId)}.json`), {\n version: 1,\n at: now,\n });\n}\n\nexport async function wasOffered(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n now = Date.now(),\n): Promise<boolean> {\n const path = join(sessionDir(dataDir, sessionId), `${OFFER_PREFIX}${digest(toolUseId)}.json`);\n const stamp = await readStamp(path);\n return stamp !== null && now - stamp.at <= EXPIRY_MS;\n}\n\n/**\n * FREE DOCS BESIDE A SEARCH. The pre-call hook marks the search it let run with\n * a free offer, by the harness's own `tool_use_id` and with the provider's name\n * for the line the after-call hook writes, and returns where the prefetch puts\n * what it got: beside the marker, under the same key. Null when the marker could\n * not be written, since nothing could then find the body.\n */\nexport async function markAugment(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n provider: string,\n now = Date.now(),\n): Promise<string | null> {\n const base = join(sessionDir(dataDir, sessionId), `${AUGMENT_PREFIX}${digest(toolUseId)}`);\n const saved: SavedAugment = { version: 1, at: now, provider: sanitize(provider, 60) };\n return (await write(`${base}.json`, saved)) ? `${base}${AUGMENT_BODY_SUFFIX}` : null;\n}\n\n/** The marker {@link markAugment} left for this call, or null when it left none. */\nexport async function augmentOf(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n now = Date.now(),\n): Promise<{ at: number; provider: string; body: string } | null> {\n const base = join(sessionDir(dataDir, sessionId), `${AUGMENT_PREFIX}${digest(toolUseId)}`);\n const row = await readJson(`${base}.json`);\n const stamp = stampOf(row);\n if (row === null || stamp === null || now - stamp.at > EXPIRY_MS) return null;\n const provider = typeof row.provider === 'string' ? sanitize(row.provider, 60) : '';\n return { at: stamp.at, provider, body: `${base}${AUGMENT_BODY_SUFFIX}` };\n}\n\n/**\n * ONE FETCH PER QUERY. True when this agent has not had this exact search\n * augmented in the last {@link AUGMENT_REPEAT_MS}, and the claim is now its:\n * the create is exclusive, so two parallel copies of one search fetch once.\n */\nexport async function claimQuery(\n dataDir: string,\n sessionId: string,\n agentId: string | undefined,\n query: string,\n now = Date.now(),\n): Promise<boolean> {\n const key = digest(JSON.stringify([agentId ?? '', query]));\n const path = join(sessionDir(dataDir, sessionId), `${QUERY_PREFIX}${key}.json`);\n const stamp: Stamp = { version: 1, at: now };\n try {\n await writeFileAtomicExclusive(path, JSON.stringify(stamp), { mode: 0o600, dirMode: 0o700 });\n return true;\n } catch {\n // Taken: by a recent search, which wins, or by an old one, which does not.\n }\n const last = await readStamp(path);\n if (last === null || now - last.at <= AUGMENT_REPEAT_MS) return false;\n return write(path, stamp);\n}\n\n/**\n * ONE RECORD PER AGENT, TARGET AND WINDOW. Subagents share the session id, so\n * the agent is in the key, and the main agent's part is the empty string, which\n * no `agent_id` can be: the decoder refuses an empty one. The target is in it\n * too, one file each, so parallel calls never share a record: one call's\n * redirect can be neither overwritten nor spent by another's. And so is the\n * {@link EXPIRY_MS} window the claim was made in, so a claim is only ever\n * created, never replaced: see {@link claimRedirect}.\n */\nfunction redirectPath(\n dataDir: string,\n sessionId: string,\n agentId: string | undefined,\n target: string,\n window: number,\n): string {\n const key = digest(JSON.stringify([agentId ?? '', target, window]));\n return join(sessionDir(dataDir, sessionId), `${REDIRECT_PREFIX}${key}.json`);\n}\n\n/**\n * NEVER REDIRECTED TWICE FOR ONE TARGET. True, once, when this agent has not\n * been redirected on this exact search or URL in the last {@link EXPIRY_MS},\n * and the claim is now its; the pre-call hook denies only on true. So the\n * agent's own retry of a redirected call runs, whether the lookup it was sent\n * to delivered, failed or was never called, and whatever other calls ran in\n * between.\n *\n * ONLY EVER AN EXCLUSIVE CREATE. Replacing an expired claim let two parallel\n * copies of one call both read the old stamp and both write, and both deny.\n * The claim's file is named by its window instead, so the one create per\n * window decides, and the previous window's claim, while it is still inside\n * {@link EXPIRY_MS}, is read and never touched: a claim made just before a\n * boundary still lasts its full span. A claim that cannot be written is false:\n * the call runs.\n */\nexport async function claimRedirect(\n dataDir: string,\n sessionId: string,\n agentId: string | undefined,\n target: string,\n now = Date.now(),\n): Promise<boolean> {\n const window = Math.floor(now / EXPIRY_MS);\n const previous = await readStamp(redirectPath(dataDir, sessionId, agentId, target, window - 1));\n if (previous !== null && now - previous.at <= EXPIRY_MS) return false;\n const stamp: Stamp = { version: 1, at: now };\n try {\n await writeFileAtomicExclusive(\n redirectPath(dataDir, sessionId, agentId, target, window),\n JSON.stringify(stamp),\n { mode: 0o600, dirMode: 0o700 },\n );\n return true;\n } catch {\n // Taken in this window, which is always inside EXPIRY_MS, or not writable.\n return false;\n }\n}\n\n/**\n * THE READ HALF OF {@link claimRedirect}: true when this agent already holds a\n * live claim on this exact search or URL. The pre-call arms ask it BEFORE the\n * router, so the retry of a call they already redirected, which they would\n * only withhold, costs no decision and leaves no offer nobody sees. It never\n * writes and never decides on its own: a false here still goes through the\n * exclusive create, which is what keeps two parallel copies to one deny.\n */\nexport async function redirectClaimed(\n dataDir: string,\n sessionId: string,\n agentId: string | undefined,\n target: string,\n now = Date.now(),\n): Promise<boolean> {\n const window = Math.floor(now / EXPIRY_MS);\n for (const at of [window, window - 1]) {\n const stamp = await readStamp(redirectPath(dataDir, sessionId, agentId, target, at));\n if (stamp !== null && now - stamp.at <= EXPIRY_MS) return true;\n }\n return false;\n}\n\n/**\n * Which session directory a tool call belongs to, or null for \"cannot tell\".\n * Null is a normal answer and its only consequence is a footer that stays quiet.\n */\nexport async function resolveProgressSession(\n dataDir: string,\n opts: { id?: string; now?: number } = {},\n): Promise<string | null> {\n const now = opts.now ?? Date.now();\n const root = join(dataDir, PROGRESS_DIR);\n let names: string[];\n try {\n const directory = await opendir(root);\n names = [];\n for await (const entry of directory) {\n if (entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name)) names.push(entry.name);\n if (names.length >= MAX_SESSIONS) break;\n }\n } catch {\n return null;\n }\n if (opts.id !== undefined && opts.id.length > 0) {\n const marker = `${BINDING_PREFIX}${digest(opts.id)}.json`;\n for (const name of names) {\n const bound = await readStamp(join(root, name, marker));\n if (bound !== null && now - bound.at <= EXPIRY_MS) return join(root, name);\n }\n // A stale or unknown id says nothing about which session asked, so the\n // sole-activity rule below still applies rather than a wrong attribution.\n }\n const live: string[] = [];\n for (const name of names) {\n const touched = await readStamp(join(root, name, SESSION_FILE));\n if (touched !== null && now - touched.at <= SESSION_ACTIVE_MS) live.push(name);\n if (live.length > 1) return null;\n }\n return live.length === 1 ? join(root, live[0] as string) : null;\n}\n\n/**\n * Record one step of one call. The caller holds the directory (from\n * {@link sessionDir} or {@link resolveProgressSession}) and the call id, so a\n * step never has to re-resolve anything on the hot path.\n */\nexport async function writeProgress(\n directory: string,\n callId: string,\n step: ProgressStep,\n now = Date.now(),\n): Promise<void> {\n const endpoint = step.provider === undefined ? undefined : await endpointOf(step.provider);\n const parameters =\n step.parameters === undefined ? undefined : await parametersOf(step.parameters);\n const saved: SavedProgress = {\n version: 1,\n at: now,\n phase: step.phase,\n operation: sanitize(step.operation ?? 'request', 24) || 'request',\n ...(step.outcome !== undefined ? { outcome: sanitize(step.outcome, 40) } : {}),\n ...(endpoint !== undefined ? { endpoint } : {}),\n ...(parameters !== undefined ? { parameters } : {}),\n ...(step.price !== undefined ? { price: sanitize(step.price, 24) } : {}),\n };\n await write(join(directory, `${digest(callId)}.json`), saved);\n}\n\nexport interface LookupFooter {\n /** A decision is in flight. */\n routing(): Promise<void>;\n /** The EXECUTED provider, which can differ from what the hint suggested. */\n calling(step: { provider: string; parameters?: unknown }): Promise<void>;\n /** The outcome, and what the provider was paid for it. */\n done(\n outcome: string,\n step?: { provider?: string; parameters?: unknown; price?: string },\n ): Promise<void>;\n}\n\n/** A footer for a session this call cannot be attributed to: it writes nothing. */\nconst SILENT: LookupFooter = {\n routing: async () => undefined,\n calling: async () => undefined,\n done: async () => undefined,\n};\n\n/**\n * The `request` tool's footer: the session is resolved ONCE, at the top of the\n * call, and each later step is one small write. An unresolvable session yields\n * {@link SILENT}, and the lookup runs exactly as it would have.\n */\nexport async function openLookupFooter(\n dataDir: string,\n opts: { id?: string; operation?: string; now?: () => number } = {},\n): Promise<LookupFooter> {\n const now = opts.now ?? Date.now;\n const directory = await resolveProgressSession(dataDir, {\n ...(opts.id !== undefined ? { id: opts.id } : {}),\n now: now(),\n }).catch(() => null);\n if (directory === null) return SILENT;\n const callId = newCallId();\n const operation = opts.operation ?? 'request';\n const step = async (patch: ProgressStep): Promise<void> => {\n await writeProgress(directory, callId, { operation, ...patch }, now());\n };\n return {\n routing: async () => {\n await step({ phase: 'routing' });\n await pruneProgress(directory, now());\n },\n calling: async (calling) => step({ phase: 'calling', ...calling }),\n done: async (outcome, detail) => step({ phase: 'done', outcome, ...detail }),\n };\n}\n\n/**\n * Remove records past {@link EXPIRY_MS}. Run from a writer, never from the\n * renderer: the footer refreshes once a second and must stay read-only.\n */\nexport async function pruneProgress(directory: string, now = Date.now()): Promise<void> {\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return;\n if (!entry.isFile() || entry.name === SESSION_FILE) continue;\n const path = join(directory, entry.name);\n const record = agesByMtime(entry.name) ? await mtimeOf(path) : await readStamp(path);\n if (record === null || now - record.at > EXPIRY_MS) {\n await rm(path, { force: true }).catch(() => undefined);\n }\n }\n } catch {\n // Housekeeping only. Nothing downstream depends on it having run.\n }\n}\n\n/**\n * A FILE THAT IS NOT A WHOLE RECORD is aged by its mtime, never read as one: a\n * temp file between its write and its rename (every writer here names them\n * `.<name>.<suffix>`), and a docs body, whose size is the provider's. Read as\n * records they are damaged, and the prune deleted them out from under a\n * parallel hook's rename.\n */\nfunction agesByMtime(name: string): boolean {\n return name.startsWith('.') || (name.startsWith(AUGMENT_PREFIX) && !name.endsWith('.json'));\n}\n\nasync function mtimeOf(path: string): Promise<Stamp | null> {\n try {\n return { version: 1, at: (await lstat(path)).mtimeMs };\n } catch {\n return null;\n }\n}\n\n/**\n * Remove the directories of sessions that are over.\n *\n * WITHOUT THIS THE ROOT ONLY GROWS, one directory per session this machine has\n * ever had, and a root big enough to hit {@link MAX_SESSIONS} would leave\n * {@link resolveProgressSession} scanning an arbitrary subset that need not\n * contain the session asking. Run from the hook, which is the one writer that\n * fires on every turn; a directory whose session is still live is never touched.\n */\nexport async function pruneSessions(dataDir: string, now = Date.now()): Promise<void> {\n const root = join(dataDir, PROGRESS_DIR);\n try {\n const directory = await opendir(root);\n let seen = 0;\n for await (const entry of directory) {\n if (++seen > MAX_SESSIONS) return;\n if (!entry.isDirectory() || !/^[a-f0-9]{64}$/.test(entry.name)) continue;\n const path = join(root, entry.name);\n const session = await readStamp(join(path, SESSION_FILE));\n if (session !== null && now - session.at <= SESSION_ACTIVE_MS) continue;\n // The touch is gone or old, so the only thing that can keep this\n // directory is a record still inside the renderer's window.\n if (await hasLiveRecord(path, now)) continue;\n await rm(path, { recursive: true, force: true }).catch(() => undefined);\n }\n } catch {\n // Housekeeping only. Nothing downstream depends on it having run.\n }\n}\n\nasync function hasLiveRecord(directory: string, now: number): Promise<boolean> {\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return true;\n if (!entry.isFile() || entry.name === SESSION_FILE) continue;\n const record = await readStamp(join(directory, entry.name));\n if (record !== null && now - record.at <= EXPIRY_MS) return true;\n }\n } catch {\n return true;\n }\n return false;\n}\n\n/**\n * The footer for one session: one line, bounded, sanitized, and empty of\n * everything but this session's own calls. Read-only by construction.\n */\nexport async function renderProgress(\n dataDir: string,\n sessionId: string,\n options: { now?: number; columns?: number } = {},\n): Promise<string> {\n const now = options.now ?? Date.now();\n // The harness truncates to the real terminal width, and `COLUMNS` rarely\n // survives into a status-line process, so the default is a wide terminal\n // rather than a narrow one: cutting a provider's path off at 80 columns on a\n // 200-column terminal loses exactly the part worth reading.\n const columns = Math.max(45, Math.min(400, options.columns || 160));\n const directory = sessionDir(dataDir, sessionId);\n const records: SavedProgress[] = [];\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return bounded('x402 · activity exceeds display limit', columns);\n if (!entry.isFile() || !CALL_FILE_RE.test(entry.name)) continue;\n const record = await readCall(join(directory, entry.name));\n if (record !== null && now - record.at <= EXPIRY_MS) records.push(record);\n }\n } catch (error) {\n // A SESSION WITH NO DIRECTORY IS IDLE, not broken: it has simply not looked\n // anything up yet, and the router being on is the thing the idle line says.\n // Any OTHER read failure is this display failing, and a display that failed\n // prints nothing rather than a status it did not read.\n return (error as NodeJS.ErrnoException).code === 'ENOENT' ? READY : '';\n }\n const running = records\n .filter((row) => row.phase !== 'done' && now - row.at <= holdMs(row))\n .sort((a, b) => b.at - a.at);\n // Only a LOOKUP goes stale out loud. A hook decision has a five-second budget,\n // so one still in flight after its hold is a dead hook, and the footer says\n // ready rather than naming a stage nothing is working on.\n const stale = records.filter(\n (row) => row.phase !== 'done' && now - row.at > holdMs(row) && row.operation === 'request',\n );\n const finished = records\n .filter((row) => row.phase === 'done' && now - row.at <= RECENT_MS)\n .sort((a, b) => b.at - a.at);\n const head = running[0] ?? finished[0] ?? stale.sort((a, b) => b.at - a.at)[0];\n if (head === undefined) return READY;\n // OVERLAPPING CALLS ARE COUNTED, NOT HIDDEN. The newest running call is the\n // one worth naming; the rest are a count, because a second endpoint and its\n // parameters do not fit a line beside the first.\n const alsoRunning = running.length - (running[0] === head ? 1 : 0);\n const suffix = alsoRunning > 0 ? ` · +${alsoRunning} more` : '';\n return bounded(`${line(head, now)}${suffix}`, columns);\n}\n\n/** What the footer says when this session has nothing running or just finished.\n * It is the visible proof that the router is on, so it is never blank. */\nconst READY = 'x402 · ready';\n\n/**\n * How long this state holds the line. A lookup in flight holds it until it\n * lands, because a provider call can take a minute; everything else holds it\n * for {@link RECENT_MS}, which is how the demo reads: one state per second or\n * so, each one still there when the next arrives.\n */\nfunction holdMs(row: SavedProgress): number {\n return row.phase !== 'done' && row.operation === 'request' ? STALE_AFTER_MS : RECENT_MS;\n}\n\n/**\n * One call, as the footer says it: `x402 · <tool>: <state> <host/path> ·\n * <parameters> · <price>`. Every field is sanitized AGAIN here, because what is\n * on disk is input to this process even when this process wrote it.\n */\nfunction line(row: SavedProgress, now: number): string {\n const operation = sanitize(row.operation, 24) || 'request';\n if (row.phase !== 'done' && now - row.at > STALE_AFTER_MS) {\n return `x402 · ${operation}: stale, no outcome recorded`;\n }\n // `selecting service` is the demo's own word for a decision in flight, and a\n // stage the hook names for itself wins over it.\n const state =\n row.phase === 'routing'\n ? sanitize(row.outcome ?? 'selecting service', 40)\n : row.phase === 'calling'\n ? 'calling'\n : sanitize(row.outcome ?? 'done', 40);\n return (\n `x402 · ${operation}: ${state}` +\n (row.endpoint !== undefined ? ` ${sanitize(row.endpoint, 110)}` : '') +\n (row.parameters !== undefined ? ` · ${sanitize(row.parameters, 180)}` : '') +\n (row.price !== undefined ? ` · ${sanitize(row.price, 24)}` : '')\n );\n}\n\n/** Whether it landed. Every caller but the augment marker ignores the answer. */\nasync function write(path: string, body: Stamp | SavedProgress | SavedAugment): Promise<boolean> {\n try {\n await writeFileAtomic(path, JSON.stringify(body), { mode: 0o600, dirMode: 0o700 });\n return true;\n } catch {\n // The footer is the only thing that can be lost here, by design.\n return false;\n }\n}\n\n/** A marker's timestamp, or null for absent, damaged or not ours. */\nasync function readStamp(path: string): Promise<Stamp | null> {\n return stampOf(await readJson(path));\n}\n\nfunction stampOf(row: Record<string, unknown> | null): Stamp | null {\n if (row === null) return null;\n return row.version === 1 && typeof row.at === 'number' && Number.isFinite(row.at)\n ? { version: 1, at: row.at }\n : null;\n}\n\n/** A call record, or null. Every field is re-checked: what is on disk is input. */\nasync function readCall(path: string): Promise<SavedProgress | null> {\n const row = await readJson(path);\n const stamp = stampOf(row);\n if (row === null || stamp === null || typeof row.operation !== 'string') return null;\n if (!['routing', 'calling', 'done'].includes(row.phase as string)) return null;\n const optional = ['outcome', 'endpoint', 'parameters', 'price'] as const;\n if (!optional.every((key) => row[key] === undefined || typeof row[key] === 'string')) return null;\n return {\n ...stamp,\n phase: row.phase as ProgressPhase,\n operation: row.operation,\n ...Object.fromEntries(\n optional.filter((key) => row[key] !== undefined).map((key) => [key, row[key]]),\n ),\n };\n}\n\n/**\n * One bounded JSON object, or null. `O_NOFOLLOW` because these files live under\n * a directory the user can write: a symlink planted here must not turn a footer\n * read into a read of something else.\n */\nasync function readJson(path: string): Promise<Record<string, unknown> | null> {\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => undefined);\n if (file === undefined) return null;\n try {\n if ((await file.stat()).size > MAX_RECORD_BYTES) return null;\n const buffer = Buffer.alloc(MAX_RECORD_BYTES + 1);\n const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);\n if (bytesRead > MAX_RECORD_BYTES) return null;\n const parsed: unknown = JSON.parse(buffer.subarray(0, bytesRead).toString('utf8'));\n return parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)\n ? null\n : (parsed as Record<string, unknown>);\n } catch {\n return null;\n } finally {\n await file.close().catch(() => undefined);\n }\n}\n"],"mappings":";;;;;;;AAAA,SAAS,YAAY,kBAAkB;AACvC,SAAS,iBAAiB;AAC1B,SAAS,OAAO,MAAM,SAAS,UAAU;AACzC,SAAS,YAAY;AAiCrB,IAAM,eAAe;AAErB,IAAM,iBAAiB;AAEvB,IAAM,eAAe;AAErB,IAAM,eAAe;AAErB,IAAM,kBAAkB;AAExB,IAAM,iBAAiB;AAGvB,IAAM,sBAAsB;AAE5B,IAAM,eAAe;AAErB,IAAM,eAAe;AAGd,IAAM,iBAAiB;AAOvB,IAAM,YAAY;AAElB,IAAM,YAAY,KAAK;AAEvB,IAAM,oBAAoB,KAAK;AAE/B,IAAM,oBAAoB,IAAI;AAErC,IAAM,cAAc;AAGpB,IAAM,eAAe;AAErB,IAAM,mBAAmB;AAyCzB,IAAM,SAAS,CAAC,UAA0B,WAAW,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK;AAEzF,SAAS,QAAQ,OAAe,OAAuB;AACrD,QAAM,QAAQ,MAAM,KAAK,KAAK;AAC9B,SAAO,MAAM,UAAU,QAAQ,QAAQ,GAAG,MAAM,MAAM,GAAG,QAAQ,CAAC,EAAE,KAAK,EAAE,CAAC;AAC9E;AAQO,SAAS,SAAS,OAAe,OAAuB;AAC7D,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AM,EAAE,SAAS,IAAI,KAAe,EAAG,QAAO;AAC1E,QAAM,WAAW,CAAC,WAAW,YAAY,cAAc,OAAO;AAC9D,MAAI,CAAC,SAAS,MAAM,CAAC,QAAQ,IAAI,GAAG,MAAM,UAAa,OAAO,IAAI,GAAG,MAAM,QAAQ,EAAG,QAAO;AAC7F,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO,IAAI;AAAA,IACX,WAAW,IAAI;AAAA,IACf,GAAG,OAAO;AAAA,MACR,SAAS,OAAO,CAAC,QAAQ,IAAI,GAAG,MAAM,MAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,KAAK,IAAI,GAAG,CAAC,CAAC;AAAA,IAC/E;AAAA,EACF;AACF;AAOA,eAAe,SAAS,MAAuD;AAC7E,QAAM,OAAO,MAAM,KAAK,MAAM,UAAU,WAAW,UAAU,UAAU,EAAE,MAAM,MAAM,MAAS;AAC9F,MAAI,SAAS,OAAW,QAAO;AAC/B,MAAI;AACF,SAAK,MAAM,KAAK,KAAK,GAAG,OAAO,iBAAkB,QAAO;AACxD,UAAM,SAAS,OAAO,MAAM,mBAAmB,CAAC;AAChD,UAAM,EAAE,UAAU,IAAI,MAAM,KAAK,KAAK,QAAQ,GAAG,OAAO,QAAQ,CAAC;AACjE,QAAI,YAAY,iBAAkB,QAAO;AACzC,UAAM,SAAkB,KAAK,MAAM,OAAO,SAAS,GAAG,SAAS,EAAE,SAAS,MAAM,CAAC;AACjF,WAAO,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,IACxE,OACC;AAAA,EACP,QAAQ;AACN,WAAO;AAAA,EACT,UAAE;AACA,UAAM,KAAK,MAAM,EAAE,MAAM,MAAM,MAAS;AAAA,EAC1C;AACF;","names":[]}
|
package/dist/chunk-TGLKKLQG.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
|
|
3
|
-
// src/router/names.ts
|
|
4
|
-
var MCP_SERVER_NAME = "x402";
|
|
5
|
-
var REQUEST_TOOL = `mcp__${MCP_SERVER_NAME}__request`;
|
|
6
|
-
|
|
7
|
-
export {
|
|
8
|
-
MCP_SERVER_NAME,
|
|
9
|
-
REQUEST_TOOL
|
|
10
|
-
};
|
|
11
|
-
//# sourceMappingURL=chunk-TGLKKLQG.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/names.ts"],"sourcesContent":["/**\n * THE NAMES THE HARNESS KNOWS THE ROUTER BY, spelled once. `install` registers\n * the MCP server under {@link MCP_SERVER_NAME}, and Claude Code exposes its tool\n * as {@link REQUEST_TOOL}; the permission rule, the server's own name and every\n * hint line the hooks inject all read these, so a rename moves them together.\n *\n * A module of its own because the hooks need the tool name and must not load\n * `install` to get it: their chunk graph is the product's floor.\n */\nexport const MCP_SERVER_NAME = 'x402';\nexport const REQUEST_TOOL = `mcp__${MCP_SERVER_NAME}__request`;\n"],"mappings":";;;AASO,IAAM,kBAAkB;AACxB,IAAM,eAAe,QAAQ,eAAe;","names":[]}
|