tenjin-cli 0.1.0-alpha.25 → 0.1.0-alpha.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -41
- package/dist/{chunk-EG7P4SM6.js → chunk-4HAV6IFE.js} +5 -5
- package/dist/{chunk-IYLECN4D.js → chunk-5HS54CLI.js} +2 -2
- package/dist/{chunk-CEMXMUIU.js → chunk-5INS5ZZF.js} +35 -6
- package/dist/chunk-5INS5ZZF.js.map +1 -0
- package/dist/{chunk-CKDD554V.js → chunk-5NUF4BHR.js} +5 -3
- package/dist/{chunk-CKDD554V.js.map → chunk-5NUF4BHR.js.map} +1 -1
- package/dist/{chunk-NTYQHAIM.js → chunk-65EJJVT3.js} +2 -2
- package/dist/{chunk-GT6W3VJM.js → chunk-6JIYGYRB.js} +2 -52
- package/dist/chunk-6JIYGYRB.js.map +1 -0
- package/dist/{chunk-EOGJKIOG.js → chunk-ALJRB7NG.js} +10 -3
- package/dist/chunk-ALJRB7NG.js.map +1 -0
- package/dist/chunk-BOAI23CX.js +222 -0
- package/dist/chunk-BOAI23CX.js.map +1 -0
- package/dist/{chunk-KGTQRJGS.js → chunk-DI7WHXOZ.js} +5 -10
- package/dist/{chunk-KGTQRJGS.js.map → chunk-DI7WHXOZ.js.map} +1 -1
- package/dist/{chunk-DRXDTITB.js → chunk-EJXIK6WY.js} +9 -9
- package/dist/{chunk-ODH7UXIS.js → chunk-GHR4BTNJ.js} +3 -2
- package/dist/{chunk-ODH7UXIS.js.map → chunk-GHR4BTNJ.js.map} +1 -1
- package/dist/chunk-H4BOQLWW.js +99 -0
- package/dist/chunk-H4BOQLWW.js.map +1 -0
- package/dist/{chunk-VYONGSMQ.js → chunk-OBPZ36HG.js} +29 -3
- package/dist/chunk-OBPZ36HG.js.map +1 -0
- package/dist/chunk-PM2MOXJ3.js +66 -0
- package/dist/chunk-PM2MOXJ3.js.map +1 -0
- package/dist/chunk-PZ5N6BAL.js +268 -0
- package/dist/chunk-PZ5N6BAL.js.map +1 -0
- package/dist/{chunk-YSW57KUT.js → chunk-VNT3CQFV.js} +17 -17
- package/dist/chunk-VNT3CQFV.js.map +1 -0
- package/dist/{chunk-SCAE6PW6.js → chunk-W36HL4TB.js} +4 -4
- package/dist/{chunk-NYPFOHSJ.js → chunk-WT7DHJNJ.js} +2 -2
- package/dist/chunk-XMIVHQ35.js +55 -0
- package/dist/chunk-XMIVHQ35.js.map +1 -0
- package/dist/{chunk-3ZYPVSIU.js → chunk-YHWBDCGS.js} +234 -41
- package/dist/chunk-YHWBDCGS.js.map +1 -0
- package/dist/{chunk-CP7O6M55.js → chunk-YLCWI6ZR.js} +61 -20
- package/dist/chunk-YLCWI6ZR.js.map +1 -0
- package/dist/{chunk-EACMJEF3.js → chunk-Z7R2QDX2.js} +35 -171
- package/dist/chunk-Z7R2QDX2.js.map +1 -0
- package/dist/chunk-ZLD6MJVJ.js +30 -0
- package/dist/chunk-ZLD6MJVJ.js.map +1 -0
- package/dist/{cli-4WMGZPBP.js → cli-2U5JB7OQ.js} +34 -31
- package/dist/{cli-4WMGZPBP.js.map → cli-2U5JB7OQ.js.map} +1 -1
- package/dist/{config-VU6U7QOU.js → config-44EGO636.js} +11 -7
- package/dist/{doctor-26JS2SG3.js → doctor-BD42BBEG.js} +136 -94
- package/dist/doctor-BD42BBEG.js.map +1 -0
- package/dist/env-proxy-KEGEMWKX.js +15 -0
- package/dist/{fund-JJN3FRRF.js → fund-WQOOUESE.js} +20 -10
- package/dist/{fund-JJN3FRRF.js.map → fund-WQOOUESE.js.map} +1 -1
- package/dist/{hook-command-S2V4UNB3.js → hook-command-23LC5NRN.js} +12 -8
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/{install-GXQ33J4G.js → install-REPLHNU7.js} +19 -13
- package/dist/{install-identity-HFQUXPSI.js → install-identity-4RDWTLJ2.js} +4 -4
- package/dist/{install-wallet-27LTEHBI.js → install-wallet-USHWL7AX.js} +8 -6
- package/dist/{install-wallet-27LTEHBI.js.map → install-wallet-USHWL7AX.js.map} +1 -1
- package/dist/{mcp-AHCZVD2U.js → mcp-T5SYCLP7.js} +238 -64
- package/dist/mcp-T5SYCLP7.js.map +1 -0
- package/dist/{pay-3TCOPGCX.js → pay-276DSSYG.js} +10 -9
- package/dist/{payments-H3LSBGSL.js → payments-TZYLJXK3.js} +5 -4
- package/dist/{payments-H3LSBGSL.js.map → payments-TZYLJXK3.js.map} +1 -1
- package/dist/{send-LKCLN5GA.js → send-YHDKZPED.js} +6 -5
- package/dist/{send-LKCLN5GA.js.map → send-YHDKZPED.js.map} +1 -1
- package/dist/{status-2FDGI4LQ.js → status-X2INT6VD.js} +4 -3
- package/dist/{status-2FDGI4LQ.js.map → status-X2INT6VD.js.map} +1 -1
- package/dist/{status-line-wiring-ZDBYHNYR.js → status-line-wiring-LW4HFRHB.js} +4 -4
- package/dist/{uninstall-ZXWABDHS.js → uninstall-NVTGU7JD.js} +21 -15
- package/dist/{uninstall-ZXWABDHS.js.map → uninstall-NVTGU7JD.js.map} +1 -1
- package/dist/{update-HEIWVOP5.js → update-QXVH2DE7.js} +17 -10
- package/dist/update-QXVH2DE7.js.map +1 -0
- package/dist/{wallet-T7JYWI6O.js → wallet-CKKB23D5.js} +8 -6
- package/dist/wallet-CKKB23D5.js.map +1 -0
- package/docs/agent-permissions.md +14 -4
- package/docs/troubleshooting.md +13 -0
- package/package.json +2 -1
- package/dist/chunk-3ZYPVSIU.js.map +0 -1
- package/dist/chunk-CEMXMUIU.js.map +0 -1
- package/dist/chunk-CP7O6M55.js.map +0 -1
- package/dist/chunk-EACMJEF3.js.map +0 -1
- package/dist/chunk-EOGJKIOG.js.map +0 -1
- package/dist/chunk-GT6W3VJM.js.map +0 -1
- package/dist/chunk-VYONGSMQ.js.map +0 -1
- package/dist/chunk-YSW57KUT.js.map +0 -1
- package/dist/doctor-26JS2SG3.js.map +0 -1
- package/dist/mcp-AHCZVD2U.js.map +0 -1
- package/dist/update-HEIWVOP5.js.map +0 -1
- /package/dist/{chunk-EG7P4SM6.js.map → chunk-4HAV6IFE.js.map} +0 -0
- /package/dist/{chunk-IYLECN4D.js.map → chunk-5HS54CLI.js.map} +0 -0
- /package/dist/{chunk-NTYQHAIM.js.map → chunk-65EJJVT3.js.map} +0 -0
- /package/dist/{chunk-DRXDTITB.js.map → chunk-EJXIK6WY.js.map} +0 -0
- /package/dist/{chunk-SCAE6PW6.js.map → chunk-W36HL4TB.js.map} +0 -0
- /package/dist/{chunk-NYPFOHSJ.js.map → chunk-WT7DHJNJ.js.map} +0 -0
- /package/dist/{config-VU6U7QOU.js.map → config-44EGO636.js.map} +0 -0
- /package/dist/{hook-command-S2V4UNB3.js.map → env-proxy-KEGEMWKX.js.map} +0 -0
- /package/dist/{install-GXQ33J4G.js.map → hook-command-23LC5NRN.js.map} +0 -0
- /package/dist/{install-identity-HFQUXPSI.js.map → install-REPLHNU7.js.map} +0 -0
- /package/dist/{pay-3TCOPGCX.js.map → install-identity-4RDWTLJ2.js.map} +0 -0
- /package/dist/{status-line-wiring-ZDBYHNYR.js.map → pay-276DSSYG.js.map} +0 -0
- /package/dist/{wallet-T7JYWI6O.js.map → status-line-wiring-LW4HFRHB.js.map} +0 -0
|
@@ -2,174 +2,10 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
|
|
|
2
2
|
import {
|
|
3
3
|
fetchFailureToCliError,
|
|
4
4
|
httpRequest
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-5INS5ZZF.js";
|
|
6
6
|
import {
|
|
7
7
|
external_exports
|
|
8
8
|
} from "./chunk-XICKN3CH.js";
|
|
9
|
-
import {
|
|
10
|
-
MCP_SERVER_NAME,
|
|
11
|
-
REQUEST_TOOL
|
|
12
|
-
} from "./chunk-TGLKKLQG.js";
|
|
13
|
-
|
|
14
|
-
// src/router/agent-tools.ts
|
|
15
|
-
import { readdir, readFile } from "node:fs/promises";
|
|
16
|
-
import { dirname, join, resolve } from "node:path";
|
|
17
|
-
var MCP_INHERITING_BUILTINS = /* @__PURE__ */ new Set([
|
|
18
|
-
"general-purpose",
|
|
19
|
-
"Explore",
|
|
20
|
-
"Plan"
|
|
21
|
-
]);
|
|
22
|
-
var MAX_AGENT_FILE_BYTES = 256 * 1024;
|
|
23
|
-
var TYPE_RE = /^[A-Za-z0-9_.:-]{1,200}$/;
|
|
24
|
-
async function requestToolAccess(agentType, lookup) {
|
|
25
|
-
if (agentType === void 0 || !TYPE_RE.test(agentType)) return "unknown";
|
|
26
|
-
try {
|
|
27
|
-
const text = await findDefinition(agentType, lookup);
|
|
28
|
-
if (text !== null) return accessOf(text);
|
|
29
|
-
return MCP_INHERITING_BUILTINS.has(agentType) ? "allowed" : "unknown";
|
|
30
|
-
} catch {
|
|
31
|
-
return "unknown";
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
function accessOf(definition) {
|
|
35
|
-
const frontmatter = frontmatterOf(definition);
|
|
36
|
-
if (frontmatter === null) return "unknown";
|
|
37
|
-
const disallowed = listField(frontmatter, "disallowedTools");
|
|
38
|
-
if (disallowed !== void 0 && disallowed.some(namesRequestTool)) return "excluded";
|
|
39
|
-
const tools = listField(frontmatter, "tools");
|
|
40
|
-
if (tools === void 0) return "allowed";
|
|
41
|
-
return tools.some(namesRequestTool) ? "allowed" : "excluded";
|
|
42
|
-
}
|
|
43
|
-
function namesRequestTool(tool) {
|
|
44
|
-
if (tool === REQUEST_TOOL || tool === `mcp__${MCP_SERVER_NAME}`) return true;
|
|
45
|
-
return tool.endsWith("*") && REQUEST_TOOL.startsWith(tool.slice(0, -1));
|
|
46
|
-
}
|
|
47
|
-
async function agentsWithoutRequestTool(lookup) {
|
|
48
|
-
const found = [];
|
|
49
|
-
const seen = /* @__PURE__ */ new Set();
|
|
50
|
-
for (const directory of agentDirs(lookup)) {
|
|
51
|
-
for (const { name, text } of await definitionsIn(directory)) {
|
|
52
|
-
const type = nameOf(text) ?? name;
|
|
53
|
-
if (seen.has(type)) continue;
|
|
54
|
-
seen.add(type);
|
|
55
|
-
if (accessOf(text) === "excluded") found.push(type);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
return found.sort();
|
|
59
|
-
}
|
|
60
|
-
async function findDefinition(agentType, lookup) {
|
|
61
|
-
for (const directory of agentDirs(lookup)) {
|
|
62
|
-
const text = await definitionIn(directory, agentType);
|
|
63
|
-
if (text !== null) return text;
|
|
64
|
-
}
|
|
65
|
-
const colon = agentType.indexOf(":");
|
|
66
|
-
if (colon > 0) {
|
|
67
|
-
const plugin = agentType.slice(0, colon);
|
|
68
|
-
const agent = agentType.slice(colon + 1);
|
|
69
|
-
for (const root of await pluginRoots(plugin, lookup.homeDir)) {
|
|
70
|
-
const text = await definitionIn(join(root, "agents"), agent);
|
|
71
|
-
if (text !== null) return text;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
return null;
|
|
75
|
-
}
|
|
76
|
-
function agentDirs(lookup) {
|
|
77
|
-
const dirs = [];
|
|
78
|
-
if (lookup.cwd !== void 0 && lookup.cwd.length > 0) {
|
|
79
|
-
let current = resolve(lookup.cwd);
|
|
80
|
-
for (; ; ) {
|
|
81
|
-
dirs.push(join(current, ".claude", "agents"));
|
|
82
|
-
const parent = dirname(current);
|
|
83
|
-
if (parent === current) break;
|
|
84
|
-
current = parent;
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
const user = join(resolve(lookup.homeDir), ".claude", "agents");
|
|
88
|
-
return [...dirs.filter((d) => d !== user), user];
|
|
89
|
-
}
|
|
90
|
-
async function definitionIn(directory, agentType) {
|
|
91
|
-
const direct = await readBounded(join(directory, `${agentType}.md`));
|
|
92
|
-
if (direct !== null && (nameOf(direct) ?? agentType) === agentType) return direct;
|
|
93
|
-
for (const { text } of await definitionsIn(directory)) {
|
|
94
|
-
if (nameOf(text) === agentType) return text;
|
|
95
|
-
}
|
|
96
|
-
return null;
|
|
97
|
-
}
|
|
98
|
-
async function definitionsIn(directory) {
|
|
99
|
-
let names;
|
|
100
|
-
try {
|
|
101
|
-
names = (await readdir(directory)).filter((n) => n.endsWith(".md")).slice(0, 200);
|
|
102
|
-
} catch {
|
|
103
|
-
return [];
|
|
104
|
-
}
|
|
105
|
-
const out = [];
|
|
106
|
-
for (const file of names) {
|
|
107
|
-
const text = await readBounded(join(directory, file));
|
|
108
|
-
if (text !== null) out.push({ name: file.slice(0, -3), text });
|
|
109
|
-
}
|
|
110
|
-
return out;
|
|
111
|
-
}
|
|
112
|
-
async function pluginRoots(plugin, homeDir) {
|
|
113
|
-
const raw = await readBounded(join(homeDir, ".claude", "plugins", "installed_plugins.json"));
|
|
114
|
-
if (raw === null) return [];
|
|
115
|
-
const parsed = JSON.parse(raw);
|
|
116
|
-
const roots = [];
|
|
117
|
-
for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {
|
|
118
|
-
if (key.split("@")[0] !== plugin || !Array.isArray(entries)) continue;
|
|
119
|
-
for (const entry of entries) {
|
|
120
|
-
const path = entry.installPath;
|
|
121
|
-
if (typeof path === "string" && path.length > 0) roots.push(path);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
return roots;
|
|
125
|
-
}
|
|
126
|
-
async function readBounded(path) {
|
|
127
|
-
try {
|
|
128
|
-
const text = await readFile(path, "utf8");
|
|
129
|
-
return text.length > MAX_AGENT_FILE_BYTES ? null : text;
|
|
130
|
-
} catch {
|
|
131
|
-
return null;
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
function frontmatterOf(text) {
|
|
135
|
-
const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
|
|
136
|
-
const open = lines.findIndex((l) => l.trim().length > 0);
|
|
137
|
-
if (open === -1 || lines[open]?.trim() !== "---") return null;
|
|
138
|
-
const end = lines.findIndex((l, i) => i > open && l.trim() === "---");
|
|
139
|
-
return end === -1 ? null : lines.slice(open + 1, end);
|
|
140
|
-
}
|
|
141
|
-
function nameOf(text) {
|
|
142
|
-
const frontmatter = frontmatterOf(text);
|
|
143
|
-
if (frontmatter === null) return null;
|
|
144
|
-
const line = frontmatter.find((l) => /^name\s*:/.test(l));
|
|
145
|
-
const value = line === void 0 ? "" : unquote(line.slice(line.indexOf(":") + 1).trim());
|
|
146
|
-
return value.length > 0 ? value : null;
|
|
147
|
-
}
|
|
148
|
-
function listField(frontmatter, key) {
|
|
149
|
-
const index = frontmatter.findIndex((l) => new RegExp(`^${key}\\s*:`).test(l));
|
|
150
|
-
if (index === -1) return void 0;
|
|
151
|
-
const line = frontmatter[index];
|
|
152
|
-
const inline = line.slice(line.indexOf(":") + 1).trim();
|
|
153
|
-
if (inline.length > 0) {
|
|
154
|
-
const body = inline.startsWith("[") && inline.endsWith("]") ? inline.slice(1, -1) : inline;
|
|
155
|
-
return body.split(",").map((part) => unquote(part.trim())).filter((part) => part.length > 0);
|
|
156
|
-
}
|
|
157
|
-
const items = [];
|
|
158
|
-
for (const next of frontmatter.slice(index + 1)) {
|
|
159
|
-
const item = /^\s+-\s*(.*)$/.exec(next);
|
|
160
|
-
if (item === null) {
|
|
161
|
-
if (next.trim().length === 0) continue;
|
|
162
|
-
break;
|
|
163
|
-
}
|
|
164
|
-
const value = unquote(item[1].trim());
|
|
165
|
-
if (value.length > 0) items.push(value);
|
|
166
|
-
}
|
|
167
|
-
return items;
|
|
168
|
-
}
|
|
169
|
-
function unquote(value) {
|
|
170
|
-
const quoted = /^(['"])(.*)\1$/.exec(value);
|
|
171
|
-
return quoted === null ? value : quoted[2];
|
|
172
|
-
}
|
|
173
9
|
|
|
174
10
|
// src/router/decision.ts
|
|
175
11
|
var ROUTER_PATH = "/api/x402-router";
|
|
@@ -359,15 +195,21 @@ function buildToolBody(request) {
|
|
|
359
195
|
};
|
|
360
196
|
}
|
|
361
197
|
var RouteSkipped = class extends Error {
|
|
362
|
-
|
|
198
|
+
/** `unreached`: the paid call could not reach the router
|
|
199
|
+
* ({@link isUnreachable}), so the free path, on the same host, is not
|
|
200
|
+
* tried and the call reads as that transport failure. */
|
|
201
|
+
constructor(why, unreached) {
|
|
363
202
|
super(`routing fee not paid: ${why}`);
|
|
364
203
|
this.why = why;
|
|
204
|
+
this.unreached = unreached;
|
|
365
205
|
}
|
|
366
206
|
why;
|
|
207
|
+
unreached;
|
|
367
208
|
};
|
|
368
209
|
var CHANNEL_BUSY = "channel_busy";
|
|
369
210
|
var PAID_PATH_ABSENT = "paid_path_absent";
|
|
370
211
|
var PAYMENT_FAILED = "payment_failed";
|
|
212
|
+
var DEADLINE_AFTER_PAYMENT_SENT = "deadline_after_payment_sent";
|
|
371
213
|
async function requestDecision(kind, request, deps) {
|
|
372
214
|
const url = new URL(deps.route?.path ?? ROUTER_PATH, deps.baseUrl).toString();
|
|
373
215
|
const options = {
|
|
@@ -392,6 +234,7 @@ async function requestDecision(kind, request, deps) {
|
|
|
392
234
|
response = await (deps.route?.send ?? httpRequest)(url, options);
|
|
393
235
|
} catch (err) {
|
|
394
236
|
if (!(err instanceof RouteSkipped)) throw err;
|
|
237
|
+
if (err.unreached !== void 0) return readDecision(err.unreached, schema);
|
|
395
238
|
const left = options.timeoutMs - (Date.now() - started);
|
|
396
239
|
if (left <= 0) return { status: "skipped", why: err.why };
|
|
397
240
|
response = await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {
|
|
@@ -399,6 +242,16 @@ async function requestDecision(kind, request, deps) {
|
|
|
399
242
|
timeoutMs: left
|
|
400
243
|
});
|
|
401
244
|
const free = readDecision(response, schema);
|
|
245
|
+
if (free.status === "failed") {
|
|
246
|
+
return {
|
|
247
|
+
status: "failed",
|
|
248
|
+
reason: free.reason,
|
|
249
|
+
...free.errorCode !== void 0 ? { errorCode: free.errorCode } : {},
|
|
250
|
+
// Still no answer, which must not end another call's backoff.
|
|
251
|
+
...free.noAnswer === true ? { noAnswer: true } : {},
|
|
252
|
+
freePath: err.why
|
|
253
|
+
};
|
|
254
|
+
}
|
|
402
255
|
return free.status === "skipped" ? free : { ...free, freePath: err.why };
|
|
403
256
|
}
|
|
404
257
|
return readDecision(response, schema);
|
|
@@ -426,7 +279,14 @@ function buildOutcomeBody(outcome) {
|
|
|
426
279
|
};
|
|
427
280
|
}
|
|
428
281
|
function readDecision(response, schema) {
|
|
429
|
-
if (!response.ok)
|
|
282
|
+
if (!response.ok) {
|
|
283
|
+
return {
|
|
284
|
+
status: "failed",
|
|
285
|
+
reason: fetchFailureToCliError(response).message,
|
|
286
|
+
...isUnreachable(response) ? { unreachable: true } : {},
|
|
287
|
+
...response.status === void 0 ? { noAnswer: true } : {}
|
|
288
|
+
};
|
|
289
|
+
}
|
|
430
290
|
if (response.status < 200 || response.status >= 300) {
|
|
431
291
|
const named = errorOf(response.json);
|
|
432
292
|
return {
|
|
@@ -452,17 +312,21 @@ function errorOf(body) {
|
|
|
452
312
|
const text = typeof message === "string" ? message.slice(0, 500) : "";
|
|
453
313
|
return { code, message: text };
|
|
454
314
|
}
|
|
315
|
+
var RESET_CODES = /* @__PURE__ */ new Set(["ECONNRESET", "UND_ERR_SOCKET"]);
|
|
316
|
+
function isUnreachable(failure) {
|
|
317
|
+
return failure.kind === "network" && failure.status === void 0 && failure.transport !== void 0 && !RESET_CODES.has(failure.transport.code ?? "");
|
|
318
|
+
}
|
|
455
319
|
|
|
456
320
|
export {
|
|
457
|
-
requestToolAccess,
|
|
458
|
-
agentsWithoutRequestTool,
|
|
459
321
|
ROUTER_PATH,
|
|
460
322
|
OfferSpecSchema,
|
|
461
323
|
RouteSkipped,
|
|
462
324
|
CHANNEL_BUSY,
|
|
463
325
|
PAID_PATH_ABSENT,
|
|
464
326
|
PAYMENT_FAILED,
|
|
327
|
+
DEADLINE_AFTER_PAYMENT_SENT,
|
|
465
328
|
requestDecision,
|
|
466
|
-
reportSpecOutcome
|
|
329
|
+
reportSpecOutcome,
|
|
330
|
+
isUnreachable
|
|
467
331
|
};
|
|
468
|
-
//# sourceMappingURL=chunk-
|
|
332
|
+
//# sourceMappingURL=chunk-Z7R2QDX2.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 { FetchJsonFailure, HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\n\n/**\n * `POST /api/x402-router`: ONE DECISION PER LOOKUP. On the free path it costs\n * nothing. Inside `tenjin mcp`, while the server answers its paid path, the\n * same body goes to that path through the stock x402 client\n * ({@link DecisionRoute}, `routing-payer.ts`); a call that path cannot take\n * falls back to the free path. The rest of this note describes the free path,\n * which is unchanged.\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 * The bounded packet travels with the hook request and the backend keeps it\n * against the decision id until that id expires. What this client keeps is\n * each offer's spec, by its id (`specs.ts`).\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/**\n * A REQUEST SPEC: the offered service's real contract, sent beside the line only\n * because this build asks for it (`accepts: [\"spec\"]`). The hook stores it by\n * the offer's id; `request({id})` shows it and `request({id, input})` fills its\n * request and pays the provider directly, with no second decision. Every field\n * is the server's, and so is checked like the rest of the answer: the payee and\n * price still meet the live 402 and the spend policy in `runPay`.\n */\nexport const ToolSpecSchema = z.strictObject({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n description: z.string().min(1).max(500),\n priceAtomic: z.string().regex(/^\\d+$/),\n priceVaries: z.boolean(),\n maxAmountAtomic: z.string().regex(/^\\d+$/),\n payTo: z.string().min(1).max(200),\n network: z.string().min(1).max(64),\n asset: z.string().min(1).max(200),\n request: z.strictObject({\n method: z.enum(['GET', 'POST']),\n url: z.string().min(1).max(2_048),\n fields: z.record(z.string(), z.enum(['path', 'query', 'body'])),\n location: z.enum(['query', 'body']),\n }),\n input: z.record(z.string(), z.unknown()),\n pinned: z.record(z.string(), z.unknown()),\n example: z.record(z.string(), z.unknown()).optional(),\n returns: z.string().min(1).max(200).optional(),\n returnsExample: z.unknown().optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n /** The fields the result promises (type, properties, items, required). The\n * agent is handed only these; the whole body is saved to a file. */\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n});\nexport type ToolSpec = z.infer<typeof ToolSpecSchema>;\n\nexport const OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });\nexport type OfferSpec = z.infer<typeof OfferSpecSchema>;\n\n/** One spec per service the line names: the offer and any alternative. */\nconst SpecsSchema = z.array(OfferSpecSchema).min(1).max(4).optional();\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 specs: SpecsSchema,\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 specs: SpecsSchema,\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 /**\n * A query with no id, answered with the spec of the service the server\n * picked under a fresh `id`: kept like a hook's, and never run in the same\n * call. `hint` is the line, with the skeleton of the next call:\n * `request({id, input: {...}})` with the required fields. `input` is what a\n * router from before the binder's removal still sends on a bound pick: it\n * is accepted so that answer parses, and never read, so it never runs.\n */\n z\n .strictObject({\n action: z.literal('spec'),\n id: IdSchema,\n spec: ToolSpecSchema,\n hint: z.string().min(1).max(2_000),\n input: z.record(z.string(), z.unknown()).optional(),\n })\n .superRefine(checkHint),\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. `spec` asks for each offered\n * service's request spec beside its line, and for the picked service's spec in\n * place of a decision on a query with no id, which only a build that parses\n * them can take: the decision schemas are strict. `bazaar` widens discovery\n * to the open Bazaar and is sent only while `experimental.bazaar` is on.\n */\nexport const CLIENT_ACCEPTS: readonly string[] = ['discovered', 'spec'];\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 offer the query is for,\n * sent only for an offer with no spec kept; `gateHint` is evidence, never\n * authority. */\nexport function buildToolBody(request: {\n query?: string;\n id?: string;\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.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 /** The paid path, when `tenjin mcp` takes it: the body goes to `path` and is\n * sent by `send`, which pays the routing fee with the stock x402 client.\n * Absent is the free path. */\n route?: DecisionRoute;\n}\n\n/** How a routing call reaches the paid path. `send` throws\n * {@link RouteSkipped} when it has no paid answer for the call, which then\n * takes the free path. */\nexport interface DecisionRoute {\n path: string;\n send: (url: string, options: HttpRequestOptions) => Promise<HttpResult>;\n}\n\n/** The paid path gave this call no answer: the wallet locked, low or over\n * its spend limits, the channel busy, or the payment failed. */\nexport class RouteSkipped extends Error {\n /** `unreached`: the paid call could not reach the router\n * ({@link isUnreachable}), so the free path, on the same host, is not\n * tried and the call reads as that transport failure. */\n constructor(\n readonly why: string,\n readonly unreached?: FetchJsonFailure,\n ) {\n super(`routing fee not paid: ${why}`);\n }\n}\n\n/** Another session's call was in flight on the wallet's routing channel. */\nexport const CHANNEL_BUSY = 'channel_busy';\n/** The server answered no paid path. */\nexport const PAID_PATH_ABSENT = 'paid_path_absent';\n/** The paid call got no answer, a refused payment or a server error. */\nexport const PAYMENT_FAILED = 'payment_failed';\n/** The payment went out and the call's budget ran out before its answer:\n * no fault. `tenjin mcp` lets the request finish, so it is recorded. */\nexport const DEADLINE_AFTER_PAYMENT_SENT = 'deadline_after_payment_sent';\n\nexport type DecisionOutcome<T> =\n /** `freePath`: the paid path skipped the call for this reason and it went\n * to the free path instead, unpaid. */\n | { status: 'decided'; decision: T; freePath?: string }\n /** On the free path nothing was paid and nothing could be, so a failure here\n * costs the turn a routing answer and nothing else. */\n | {\n status: 'failed';\n reason: string;\n errorCode?: string;\n freePath?: string;\n /** The router could not be reached at all ({@link isUnreachable}). */\n unreachable?: true;\n /** No answer came back at all: a transport failure or a timeout. */\n noAnswer?: true;\n }\n /** The paid path gave no answer ({@link RouteSkipped}) and no time was left\n * for the free path: the native tool runs. */\n | { status: 'skipped'; why: 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 and answers with\n * each offered service's spec. The tool sends `{ query }`, which the backend\n * answers with the spec of the service its gate picks, or `{ query, id }` for\n * the free docs offer, which has no spec and is bound from the query. Every\n * provider call is built here, from a spec, or for the docs lookup by the\n * backend from the query.\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; 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 gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(deps.route?.path ?? 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.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n const started = Date.now();\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n let response: HttpResult;\n try {\n response = await (deps.route?.send ?? httpRequest)(url, options);\n } catch (err) {\n if (!(err instanceof RouteSkipped)) throw err;\n if (err.unreached !== undefined) return readDecision(err.unreached, schema);\n const left = options.timeoutMs - (Date.now() - started);\n if (left <= 0) return { status: 'skipped', why: err.why };\n // A CALL THE PAID PATH COULD NOT TAKE STILL ROUTES, on the free path,\n // unpaid, inside what is left of its budget, and says why.\n response = await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n ...options,\n timeoutMs: left,\n });\n const free = readDecision(response, schema);\n // A failure here ran on what a paid attempt left of the budget, so it says\n // nothing about the router being down: it never starts the backoff.\n if (free.status === 'failed') {\n return {\n status: 'failed',\n reason: free.reason,\n ...(free.errorCode !== undefined ? { errorCode: free.errorCode } : {}),\n // Still no answer, which must not end another call's backoff.\n ...(free.noAnswer === true ? { noAnswer: true as const } : {}),\n freePath: err.why,\n };\n }\n return free.status === 'skipped' ? free : { ...free, freePath: err.why };\n }\n return readDecision(response, schema);\n}\n\n/** How a call run from a request spec ended, for the server's offer-to-call\n * count. No text: the id, the outcome, the provider's status and the time. */\nexport interface SpecOutcome {\n id: string;\n status: 'fulfilled' | 'unverified' | 'failed' | 'needs_approval';\n httpStatus?: number;\n ms?: number;\n}\n\n/** The outcome report's own deadline: it is telemetry and never holds a result. */\nexport const OUTCOME_TIMEOUT_MS = 3_000;\n\n/**\n * TELL THE SERVER A SPEC WAS USED. The client called and paid the provider\n * itself, so this is the only word the server gets that its offer was taken.\n * Never throws and never waits on anything the caller needs: a lost report\n * costs one count.\n */\nexport async function reportSpecOutcome(\n outcome: SpecOutcome,\n deps: Pick<DecisionDeps, 'ctx' | 'baseUrl' | 'fetchImpl'>,\n): Promise<void> {\n try {\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: OUTCOME_TIMEOUT_MS,\n blockRedirects: true,\n jsonBody: buildOutcomeBody(outcome),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n } catch {\n // Telemetry only.\n }\n}\n\n/** The exact body of an outcome report, pinned to the shared fixtures. */\nexport function buildOutcomeBody(outcome: SpecOutcome): Record<string, unknown> {\n return {\n schemaVersion: 1,\n id: outcome.id,\n status: outcome.status,\n ...(outcome.httpStatus !== undefined ? { httpStatus: outcome.httpStatus } : {}),\n ...(outcome.ms !== undefined ? { ms: Math.max(0, Math.round(outcome.ms)) } : {}),\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) {\n return {\n status: 'failed',\n reason: fetchFailureToCliError(response).message,\n ...(isUnreachable(response) ? { unreachable: true as const } : {}),\n ...(response.status === undefined ? { noAnswer: true as const } : {}),\n };\n }\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\n/** A dropped socket, which a fresh connection usually gets past. */\nconst RESET_CODES = new Set(['ECONNRESET', 'UND_ERR_SOCKET']);\n\n/**\n * A ROUTER THAT CANNOT BE REACHED: the transport named the layer that refused\n * the connection (DNS, TLS, a refused connection, a proxy refusing the tunnel)\n * and no status came back. Never the call's own timeout: that is the gate's\n * few seconds, and a slow decision or a cold start must not take the router\n * away from every session. Never a status, even with a body that failed to\n * read, and never a reset socket, which the free path retries on a fresh one.\n */\nexport function isUnreachable(failure: FetchJsonFailure): boolean {\n return (\n failure.kind === 'network' &&\n failure.status === undefined &&\n failure.transport !== undefined &&\n !RESET_CODES.has(failure.transport.code ?? '')\n );\n}\n"],"mappings":";;;;;;;;;;AA2BO,IAAM,cAAc;AAO3B,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EAC7B,KAAK,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM;AAAA,EACjC,QAAQ,iBAAE,KAAK,CAAC,OAAO,QAAQ,OAAO,SAAS,UAAU,QAAQ,SAAS,CAAC;AAAA,EAC3E,SAAS,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,OAAO,CAAC;AAAA,EACxC,MAAM,iBACH,OAAO,EACP,IAAI,MAAM,IAAI,EACd,SAAS;AACd,CAAC;AAED,IAAM,iBAAiB,iBAAE,OAAO;AAAA;AAAA;AAAA,EAG9B,WAAW,iBAAE,O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D;AAAA,EACF;AACA,QAAM,SAAS,OAAO,UAAU,SAAS,IAAI;AAC7C,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,EAAE,QAAQ,UAAU,QAAQ,yDAAyD;AAAA,EAC9F;AACA,SAAO,EAAE,QAAQ,WAAW,UAAU,OAAO,KAAmB;AAClE;AAIA,SAAS,QAAQ,MAAyD;AACxE,MAAI,SAAS,QAAQ,OAAO,SAAS,SAAU,QAAO;AACtD,QAAM,QAAS,KAA6B;AAC5C,MAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AACxD,QAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,MAAI,OAAO,SAAS,YAAY,KAAK,WAAW,KAAK,KAAK,SAAS,GAAI,QAAO;AAC9E,QAAM,OAAO,OAAO,YAAY,WAAW,QAAQ,MAAM,GAAG,GAAG,IAAI;AACnE,SAAO,EAAE,MAAM,SAAS,KAAK;AAC/B;AAGA,IAAM,cAAc,oBAAI,IAAI,CAAC,cAAc,gBAAgB,CAAC;AAUrD,SAAS,cAAc,SAAoC;AAChE,SACE,QAAQ,SAAS,aACjB,QAAQ,WAAW,UACnB,QAAQ,cAAc,UACtB,CAAC,YAAY,IAAI,QAAQ,UAAU,QAAQ,EAAE;AAEjD;","names":[]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// src/lib/env-proxy.ts
|
|
4
|
+
import * as http from "node:http";
|
|
5
|
+
var PROXY_VARIABLES = ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"];
|
|
6
|
+
var nodeSetGlobalProxy = http.setGlobalProxyFromEnv;
|
|
7
|
+
function proxyVariable(env) {
|
|
8
|
+
return PROXY_VARIABLES.find((name) => (env[name] ?? "") !== "");
|
|
9
|
+
}
|
|
10
|
+
function envProxySupported(setGlobal = nodeSetGlobalProxy) {
|
|
11
|
+
return typeof setGlobal === "function";
|
|
12
|
+
}
|
|
13
|
+
function useEnvProxy(env, setGlobal = nodeSetGlobalProxy ?? null) {
|
|
14
|
+
if (proxyVariable(env) === void 0) return "none";
|
|
15
|
+
if (typeof setGlobal !== "function") return "unsupported";
|
|
16
|
+
try {
|
|
17
|
+
setGlobal(env);
|
|
18
|
+
return "set";
|
|
19
|
+
} catch {
|
|
20
|
+
return "invalid";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export {
|
|
25
|
+
PROXY_VARIABLES,
|
|
26
|
+
proxyVariable,
|
|
27
|
+
envProxySupported,
|
|
28
|
+
useEnvProxy
|
|
29
|
+
};
|
|
30
|
+
//# sourceMappingURL=chunk-ZLD6MJVJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/env-proxy.ts"],"sourcesContent":["import * as http from 'node:http';\n\n/** Named, never quoted: a proxy URL can carry its own credentials. */\nexport const PROXY_VARIABLES = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'] as const;\n\ntype SetGlobalProxy = (env: NodeJS.ProcessEnv) => () => void;\n\n/** Node 24.14 added it; `engines` still admits 24.0, where it is absent. */\nconst nodeSetGlobalProxy = (http as { setGlobalProxyFromEnv?: SetGlobalProxy })\n .setGlobalProxyFromEnv;\n\n/** The first proxy variable this environment sets, or undefined. */\nexport function proxyVariable(env: NodeJS.ProcessEnv): string | undefined {\n return PROXY_VARIABLES.find((name) => (env[name] ?? '') !== '');\n}\n\n/** Can this Node route `fetch` through the proxy the environment names? */\nexport function envProxySupported(setGlobal: unknown = nodeSetGlobalProxy): boolean {\n return typeof setGlobal === 'function';\n}\n\nexport type EnvProxyResult = 'none' | 'set' | 'unsupported' | 'invalid';\n\n/**\n * Send `fetch` and `https.request` through the proxy the environment names.\n * Node's `fetch` ignores HTTPS_PROXY, HTTP_PROXY and NO_PROXY unless\n * NODE_USE_ENV_PROXY=1, so on a network where the proxy is the only way out the\n * harness reaches the internet and Tenjin does not. Called once by the bin\n * entry, so the CLI, the hooks and `tenjin mcp` all get it. Never throws: a\n * proxy URL Node cannot parse leaves the transport as it was.\n */\nexport function useEnvProxy(\n env: NodeJS.ProcessEnv,\n setGlobal: SetGlobalProxy | null = nodeSetGlobalProxy ?? null,\n): EnvProxyResult {\n if (proxyVariable(env) === undefined) return 'none';\n if (typeof setGlobal !== 'function') return 'unsupported';\n try {\n setGlobal(env);\n return 'set';\n } catch {\n return 'invalid';\n }\n}\n"],"mappings":";;;AAAA,YAAY,UAAU;AAGf,IAAM,kBAAkB,CAAC,eAAe,eAAe,cAAc,YAAY;AAKxF,IAAM,qBACH;AAGI,SAAS,cAAc,KAA4C;AACxE,SAAO,gBAAgB,KAAK,CAAC,UAAU,IAAI,IAAI,KAAK,QAAQ,EAAE;AAChE;AAGO,SAAS,kBAAkB,YAAqB,oBAA6B;AAClF,SAAO,OAAO,cAAc;AAC9B;AAYO,SAAS,YACd,KACA,YAAmC,sBAAsB,MACzC;AAChB,MAAI,cAAc,GAAG,MAAM,OAAW,QAAO;AAC7C,MAAI,OAAO,cAAc,WAAY,QAAO;AAC5C,MAAI;AACF,cAAU,GAAG;AACb,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -2,7 +2,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
|
|
|
2
2
|
import {
|
|
3
3
|
maybeUpdate,
|
|
4
4
|
readUpdateSignal
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-W36HL4TB.js";
|
|
6
6
|
import {
|
|
7
7
|
defaultIo,
|
|
8
8
|
emitFailure,
|
|
@@ -10,19 +10,19 @@ import {
|
|
|
10
10
|
} from "./chunk-UDWGT4FX.js";
|
|
11
11
|
import {
|
|
12
12
|
noteBaseUrlFlag
|
|
13
|
-
} from "./chunk-
|
|
14
|
-
import "./chunk-
|
|
13
|
+
} from "./chunk-WT7DHJNJ.js";
|
|
14
|
+
import "./chunk-5INS5ZZF.js";
|
|
15
15
|
import {
|
|
16
16
|
PERMISSIONS_DOC_URL
|
|
17
17
|
} from "./chunk-A36LQPHV.js";
|
|
18
|
+
import {
|
|
19
|
+
package_default
|
|
20
|
+
} from "./chunk-GHR4BTNJ.js";
|
|
18
21
|
import "./chunk-2I4QTOLB.js";
|
|
19
22
|
import "./chunk-HII5HOQV.js";
|
|
20
23
|
import {
|
|
21
24
|
external_exports
|
|
22
25
|
} from "./chunk-XICKN3CH.js";
|
|
23
|
-
import {
|
|
24
|
-
package_default
|
|
25
|
-
} from "./chunk-ODH7UXIS.js";
|
|
26
26
|
import {
|
|
27
27
|
CliError
|
|
28
28
|
} from "./chunk-JLEF5WHM.js";
|
|
@@ -3495,7 +3495,7 @@ function registerCore(reg) {
|
|
|
3495
3495
|
const { runCommand, leaf: leaf2, addGlobalFlags: addGlobalFlags2 } = reg;
|
|
3496
3496
|
leaf2(SETUP, "install", "set up Tenjin for Claude Code and create a wallet").description(
|
|
3497
3497
|
"Set up Claude Code to use Tenjin: seven hook entries, the `x402` MCP server and its permission rule, spend limits for each lookup, and a wallet if this machine has none."
|
|
3498
|
-
).option("--project", "write into this project's .claude/settings.json instead of your home one").option("--no-wallet", "create no wallet").option("--refresh", "re-register the hook entries this machine already has; add nothing").option(
|
|
3498
|
+
).option("--project", "write into this project's .claude/settings.json instead of your home one").option("--no-wallet", "create no wallet").option("--refresh", "re-register the hook entries this machine already has; add nothing").option("--yes", "accept the default spend limits instead of asking").option(
|
|
3499
3499
|
"--status-line <mode>",
|
|
3500
3500
|
"the live footer: `own` registers it when you have no status line of your own, `compose` appends it to the one you do have, `skip` leaves the setting alone"
|
|
3501
3501
|
).addHelpText(
|
|
@@ -3512,12 +3512,13 @@ Learn more:
|
|
|
3512
3512
|
).action(async function() {
|
|
3513
3513
|
await runCommand("install", this, async (ctx) => {
|
|
3514
3514
|
const o = this.opts();
|
|
3515
|
-
const { runRouterInstall } = await import("./install-
|
|
3516
|
-
const { statusLineMode } = await import("./status-line-wiring-
|
|
3515
|
+
const { runRouterInstall } = await import("./install-REPLHNU7.js");
|
|
3516
|
+
const { statusLineMode } = await import("./status-line-wiring-LW4HFRHB.js");
|
|
3517
3517
|
return runRouterInstall(
|
|
3518
3518
|
{
|
|
3519
3519
|
...o.project === true ? { project: true } : {},
|
|
3520
3520
|
...o.refresh === true ? { refresh: true } : {},
|
|
3521
|
+
...o.yes === true ? { yes: true } : {},
|
|
3521
3522
|
...o.statusLine !== void 0 ? { statusLine: statusLineMode(String(o.statusLine)) } : {},
|
|
3522
3523
|
...o.wallet === false ? { noWallet: true } : {}
|
|
3523
3524
|
},
|
|
@@ -3530,7 +3531,7 @@ Learn more:
|
|
|
3530
3531
|
).option("--project", "remove from this project's .claude/settings.json").action(async function() {
|
|
3531
3532
|
await runCommand("uninstall", this, async (ctx) => {
|
|
3532
3533
|
const o = this.opts();
|
|
3533
|
-
const { runRouterUninstall } = await import("./uninstall-
|
|
3534
|
+
const { runRouterUninstall } = await import("./uninstall-NVTGU7JD.js");
|
|
3534
3535
|
return runRouterUninstall({ ...o.project === true ? { project: true } : {} }, ctx);
|
|
3535
3536
|
});
|
|
3536
3537
|
});
|
|
@@ -3546,7 +3547,7 @@ Examples:
|
|
|
3546
3547
|
`
|
|
3547
3548
|
).action(async function() {
|
|
3548
3549
|
await runCommand("doctor", this, async (ctx) => {
|
|
3549
|
-
const { runRouterDoctor } = await import("./doctor-
|
|
3550
|
+
const { runRouterDoctor } = await import("./doctor-BD42BBEG.js");
|
|
3550
3551
|
return runRouterDoctor(ctx, this.opts().project === true ? { project: true } : {});
|
|
3551
3552
|
});
|
|
3552
3553
|
});
|
|
@@ -3554,7 +3555,7 @@ Examples:
|
|
|
3554
3555
|
"Update tenjin-cli to the newest version npm publishes on the latest tag. It then runs `install --refresh` on the new binary, so every profile on this machine gets the skills and hook scripts of the build that just landed."
|
|
3555
3556
|
).option("--check", "report whether a newer version exists without installing it").action(async function() {
|
|
3556
3557
|
await runCommand("update", this, async (ctx) => {
|
|
3557
|
-
const { runUpdate } = await import("./update-
|
|
3558
|
+
const { runUpdate } = await import("./update-QXVH2DE7.js");
|
|
3558
3559
|
return runUpdate({ check: this.opts().check === true }, ctx);
|
|
3559
3560
|
});
|
|
3560
3561
|
});
|
|
@@ -3573,7 +3574,7 @@ Examples:
|
|
|
3573
3574
|
);
|
|
3574
3575
|
config.action(async function() {
|
|
3575
3576
|
await runCommand("config", this, async (ctx) => {
|
|
3576
|
-
const { runConfigList } = await import("./config-
|
|
3577
|
+
const { runConfigList } = await import("./config-44EGO636.js");
|
|
3577
3578
|
return runConfigList(ctx);
|
|
3578
3579
|
});
|
|
3579
3580
|
});
|
|
@@ -3581,7 +3582,7 @@ Examples:
|
|
|
3581
3582
|
"Print one effective config value by key. The effective value is what the command would use, defaults and environment overrides included."
|
|
3582
3583
|
).action(async function(key) {
|
|
3583
3584
|
await runCommand("config.get", this, async (ctx) => {
|
|
3584
|
-
const { runConfigGet } = await import("./config-
|
|
3585
|
+
const { runConfigGet } = await import("./config-44EGO636.js");
|
|
3585
3586
|
return runConfigGet({ key }, ctx);
|
|
3586
3587
|
});
|
|
3587
3588
|
});
|
|
@@ -3593,7 +3594,7 @@ Examples:
|
|
|
3593
3594
|
).option("--local", "with --project, write .tenjin/config.local.json instead, which is yours").action(async function(key, value) {
|
|
3594
3595
|
const o = this.opts();
|
|
3595
3596
|
await runCommand("config.set", this, async (ctx) => {
|
|
3596
|
-
const { runConfigSet } = await import("./config-
|
|
3597
|
+
const { runConfigSet } = await import("./config-44EGO636.js");
|
|
3597
3598
|
return runConfigSet(
|
|
3598
3599
|
{ key, value, project: o.project === true, local: o.local === true },
|
|
3599
3600
|
ctx
|
|
@@ -3615,38 +3616,40 @@ Examples:
|
|
|
3615
3616
|
).action(async function() {
|
|
3616
3617
|
await runCommand("wallet.create", this, async (ctx) => {
|
|
3617
3618
|
const o = this.opts();
|
|
3618
|
-
const { runWalletCreate } = await import("./wallet-
|
|
3619
|
+
const { runWalletCreate } = await import("./wallet-CKKB23D5.js");
|
|
3619
3620
|
return runWalletCreate(ctx, o.replace === true ? { replace: true } : {});
|
|
3620
3621
|
});
|
|
3621
3622
|
});
|
|
3622
|
-
addGlobalFlags2(wallet.command("show")).summary("show the wallet address and key source").description(
|
|
3623
|
-
"Print the active wallet address and where its key comes from. The private key is never printed, by any flag."
|
|
3624
|
-
).action(async function() {
|
|
3623
|
+
addGlobalFlags2(wallet.command("show")).alias("address").summary("show the wallet address and key source").description(
|
|
3624
|
+
"Print the active wallet address and where its key comes from. The private key is never printed, by any flag. At a terminal it also draws the address as a QR code for a phone wallet to scan."
|
|
3625
|
+
).option("--no-qr", "print the address without the QR code").action(async function() {
|
|
3625
3626
|
await runCommand("wallet.show", this, async (ctx) => {
|
|
3626
|
-
const
|
|
3627
|
-
|
|
3627
|
+
const o = this.opts();
|
|
3628
|
+
const { runWalletShow } = await import("./wallet-CKKB23D5.js");
|
|
3629
|
+
return runWalletShow(ctx, o.qr === false ? { qr: false } : {});
|
|
3628
3630
|
});
|
|
3629
3631
|
});
|
|
3630
3632
|
addGlobalFlags2(wallet.command("balance")).summary("show the wallet USDC balance on Base").description(
|
|
3631
3633
|
"Read the wallet USDC balance on Base. It is a chain read: no key is unlocked and nothing is spent."
|
|
3632
3634
|
).action(async function() {
|
|
3633
3635
|
await runCommand("wallet.balance", this, async (ctx) => {
|
|
3634
|
-
const { runWalletBalance } = await import("./wallet-
|
|
3636
|
+
const { runWalletBalance } = await import("./wallet-CKKB23D5.js");
|
|
3635
3637
|
return runWalletBalance(ctx);
|
|
3636
3638
|
});
|
|
3637
3639
|
});
|
|
3638
3640
|
addGlobalFlags2(wallet.command("fund [amountUsd]")).summary("card-fund this wallet through Coinbase Onramp").description(
|
|
3639
3641
|
"Mint a Coinbase Onramp checkout link bound to THIS wallet, open it in the browser, and wait for the USDC to land on Base. Minting moves no money: a human completes the payment on pay.coinbase.com."
|
|
3640
|
-
).option("--no-open", "print the checkout link without opening a browser").option(
|
|
3642
|
+
).option("--no-open", "print the checkout link without opening a browser").option("--no-qr", "skip the QR code of the address for sending USDC from a phone").option(
|
|
3641
3643
|
"--no-wait",
|
|
3642
3644
|
"return once the link is issued instead of polling the balance (already the default when not at a TTY)"
|
|
3643
3645
|
).action(async function(amountUsd) {
|
|
3644
3646
|
await runCommand("wallet.fund", this, async (ctx) => {
|
|
3645
3647
|
const o = this.opts();
|
|
3646
|
-
const { runFund } = await import("./fund-
|
|
3648
|
+
const { runFund } = await import("./fund-WQOOUESE.js");
|
|
3647
3649
|
return runFund(ctx, {
|
|
3648
3650
|
...amountUsd !== void 0 ? { amountUsd } : {},
|
|
3649
3651
|
...o.open === false ? { open: false } : {},
|
|
3652
|
+
...o.qr === false ? { qr: false } : {},
|
|
3650
3653
|
...o.wait === false ? { wait: false } : {}
|
|
3651
3654
|
});
|
|
3652
3655
|
});
|
|
@@ -3662,7 +3665,7 @@ Examples:
|
|
|
3662
3665
|
).action(async function(amount, token, to) {
|
|
3663
3666
|
await runCommand("wallet.send", this, async (ctx) => {
|
|
3664
3667
|
const o = this.opts();
|
|
3665
|
-
const { runSend } = await import("./send-
|
|
3668
|
+
const { runSend } = await import("./send-YHDKZPED.js");
|
|
3666
3669
|
return runSend({ amount, token, to, ...o.yes === true ? { yes: true } : {} }, ctx);
|
|
3667
3670
|
});
|
|
3668
3671
|
});
|
|
@@ -3682,7 +3685,7 @@ Examples:
|
|
|
3682
3685
|
).action(async function(url) {
|
|
3683
3686
|
await runCommand("pay", this, async (ctx) => {
|
|
3684
3687
|
const o = this.opts();
|
|
3685
|
-
const { runPay } = await import("./pay-
|
|
3688
|
+
const { runPay } = await import("./pay-276DSSYG.js");
|
|
3686
3689
|
return runPay(
|
|
3687
3690
|
{
|
|
3688
3691
|
url,
|
|
@@ -3718,7 +3721,7 @@ function registerRouter(reg) {
|
|
|
3718
3721
|
]) {
|
|
3719
3722
|
addGlobalFlags2(hook.command(name)).summary(summary).action(async function() {
|
|
3720
3723
|
const ctx = buildContext2(this);
|
|
3721
|
-
const { runHookCommand } = await import("./hook-command-
|
|
3724
|
+
const { runHookCommand } = await import("./hook-command-23LC5NRN.js");
|
|
3722
3725
|
await runHookCommand(name, io, {
|
|
3723
3726
|
dataDir: ctx.dataDir,
|
|
3724
3727
|
...ctx.flags.baseUrl !== void 0 ? { baseUrl: ctx.flags.baseUrl } : {}
|
|
@@ -3731,7 +3734,7 @@ function registerRouter(reg) {
|
|
|
3731
3734
|
"Run the local stdio MCP server that carries the `request` tool: one free routing decision per lookup, then the provider call, built here from the offer's spec and your assistant's input where it has one, under your local spend policy. It speaks on stdin and stdout and runs until the client disconnects, so it prints no envelope of its own."
|
|
3732
3735
|
).action(async function() {
|
|
3733
3736
|
const ctx = buildContext2(this);
|
|
3734
|
-
const { runRouterMcpServer } = await import("./mcp-
|
|
3737
|
+
const { runRouterMcpServer } = await import("./mcp-T5SYCLP7.js");
|
|
3735
3738
|
await runRouterMcpServer({ dataDir: ctx.dataDir, flags: ctx.flags });
|
|
3736
3739
|
});
|
|
3737
3740
|
leaf2(INTEGRATION, "status-line", "the live footer, for Claude Code's status line").description(
|
|
@@ -3745,7 +3748,7 @@ function registerRouter(reg) {
|
|
|
3745
3748
|
"Report the rolling 24h spend window from spend.json: what has settled, what is reserved by a request still in flight, and the per-call and per-day caps in force."
|
|
3746
3749
|
).action(async function() {
|
|
3747
3750
|
await runCommand("status", this, async (ctx) => {
|
|
3748
|
-
const { runRouterStatus } = await import("./status-
|
|
3751
|
+
const { runRouterStatus } = await import("./status-X2INT6VD.js");
|
|
3749
3752
|
return runRouterStatus(ctx);
|
|
3750
3753
|
});
|
|
3751
3754
|
});
|
|
@@ -3756,7 +3759,7 @@ function registerRouter(reg) {
|
|
|
3756
3759
|
"For each paid lookup whose seller never confirmed settlement and whose authorization has expired, ask USDC on Base (through the configured rpcUrl) whether it was used: used means it was charged, unused means it never can be. Nothing is signed or sent but that one read."
|
|
3757
3760
|
).action(async function() {
|
|
3758
3761
|
await runCommand("payments.reconcile", this, async (ctx) => {
|
|
3759
|
-
const { runPaymentsReconcile } = await import("./payments-
|
|
3762
|
+
const { runPaymentsReconcile } = await import("./payments-TZYLJXK3.js");
|
|
3760
3763
|
return runPaymentsReconcile(ctx);
|
|
3761
3764
|
});
|
|
3762
3765
|
});
|
|
@@ -3906,4 +3909,4 @@ export {
|
|
|
3906
3909
|
buildProgram,
|
|
3907
3910
|
main
|
|
3908
3911
|
};
|
|
3909
|
-
//# sourceMappingURL=cli-
|
|
3912
|
+
//# sourceMappingURL=cli-2U5JB7OQ.js.map
|