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,164 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
hasCode
|
|
4
|
+
} from "./chunk-2I4QTOLB.js";
|
|
5
|
+
import {
|
|
6
|
+
external_exports
|
|
7
|
+
} from "./chunk-W3LVZ2EN.js";
|
|
8
|
+
import {
|
|
9
|
+
spendLedgerPath
|
|
10
|
+
} from "./chunk-K6AXXYCG.js";
|
|
11
|
+
|
|
12
|
+
// src/lib/spend-ledger.ts
|
|
13
|
+
import { readFile } from "node:fs/promises";
|
|
14
|
+
var DEFAULT_WINDOW_MS = 864e5;
|
|
15
|
+
var RESERVATION_TTL_MS = 6e5;
|
|
16
|
+
var ReservationSchema = external_exports.object({
|
|
17
|
+
id: external_exports.string(),
|
|
18
|
+
amountAtomic: external_exports.string().regex(/^\d+$/),
|
|
19
|
+
atMs: external_exports.number(),
|
|
20
|
+
/** Optional so a ledger written by an older build still parses. */
|
|
21
|
+
requestKey: external_exports.string().optional(),
|
|
22
|
+
mode: external_exports.enum(["automatic", "manual"]).optional()
|
|
23
|
+
});
|
|
24
|
+
var ExposureSchema = external_exports.object({
|
|
25
|
+
nonce: external_exports.string(),
|
|
26
|
+
amountAtomic: external_exports.string().regex(/^\d+$/),
|
|
27
|
+
atMs: external_exports.number(),
|
|
28
|
+
mode: external_exports.enum(["automatic", "manual"]).optional()
|
|
29
|
+
});
|
|
30
|
+
var LedgerSchema = external_exports.object({
|
|
31
|
+
schemaVersion: external_exports.literal(2),
|
|
32
|
+
windowStartMs: external_exports.number(),
|
|
33
|
+
/**
|
|
34
|
+
* EXPOSURE: every authorization this window transmitted. A signed EIP-3009
|
|
35
|
+
* authorization is a bearer instrument, so total exposure stays recorded,
|
|
36
|
+
* whatever any counterparty later says it took.
|
|
37
|
+
*/
|
|
38
|
+
committedAtomic: external_exports.string().regex(/^\d+$/),
|
|
39
|
+
automaticCommittedAtomic: external_exports.string().regex(/^\d+$/).optional(),
|
|
40
|
+
/**
|
|
41
|
+
* SETTLED: what counterparties reported actually taking, which the router's
|
|
42
|
+
* waived outcomes made a different number from the line above (2026-09-23
|
|
43
|
+
* lookup contract). Optional so a ledger an older build wrote still parses;
|
|
44
|
+
* absent means "everything committed was settled", which is what that build
|
|
45
|
+
* assumed. Reporting only, never a budget input: under-counting exposure
|
|
46
|
+
* because a server said "no charge" is exactly the hole this avoids.
|
|
47
|
+
*/
|
|
48
|
+
settledAtomic: external_exports.string().regex(/^\d+$/).optional(),
|
|
49
|
+
reservations: external_exports.array(ReservationSchema),
|
|
50
|
+
/** Optional so a ledger an older build wrote still parses; such a ledger
|
|
51
|
+
* simply has nothing a reconcile can release. */
|
|
52
|
+
exposures: external_exports.array(ExposureSchema).optional()
|
|
53
|
+
});
|
|
54
|
+
function emptyLedger(nowMs) {
|
|
55
|
+
return {
|
|
56
|
+
schemaVersion: 2,
|
|
57
|
+
windowStartMs: nowMs,
|
|
58
|
+
committedAtomic: "0",
|
|
59
|
+
automaticCommittedAtomic: "0",
|
|
60
|
+
settledAtomic: "0",
|
|
61
|
+
reservations: []
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function spentOf(ledger) {
|
|
65
|
+
return ledger.reservations.reduce(
|
|
66
|
+
(sum, r) => sum + (r.mode === "manual" ? 0n : BigInt(r.amountAtomic)),
|
|
67
|
+
BigInt(ledger.automaticCommittedAtomic ?? ledger.committedAtomic)
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
async function readLedger(path) {
|
|
71
|
+
let raw;
|
|
72
|
+
try {
|
|
73
|
+
raw = await readFile(path, "utf8");
|
|
74
|
+
} catch (err) {
|
|
75
|
+
if (hasCode(err, "ENOENT")) return { ledger: null };
|
|
76
|
+
return { ledger: null, corrupt: err instanceof Error ? err.message : String(err) };
|
|
77
|
+
}
|
|
78
|
+
let json;
|
|
79
|
+
try {
|
|
80
|
+
json = JSON.parse(raw);
|
|
81
|
+
} catch {
|
|
82
|
+
return { ledger: null, corrupt: "not valid JSON" };
|
|
83
|
+
}
|
|
84
|
+
const parsed = LedgerSchema.safeParse(json);
|
|
85
|
+
if (parsed.success) return { ledger: parsed.data };
|
|
86
|
+
const issue = parsed.error.issues[0];
|
|
87
|
+
const field = issue?.path.join(".");
|
|
88
|
+
const message = issue?.message ?? "schema mismatch";
|
|
89
|
+
return {
|
|
90
|
+
ledger: null,
|
|
91
|
+
corrupt: field !== void 0 && field.length > 0 ? `${field}: ${message}` : message
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
async function readSpendSummary(dir, opts = {}) {
|
|
95
|
+
const { ledger } = await readLedger(spendLedgerPath(dir));
|
|
96
|
+
if (ledger === null) return null;
|
|
97
|
+
const nowMs = (opts.now ?? Date.now)();
|
|
98
|
+
const windowMs = opts.windowMs ?? DEFAULT_WINDOW_MS;
|
|
99
|
+
if (nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);
|
|
100
|
+
return {
|
|
101
|
+
...ledger,
|
|
102
|
+
reservations: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS)
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// src/lib/policy.ts
|
|
107
|
+
function normCreator(value) {
|
|
108
|
+
return value.trim().toLowerCase();
|
|
109
|
+
}
|
|
110
|
+
function evaluateSpendPolicy(policy, req) {
|
|
111
|
+
if (req.maxPriceAtomic !== void 0 && req.amountAtomic > req.maxPriceAtomic) {
|
|
112
|
+
return {
|
|
113
|
+
decision: "deny",
|
|
114
|
+
reason: "price_cap_exceeded",
|
|
115
|
+
message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
if (policy.allowlistCreators.length > 0) {
|
|
119
|
+
const allowed = policy.allowlistCreators.map(normCreator);
|
|
120
|
+
if (!allowed.includes(normCreator(req.creator))) {
|
|
121
|
+
return {
|
|
122
|
+
decision: "deny",
|
|
123
|
+
reason: "not_allowlisted",
|
|
124
|
+
message: `Creator "${req.creator}" is not in allowlistCreators.`
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (req.mode === "manual") {
|
|
129
|
+
return req.amountAtomic > 0n ? {
|
|
130
|
+
decision: "confirm",
|
|
131
|
+
reason: "confirm_always",
|
|
132
|
+
message: "Manual payment requires explicit consent."
|
|
133
|
+
} : { decision: "allow", reason: "within_policy", message: "No payment required." };
|
|
134
|
+
}
|
|
135
|
+
if (policy.sessionBudgetAtomic !== null) {
|
|
136
|
+
const projected = req.sessionSpentAtomic + req.amountAtomic;
|
|
137
|
+
if (projected > policy.sessionBudgetAtomic) {
|
|
138
|
+
return {
|
|
139
|
+
decision: "deny",
|
|
140
|
+
reason: "session_budget_exceeded",
|
|
141
|
+
message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (req.amountAtomic > policy.maxAutoSpendAtomic) {
|
|
146
|
+
return {
|
|
147
|
+
decision: "deny",
|
|
148
|
+
reason: "above_auto_spend",
|
|
149
|
+
message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; automatic payment refused.`
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
return { decision: "allow", reason: "within_policy", message: "within spend policy" };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export {
|
|
156
|
+
DEFAULT_WINDOW_MS,
|
|
157
|
+
RESERVATION_TTL_MS,
|
|
158
|
+
emptyLedger,
|
|
159
|
+
spentOf,
|
|
160
|
+
readLedger,
|
|
161
|
+
readSpendSummary,
|
|
162
|
+
evaluateSpendPolicy
|
|
163
|
+
};
|
|
164
|
+
//# sourceMappingURL=chunk-U2ATFMKZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/spend-ledger.ts","../src/lib/policy.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { hasCode } from './errno';\nimport { spendLedgerPath } from './paths';\n\n/**\n * The spend ledger's READ side: its shape, the two expiries, and a read-only\n * summary. It lives outside `lib/wallet` so the router hooks can measure an\n * offer against the same session total an authorization would, without the\n * wallet entering their chunk graph (`src/router/dist-chunks.test.ts`). The\n * write side, with its lock and reservations, stays in `lib/wallet/spend.ts`.\n */\n\nexport const DEFAULT_WINDOW_MS = 86_400_000; // 24h rolling day\nexport const RESERVATION_TTL_MS = 600_000; // 10 min: a dangling reservation self-expires\n\nconst ReservationSchema = z.object({\n id: z.string(),\n amountAtomic: z.string().regex(/^\\d+$/),\n atMs: z.number(),\n /** Optional so a ledger written by an older build still parses. */\n requestKey: z.string().optional(),\n mode: z.enum(['automatic', 'manual']).optional(),\n});\nexport type Reservation = z.infer<typeof ReservationSchema>;\n\n/**\n * ONE TRANSMITTED AUTHORIZATION, by its EIP-3009 nonce: what it exposed and\n * when, so a payment the chain later proves was never charged can give back\n * exactly its own amount inside the window it was counted in.\n */\nconst ExposureSchema = z.object({\n nonce: z.string(),\n amountAtomic: z.string().regex(/^\\d+$/),\n atMs: z.number(),\n mode: z.enum(['automatic', 'manual']).optional(),\n});\nexport type Exposure = z.infer<typeof ExposureSchema>;\n\nconst LedgerSchema = z.object({\n schemaVersion: z.literal(2),\n windowStartMs: z.number(),\n /**\n * EXPOSURE: every authorization this window transmitted. A signed EIP-3009\n * authorization is a bearer instrument, so total exposure stays recorded,\n * whatever any counterparty later says it took.\n */\n committedAtomic: z.string().regex(/^\\d+$/),\n automaticCommittedAtomic: z.string().regex(/^\\d+$/).optional(),\n /**\n * SETTLED: what counterparties reported actually taking, which the router's\n * waived outcomes made a different number from the line above (2026-09-23\n * lookup contract). Optional so a ledger an older build wrote still parses;\n * absent means \"everything committed was settled\", which is what that build\n * assumed. Reporting only, never a budget input: under-counting exposure\n * because a server said \"no charge\" is exactly the hole this avoids.\n */\n settledAtomic: z.string().regex(/^\\d+$/).optional(),\n reservations: z.array(ReservationSchema),\n /** Optional so a ledger an older build wrote still parses; such a ledger\n * simply has nothing a reconcile can release. */\n exposures: z.array(ExposureSchema).optional(),\n});\nexport type Ledger = z.infer<typeof LedgerSchema>;\n\nexport function emptyLedger(nowMs: number): Ledger {\n return {\n schemaVersion: 2,\n windowStartMs: nowMs,\n committedAtomic: '0',\n automaticCommittedAtomic: '0',\n settledAtomic: '0',\n reservations: [],\n };\n}\n\n/** Automatic exposure plus automatic pending reservations: the budget's input.\n * Legacy records with no mode/counter conservatively count as automatic. */\nexport function spentOf(ledger: {\n committedAtomic: string;\n automaticCommittedAtomic?: string;\n reservations: { amountAtomic: string; mode?: 'automatic' | 'manual' }[];\n}): bigint {\n return ledger.reservations.reduce(\n (sum, r) => sum + (r.mode === 'manual' ? 0n : BigInt(r.amountAtomic)),\n BigInt(ledger.automaticCommittedAtomic ?? ledger.committedAtomic),\n );\n}\n\n/**\n * ABSENT and CORRUPT both reset the window, but they are not the same fact: the\n * first is a first run, the second is spend that existed and is now gone. Only\n * the second is worth telling anyone about, so the two stay distinguishable here\n * rather than collapsing into one null.\n */\ninterface LedgerRead {\n ledger: Ledger | null;\n /** Set only when the file EXISTS and could not be turned back into a ledger. */\n corrupt?: string;\n}\n\nexport async function readLedger(path: string): Promise<LedgerRead> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n // A missing file is the ordinary first run. Any other read failure means a\n // file is there and unusable, which is the corrupt case by another name.\n if (hasCode(err, 'ENOENT')) return { ledger: null };\n return { ledger: null, corrupt: err instanceof Error ? err.message : String(err) };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { ledger: null, corrupt: 'not valid JSON' };\n }\n const parsed = LedgerSchema.safeParse(json);\n if (parsed.success) return { ledger: parsed.data };\n const issue = parsed.error.issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // Field-qualified: \"expected number, received undefined\" names nothing on its\n // own. zod never echoes the received VALUE, so no spend figure rides along.\n return {\n ledger: null,\n corrupt: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n}\n\nexport interface SpendSummary {\n windowStartMs: number;\n committedAtomic: string;\n automaticCommittedAtomic?: string;\n reservations: {\n amountAtomic: string;\n atMs: number;\n requestKey?: string;\n mode?: 'automatic' | 'manual';\n }[];\n}\n\n/**\n * The ledger AS AN AUTHORIZATION WOULD SEE IT, for `tenjin status`. Read-only,\n * and it applies the same two expiries the authorizer applies before it\n * evaluates a spend: a rolling window that has run out reads as a fresh one,\n * and reservations past their TTL are gone. Summing the raw file instead\n * reported spend as current, and crashed reservations as open, until the next\n * payment happened to rewrite it.\n *\n * `null` for absent or unreadable, which is the same thing to a report.\n */\nexport async function readSpendSummary(\n dir: string,\n opts: { now?: () => number; windowMs?: number } = {},\n): Promise<SpendSummary | null> {\n const { ledger } = await readLedger(spendLedgerPath(dir));\n if (ledger === null) return null;\n const nowMs = (opts.now ?? Date.now)();\n const windowMs = opts.windowMs ?? DEFAULT_WINDOW_MS;\n if (nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);\n return {\n ...ledger,\n reservations: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS),\n };\n}\n","/**\n * Spend-policy evaluation, pure and provider-agnostic. The wallet provider layer\n * (lib/wallet/spend.ts) owns the ledger and calls this; a future hosted provider\n * (Privy, B5) reuses the same decision rules, so the knobs live in exactly one\n * place. Nothing here does IO, the caller supplies the already-spent total and\n * decides how to satisfy a `confirm` decision (a `--yes`, a TTY prompt, or a\n * non-interactive refusal).\n */\n\nexport type PaymentMode = 'automatic' | 'manual';\n\nexport interface SpendPolicy {\n /** Automatic per-call ceiling; zero blocks positive automatic payments. */\n maxAutoSpendAtomic: bigint;\n /** Rolling ceiling on automatic exposure. null = no ceiling; zero blocks positive automatic payments. */\n sessionBudgetAtomic: bigint | null;\n /** Creators (handle or 0x-address, lowercased) all payments are restricted to.\n * Empty = no restriction. A non-empty list is a hard gate: a non-member is\n * denied even with `--yes`. */\n allowlistCreators: string[];\n}\n\nexport interface SpendRequest {\n /** Omitted by legacy consumers: conservatively automatic. */\n mode?: PaymentMode;\n amountAtomic: bigint;\n /** Creator identity from the 402 preview / candidate, handle or 0x address. */\n creator: string;\n /** The caller's `--max-price` cap, if given. A hard ceiling, never bypassable. */\n maxPriceAtomic?: bigint;\n /** Cumulative spend already recorded in this rolling session window. */\n sessionSpentAtomic: bigint;\n}\n\n/**\n * `allow`: within policy, proceed silently. `confirm`: an approval is required ,\n * the caller satisfies it with `--yes`, an interactive prompt, or refuses. `deny`:\n * a hard gate blocked it (price cap, allowlist, session budget); NOT satisfiable\n * by `--yes` or a prompt.\n */\nexport type SpendDecision = 'allow' | 'confirm' | 'deny';\n\n/**\n * `duplicate_in_flight` is the one reason this pure evaluator never returns: it\n * is a fact about the ledger (an identical request already holds a reservation\n * in this turn), so the authorizer raises it. It lives in the union because\n * every caller renders a decision's reason from one vocabulary.\n */\nexport type PolicyReason =\n | 'within_policy'\n | 'duplicate_in_flight'\n | 'price_cap_exceeded'\n | 'not_allowlisted'\n | 'session_budget_exceeded'\n | 'above_auto_spend'\n | 'confirm_always';\n\nexport interface PolicyEvaluation {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n}\n\n/** Normalize a creator identity for allowlist comparison (case-insensitive; a\n * word-handle and a 0x address are both single tokens). */\nfunction normCreator(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/** Hard price/creator checks apply in both modes. Manual payments require consent;\n * automatic payments must fit both configured ceilings without prompting. */\nexport function evaluateSpendPolicy(policy: SpendPolicy, req: SpendRequest): PolicyEvaluation {\n if (req.maxPriceAtomic !== undefined && req.amountAtomic > req.maxPriceAtomic) {\n return {\n decision: 'deny',\n reason: 'price_cap_exceeded',\n message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`,\n };\n }\n\n if (policy.allowlistCreators.length > 0) {\n const allowed = policy.allowlistCreators.map(normCreator);\n if (!allowed.includes(normCreator(req.creator))) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${req.creator}\" is not in allowlistCreators.`,\n };\n }\n }\n\n if (req.mode === 'manual') {\n return req.amountAtomic > 0n\n ? {\n decision: 'confirm',\n reason: 'confirm_always',\n message: 'Manual payment requires explicit consent.',\n }\n : { decision: 'allow', reason: 'within_policy', message: 'No payment required.' };\n }\n\n if (policy.sessionBudgetAtomic !== null) {\n const projected = req.sessionSpentAtomic + req.amountAtomic;\n if (projected > policy.sessionBudgetAtomic) {\n return {\n decision: 'deny',\n reason: 'session_budget_exceeded',\n message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`,\n };\n }\n }\n\n if (req.amountAtomic > policy.maxAutoSpendAtomic) {\n return {\n decision: 'deny',\n reason: 'above_auto_spend',\n message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; automatic payment refused.`,\n };\n }\n\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,gBAAgB;AAalB,IAAM,oBAAoB;AAC1B,IAAM,qBAAqB;AAElC,IAAM,oBAAoB,iBAAE,OAAO;AAAA,EACjC,IAAI,iBAAE,OAAO;AAAA,EACb,cAAc,iBAAE,OAAO,EAAE,MAAM,OAAO;AAAA,EACtC,MAAM,iBAAE,OAAO;AAAA;AAAA,EAEf,YAAY,iBAAE,OAAO,EAAE,SAAS;AAAA,EAChC,MAAM,iBAAE,KAAK,CAAC,aAAa,QAAQ,CAAC,EAAE,SAAS;AACjD,CAAC;AAQD,IAAM,iBAAiB,iBAAE,OAAO;AAAA,EAC9B,OAAO,iBAAE,OAAO;AAAA,EAChB,cAAc,iBAAE,OAAO,EAAE,MAAM,OAAO;AAAA,EACtC,MAAM,iBAAE,OAAO;AAAA,EACf,MAAM,iBAAE,KAAK,CAAC,aAAa,QAAQ,CAAC,EAAE,SAAS;AACjD,CAAC;AAGD,IAAM,eAAe,iBAAE,OAAO;AAAA,EAC5B,eAAe,iBAAE,QAAQ,CAAC;AAAA,EAC1B,eAAe,iBAAE,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMxB,iBAAiB,iBAAE,OAAO,EAAE,MAAM,OAAO;AAAA,EACzC,0BAA0B,iBAAE,OAAO,EAAE,MAAM,OAAO,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAS7D,eAAe,iBAAE,OAAO,EAAE,MAAM,OAAO,EAAE,SAAS;AAAA,EAClD,cAAc,iBAAE,MAAM,iBAAiB;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,+CAA+C,SAAS,wBAAwB,OAAO,mBAAmB;AAAA,MACrH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,oBAAoB;AAChD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,0BAA0B,OAAO,kBAAkB;AAAA,IACvF;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,sBAAsB;AACtF;","names":[]}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
fetchFailureToCliError,
|
|
4
|
+
httpRequest
|
|
5
|
+
} from "./chunk-2AQO4YDI.js";
|
|
6
|
+
import {
|
|
7
|
+
external_exports
|
|
8
|
+
} from "./chunk-W3LVZ2EN.js";
|
|
9
|
+
|
|
10
|
+
// src/router/decision.ts
|
|
11
|
+
var ROUTER_PATH = "/api/x402-router";
|
|
12
|
+
var RequestSchema = external_exports.object({
|
|
13
|
+
url: external_exports.string().min(1).max(16384),
|
|
14
|
+
method: external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]),
|
|
15
|
+
headers: external_exports.record(external_exports.string(), external_exports.string()),
|
|
16
|
+
body: external_exports.string().max(256 * 1024).optional()
|
|
17
|
+
});
|
|
18
|
+
var ContractSchema = external_exports.object({
|
|
19
|
+
/** Flat, for display and for the result check; never re-encoded into a call:
|
|
20
|
+
* the server built `request` from them and this client sends that verbatim. */
|
|
21
|
+
arguments: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
|
|
22
|
+
resultSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
|
|
23
|
+
request: RequestSchema
|
|
24
|
+
});
|
|
25
|
+
var DiagnosticsSchema = external_exports.object({
|
|
26
|
+
reasonCode: external_exports.string().min(1).max(64),
|
|
27
|
+
stage: external_exports.string().min(1).max(32),
|
|
28
|
+
missing: external_exports.array(external_exports.string().max(200)).max(60),
|
|
29
|
+
nextAction: external_exports.string().max(500)
|
|
30
|
+
});
|
|
31
|
+
var IdSchema = external_exports.string().regex(/^[A-Za-z0-9_-]{8,64}$/).describe(
|
|
32
|
+
"The turn id, an OPAQUE HANDLE: it is the one piece of server text this client puts in a model-facing line, so the alphabet is pinned here rather than escaped later."
|
|
33
|
+
);
|
|
34
|
+
var RefusedSchema = external_exports.strictObject({
|
|
35
|
+
reason: external_exports.string().max(2e3).optional(),
|
|
36
|
+
diagnostics: DiagnosticsSchema
|
|
37
|
+
});
|
|
38
|
+
var CapabilityFields = {
|
|
39
|
+
capabilityId: external_exports.string().min(1).max(200),
|
|
40
|
+
category: external_exports.string().min(1).max(64),
|
|
41
|
+
/** The service's own name, not the x402 reseller in front of it. */
|
|
42
|
+
provider: external_exports.string().min(1).max(120),
|
|
43
|
+
capabilityDescription: external_exports.string().min(1).max(500),
|
|
44
|
+
/** What the provider charges, atomic USDC. The `request` tool refuses a live
|
|
45
|
+
* 402 above it; `gateSpend` still caps the amount actually signed. */
|
|
46
|
+
providerPriceAtomic: external_exports.string().regex(/^\d+$/)
|
|
47
|
+
};
|
|
48
|
+
function checkHint(decision, ctx) {
|
|
49
|
+
if (/[\p{Cc}\p{Cf}]/u.test(decision.hint)) {
|
|
50
|
+
ctx.addIssue({ code: "custom", path: ["hint"], message: "a hint is one plain line" });
|
|
51
|
+
}
|
|
52
|
+
if (!decision.hint.includes("request({")) {
|
|
53
|
+
ctx.addIssue({ code: "custom", path: ["hint"], message: "a hint names the call to make" });
|
|
54
|
+
}
|
|
55
|
+
if (!decision.hint.includes(decision.id)) {
|
|
56
|
+
ctx.addIssue({
|
|
57
|
+
code: "custom",
|
|
58
|
+
path: ["hint"],
|
|
59
|
+
message: "a hint carries this answer's own id"
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
var DiscoveredCandidateSchema = external_exports.strictObject({
|
|
64
|
+
source: external_exports.string().min(1).max(64),
|
|
65
|
+
provider: external_exports.string().min(1).max(120),
|
|
66
|
+
url: external_exports.string().min(1).max(2048),
|
|
67
|
+
method: external_exports.enum(["GET", "POST"]),
|
|
68
|
+
description: external_exports.string().max(500),
|
|
69
|
+
providerPriceAtomic: external_exports.string().regex(/^\d+$/),
|
|
70
|
+
network: external_exports.string().min(1).max(64),
|
|
71
|
+
payTo: external_exports.string().min(1).max(200),
|
|
72
|
+
input: external_exports.strictObject({
|
|
73
|
+
location: external_exports.enum(["body", "query"]),
|
|
74
|
+
schema: external_exports.record(external_exports.string(), external_exports.unknown())
|
|
75
|
+
})
|
|
76
|
+
});
|
|
77
|
+
var DiscoveredSchema = external_exports.strictObject({
|
|
78
|
+
action: external_exports.literal("discovered"),
|
|
79
|
+
id: IdSchema,
|
|
80
|
+
candidate: DiscoveredCandidateSchema,
|
|
81
|
+
/** THE LINE, FINISHED, as on `execute`: it carries the seller's
|
|
82
|
+
* description and the input it takes. */
|
|
83
|
+
hint: external_exports.string().min(1).max(2e3)
|
|
84
|
+
}).superRefine(checkHint);
|
|
85
|
+
var HookDecisionSchema = external_exports.discriminatedUnion("action", [
|
|
86
|
+
external_exports.strictObject({
|
|
87
|
+
action: external_exports.literal("execute"),
|
|
88
|
+
id: IdSchema,
|
|
89
|
+
...CapabilityFields,
|
|
90
|
+
/** The x402 URL a lookup would pay, for the line the server writes. */
|
|
91
|
+
endpoint: external_exports.string().min(1).max(2048),
|
|
92
|
+
/** What to pass in `query`, in the service's own terms. */
|
|
93
|
+
usage: external_exports.string().min(1).max(300),
|
|
94
|
+
/**
|
|
95
|
+
* THE LINE, FINISHED. The server writes it with the real id in it and, on a
|
|
96
|
+
* native call, the exact search or URL that was denied. The client injects
|
|
97
|
+
* it and composes nothing, which is why there is no hint builder here any
|
|
98
|
+
* more: two sides writing the same sentence is how they drift. The same
|
|
99
|
+
* bound as a discovered line's.
|
|
100
|
+
*/
|
|
101
|
+
hint: external_exports.string().min(1).max(2e3)
|
|
102
|
+
}).superRefine(checkHint),
|
|
103
|
+
DiscoveredSchema,
|
|
104
|
+
RefusedSchema.extend({ action: external_exports.literal("native") }),
|
|
105
|
+
RefusedSchema.extend({ action: external_exports.literal("needs_input") })
|
|
106
|
+
]);
|
|
107
|
+
var ToolDecisionSchema = external_exports.discriminatedUnion("action", [
|
|
108
|
+
external_exports.strictObject({
|
|
109
|
+
action: external_exports.literal("execute"),
|
|
110
|
+
...CapabilityFields,
|
|
111
|
+
contract: ContractSchema
|
|
112
|
+
}),
|
|
113
|
+
DiscoveredSchema,
|
|
114
|
+
RefusedSchema.extend({ action: external_exports.literal("native") }),
|
|
115
|
+
RefusedSchema.extend({ action: external_exports.literal("needs_input") })
|
|
116
|
+
]);
|
|
117
|
+
function envelope(decision) {
|
|
118
|
+
return external_exports.strictObject({
|
|
119
|
+
schemaVersion: external_exports.literal(1),
|
|
120
|
+
routerVersion: external_exports.string().min(1).max(64),
|
|
121
|
+
decision,
|
|
122
|
+
/** A plain sentence about the CALL, such as an id that had expired. Never a
|
|
123
|
+
* failure: the decision beside it ran anyway. */
|
|
124
|
+
note: external_exports.string().max(500).optional(),
|
|
125
|
+
jev: external_exports.object({ calls: external_exports.number(), latencyMs: external_exports.number() }).optional()
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
var HookResponseSchema = envelope(HookDecisionSchema);
|
|
129
|
+
var ToolResponseSchema = envelope(ToolDecisionSchema);
|
|
130
|
+
var CLIENT_ACCEPTS = ["discovered"];
|
|
131
|
+
var BAZAAR_ACCEPT = "bazaar";
|
|
132
|
+
function acceptsFor(bazaar) {
|
|
133
|
+
return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];
|
|
134
|
+
}
|
|
135
|
+
function buildHookBody(packet, extras = {}) {
|
|
136
|
+
return {
|
|
137
|
+
schemaVersion: 1,
|
|
138
|
+
...extras.sessionId !== void 0 ? { sessionId: extras.sessionId } : {},
|
|
139
|
+
...extras.accepts !== void 0 ? { accepts: [...extras.accepts] } : {},
|
|
140
|
+
packet
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function buildToolBody(request) {
|
|
144
|
+
return {
|
|
145
|
+
schemaVersion: 1,
|
|
146
|
+
...request.query !== void 0 ? { query: request.query } : {},
|
|
147
|
+
...request.id !== void 0 ? { id: request.id } : {},
|
|
148
|
+
...request.input !== void 0 ? { input: request.input } : {},
|
|
149
|
+
...request.gateHint !== void 0 ? { gateHint: request.gateHint } : {},
|
|
150
|
+
...request.accepts !== void 0 ? { accepts: [...request.accepts] } : {}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
async function requestDecision(kind, request, deps) {
|
|
154
|
+
const url = new URL(ROUTER_PATH, deps.baseUrl).toString();
|
|
155
|
+
const options = {
|
|
156
|
+
method: "POST",
|
|
157
|
+
timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,
|
|
158
|
+
blockRedirects: true,
|
|
159
|
+
jsonBody: kind === "hook" ? buildHookBody(request.packet, {
|
|
160
|
+
...request.sessionId !== void 0 ? { sessionId: request.sessionId } : {},
|
|
161
|
+
accepts: acceptsFor(deps.acceptsBazaar === true)
|
|
162
|
+
}) : buildToolBody({
|
|
163
|
+
...request.query !== void 0 ? { query: request.query } : {},
|
|
164
|
+
...request.id !== void 0 ? { id: request.id } : {},
|
|
165
|
+
...request.input !== void 0 ? { input: request.input } : {},
|
|
166
|
+
...request.gateHint !== void 0 ? { gateHint: request.gateHint } : {},
|
|
167
|
+
accepts: acceptsFor(deps.acceptsBazaar === true)
|
|
168
|
+
}),
|
|
169
|
+
...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
|
|
170
|
+
};
|
|
171
|
+
return readDecision(
|
|
172
|
+
await httpRequest(url, options),
|
|
173
|
+
kind === "hook" ? HookResponseSchema : ToolResponseSchema
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
function readDecision(response, schema) {
|
|
177
|
+
if (!response.ok) return { status: "failed", reason: fetchFailureToCliError(response).message };
|
|
178
|
+
if (response.status < 200 || response.status >= 300) {
|
|
179
|
+
const named = errorOf(response.json);
|
|
180
|
+
return {
|
|
181
|
+
status: "failed",
|
|
182
|
+
// The backend's own code and message, never a bare status line: a typed
|
|
183
|
+
// refusal the host could act on was arriving as "answered 400".
|
|
184
|
+
reason: named === null ? `The router endpoint answered ${response.status}.` : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,
|
|
185
|
+
...named !== null ? { errorCode: named.code } : {}
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
const parsed = schema.safeParse(response.json);
|
|
189
|
+
if (!parsed.success) {
|
|
190
|
+
return { status: "failed", reason: "The router returned a decision this build cannot read." };
|
|
191
|
+
}
|
|
192
|
+
return { status: "decided", decision: parsed.data };
|
|
193
|
+
}
|
|
194
|
+
function errorOf(body) {
|
|
195
|
+
if (body === null || typeof body !== "object") return null;
|
|
196
|
+
const error = body.error;
|
|
197
|
+
if (error === null || typeof error !== "object") return null;
|
|
198
|
+
const { code, message } = error;
|
|
199
|
+
if (typeof code !== "string" || code.length === 0 || code.length > 64) return null;
|
|
200
|
+
const text = typeof message === "string" ? message.slice(0, 500) : "";
|
|
201
|
+
return { code, message: text };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export {
|
|
205
|
+
ROUTER_PATH,
|
|
206
|
+
requestDecision
|
|
207
|
+
};
|
|
208
|
+
//# sourceMappingURL=chunk-UY2TOI3B.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\n\n/**\n * `POST /api/x402-router`: ONE FREE DECISION PER LOOKUP.\n *\n * The routing decision costs nothing and nobody signs for it. The hook asks for\n * it from the user's own words, the backend answers with what it would do and\n * what the provider charges, and the only payment on the wire is the one\n * `runPay` makes to that provider. That deletes the router fee and everything\n * built to carry it: the 402 probe, the requirements cache, the stale-quote\n * retry, the settlement accounting and one Base settlement of about 1.5 s from\n * every paid lookup.\n *\n * NOTHING IS STORED LOCALLY. The bounded packet travels with the request and\n * the backend keeps it against the decision id until that id expires, which is\n * how `request({query})` reaches the same calibrated input with no session\n * file, no timestamp latch and no guess about which window this process serves.\n */\n\nexport const ROUTER_PATH = '/api/x402-router';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, a non-execute with no diagnostics parsed\n * with nothing to act on, and a hook answer carrying a contract parsed as\n * though the hook had quoted a price. Each of those is drift the shared\n * fixtures exist to catch, so each is now a parse failure that names itself.\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.strictObject({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. The `request` tool refuses a live\n * 402 above it; `gateSpend` still caps the amount actually signed. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n};\n\n/**\n * STRUCTURE, NEVER WORDING. A hint lands in the model's context verbatim, so\n * its shape is checked the way the id's alphabet is: one line, no control\n * characters, and it has to be the call it claims to be, naming the id this\n * same answer carries. A hint that fails any of these is a protocol error and\n * the turn falls back to the generic line; nothing here rewrites a word of a\n * hint that passes. Both offering arms, `execute` and `discovered`, hold it.\n */\nfunction checkHint(decision: { id: string; hint: string }, ctx: z.RefinementCtx): void {\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n}\n\n/**\n * A PAY-PER-CALL SERVICE NOBODY CURATED. When no capability in the catalog fits\n * but a listed x402 service could do the step, the server names that one\n * service: who sells it, where, for how much, and the input it takes. The\n * candidate is the seller's own listing, so every field is data for the host\n * to judge, never an instruction; the host builds the `input` and the tool\n * call pays through the same `runPay` path and caps as a curated lookup.\n */\nconst DiscoveredCandidateSchema = z.strictObject({\n source: z.string().min(1).max(64),\n provider: z.string().min(1).max(120),\n url: z.string().min(1).max(2_048),\n method: z.enum(['GET', 'POST']),\n description: z.string().max(500),\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n network: z.string().min(1).max(64),\n payTo: z.string().min(1).max(200),\n input: z.strictObject({\n location: z.enum(['body', 'query']),\n schema: z.record(z.string(), z.unknown()),\n }),\n});\n\n/** The same answer on both calls: the hook's offer, and the tool's fallback\n * when a query with no id found no curated capability. */\nconst DiscoveredSchema = z\n .strictObject({\n action: z.literal('discovered'),\n id: IdSchema,\n candidate: DiscoveredCandidateSchema,\n /** THE LINE, FINISHED, as on `execute`: it carries the seller's\n * description and the input it takes. */\n hint: z.string().min(1).max(2_000),\n })\n .superRefine(checkHint);\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .strictObject({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. */\n endpoint: z.string().min(1).max(2_048),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift. The same\n * bound as a discovered line's.\n */\n hint: z.string().min(1).max(2_000),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.strictObject({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool';\n\n/**\n * What this client can act on beyond the curated answers, sent on both calls.\n * `discovered` is Tenjin's reviewed list of third-party services, on for every\n * build that parses it; the server answers that arm only to a request that\n * lists it, so an older build never sees one. `bazaar` widens it to the open\n * Bazaar and is sent only while `experimental.bazaar` is on.\n */\nexport const CLIENT_ACCEPTS: readonly string[] = ['discovered'];\nexport const BAZAAR_ACCEPT = 'bazaar';\n\n/** The `accepts` this build sends, with the open Bazaar or without it. */\nexport function acceptsFor(bazaar: boolean): string[] {\n return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];\n}\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route reads it with a strict object, so an extra field is a\n * 400, and a 400 is a turn with no hint.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone. `sessionId` is the harness's own session id, which the\n * server uses only so one session is not offered the same discovered service\n * twice.\n */\nexport function buildHookBody(\n packet: Packet,\n extras: { sessionId?: string; accepts?: readonly string[] } = {},\n): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(extras.sessionId !== undefined ? { sessionId: extras.sessionId } : {}),\n ...(extras.accepts !== undefined ? { accepts: [...extras.accepts] } : {}),\n packet,\n };\n}\n\n/** The exact body the tool call sends. `id` is the turn whose packet decides\n * with this query; `gateHint` is evidence, never authority. `input` is the\n * host's own input for a discovered service, and stands in for `query`. */\nexport function buildToolBody(request: {\n query?: string;\n id?: string;\n input?: Record<string, unknown>;\n gateHint?: GateHint;\n accepts?: readonly string[];\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.input !== undefined ? { input: request.input } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n ...(request.accepts !== undefined ? { accepts: [...request.accepts] } : {}),\n };\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(kind: CallKind, value: unknown): { success: boolean } {\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n return { success: schema.safeParse(value).success };\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n /** `experimental.bazaar`: add {@link BAZAAR_ACCEPT}, so a service from the\n * open Bazaar may come back. Off by default: curated and the Tenjin list. */\n acceptsBazaar?: boolean;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n}\n\nexport type DecisionOutcome<T> =\n | { status: 'decided'; decision: T }\n /** Nothing was paid and nothing could be: the endpoint is free, so a failure\n * here costs the turn a routing answer and nothing else. */\n | { status: 'failed'; reason: string; errorCode?: string };\n\n/**\n * ONE FREE CALL, IN TWO FORMS. The hook sends `{ packet }`: the backend runs\n * the gate, and on `execute` stores that packet under an id. The tool sends\n * `{ query, id? }`: the backend makes THE decision from that query plus the\n * packet it stored, and answers with the contract to run. A discovered\n * service's id is sent with the host's own `{ input }` instead of a query.\n *\n * The tool never sends a packet of its own. The turn's context lives on the\n * backend against the id, and the query the model wrote is what the routing\n * corpus is calibrated against: 55 of 56 for query plus packet, 53 of 56 for\n * the raw prompt, measured on jev-1.13.0.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet; sessionId?: string },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query?: string; id?: string; input?: Record<string, unknown>; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n sessionId?: string;\n id?: string;\n input?: Record<string, unknown>;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(ROUTER_PATH, deps.baseUrl).toString();\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet, {\n ...(request.sessionId !== undefined ? { sessionId: request.sessionId } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n })\n : buildToolBody({\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.input !== undefined ? { input: request.input } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n return readDecision(\n await httpRequest(url, options),\n kind === 'hook' ? HookResponseSchema : ToolResponseSchema,\n );\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason; nothing was paid either way,\n // because there is nothing to pay for on this route.\n if (!response.ok) return { status: 'failed', reason: fetchFailureToCliError(response).message };\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n"],"mappings":";;;;;;;;;;AAuBO,IAAM,cAAc;AAO3B,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EAC7B,KAAK,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM;AAAA,EACjC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