tenjin-cli 0.1.0-alpha.2 → 0.1.0-alpha.21
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/NOTICE.md +54 -7
- package/README.md +175 -256
- package/dist/{_esm-FEASBWRP.js → _esm-CE7KNONL.js} +9 -10
- package/dist/{ccip-NQXCEK2U.js → ccip-7RMRLAGV.js} +4 -4
- package/dist/{ccip-XR5NE5QK.js → ccip-NLCSCHKI.js} +5 -5
- package/dist/chunk-2AQO4YDI.js +291 -0
- package/dist/chunk-2AQO4YDI.js.map +1 -0
- package/dist/chunk-2QYORQBF.js +55 -0
- package/dist/chunk-2QYORQBF.js.map +1 -0
- package/dist/chunk-3EUTWC2B.js +194 -0
- package/dist/chunk-3EUTWC2B.js.map +1 -0
- package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
- package/dist/chunk-7QKHZQKW.js +1680 -0
- package/dist/chunk-7QKHZQKW.js.map +1 -0
- package/dist/chunk-A36LQPHV.js +29 -0
- package/dist/chunk-A36LQPHV.js.map +1 -0
- package/dist/{chunk-XJIW7USF.js → chunk-AQRUD5GQ.js} +115 -11
- package/dist/chunk-AQRUD5GQ.js.map +1 -0
- package/dist/{chunk-UGX7YPX2.js → chunk-AWQPGIR6.js} +7 -9
- package/dist/{chunk-UGX7YPX2.js.map → chunk-AWQPGIR6.js.map} +1 -1
- package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
- package/dist/chunk-C363JZN2.js +127 -0
- package/dist/chunk-C363JZN2.js.map +1 -0
- package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
- package/dist/chunk-ETW2ASBP.js +10562 -0
- package/dist/chunk-ETW2ASBP.js.map +1 -0
- package/dist/chunk-GHTPYKDT.js +112 -0
- package/dist/chunk-GHTPYKDT.js.map +1 -0
- package/dist/{chunk-CYOF7ROH.js → chunk-HPWO4O6S.js} +3 -3
- package/dist/chunk-IOB7URFH.js +242 -0
- package/dist/chunk-IOB7URFH.js.map +1 -0
- package/dist/chunk-IOIHYOU4.js +1784 -0
- package/dist/chunk-IOIHYOU4.js.map +1 -0
- package/dist/chunk-JLEF5WHM.js +132 -0
- package/dist/chunk-JLEF5WHM.js.map +1 -0
- package/dist/chunk-JN7TMXVF.js +172 -0
- package/dist/chunk-JN7TMXVF.js.map +1 -0
- package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
- package/dist/chunk-K6AXXYCG.js +109 -0
- package/dist/chunk-K6AXXYCG.js.map +1 -0
- package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
- package/dist/chunk-LAIZ2AQA.js +107 -0
- package/dist/chunk-LAIZ2AQA.js.map +1 -0
- package/dist/chunk-LHHMV4GU.js +27 -0
- package/dist/chunk-LHHMV4GU.js.map +1 -0
- package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
- package/dist/chunk-MEFB5KHA.js.map +1 -0
- package/dist/{chunk-NCE5NSN6.js → chunk-N35E6CM2.js} +140 -10
- package/dist/chunk-N35E6CM2.js.map +1 -0
- package/dist/chunk-N4DJEQAF.js +190 -0
- package/dist/chunk-N4DJEQAF.js.map +1 -0
- package/dist/chunk-O2JYBOUO.js +47 -0
- package/dist/chunk-O2JYBOUO.js.map +1 -0
- package/dist/chunk-OSUD6YZZ.js +451 -0
- package/dist/chunk-OSUD6YZZ.js.map +1 -0
- package/dist/chunk-OTPEH3AH.js +926 -0
- package/dist/chunk-OTPEH3AH.js.map +1 -0
- package/dist/chunk-PJEG2JIJ.js +242 -0
- package/dist/chunk-PJEG2JIJ.js.map +1 -0
- package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
- package/dist/chunk-QF4SSCQV.js +377 -0
- package/dist/chunk-QF4SSCQV.js.map +1 -0
- package/dist/chunk-QHILSA6G.js +82 -0
- package/dist/chunk-QHILSA6G.js.map +1 -0
- package/dist/chunk-QRFONFRW.js +231 -0
- package/dist/chunk-QRFONFRW.js.map +1 -0
- package/dist/{chunk-N62ROTMC.js → chunk-RCJQARZF.js} +14 -10
- package/dist/chunk-RCJQARZF.js.map +1 -0
- package/dist/{chunk-S3IGX57D.js → chunk-RGVOODF4.js} +7703 -7475
- package/dist/chunk-RGVOODF4.js.map +1 -0
- package/dist/chunk-S2NRVRPF.js +171 -0
- package/dist/chunk-S2NRVRPF.js.map +1 -0
- package/dist/chunk-SRVDXR6B.js +337 -0
- package/dist/chunk-SRVDXR6B.js.map +1 -0
- package/dist/chunk-TGLKKLQG.js +11 -0
- package/dist/chunk-TGLKKLQG.js.map +1 -0
- package/dist/{chunk-RRN3YTK7.js → chunk-TTNESUPQ.js} +3 -3
- package/dist/chunk-U2ATFMKZ.js +164 -0
- package/dist/chunk-U2ATFMKZ.js.map +1 -0
- package/dist/chunk-UY2TOI3B.js +208 -0
- package/dist/chunk-UY2TOI3B.js.map +1 -0
- package/dist/{chunk-OYMYCW7J.js → chunk-W3LVZ2EN.js} +605 -97
- package/dist/chunk-W3LVZ2EN.js.map +1 -0
- package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
- package/dist/{chunk-Z6MFJV5Z.js → chunk-YVODPFTL.js} +851 -500
- package/dist/chunk-YVODPFTL.js.map +1 -0
- package/dist/{cli-4NNBEQYH.js → cli-7KJ4QLUU.js} +367 -216
- package/dist/cli-7KJ4QLUU.js.map +1 -0
- package/dist/config-MSN6H4MD.js +41 -0
- package/dist/dist-3LOO6M4U.js +2842 -0
- package/dist/dist-3LOO6M4U.js.map +1 -0
- package/dist/doctor-ITUCKN6C.js +453 -0
- package/dist/doctor-ITUCKN6C.js.map +1 -0
- package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
- package/dist/fund-XPB4IIG5.js +298 -0
- package/dist/fund-XPB4IIG5.js.map +1 -0
- package/dist/hook-command-VVV2Q23L.js +1265 -0
- package/dist/hook-command-VVV2Q23L.js.map +1 -0
- package/dist/index.js +11 -3
- package/dist/index.js.map +1 -1
- package/dist/install-OSJRM2ME.js +63 -0
- package/dist/install-identity-YIWKQOUD.js +27 -0
- package/dist/install-wallet-BWJO2SUC.js +107 -0
- package/dist/install-wallet-BWJO2SUC.js.map +1 -0
- package/dist/mcp-KE5YKPS2.js +10174 -0
- package/dist/mcp-KE5YKPS2.js.map +1 -0
- package/dist/paths-MUXHUOCM.js +57 -0
- package/dist/pay-MUV2U232.js +46 -0
- package/dist/payments-4D27K4L2.js +48 -0
- package/dist/payments-4D27K4L2.js.map +1 -0
- package/dist/redact-6W23GGJC.js +15 -0
- package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
- package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
- package/dist/send-BXHFKDBF.js +225 -0
- package/dist/send-BXHFKDBF.js.map +1 -0
- package/dist/status-3Z3YPRSE.js +71 -0
- package/dist/status-3Z3YPRSE.js.map +1 -0
- package/dist/status-line-CKRMGZ3Q.js +87 -0
- package/dist/status-line-CKRMGZ3Q.js.map +1 -0
- package/dist/status-line-wiring-GECLIIBT.js +29 -0
- package/dist/status-line-wiring-GECLIIBT.js.map +1 -0
- package/dist/tenjin-daemon.mjs +20598 -0
- package/dist/tenjin-shim.mjs +251 -0
- package/dist/tenjin-vitest-reporter.mjs +49 -0
- package/dist/uninstall-BZTVWJ7W.js +165 -0
- package/dist/uninstall-BZTVWJ7W.js.map +1 -0
- package/dist/update-IQQTEOI5.js +433 -0
- package/dist/update-IQQTEOI5.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
- package/dist/viemAdapter-By13KInL-X2VY6CY3.js.map +1 -0
- package/dist/wallet-UFXQ57TZ.js +33 -0
- package/dist/wallet-UFXQ57TZ.js.map +1 -0
- package/dist/wallet-kdf-worker.mjs +980 -0
- package/docs/agent-permissions.md +141 -0
- package/docs/safety-model.md +70 -0
- package/package.json +14 -9
- package/LICENSE +0 -21
- package/dist/buy-U35DQ6XM.js +0 -1598
- package/dist/buy-U35DQ6XM.js.map +0 -1
- package/dist/candidate-RLYCQMF5.js +0 -127
- package/dist/candidate-RLYCQMF5.js.map +0 -1
- package/dist/chunk-27ONARHV.js +0 -171
- package/dist/chunk-27ONARHV.js.map +0 -1
- package/dist/chunk-3OV7E5G5.js +0 -18
- package/dist/chunk-3OV7E5G5.js.map +0 -1
- package/dist/chunk-7KUW4MJD.js +0 -59
- package/dist/chunk-7KUW4MJD.js.map +0 -1
- package/dist/chunk-7PHSZKQS.js +0 -333
- package/dist/chunk-7PHSZKQS.js.map +0 -1
- package/dist/chunk-IYLHQMT5.js +0 -211
- package/dist/chunk-IYLHQMT5.js.map +0 -1
- package/dist/chunk-JPHG2JW3.js +0 -96
- package/dist/chunk-JPHG2JW3.js.map +0 -1
- package/dist/chunk-MUBUQVC3.js +0 -67
- package/dist/chunk-MUBUQVC3.js.map +0 -1
- package/dist/chunk-N62ROTMC.js.map +0 -1
- package/dist/chunk-NCE5NSN6.js.map +0 -1
- package/dist/chunk-OYMYCW7J.js.map +0 -1
- package/dist/chunk-QNP7H47L.js +0 -152
- package/dist/chunk-QNP7H47L.js.map +0 -1
- package/dist/chunk-RY4XKNV3.js +0 -140
- package/dist/chunk-RY4XKNV3.js.map +0 -1
- package/dist/chunk-S3IGX57D.js.map +0 -1
- package/dist/chunk-TFGSOPWR.js +0 -261
- package/dist/chunk-TFGSOPWR.js.map +0 -1
- package/dist/chunk-TLCMMYLY.js +0 -126
- package/dist/chunk-TLCMMYLY.js.map +0 -1
- package/dist/chunk-UO22YNY4.js +0 -69
- package/dist/chunk-UO22YNY4.js.map +0 -1
- package/dist/chunk-UPIEAMGH.js +0 -160
- package/dist/chunk-UPIEAMGH.js.map +0 -1
- package/dist/chunk-XJIW7USF.js.map +0 -1
- package/dist/chunk-YBMMV4Y4.js.map +0 -1
- package/dist/chunk-YIYQ2ZNT.js +0 -286
- package/dist/chunk-YIYQ2ZNT.js.map +0 -1
- package/dist/chunk-YN5SHIXQ.js +0 -126
- package/dist/chunk-YN5SHIXQ.js.map +0 -1
- package/dist/chunk-Z52RA3NC.js +0 -137
- package/dist/chunk-Z52RA3NC.js.map +0 -1
- package/dist/chunk-Z6MFJV5Z.js.map +0 -1
- package/dist/cli-4NNBEQYH.js.map +0 -1
- package/dist/config-2VSXWWHK.js +0 -21
- package/dist/doctor-JJPNIBYH.js +0 -20
- package/dist/inspect-JGYJWFDP.js +0 -96
- package/dist/inspect-JGYJWFDP.js.map +0 -1
- package/dist/install-ZQRMSRGW.js +0 -378
- package/dist/install-ZQRMSRGW.js.map +0 -1
- package/dist/lookup-WYVTOMVY.js +0 -113
- package/dist/lookup-WYVTOMVY.js.map +0 -1
- package/dist/outcome-HKKT6QIA.js +0 -66
- package/dist/outcome-HKKT6QIA.js.map +0 -1
- package/dist/publish-D76B3MBK.js +0 -1480
- package/dist/publish-D76B3MBK.js.map +0 -1
- package/dist/usdc-JIAJW4SV.js +0 -22
- package/dist/wallet-6QKS6UHW.js +0 -179
- package/dist/wallet-6QKS6UHW.js.map +0 -1
- package/dist/wallet-PA54CRBL.js +0 -30
- package/skills/tenjin/SKILL.md +0 -199
- package/skills/tenjin-publish/SKILL.md +0 -96
- package/skills/tenjin-search/SKILL.md +0 -122
- /package/dist/{_esm-FEASBWRP.js.map → _esm-CE7KNONL.js.map} +0 -0
- /package/dist/{ccip-NQXCEK2U.js.map → ccip-7RMRLAGV.js.map} +0 -0
- /package/dist/{ccip-XR5NE5QK.js.map → ccip-NLCSCHKI.js.map} +0 -0
- /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
- /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
- /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
- /package/dist/{chunk-CYOF7ROH.js.map → chunk-HPWO4O6S.js.map} +0 -0
- /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
- /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
- /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
- /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
- /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
- /package/dist/{config-2VSXWWHK.js.map → config-MSN6H4MD.js.map} +0 -0
- /package/dist/{doctor-JJPNIBYH.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → install-OSJRM2ME.js.map} +0 -0
- /package/dist/{secp256k1-N3ZHU7LB.js.map → install-identity-YIWKQOUD.js.map} +0 -0
- /package/dist/{usdc-JIAJW4SV.js.map → paths-MUXHUOCM.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → pay-MUV2U232.js.map} +0 -0
- /package/dist/{wallet-PA54CRBL.js.map → redact-6W23GGJC.js.map} +0 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
MCP_SERVER_NAME,
|
|
4
|
+
REQUEST_TOOL
|
|
5
|
+
} from "./chunk-TGLKKLQG.js";
|
|
6
|
+
|
|
7
|
+
// src/router/agent-tools.ts
|
|
8
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
9
|
+
import { dirname, join, resolve } from "node:path";
|
|
10
|
+
var MCP_INHERITING_BUILTINS = /* @__PURE__ */ new Set([
|
|
11
|
+
"general-purpose",
|
|
12
|
+
"Explore",
|
|
13
|
+
"Plan"
|
|
14
|
+
]);
|
|
15
|
+
var MAX_AGENT_FILE_BYTES = 256 * 1024;
|
|
16
|
+
var TYPE_RE = /^[A-Za-z0-9_.:-]{1,200}$/;
|
|
17
|
+
async function requestToolAccess(agentType, lookup) {
|
|
18
|
+
if (agentType === void 0 || !TYPE_RE.test(agentType)) return "unknown";
|
|
19
|
+
try {
|
|
20
|
+
const text = await findDefinition(agentType, lookup);
|
|
21
|
+
if (text !== null) return accessOf(text);
|
|
22
|
+
return MCP_INHERITING_BUILTINS.has(agentType) ? "allowed" : "unknown";
|
|
23
|
+
} catch {
|
|
24
|
+
return "unknown";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function accessOf(definition) {
|
|
28
|
+
const frontmatter = frontmatterOf(definition);
|
|
29
|
+
if (frontmatter === null) return "unknown";
|
|
30
|
+
const disallowed = listField(frontmatter, "disallowedTools");
|
|
31
|
+
if (disallowed !== void 0 && disallowed.some(namesRequestTool)) return "excluded";
|
|
32
|
+
const tools = listField(frontmatter, "tools");
|
|
33
|
+
if (tools === void 0) return "allowed";
|
|
34
|
+
return tools.some(namesRequestTool) ? "allowed" : "excluded";
|
|
35
|
+
}
|
|
36
|
+
function namesRequestTool(tool) {
|
|
37
|
+
if (tool === REQUEST_TOOL || tool === `mcp__${MCP_SERVER_NAME}`) return true;
|
|
38
|
+
return tool.endsWith("*") && REQUEST_TOOL.startsWith(tool.slice(0, -1));
|
|
39
|
+
}
|
|
40
|
+
async function agentsWithoutRequestTool(lookup) {
|
|
41
|
+
const found = [];
|
|
42
|
+
const seen = /* @__PURE__ */ new Set();
|
|
43
|
+
for (const directory of agentDirs(lookup)) {
|
|
44
|
+
for (const { name, text } of await definitionsIn(directory)) {
|
|
45
|
+
const type = nameOf(text) ?? name;
|
|
46
|
+
if (seen.has(type)) continue;
|
|
47
|
+
seen.add(type);
|
|
48
|
+
if (accessOf(text) === "excluded") found.push(type);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return found.sort();
|
|
52
|
+
}
|
|
53
|
+
async function findDefinition(agentType, lookup) {
|
|
54
|
+
for (const directory of agentDirs(lookup)) {
|
|
55
|
+
const text = await definitionIn(directory, agentType);
|
|
56
|
+
if (text !== null) return text;
|
|
57
|
+
}
|
|
58
|
+
const colon = agentType.indexOf(":");
|
|
59
|
+
if (colon > 0) {
|
|
60
|
+
const plugin = agentType.slice(0, colon);
|
|
61
|
+
const agent = agentType.slice(colon + 1);
|
|
62
|
+
for (const root of await pluginRoots(plugin, lookup.homeDir)) {
|
|
63
|
+
const text = await definitionIn(join(root, "agents"), agent);
|
|
64
|
+
if (text !== null) return text;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
function agentDirs(lookup) {
|
|
70
|
+
const dirs = [];
|
|
71
|
+
if (lookup.cwd !== void 0 && lookup.cwd.length > 0) {
|
|
72
|
+
let current = resolve(lookup.cwd);
|
|
73
|
+
for (; ; ) {
|
|
74
|
+
dirs.push(join(current, ".claude", "agents"));
|
|
75
|
+
const parent = dirname(current);
|
|
76
|
+
if (parent === current) break;
|
|
77
|
+
current = parent;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const user = join(resolve(lookup.homeDir), ".claude", "agents");
|
|
81
|
+
return [...dirs.filter((d) => d !== user), user];
|
|
82
|
+
}
|
|
83
|
+
async function definitionIn(directory, agentType) {
|
|
84
|
+
const direct = await readBounded(join(directory, `${agentType}.md`));
|
|
85
|
+
if (direct !== null && (nameOf(direct) ?? agentType) === agentType) return direct;
|
|
86
|
+
for (const { text } of await definitionsIn(directory)) {
|
|
87
|
+
if (nameOf(text) === agentType) return text;
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
async function definitionsIn(directory) {
|
|
92
|
+
let names;
|
|
93
|
+
try {
|
|
94
|
+
names = (await readdir(directory)).filter((n) => n.endsWith(".md")).slice(0, 200);
|
|
95
|
+
} catch {
|
|
96
|
+
return [];
|
|
97
|
+
}
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const file of names) {
|
|
100
|
+
const text = await readBounded(join(directory, file));
|
|
101
|
+
if (text !== null) out.push({ name: file.slice(0, -3), text });
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
async function pluginRoots(plugin, homeDir) {
|
|
106
|
+
const raw = await readBounded(join(homeDir, ".claude", "plugins", "installed_plugins.json"));
|
|
107
|
+
if (raw === null) return [];
|
|
108
|
+
const parsed = JSON.parse(raw);
|
|
109
|
+
const roots = [];
|
|
110
|
+
for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {
|
|
111
|
+
if (key.split("@")[0] !== plugin || !Array.isArray(entries)) continue;
|
|
112
|
+
for (const entry of entries) {
|
|
113
|
+
const path = entry.installPath;
|
|
114
|
+
if (typeof path === "string" && path.length > 0) roots.push(path);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return roots;
|
|
118
|
+
}
|
|
119
|
+
async function readBounded(path) {
|
|
120
|
+
try {
|
|
121
|
+
const text = await readFile(path, "utf8");
|
|
122
|
+
return text.length > MAX_AGENT_FILE_BYTES ? null : text;
|
|
123
|
+
} catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function frontmatterOf(text) {
|
|
128
|
+
const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
|
|
129
|
+
const open = lines.findIndex((l) => l.trim().length > 0);
|
|
130
|
+
if (open === -1 || lines[open]?.trim() !== "---") return null;
|
|
131
|
+
const end = lines.findIndex((l, i) => i > open && l.trim() === "---");
|
|
132
|
+
return end === -1 ? null : lines.slice(open + 1, end);
|
|
133
|
+
}
|
|
134
|
+
function nameOf(text) {
|
|
135
|
+
const frontmatter = frontmatterOf(text);
|
|
136
|
+
if (frontmatter === null) return null;
|
|
137
|
+
const line = frontmatter.find((l) => /^name\s*:/.test(l));
|
|
138
|
+
const value = line === void 0 ? "" : unquote(line.slice(line.indexOf(":") + 1).trim());
|
|
139
|
+
return value.length > 0 ? value : null;
|
|
140
|
+
}
|
|
141
|
+
function listField(frontmatter, key) {
|
|
142
|
+
const index = frontmatter.findIndex((l) => new RegExp(`^${key}\\s*:`).test(l));
|
|
143
|
+
if (index === -1) return void 0;
|
|
144
|
+
const line = frontmatter[index];
|
|
145
|
+
const inline = line.slice(line.indexOf(":") + 1).trim();
|
|
146
|
+
if (inline.length > 0) {
|
|
147
|
+
const body = inline.startsWith("[") && inline.endsWith("]") ? inline.slice(1, -1) : inline;
|
|
148
|
+
return body.split(",").map((part) => unquote(part.trim())).filter((part) => part.length > 0);
|
|
149
|
+
}
|
|
150
|
+
const items = [];
|
|
151
|
+
for (const next of frontmatter.slice(index + 1)) {
|
|
152
|
+
const item = /^\s+-\s*(.*)$/.exec(next);
|
|
153
|
+
if (item === null) {
|
|
154
|
+
if (next.trim().length === 0) continue;
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
const value = unquote(item[1].trim());
|
|
158
|
+
if (value.length > 0) items.push(value);
|
|
159
|
+
}
|
|
160
|
+
return items;
|
|
161
|
+
}
|
|
162
|
+
function unquote(value) {
|
|
163
|
+
const quoted = /^(['"])(.*)\1$/.exec(value);
|
|
164
|
+
return quoted === null ? value : quoted[2];
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export {
|
|
168
|
+
requestToolAccess,
|
|
169
|
+
agentsWithoutRequestTool
|
|
170
|
+
};
|
|
171
|
+
//# sourceMappingURL=chunk-S2NRVRPF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/agent-tools.ts"],"sourcesContent":["import { readdir, readFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { MCP_SERVER_NAME, REQUEST_TOOL } from './names';\n\n/**\n * CAN THIS SUBAGENT CALL `request` AT ALL? An offer to an agent whose definition\n * leaves the tool out is a line it cannot act on, and a router call spent to\n * write it. Claude Code defines a custom agent in a Markdown file whose\n * frontmatter may carry `tools:` (an allowlist) and `disallowedTools:`; this\n * reads that, and nothing else, and never writes to it.\n *\n * ONLY `allowed` IS ACTED ON. A subagent is redirected or offered a lookup\n * only when this KNOWS it can make the call: a definition whose tools cover\n * the request tool (or that has no `tools:` and so inherits everything), or a\n * built-in in {@link MCP_INHERITING_BUILTINS}. Every other built-in, and any\n * type with no definition this can find or read, is `unknown`, and `unknown`\n * gets no router call: `claude-code-guide` ships with Bash, Read, WebFetch and\n * WebSearch and no MCP tools, and denying its WebFetch would strand it exactly\n * as #377 reported.\n *\n * WHERE A DEFINITION LIVES, in the harness's own precedence: the project's\n * `.claude/agents` (from `cwd` up to the filesystem root, nearest first), then\n * `~/.claude/agents`, then an installed plugin's `agents/` for a `plugin:agent`\n * type. A file is found by its name first and by its frontmatter `name:`\n * second, because the type is the `name:` and the file name only usually\n * matches it.\n */\n\nexport type RequestToolAccess = 'allowed' | 'excluded' | 'unknown';\n\n/**\n * The built-in agent types that have no definition file and still inherit MCP\n * tools, so can call `mcp__x402__request`. From Claude Code's own Agent tool\n * listing (2.1.28x): `general-purpose` has every tool, and `Explore` and `Plan`\n * exclude only editing and agent tools, never MCP. Built-ins with a fixed tool\n * list, such as `claude-code-guide` (Bash, Read, WebFetch, WebSearch) and\n * `statusline-setup` (Read, Edit), are deliberately absent.\n */\nexport const MCP_INHERITING_BUILTINS: ReadonlySet<string> = new Set([\n 'general-purpose',\n 'Explore',\n 'Plan',\n]);\n\nexport interface AgentLookup {\n cwd?: string;\n homeDir: string;\n}\n\nconst MAX_AGENT_FILE_BYTES = 256 * 1024;\nconst TYPE_RE = /^[A-Za-z0-9_.:-]{1,200}$/;\n\nexport async function requestToolAccess(\n agentType: string | undefined,\n lookup: AgentLookup,\n): Promise<RequestToolAccess> {\n if (agentType === undefined || !TYPE_RE.test(agentType)) return 'unknown';\n try {\n const text = await findDefinition(agentType, lookup);\n if (text !== null) return accessOf(text);\n return MCP_INHERITING_BUILTINS.has(agentType) ? 'allowed' : 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\n/** What one definition's frontmatter says about the request tool. */\nexport function accessOf(definition: string): RequestToolAccess {\n const frontmatter = frontmatterOf(definition);\n if (frontmatter === null) return 'unknown';\n const disallowed = listField(frontmatter, 'disallowedTools');\n if (disallowed !== undefined && disallowed.some(namesRequestTool)) return 'excluded';\n const tools = listField(frontmatter, 'tools');\n if (tools === undefined) return 'allowed';\n return tools.some(namesRequestTool) ? 'allowed' : 'excluded';\n}\n\n/**\n * Does one `tools:` or `disallowedTools:` entry cover the request tool? The\n * tool itself, the bare server, or any `*`-suffixed pattern the tool's name\n * starts with: `*`, `mcp__*`, `mcp__x402__*` and every prefix between.\n */\nfunction namesRequestTool(tool: string): boolean {\n if (tool === REQUEST_TOOL || tool === `mcp__${MCP_SERVER_NAME}`) return true;\n return tool.endsWith('*') && REQUEST_TOOL.startsWith(tool.slice(0, -1));\n}\n\n/**\n * Every custom agent this project and this user define whose tools leave the\n * request tool out, for `doctor` to name. Plugin agents are not listed: their\n * files are not the user's to edit.\n */\nexport async function agentsWithoutRequestTool(lookup: AgentLookup): Promise<string[]> {\n const found: string[] = [];\n const seen = new Set<string>();\n for (const directory of agentDirs(lookup)) {\n for (const { name, text } of await definitionsIn(directory)) {\n const type = nameOf(text) ?? name;\n if (seen.has(type)) continue;\n seen.add(type);\n if (accessOf(text) === 'excluded') found.push(type);\n }\n }\n return found.sort();\n}\n\nasync function findDefinition(agentType: string, lookup: AgentLookup): Promise<string | null> {\n for (const directory of agentDirs(lookup)) {\n const text = await definitionIn(directory, agentType);\n if (text !== null) return text;\n }\n const colon = agentType.indexOf(':');\n if (colon > 0) {\n const plugin = agentType.slice(0, colon);\n const agent = agentType.slice(colon + 1);\n for (const root of await pluginRoots(plugin, lookup.homeDir)) {\n const text = await definitionIn(join(root, 'agents'), agent);\n if (text !== null) return text;\n }\n }\n return null;\n}\n\nfunction agentDirs(lookup: AgentLookup): string[] {\n const dirs: string[] = [];\n if (lookup.cwd !== undefined && lookup.cwd.length > 0) {\n let current = resolve(lookup.cwd);\n for (;;) {\n dirs.push(join(current, '.claude', 'agents'));\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n }\n const user = join(resolve(lookup.homeDir), '.claude', 'agents');\n // The user's directory is also an ancestor of most projects; it counts once,\n // in its own place in the order.\n return [...dirs.filter((d) => d !== user), user];\n}\n\nasync function definitionIn(directory: string, agentType: string): Promise<string | null> {\n const direct = await readBounded(join(directory, `${agentType}.md`));\n if (direct !== null && (nameOf(direct) ?? agentType) === agentType) return direct;\n for (const { text } of await definitionsIn(directory)) {\n if (nameOf(text) === agentType) return text;\n }\n return null;\n}\n\nasync function definitionsIn(directory: string): Promise<{ name: string; text: string }[]> {\n let names: string[];\n try {\n names = (await readdir(directory)).filter((n) => n.endsWith('.md')).slice(0, 200);\n } catch {\n return [];\n }\n const out: { name: string; text: string }[] = [];\n for (const file of names) {\n const text = await readBounded(join(directory, file));\n if (text !== null) out.push({ name: file.slice(0, -3), text });\n }\n return out;\n}\n\n/** Install paths `installed_plugins.json` records for `<plugin>@<marketplace>`. */\nasync function pluginRoots(plugin: string, homeDir: string): Promise<string[]> {\n const raw = await readBounded(join(homeDir, '.claude', 'plugins', 'installed_plugins.json'));\n if (raw === null) return [];\n const parsed = JSON.parse(raw) as { plugins?: Record<string, unknown> };\n const roots: string[] = [];\n for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {\n if (key.split('@')[0] !== plugin || !Array.isArray(entries)) continue;\n for (const entry of entries) {\n const path = (entry as { installPath?: unknown }).installPath;\n if (typeof path === 'string' && path.length > 0) roots.push(path);\n }\n }\n return roots;\n}\n\nasync function readBounded(path: string): Promise<string | null> {\n try {\n const text = await readFile(path, 'utf8');\n return text.length > MAX_AGENT_FILE_BYTES ? null : text;\n } catch {\n return null;\n }\n}\n\nfunction frontmatterOf(text: string): string[] | null {\n const lines = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const open = lines.findIndex((l) => l.trim().length > 0);\n if (open === -1 || lines[open]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > open && l.trim() === '---');\n return end === -1 ? null : lines.slice(open + 1, end);\n}\n\nfunction nameOf(text: string): string | null {\n const frontmatter = frontmatterOf(text);\n if (frontmatter === null) return null;\n const line = frontmatter.find((l) => /^name\\s*:/.test(l));\n const value = line === undefined ? '' : unquote(line.slice(line.indexOf(':') + 1).trim());\n return value.length > 0 ? value : null;\n}\n\n/**\n * A top-level list field in the three spellings agent files use: `a, b, c`,\n * `[a, b]`, or a block of `- a` lines. `undefined` when the key is absent.\n */\nfunction listField(frontmatter: string[], key: string): string[] | undefined {\n const index = frontmatter.findIndex((l) => new RegExp(`^${key}\\\\s*:`).test(l));\n if (index === -1) return undefined;\n const line = frontmatter[index]!;\n const inline = line.slice(line.indexOf(':') + 1).trim();\n if (inline.length > 0) {\n const body = inline.startsWith('[') && inline.endsWith(']') ? inline.slice(1, -1) : inline;\n return body\n .split(',')\n .map((part) => unquote(part.trim()))\n .filter((part) => part.length > 0);\n }\n const items: string[] = [];\n for (const next of frontmatter.slice(index + 1)) {\n const item = /^\\s+-\\s*(.*)$/.exec(next);\n if (item === null) {\n if (next.trim().length === 0) continue;\n break;\n }\n const value = unquote(item[1]!.trim());\n if (value.length > 0) items.push(value);\n }\n return items;\n}\n\nfunction unquote(value: string): string {\n const quoted = /^(['\"])(.*)\\1$/.exec(value);\n return quoted === null ? value : quoted[2]!;\n}\n"],"mappings":";;;;;;;AAAA,SAAS,SAAS,gBAAgB;AAClC,SAAS,SAAS,MAAM,eAAe;AAqChC,IAAM,0BAA+C,oBAAI,IAAI;AAAA,EAClE;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOD,IAAM,uBAAuB,MAAM;AACnC,IAAM,UAAU;AAEhB,eAAsB,kBACpB,WACA,QAC4B;AAC5B,MAAI,cAAc,UAAa,CAAC,QAAQ,KAAK,SAAS,EAAG,QAAO;AAChE,MAAI;AACF,UAAM,OAAO,MAAM,eAAe,WAAW,MAAM;AACnD,QAA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C1C,SAAO,WAAW,OAAO,QAAQ,OAAO,CAAC;AAC3C;","names":[]}
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
resolvePublicDestination
|
|
4
|
+
} from "./chunk-LAIZ2AQA.js";
|
|
5
|
+
import {
|
|
6
|
+
USDC_ADDRESS
|
|
7
|
+
} from "./chunk-QHILSA6G.js";
|
|
8
|
+
import {
|
|
9
|
+
releaseUnchargedExposure
|
|
10
|
+
} from "./chunk-N4DJEQAF.js";
|
|
11
|
+
import {
|
|
12
|
+
mask
|
|
13
|
+
} from "./chunk-7QKHZQKW.js";
|
|
14
|
+
import {
|
|
15
|
+
withFileLock
|
|
16
|
+
} from "./chunk-MEFB5KHA.js";
|
|
17
|
+
import {
|
|
18
|
+
hasCode
|
|
19
|
+
} from "./chunk-2I4QTOLB.js";
|
|
20
|
+
import {
|
|
21
|
+
writeFileAtomic
|
|
22
|
+
} from "./chunk-JLEF5WHM.js";
|
|
23
|
+
import {
|
|
24
|
+
downloadsDir,
|
|
25
|
+
paidLedgerPath
|
|
26
|
+
} from "./chunk-K6AXXYCG.js";
|
|
27
|
+
|
|
28
|
+
// src/router/paid.ts
|
|
29
|
+
import { randomBytes } from "node:crypto";
|
|
30
|
+
import { appendFile, mkdir, open, readFile, rm } from "node:fs/promises";
|
|
31
|
+
import { request as httpsRequest } from "node:https";
|
|
32
|
+
import { dirname, join } from "node:path";
|
|
33
|
+
var MAX_SENT_CHARS = 4096;
|
|
34
|
+
function maskDeep(value) {
|
|
35
|
+
if (typeof value === "string") return mask(value);
|
|
36
|
+
if (Array.isArray(value)) return value.map(maskDeep);
|
|
37
|
+
if (value !== null && typeof value === "object") {
|
|
38
|
+
return Object.fromEntries(
|
|
39
|
+
Object.entries(value).map(([key, entry]) => [
|
|
40
|
+
mask(key),
|
|
41
|
+
maskDeep(entry)
|
|
42
|
+
])
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
function recordedSent(sent) {
|
|
48
|
+
return mask(sent).slice(0, MAX_SENT_CHARS);
|
|
49
|
+
}
|
|
50
|
+
async function appendPaidRecord(dataDir, record) {
|
|
51
|
+
try {
|
|
52
|
+
const path = paidLedgerPath(dataDir);
|
|
53
|
+
await mkdir(dirname(path), { recursive: true, mode: 448 });
|
|
54
|
+
await withFileLock(
|
|
55
|
+
`${path}.lock`,
|
|
56
|
+
() => appendFile(path, `${JSON.stringify(record)}
|
|
57
|
+
`, { mode: 384 })
|
|
58
|
+
);
|
|
59
|
+
} catch {
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
var AUTHORIZATION_STATE_SELECTOR = "0xe94a0102";
|
|
63
|
+
var WORD_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
64
|
+
var MAX_RECONCILE_CHECKS = 3;
|
|
65
|
+
var RECHECK_MS = 10 * 6e4;
|
|
66
|
+
var RECONCILE_TIMEOUT_MS = 1500;
|
|
67
|
+
async function authorizationUsed(authorization, rpcUrl, opts = {}) {
|
|
68
|
+
const result = await rpcCall(
|
|
69
|
+
rpcUrl,
|
|
70
|
+
"eth_call",
|
|
71
|
+
[
|
|
72
|
+
{
|
|
73
|
+
to: USDC_ADDRESS,
|
|
74
|
+
data: `${AUTHORIZATION_STATE_SELECTOR}${authorization.from.slice(2).toLowerCase().padStart(64, "0")}${authorization.nonce.slice(2).toLowerCase()}`
|
|
75
|
+
},
|
|
76
|
+
opts.blockTag ?? "latest"
|
|
77
|
+
],
|
|
78
|
+
opts
|
|
79
|
+
);
|
|
80
|
+
if (typeof result !== "string" || !WORD_RE.test(result)) return null;
|
|
81
|
+
return BigInt(result) !== 0n;
|
|
82
|
+
}
|
|
83
|
+
async function latestBlock(rpcUrl, opts = {}) {
|
|
84
|
+
const result = await rpcCall(rpcUrl, "eth_getBlockByNumber", ["latest", false], opts);
|
|
85
|
+
if (result === null || typeof result !== "object") return null;
|
|
86
|
+
const { number, timestamp } = result;
|
|
87
|
+
if (typeof number !== "string" || !/^0x[0-9a-fA-F]+$/.test(number)) return null;
|
|
88
|
+
if (typeof timestamp !== "string" || !/^0x[0-9a-fA-F]+$/.test(timestamp)) return null;
|
|
89
|
+
return { tag: number, timestamp: Number(BigInt(timestamp)) };
|
|
90
|
+
}
|
|
91
|
+
async function rpcCall(rpcUrl, method, params, opts) {
|
|
92
|
+
try {
|
|
93
|
+
const res = await (opts.fetchImpl ?? fetch)(rpcUrl, {
|
|
94
|
+
method: "POST",
|
|
95
|
+
headers: { "content-type": "application/json" },
|
|
96
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
97
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? RECONCILE_TIMEOUT_MS)
|
|
98
|
+
});
|
|
99
|
+
if (!res.ok) return null;
|
|
100
|
+
return (await res.json())?.result ?? null;
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async function reconcilePayments(dataDir, opts) {
|
|
106
|
+
const path = paidLedgerPath(dataDir);
|
|
107
|
+
const now = (opts.now ?? Date.now)();
|
|
108
|
+
const records = parseLedger(await readFile(path, "utf8").catch(() => ""));
|
|
109
|
+
const open2 = records.filter(
|
|
110
|
+
(entry) => entry.record !== null && entry.record.settlement === "unknown"
|
|
111
|
+
);
|
|
112
|
+
const recheckMs = opts.recheckMs ?? RECHECK_MS;
|
|
113
|
+
const due = open2.filter(
|
|
114
|
+
({ record }) => record.authorization !== void 0 && Number(record.authorization.validBefore) * 1e3 < now && (record.lastCheckedAt === void 0 || now - Date.parse(record.lastCheckedAt) >= recheckMs)
|
|
115
|
+
);
|
|
116
|
+
const answers = /* @__PURE__ */ new Map();
|
|
117
|
+
const asked = /* @__PURE__ */ new Set();
|
|
118
|
+
let checked = 0;
|
|
119
|
+
const rpc = {
|
|
120
|
+
...opts.fetchImpl !== void 0 ? { fetchImpl: opts.fetchImpl } : {},
|
|
121
|
+
...opts.timeoutMs !== void 0 ? { timeoutMs: opts.timeoutMs } : {}
|
|
122
|
+
};
|
|
123
|
+
const block = due.length > 0 ? await latestBlock(opts.rpcUrl, rpc) : null;
|
|
124
|
+
for (const { record } of due.slice(0, opts.max ?? MAX_RECONCILE_CHECKS)) {
|
|
125
|
+
if (block !== null && Number(record.authorization.validBefore) >= block.timestamp) continue;
|
|
126
|
+
checked += 1;
|
|
127
|
+
asked.add(record.authorization.nonce);
|
|
128
|
+
if (block === null) continue;
|
|
129
|
+
const used = await authorizationUsed(record.authorization, opts.rpcUrl, {
|
|
130
|
+
...rpc,
|
|
131
|
+
blockTag: block.tag
|
|
132
|
+
});
|
|
133
|
+
if (used !== null) answers.set(record.authorization.nonce, used ? "settled" : "not_charged");
|
|
134
|
+
}
|
|
135
|
+
let releasedAtomic = 0n;
|
|
136
|
+
for (const [nonce, answer] of [...answers]) {
|
|
137
|
+
if (answer !== "not_charged") continue;
|
|
138
|
+
const released = await releaseUnchargedExposure(dataDir, nonce, {
|
|
139
|
+
...opts.now !== void 0 ? { now: opts.now } : {}
|
|
140
|
+
});
|
|
141
|
+
if (released === null) answers.delete(nonce);
|
|
142
|
+
else releasedAtomic += released;
|
|
143
|
+
}
|
|
144
|
+
if (asked.size > 0) {
|
|
145
|
+
await withFileLock(`${path}.lock`, async () => {
|
|
146
|
+
const current = parseLedger(await readFile(path, "utf8").catch(() => ""));
|
|
147
|
+
const lines = current.map(({ line, record }) => {
|
|
148
|
+
const nonce = record?.settlement === "unknown" && record.authorization !== void 0 ? record.authorization.nonce : void 0;
|
|
149
|
+
if (nonce === void 0 || !asked.has(nonce)) return line;
|
|
150
|
+
const answer = answers.get(nonce);
|
|
151
|
+
const stamp = new Date(now).toISOString();
|
|
152
|
+
return JSON.stringify(
|
|
153
|
+
answer === void 0 ? { ...record, lastCheckedAt: stamp } : { ...record, settlement: answer, lastCheckedAt: stamp, reconciledAt: stamp }
|
|
154
|
+
);
|
|
155
|
+
});
|
|
156
|
+
await writeFileAtomic(path, lines.map((line) => `${line}
|
|
157
|
+
`).join(""), { mode: 384 });
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
const settled = [...answers.values()].filter((value) => value === "settled").length;
|
|
161
|
+
return {
|
|
162
|
+
checked,
|
|
163
|
+
settled,
|
|
164
|
+
notCharged: answers.size - settled,
|
|
165
|
+
unknown: open2.length - answers.size,
|
|
166
|
+
releasedAtomic: releasedAtomic.toString()
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function parseLedger(raw) {
|
|
170
|
+
return raw.split("\n").filter((line) => line.trim().length > 0).map((line) => {
|
|
171
|
+
try {
|
|
172
|
+
const value = JSON.parse(line);
|
|
173
|
+
return { line, record: value !== null && value.version === 1 ? value : null };
|
|
174
|
+
} catch {
|
|
175
|
+
return { line, record: null };
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
180
|
+
"png",
|
|
181
|
+
"jpg",
|
|
182
|
+
"jpeg",
|
|
183
|
+
"webp",
|
|
184
|
+
"gif",
|
|
185
|
+
"svg",
|
|
186
|
+
"mp3",
|
|
187
|
+
"wav",
|
|
188
|
+
"m4a",
|
|
189
|
+
"ogg",
|
|
190
|
+
"mp4",
|
|
191
|
+
"webm",
|
|
192
|
+
"mov"
|
|
193
|
+
]);
|
|
194
|
+
var MAX_MEDIA_FILES = 5;
|
|
195
|
+
var MAX_MEDIA_BYTES = 200 * 1024 * 1024;
|
|
196
|
+
var MEDIA_TIMEOUT_MS = 6e4;
|
|
197
|
+
var MAX_REDIRECTS = 3;
|
|
198
|
+
var URL_RE = /https:\/\/[^\s"'<>\\]+/g;
|
|
199
|
+
function mediaUrlsIn(result, limit = MAX_MEDIA_FILES) {
|
|
200
|
+
const found = [];
|
|
201
|
+
for (const match of result.matchAll(URL_RE)) {
|
|
202
|
+
if (found.length >= limit) break;
|
|
203
|
+
let url;
|
|
204
|
+
try {
|
|
205
|
+
url = new URL(match[0]);
|
|
206
|
+
} catch {
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const ext = url.pathname.split(".").pop()?.toLowerCase() ?? "";
|
|
210
|
+
if (!url.pathname.includes(".") || !MEDIA_EXTENSIONS.has(ext)) continue;
|
|
211
|
+
if (!found.includes(url.toString())) found.push(url.toString());
|
|
212
|
+
}
|
|
213
|
+
return found;
|
|
214
|
+
}
|
|
215
|
+
var pinnedGet = (target, signal) => new Promise((resolve, reject) => {
|
|
216
|
+
const req = httpsRequest(
|
|
217
|
+
target.url,
|
|
218
|
+
{
|
|
219
|
+
method: "GET",
|
|
220
|
+
signal,
|
|
221
|
+
lookup: pinnedLookup(target)
|
|
222
|
+
},
|
|
223
|
+
(res) => {
|
|
224
|
+
const length = Number(res.headers["content-length"]);
|
|
225
|
+
const location = res.headers.location;
|
|
226
|
+
resolve({
|
|
227
|
+
status: res.statusCode ?? 0,
|
|
228
|
+
...typeof location === "string" ? { location } : {},
|
|
229
|
+
...Number.isFinite(length) ? { contentLength: length } : {},
|
|
230
|
+
body: res,
|
|
231
|
+
discard: () => res.destroy()
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
);
|
|
235
|
+
req.on("error", reject);
|
|
236
|
+
req.end();
|
|
237
|
+
});
|
|
238
|
+
function pinnedLookup(target) {
|
|
239
|
+
return ((_host, options, callback) => {
|
|
240
|
+
if (options.all === true) {
|
|
241
|
+
callback(null, [{ address: target.address, family: target.family }]);
|
|
242
|
+
} else {
|
|
243
|
+
callback(null, target.address, target.family);
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
async function saveMedia(dataDir, stem, urls, deps = {}) {
|
|
248
|
+
const saved = [];
|
|
249
|
+
for (const [index, url] of urls.entries()) {
|
|
250
|
+
const path = await saveOne(dataDir, `${stem}-${index + 1}`, url, deps);
|
|
251
|
+
if (path !== null) saved.push(path);
|
|
252
|
+
}
|
|
253
|
+
return saved;
|
|
254
|
+
}
|
|
255
|
+
async function saveOne(dataDir, stem, raw, deps) {
|
|
256
|
+
const transport = deps.transport ?? pinnedGet;
|
|
257
|
+
const maxBytes = deps.maxBytes ?? MAX_MEDIA_BYTES;
|
|
258
|
+
const signal = AbortSignal.timeout(deps.timeoutMs ?? MEDIA_TIMEOUT_MS);
|
|
259
|
+
let target = raw;
|
|
260
|
+
let path = null;
|
|
261
|
+
try {
|
|
262
|
+
let res = null;
|
|
263
|
+
for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
|
|
264
|
+
const pinned = await resolvePublicDestination(target, deps.destination ?? {});
|
|
265
|
+
res = await transport(pinned, signal);
|
|
266
|
+
if (res.status < 300 || res.status >= 400 || res.location === void 0) break;
|
|
267
|
+
res.discard();
|
|
268
|
+
target = new URL(res.location, target).toString();
|
|
269
|
+
res = null;
|
|
270
|
+
}
|
|
271
|
+
if (res === null || res.status < 200 || res.status >= 300) {
|
|
272
|
+
res?.discard();
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
if ((res.contentLength ?? 0) > maxBytes) {
|
|
276
|
+
res.discard();
|
|
277
|
+
return null;
|
|
278
|
+
}
|
|
279
|
+
const ext = new URL(target).pathname.split(".").pop()?.toLowerCase() ?? "bin";
|
|
280
|
+
const file = await createUniqueFile(
|
|
281
|
+
downloadsDir(dataDir),
|
|
282
|
+
`${stem}-${(deps.now ?? Date.now)()}`,
|
|
283
|
+
MEDIA_EXTENSIONS.has(ext) ? ext : "bin"
|
|
284
|
+
);
|
|
285
|
+
path = file.path;
|
|
286
|
+
let size = 0;
|
|
287
|
+
try {
|
|
288
|
+
for await (const chunk of res.body) {
|
|
289
|
+
size += chunk.byteLength;
|
|
290
|
+
if (size > maxBytes) {
|
|
291
|
+
res.discard();
|
|
292
|
+
throw new Error("media over the size cap");
|
|
293
|
+
}
|
|
294
|
+
await writeAll(file.handle, chunk);
|
|
295
|
+
}
|
|
296
|
+
} finally {
|
|
297
|
+
await file.handle.close();
|
|
298
|
+
}
|
|
299
|
+
return path;
|
|
300
|
+
} catch {
|
|
301
|
+
if (path !== null) await rm(path, { force: true }).catch(() => void 0);
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
async function writeAll(handle, bytes) {
|
|
306
|
+
let offset = 0;
|
|
307
|
+
while (offset < bytes.byteLength) {
|
|
308
|
+
const { bytesWritten } = await handle.write(bytes, offset, bytes.byteLength - offset);
|
|
309
|
+
if (bytesWritten <= 0) throw new Error("the file write made no progress");
|
|
310
|
+
offset += bytesWritten;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
async function createUniqueFile(directory, stem, ext) {
|
|
314
|
+
await mkdir(directory, { recursive: true });
|
|
315
|
+
const safe = stem.replace(/[^A-Za-z0-9_-]+/g, "-").slice(0, 100) || "lookup";
|
|
316
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
317
|
+
const path = join(directory, `${safe}-${randomBytes(4).toString("hex")}.${ext}`);
|
|
318
|
+
try {
|
|
319
|
+
return { path, handle: await open(path, "wx", 384) };
|
|
320
|
+
} catch (err) {
|
|
321
|
+
if (attempt >= 4 || !hasCode(err, "EEXIST")) throw err;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export {
|
|
327
|
+
maskDeep,
|
|
328
|
+
recordedSent,
|
|
329
|
+
appendPaidRecord,
|
|
330
|
+
reconcilePayments,
|
|
331
|
+
MAX_MEDIA_FILES,
|
|
332
|
+
mediaUrlsIn,
|
|
333
|
+
saveMedia,
|
|
334
|
+
writeAll,
|
|
335
|
+
createUniqueFile
|
|
336
|
+
};
|
|
337
|
+
//# sourceMappingURL=chunk-SRVDXR6B.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/paid.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { appendFile, mkdir, open, readFile, rm, type FileHandle } from 'node:fs/promises';\nimport { request as httpsRequest } from 'node:https';\nimport type { LookupFunction } from 'node:net';\nimport { dirname, join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { resolvePublicDestination, type DestinationOptions } from '../lib/destination';\nimport { hasCode } from '../lib/errno';\nimport { withFileLock } from '../lib/lock';\nimport { downloadsDir, paidLedgerPath } from '../lib/paths';\nimport { mask } from '../lib/redact';\nimport { USDC_ADDRESS } from '../lib/usdc-balance';\nimport { releaseUnchargedExposure } from '../lib/wallet/spend';\n\n/**\n * WHAT A PAID ROUTER CALL BOUGHT, KEPT ON THIS MACHINE. One JSON line per paid\n * call in `~/.tenjin/paid/ledger.jsonl`: who was paid, for what, how much, the\n * settlement it carried and the files it saved. It is the user's own record\n * and the receipt `tenjin payments reconcile` resolves an unknown settlement\n * against. Nothing here can fail a lookup: every write swallows its own error.\n */\n\nexport type Settlement = 'settled' | 'unknown' | 'not_charged';\n\n/** The EIP-3009 authorization that was signed, enough to ask the token later\n * whether it was used. */\nexport interface SignedAuthorization {\n from: string;\n nonce: string;\n /** Unix seconds; after it the authorization can no longer be used. */\n validBefore: string;\n}\n\nexport interface PaidRecord {\n version: 1;\n ts: string;\n capabilityId: string;\n provider: string;\n url: string;\n /** The input or query sent, masked and cut to {@link MAX_SENT_CHARS}. */\n sent: string;\n amountAtomic: string;\n txHash?: string;\n settlement: Settlement;\n savedFiles: string[];\n authorization?: SignedAuthorization;\n /** When reconcile last asked the chain about it, so a slow or rate-limited\n * RPC is not asked about the same record on every lookup. */\n lastCheckedAt?: string;\n}\n\nexport const MAX_SENT_CHARS = 4_096;\n\n/**\n * A JSON value with every object key and string leaf masked on its own. The\n * mask anchors on word boundaries, which a serialized string hides: after an\n * escaped `\\n` a key reads as `nsk-ant-…`, one word, and passes.\n */\nexport function maskDeep(value: unknown): unknown {\n if (typeof value === 'string') return mask(value);\n if (Array.isArray(value)) return value.map(maskDeep);\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n mask(key),\n maskDeep(entry),\n ]),\n );\n }\n return value;\n}\n\n/** The input or query as it is recorded: secrets masked, then cut. */\nexport function recordedSent(sent: string): string {\n return mask(sent).slice(0, MAX_SENT_CHARS);\n}\n\nexport async function appendPaidRecord(dataDir: string, record: PaidRecord): Promise<void> {\n try {\n const path = paidLedgerPath(dataDir);\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n // Under the lock reconcile rewrites with, so an append is never lost to it.\n await withFileLock(`${path}.lock`, () =>\n appendFile(path, `${JSON.stringify(record)}\\n`, { mode: 0o600 }),\n );\n } catch {\n // The record is the user's convenience; the lookup already happened.\n }\n}\n\n/** `authorizationState(address,bytes32)`: the first four bytes of its keccak-256. */\nconst AUTHORIZATION_STATE_SELECTOR = '0xe94a0102';\nconst WORD_RE = /^0x[0-9a-fA-F]{64}$/;\n/** How many unknown settlements one pass asks the chain about. */\nexport const MAX_RECONCILE_CHECKS = 3;\n/** How long a record the chain could not answer for waits before it is asked\n * about again by the lookup-time pass. */\nexport const RECHECK_MS = 10 * 60_000;\nconst RECONCILE_TIMEOUT_MS = 1_500;\n\n/**\n * Whether USDC on Base has used this authorization: true once a facilitator\n * settled it, false while it has not. Null when the RPC could not say.\n */\nexport async function authorizationUsed(\n authorization: SignedAuthorization,\n rpcUrl: string,\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number; blockTag?: string } = {},\n): Promise<boolean | null> {\n const result = await rpcCall(\n rpcUrl,\n 'eth_call',\n [\n {\n to: USDC_ADDRESS,\n data: `${AUTHORIZATION_STATE_SELECTOR}${authorization.from.slice(2).toLowerCase().padStart(64, '0')}${authorization.nonce.slice(2).toLowerCase()}`,\n },\n opts.blockTag ?? 'latest',\n ],\n opts,\n );\n if (typeof result !== 'string' || !WORD_RE.test(result)) return null;\n return BigInt(result) !== 0n;\n}\n\n/**\n * The chain's own clock: the latest block's number and timestamp (seconds).\n * Expiry is decided against it, not this machine's clock, and the state is\n * read at that same block: a node that lags, or a clock running ahead, then\n * agrees with itself. Null when the RPC could not say.\n */\nexport async function latestBlock(\n rpcUrl: string,\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number } = {},\n): Promise<{ tag: string; timestamp: number } | null> {\n const result = await rpcCall(rpcUrl, 'eth_getBlockByNumber', ['latest', false], opts);\n if (result === null || typeof result !== 'object') return null;\n const { number, timestamp } = result as { number?: unknown; timestamp?: unknown };\n if (typeof number !== 'string' || !/^0x[0-9a-fA-F]+$/.test(number)) return null;\n if (typeof timestamp !== 'string' || !/^0x[0-9a-fA-F]+$/.test(timestamp)) return null;\n return { tag: number, timestamp: Number(BigInt(timestamp)) };\n}\n\nasync function rpcCall(\n rpcUrl: string,\n method: string,\n params: unknown[],\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number },\n): Promise<unknown> {\n try {\n const res = await (opts.fetchImpl ?? fetch)(rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),\n signal: AbortSignal.timeout(opts.timeoutMs ?? RECONCILE_TIMEOUT_MS),\n });\n if (!res.ok) return null;\n return ((await res.json()) as { result?: unknown } | null)?.result ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface ReconcileOutcome {\n /** Records asked about in this pass. */\n checked: number;\n /** The authorization was used: the amount was charged. */\n settled: number;\n /** It expired unused: nothing was charged. */\n notCharged: number;\n /** Still unknown: not yet expired, no authorization on record, or the RPC\n * could not answer. */\n unknown: number;\n /** What the not-charged payments gave back to today's automatic budget. */\n releasedAtomic: string;\n}\n\n/**\n * RESOLVE \"SETTLEMENT UNKNOWN\" FROM THE CHAIN. A paid call whose seller never\n * confirmed settlement leaves a record marked `unknown`. Once the chain's\n * latest block is past its authorization's `validBefore`, the token's own\n * `authorizationState(from, nonce)` read AT THAT BLOCK is final: used means\n * charged, unused means it can never be charged, since no later block can\n * carry it. This machine's clock only decides whether the chain is worth\n * asking. At most `max` records are asked about per pass, and\n * a record the RPC cannot answer for stays unknown, stamped `lastCheckedAt`,\n * and is not asked about again for `recheckMs`.\n *\n * The chain is asked outside the lock; the file is re-read and rewritten under\n * it, so an append made meanwhile is kept.\n */\nexport async function reconcilePayments(\n dataDir: string,\n opts: {\n rpcUrl: string;\n fetchImpl?: typeof fetch;\n now?: () => number;\n max?: number;\n timeoutMs?: number;\n /** Defaults to {@link RECHECK_MS}; the command passes 0. */\n recheckMs?: number;\n },\n): Promise<ReconcileOutcome> {\n const path = paidLedgerPath(dataDir);\n const now = (opts.now ?? Date.now)();\n const records = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n const open = records.filter(\n (entry): entry is { line: string; record: PaidRecord } =>\n entry.record !== null && entry.record.settlement === 'unknown',\n );\n const recheckMs = opts.recheckMs ?? RECHECK_MS;\n const due = open.filter(\n ({ record }) =>\n record.authorization !== undefined &&\n Number(record.authorization.validBefore) * 1_000 < now &&\n (record.lastCheckedAt === undefined || now - Date.parse(record.lastCheckedAt) >= recheckMs),\n );\n const answers = new Map<string, Settlement>();\n const asked = new Set<string>();\n let checked = 0;\n const rpc = {\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n };\n const block = due.length > 0 ? await latestBlock(opts.rpcUrl, rpc) : null;\n for (const { record } of due.slice(0, opts.max ?? MAX_RECONCILE_CHECKS)) {\n // Not past validBefore on the chain yet: not asked, and not stamped.\n if (block !== null && Number(record.authorization!.validBefore) >= block.timestamp) continue;\n checked += 1;\n asked.add(record.authorization!.nonce);\n if (block === null) continue;\n const used = await authorizationUsed(record.authorization!, opts.rpcUrl, {\n ...rpc,\n blockTag: block.tag,\n });\n if (used !== null) answers.set(record.authorization!.nonce, used ? 'settled' : 'not_charged');\n }\n // NOT CHARGED GIVES THE DAILY BUDGET BACK FIRST: exactly that payment's\n // exposure, by its nonce, while it is still inside the window that counted\n // it. Only then is the record marked; a release that could not be written\n // leaves it unknown, and the next pass asks again. A second release of the\n // same nonce finds nothing, so a retry never gives back twice.\n let releasedAtomic = 0n;\n for (const [nonce, answer] of [...answers]) {\n if (answer !== 'not_charged') continue;\n const released = await releaseUnchargedExposure(dataDir, nonce, {\n ...(opts.now !== undefined ? { now: opts.now } : {}),\n });\n if (released === null) answers.delete(nonce);\n else releasedAtomic += released;\n }\n if (asked.size > 0) {\n await withFileLock(`${path}.lock`, async () => {\n const current = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n const lines = current.map(({ line, record }) => {\n const nonce =\n record?.settlement === 'unknown' && record.authorization !== undefined\n ? record.authorization.nonce\n : undefined;\n if (nonce === undefined || !asked.has(nonce)) return line;\n const answer = answers.get(nonce);\n const stamp = new Date(now).toISOString();\n return JSON.stringify(\n answer === undefined\n ? { ...record, lastCheckedAt: stamp }\n : { ...record, settlement: answer, lastCheckedAt: stamp, reconciledAt: stamp },\n );\n });\n await writeFileAtomic(path, lines.map((line) => `${line}\\n`).join(''), { mode: 0o600 });\n });\n }\n const settled = [...answers.values()].filter((value) => value === 'settled').length;\n return {\n checked,\n settled,\n notCharged: answers.size - settled,\n unknown: open.length - answers.size,\n releasedAtomic: releasedAtomic.toString(),\n };\n}\n\n/** Every line, and the record it holds when it is one; other lines ride along. */\nfunction parseLedger(raw: string): { line: string; record: PaidRecord | null }[] {\n return raw\n .split('\\n')\n .filter((line) => line.trim().length > 0)\n .map((line) => {\n try {\n const value = JSON.parse(line) as PaidRecord;\n return { line, record: value !== null && value.version === 1 ? value : null };\n } catch {\n return { line, record: null };\n }\n });\n}\n\n/** The media a paid result links to, by the extension its path ends in. */\nconst MEDIA_EXTENSIONS = new Set([\n 'png',\n 'jpg',\n 'jpeg',\n 'webp',\n 'gif',\n 'svg',\n 'mp3',\n 'wav',\n 'm4a',\n 'ogg',\n 'mp4',\n 'webm',\n 'mov',\n]);\nexport const MAX_MEDIA_FILES = 5;\nexport const MAX_MEDIA_BYTES = 200 * 1024 * 1024;\nexport const MEDIA_TIMEOUT_MS = 60_000;\nconst MAX_REDIRECTS = 3;\nconst URL_RE = /https:\\/\\/[^\\s\"'<>\\\\]+/g;\n\n/** Every https URL in the result whose path ends in a media extension, in\n * order and without repeats, at most {@link MAX_MEDIA_FILES}. */\nexport function mediaUrlsIn(result: string, limit = MAX_MEDIA_FILES): string[] {\n const found: string[] = [];\n for (const match of result.matchAll(URL_RE)) {\n if (found.length >= limit) break;\n let url: URL;\n try {\n url = new URL(match[0]);\n } catch {\n continue;\n }\n const ext = url.pathname.split('.').pop()?.toLowerCase() ?? '';\n if (!url.pathname.includes('.') || !MEDIA_EXTENSIONS.has(ext)) continue;\n if (!found.includes(url.toString())) found.push(url.toString());\n }\n return found;\n}\n\n/** One GET the media download makes, connected to the address it validated. */\nexport interface PinnedTarget {\n url: URL;\n /** The address `resolvePublicDestination` checked; the socket goes here. */\n address: string;\n family: 4 | 6;\n}\n\nexport interface MediaResponse {\n status: number;\n location?: string;\n contentLength?: number;\n body: AsyncIterable<Uint8Array>;\n /** Drop the connection without reading the rest. */\n discard: () => void;\n}\n\nexport type MediaTransport = (target: PinnedTarget, signal: AbortSignal) => Promise<MediaResponse>;\n\nexport interface MediaDeps {\n /** Test seam; production connects with {@link pinnedGet}. */\n transport?: MediaTransport;\n destination?: DestinationOptions;\n now?: () => number;\n timeoutMs?: number;\n maxBytes?: number;\n}\n\n/**\n * CONNECT TO THE ADDRESS THAT WAS CHECKED. `fetch` resolves the name again on\n * its own, so a host answering publicly to the check and privately a moment\n * later (DNS rebinding) would get the request. `node:https` with a `lookup`\n * that hands back the one validated address closes that: the socket goes to\n * it, and TLS still verifies the certificate against the URL's own host name.\n */\nexport const pinnedGet: MediaTransport = (target, signal) =>\n new Promise((resolve, reject) => {\n const req = httpsRequest(\n target.url,\n {\n method: 'GET',\n signal,\n lookup: pinnedLookup(target),\n },\n (res) => {\n const length = Number(res.headers['content-length']);\n const location = res.headers.location;\n resolve({\n status: res.statusCode ?? 0,\n ...(typeof location === 'string' ? { location } : {}),\n ...(Number.isFinite(length) ? { contentLength: length } : {}),\n body: res,\n discard: () => res.destroy(),\n });\n },\n );\n req.on('error', reject);\n req.end();\n });\n\n/** A `lookup` that answers every name with the one validated address. */\nexport function pinnedLookup(target: Pick<PinnedTarget, 'address' | 'family'>): LookupFunction {\n return ((_host: string, options: { all?: boolean }, callback: LookupCallback) => {\n if (options.all === true) {\n callback(null, [{ address: target.address, family: target.family }]);\n } else {\n callback(null, target.address, target.family);\n }\n }) as unknown as LookupFunction;\n}\n\ntype LookupCallback = (\n err: Error | null,\n address: string | { address: string; family: number }[],\n family?: number,\n) => void;\n\n/**\n * Download each URL into the downloads dir, one at a time, each under its own\n * size cap and deadline, every hop of a redirect validated and connected to\n * the address it validated. Returns the paths that were written; a URL that\n * fails is skipped and never fails the call.\n */\nexport async function saveMedia(\n dataDir: string,\n stem: string,\n urls: string[],\n deps: MediaDeps = {},\n): Promise<string[]> {\n const saved: string[] = [];\n for (const [index, url] of urls.entries()) {\n const path = await saveOne(dataDir, `${stem}-${index + 1}`, url, deps);\n if (path !== null) saved.push(path);\n }\n return saved;\n}\n\nasync function saveOne(\n dataDir: string,\n stem: string,\n raw: string,\n deps: MediaDeps,\n): Promise<string | null> {\n const transport = deps.transport ?? pinnedGet;\n const maxBytes = deps.maxBytes ?? MAX_MEDIA_BYTES;\n const signal = AbortSignal.timeout(deps.timeoutMs ?? MEDIA_TIMEOUT_MS);\n let target = raw;\n let path: string | null = null;\n try {\n let res: MediaResponse | null = null;\n for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {\n const pinned = await resolvePublicDestination(target, deps.destination ?? {});\n res = await transport(pinned, signal);\n if (res.status < 300 || res.status >= 400 || res.location === undefined) break;\n res.discard();\n target = new URL(res.location, target).toString();\n res = null;\n }\n if (res === null || res.status < 200 || res.status >= 300) {\n res?.discard();\n return null;\n }\n if ((res.contentLength ?? 0) > maxBytes) {\n res.discard();\n return null;\n }\n const ext = new URL(target).pathname.split('.').pop()?.toLowerCase() ?? 'bin';\n const file = await createUniqueFile(\n downloadsDir(dataDir),\n `${stem}-${(deps.now ?? Date.now)()}`,\n MEDIA_EXTENSIONS.has(ext) ? ext : 'bin',\n );\n path = file.path;\n let size = 0;\n try {\n for await (const chunk of res.body) {\n size += chunk.byteLength;\n if (size > maxBytes) {\n res.discard();\n throw new Error('media over the size cap');\n }\n await writeAll(file.handle, chunk);\n }\n } finally {\n await file.handle.close();\n }\n return path;\n } catch {\n if (path !== null) await rm(path, { force: true }).catch(() => undefined);\n return null;\n }\n}\n\n/**\n * EVERY BYTE, OR A THROW. `FileHandle.write` may write fewer bytes than it was\n * handed and says so only in `bytesWritten`; a caller that ignores it saves a\n * file with a hole in it. A write that makes no progress is an error.\n */\nexport async function writeAll(\n handle: Pick<FileHandle, 'write'>,\n bytes: Uint8Array,\n): Promise<void> {\n let offset = 0;\n while (offset < bytes.byteLength) {\n const { bytesWritten } = await handle.write(bytes, offset, bytes.byteLength - offset);\n if (bytesWritten <= 0) throw new Error('the file write made no progress');\n offset += bytesWritten;\n }\n}\n\n/**\n * A NEW FILE, NEVER ANOTHER CALL'S. The name is the stem plus a random suffix,\n * created with an exclusive flag, so two lookups finishing in the same\n * millisecond each get their own file; a clash is retried with a new suffix.\n */\nexport async function createUniqueFile(\n directory: string,\n stem: string,\n ext: string,\n): Promise<{ path: string; handle: FileHandle }> {\n await mkdir(directory, { recursive: true });\n const safe = stem.replace(/[^A-Za-z0-9_-]+/g, '-').slice(0, 100) || 'lookup';\n for (let attempt = 0; ; attempt += 1) {\n const path = join(directory, `${safe}-${randomBytes(4).toString('hex')}.${ext}`);\n try {\n return { path, handle: await open(path, 'wx', 0o600) };\n } catch (err) {\n if (attempt >= 4 || !hasCode(err, 'EEXIST')) throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,mBAAmB;AAC5B,SAAS,YAAY,OAAO,MAAM,UAAU,U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ACf,MAAI,SAAS;AACb,SAAO,SAAS,MAAM,YAAY;AAChC,UAAM,EAAE,aAAa,IAAI,MAAM,OAAO,MAAM,OAAO,QAAQ,MAAM,aAAa,MAAM;AACpF,QAAI,gBAAgB,EAAG,OAAM,IAAI,MAAM,iCAAiC;AACxE,cAAU;AAAA,EACZ;AACF;AAOA,eAAsB,iBACpB,WACA,MACA,KAC+C;AAC/C,QAAM,MAAM,WAAW,EAAE,WAAW,KAAK,CAAC;AAC1C,QAAM,OAAO,KAAK,QAAQ,oBAAoB,GAAG,EAAE,MAAM,GAAG,GAAG,KAAK;AACpE,WAAS,UAAU,KAAK,WAAW,GAAG;AACpC,UAAM,OAAO,KAAK,WAAW,GAAG,IAAI,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,IAAI,GAAG,EAAE;AAC/E,QAAI;AACF,aAAO,EAAE,MAAM,QAAQ,MAAM,KAAK,MAAM,MAAM,GAAK,EAAE;AAAA,IACvD,SAAS,KAAK;AACZ,UAAI,WAAW,KAAK,CAAC,QAAQ,KAAK,QAAQ,EAAG,OAAM;AAAA,IACrD;AAAA,EACF;AACF;","names":["open"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
keccak_256
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-KG3D7FIF.js";
|
|
5
5
|
|
|
6
6
|
// node_modules/.pnpm/abitype@1.2.3_typescript@6.0.3_zod@3.25.76/node_modules/abitype/dist/esm/version.js
|
|
7
7
|
var version = "1.2.3";
|
|
@@ -5630,7 +5630,7 @@ async function call(client, args) {
|
|
|
5630
5630
|
if (isAbortError(err))
|
|
5631
5631
|
throw err;
|
|
5632
5632
|
const data2 = getRevertErrorData(err);
|
|
5633
|
-
const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await import("./ccip-
|
|
5633
|
+
const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await import("./ccip-7RMRLAGV.js");
|
|
5634
5634
|
if (client.ccipRead !== false && data2?.slice(0, 10) === offchainLookupSignature2 && to)
|
|
5635
5635
|
return {
|
|
5636
5636
|
data: await offchainLookup2(client, { data: data2, requestOptions, to })
|
|
@@ -6196,4 +6196,4 @@ export {
|
|
|
6196
6196
|
ccipRequest,
|
|
6197
6197
|
call
|
|
6198
6198
|
};
|
|
6199
|
-
//# sourceMappingURL=chunk-
|
|
6199
|
+
//# sourceMappingURL=chunk-TTNESUPQ.js.map
|