tenjin-cli 0.1.0-alpha.13 → 0.1.0-alpha.15
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 +51 -3
- package/dist/buy-VIRNSYGN.js +47 -0
- package/dist/{chunk-OC3EIDCP.js → chunk-2MYQN7HM.js} +71 -26
- package/dist/chunk-2MYQN7HM.js.map +1 -0
- package/dist/{chunk-XXY77EZJ.js → chunk-2RF2GIJQ.js} +57 -226
- package/dist/chunk-2RF2GIJQ.js.map +1 -0
- package/dist/chunk-3GL2Z5QK.js +57 -0
- package/dist/chunk-3GL2Z5QK.js.map +1 -0
- package/dist/{chunk-OXUJ3FXU.js → chunk-4CQIDQOT.js} +41 -8
- package/dist/chunk-4CQIDQOT.js.map +1 -0
- package/dist/{chunk-YMUJZWHB.js → chunk-4KG27W2S.js} +10 -10
- package/dist/chunk-4KG27W2S.js.map +1 -0
- package/dist/{chunk-SPUORKD7.js → chunk-5QQTYWEU.js} +13 -13
- package/dist/chunk-5QQTYWEU.js.map +1 -0
- package/dist/chunk-65DTCCJ7.js +21 -0
- package/dist/chunk-65DTCCJ7.js.map +1 -0
- package/dist/{chunk-BRAVLUGI.js → chunk-A5DKHMUN.js} +28 -13
- package/dist/chunk-A5DKHMUN.js.map +1 -0
- package/dist/chunk-B63XPWQ4.js +246 -0
- package/dist/chunk-B63XPWQ4.js.map +1 -0
- package/dist/{chunk-47YKYDOF.js → chunk-CAR6FHK6.js} +5 -5
- package/dist/{chunk-JVBMPU5G.js → chunk-CPCX67TI.js} +22 -22
- package/dist/{chunk-TXVC46SA.js → chunk-CQBVCYI2.js} +40 -53
- package/dist/chunk-CQBVCYI2.js.map +1 -0
- package/dist/chunk-DBU5CXBV.js +4731 -0
- package/dist/chunk-DBU5CXBV.js.map +1 -0
- package/dist/chunk-DHJD77OW.js +81 -0
- package/dist/chunk-DHJD77OW.js.map +1 -0
- package/dist/{chunk-XGZ5EVMB.js → chunk-EDZSNPE5.js} +2 -2
- package/dist/{chunk-736DW4V3.js → chunk-EFWZPUTC.js} +2 -2
- package/dist/chunk-EPFL6CTE.js +448 -0
- package/dist/chunk-EPFL6CTE.js.map +1 -0
- package/dist/{chunk-3P3ES4XU.js → chunk-GHLVXVZD.js} +3 -5
- package/dist/{chunk-3P3ES4XU.js.map → chunk-GHLVXVZD.js.map} +1 -1
- package/dist/{chunk-UUARTUY2.js → chunk-H3SOOJ2I.js} +264 -33
- package/dist/chunk-H3SOOJ2I.js.map +1 -0
- package/dist/{chunk-OUJDDY5L.js → chunk-HPJGOLTN.js} +32 -32
- package/dist/chunk-HPJGOLTN.js.map +1 -0
- package/dist/{chunk-J6FUAIRR.js → chunk-HRGBS2PA.js} +4 -6
- package/dist/{chunk-J6FUAIRR.js.map → chunk-HRGBS2PA.js.map} +1 -1
- package/dist/{chunk-NKN4YC5C.js → chunk-ITUXPJIS.js} +55 -58
- package/dist/chunk-ITUXPJIS.js.map +1 -0
- package/dist/{chunk-CA3JV7FX.js → chunk-JBIKAAT3.js} +2 -2
- package/dist/{chunk-CA3JV7FX.js.map → chunk-JBIKAAT3.js.map} +1 -1
- package/dist/{chunk-6JKD46OJ.js → chunk-KAJZHIQ4.js} +13 -10
- package/dist/chunk-KAJZHIQ4.js.map +1 -0
- package/dist/{chunk-OWVVI4VQ.js → chunk-KINZ23CV.js} +107 -4535
- package/dist/chunk-KINZ23CV.js.map +1 -0
- package/dist/{chunk-WMFRCSNC.js → chunk-LRYV3SK7.js} +9 -7
- package/dist/{chunk-WMFRCSNC.js.map → chunk-LRYV3SK7.js.map} +1 -1
- package/dist/{chunk-T4UWMVKV.js → chunk-NIKXHWOL.js} +11 -13
- package/dist/{chunk-T4UWMVKV.js.map → chunk-NIKXHWOL.js.map} +1 -1
- package/dist/chunk-OKDRDT74.js +209 -0
- package/dist/chunk-OKDRDT74.js.map +1 -0
- package/dist/chunk-OKYSNAS3.js +2144 -0
- package/dist/chunk-OKYSNAS3.js.map +1 -0
- package/dist/{chunk-B676GPS2.js → chunk-OLWTRUTS.js} +7 -3
- package/dist/{chunk-B676GPS2.js.map → chunk-OLWTRUTS.js.map} +1 -1
- package/dist/{chunk-WU5CZPLD.js → chunk-QQ6ELLSA.js} +6 -8
- package/dist/{chunk-WU5CZPLD.js.map → chunk-QQ6ELLSA.js.map} +1 -1
- package/dist/{chunk-WVHPGQH5.js → chunk-QZ6ROAJU.js} +8 -4
- package/dist/chunk-QZ6ROAJU.js.map +1 -0
- package/dist/{chunk-L4XNT3UW.js → chunk-R7RSCBI7.js} +167 -52
- package/dist/chunk-R7RSCBI7.js.map +1 -0
- package/dist/{chunk-ELVDOTU7.js → chunk-U6VPKMGC.js} +128 -28
- package/dist/chunk-U6VPKMGC.js.map +1 -0
- package/dist/{chunk-FKSAUOJU.js → chunk-UO22YNY4.js} +1 -69
- package/dist/chunk-UO22YNY4.js.map +1 -0
- package/dist/{chunk-IAR25V2E.js → chunk-US456VUI.js} +6 -6
- package/dist/{chunk-IKAJSA7E.js → chunk-V44J2MXV.js} +80 -34
- package/dist/chunk-V44J2MXV.js.map +1 -0
- package/dist/{chunk-IFPKA32J.js → chunk-VJQKL3YH.js} +10 -7
- package/dist/{chunk-IFPKA32J.js.map → chunk-VJQKL3YH.js.map} +1 -1
- package/dist/{chunk-GCGMXA2O.js → chunk-VJSQSLBM.js} +52 -20
- package/dist/chunk-VJSQSLBM.js.map +1 -0
- package/dist/{chunk-IGHSLJUF.js → chunk-VYOJOX4Z.js} +9 -7
- package/dist/chunk-VYOJOX4Z.js.map +1 -0
- package/dist/chunk-WY2K35OL.js +269 -0
- package/dist/chunk-WY2K35OL.js.map +1 -0
- package/dist/{chunk-PAOVPSP6.js → chunk-ZFJJ3EXC.js} +53 -5
- package/dist/chunk-ZFJJ3EXC.js.map +1 -0
- package/dist/chunk-ZOBNS7CX.js +73 -0
- package/dist/chunk-ZOBNS7CX.js.map +1 -0
- package/dist/{cli-XK5JZWU6.js → cli-KKRKBU5T.js} +76 -47
- package/dist/{cli-XK5JZWU6.js.map → cli-KKRKBU5T.js.map} +1 -1
- package/dist/config-JMRUNYE6.js +37 -0
- package/dist/discover-B5HF6SHM.js +102 -0
- package/dist/discover-B5HF6SHM.js.map +1 -0
- package/dist/doctor-ZBG7X66D.js +32 -0
- package/dist/edit-PZJIILQE.js +40 -0
- package/dist/{fund-JF6A76YS.js → fund-EUDH5KPA.js} +19 -17
- package/dist/index.js +1 -1
- package/dist/inspect-QC6WEQPN.js +37 -0
- package/dist/{install-YQVM3SUW.js → install-GNK2W3PI.js} +286 -447
- package/dist/install-GNK2W3PI.js.map +1 -0
- package/dist/outcome-KSGWZHUS.js +24 -0
- package/dist/pay-BC4UICPA.js +361 -0
- package/dist/pay-BC4UICPA.js.map +1 -0
- package/dist/publish-LXWFDIKF.js +42 -0
- package/dist/{read-UF7QVQOU.js → read-JMNUQ56P.js} +22 -20
- package/dist/{read-UF7QVQOU.js.map → read-JMNUQ56P.js.map} +1 -1
- package/dist/{run-GDZWHNWZ.js → run-XYTQ5TWQ.js} +54 -45
- package/dist/{run-GDZWHNWZ.js.map → run-XYTQ5TWQ.js.map} +1 -1
- package/dist/search-TSQAB45E.js +25 -0
- package/dist/{send-SI254H3R.js → send-G746D7PQ.js} +14 -14
- package/dist/{session-GJZJEXLJ.js → session-JBKWMJ24.js} +18 -17
- package/dist/{session-GJZJEXLJ.js.map → session-JBKWMJ24.js.map} +1 -1
- package/dist/{skill-heal-BPFT22XS.js → skill-heal-WKD67SLJ.js} +17 -9
- package/dist/skill-heal-WKD67SLJ.js.map +1 -0
- package/dist/skill-placement-RIU4AMC2.js +20 -0
- package/dist/{uninstall-7ZZG6WQ5.js → uninstall-5E263VTS.js} +15 -9
- package/dist/uninstall-5E263VTS.js.map +1 -0
- package/dist/{update-FPSBITLB.js → update-R76LHOZW.js} +18 -16
- package/dist/update-R76LHOZW.js.map +1 -0
- package/dist/{wallet-NS7TYWNN.js → wallet-TQ7D5EQ7.js} +7 -7
- package/dist/{wallet-TZVD2M4I.js → wallet-ZAVXWLWP.js} +11 -11
- package/dist/wallet-ZAVXWLWP.js.map +1 -0
- package/docs/agent-permissions.md +117 -18
- package/docs/command-reference.md +102 -50
- package/docs/safety-model.md +9 -0
- package/package.json +1 -1
- package/skills/tenjin/SKILL.md +38 -29
- package/skills/tenjin-pay/SKILL.md +76 -0
- package/skills/tenjin-publish/SKILL.md +184 -205
- package/skills/tenjin-publish/references/maintain.md +39 -0
- package/skills/tenjin-search/SKILL.md +92 -280
- package/skills/tenjin-search/references/permissions.md +112 -0
- package/dist/buy-X4VPHFUA.js +0 -44
- package/dist/chunk-3NZCU6SD.js +0 -125
- package/dist/chunk-3NZCU6SD.js.map +0 -1
- package/dist/chunk-6JKD46OJ.js.map +0 -1
- package/dist/chunk-BRAVLUGI.js.map +0 -1
- package/dist/chunk-ELVDOTU7.js.map +0 -1
- package/dist/chunk-FKSAUOJU.js.map +0 -1
- package/dist/chunk-GCGMXA2O.js.map +0 -1
- package/dist/chunk-IGHSLJUF.js.map +0 -1
- package/dist/chunk-IKAJSA7E.js.map +0 -1
- package/dist/chunk-L4XNT3UW.js.map +0 -1
- package/dist/chunk-NKN4YC5C.js.map +0 -1
- package/dist/chunk-OC3EIDCP.js.map +0 -1
- package/dist/chunk-OE36HRWG.js +0 -939
- package/dist/chunk-OE36HRWG.js.map +0 -1
- package/dist/chunk-OUJDDY5L.js.map +0 -1
- package/dist/chunk-OWVVI4VQ.js.map +0 -1
- package/dist/chunk-OXUJ3FXU.js.map +0 -1
- package/dist/chunk-PAOVPSP6.js.map +0 -1
- package/dist/chunk-SPUORKD7.js.map +0 -1
- package/dist/chunk-TXVC46SA.js.map +0 -1
- package/dist/chunk-UUARTUY2.js.map +0 -1
- package/dist/chunk-WVHPGQH5.js.map +0 -1
- package/dist/chunk-XXY77EZJ.js.map +0 -1
- package/dist/chunk-YMUJZWHB.js.map +0 -1
- package/dist/chunk-ZQIQ55KK.js +0 -51
- package/dist/chunk-ZQIQ55KK.js.map +0 -1
- package/dist/config-CNK7MYUR.js +0 -26
- package/dist/doctor-R7N7FUX5.js +0 -27
- package/dist/edit-QSUEG7CL.js +0 -38
- package/dist/inspect-NFNAA4LA.js +0 -35
- package/dist/install-YQVM3SUW.js.map +0 -1
- package/dist/outcome-IUSYFJTN.js +0 -22
- package/dist/publish-O2I6IAEL.js +0 -40
- package/dist/search-JVOHEF3E.js +0 -23
- package/dist/skill-heal-BPFT22XS.js.map +0 -1
- package/dist/uninstall-7ZZG6WQ5.js.map +0 -1
- package/dist/update-FPSBITLB.js.map +0 -1
- /package/dist/{buy-X4VPHFUA.js.map → buy-VIRNSYGN.js.map} +0 -0
- /package/dist/{chunk-47YKYDOF.js.map → chunk-CAR6FHK6.js.map} +0 -0
- /package/dist/{chunk-JVBMPU5G.js.map → chunk-CPCX67TI.js.map} +0 -0
- /package/dist/{chunk-XGZ5EVMB.js.map → chunk-EDZSNPE5.js.map} +0 -0
- /package/dist/{chunk-736DW4V3.js.map → chunk-EFWZPUTC.js.map} +0 -0
- /package/dist/{chunk-IAR25V2E.js.map → chunk-US456VUI.js.map} +0 -0
- /package/dist/{config-CNK7MYUR.js.map → config-JMRUNYE6.js.map} +0 -0
- /package/dist/{doctor-R7N7FUX5.js.map → doctor-ZBG7X66D.js.map} +0 -0
- /package/dist/{edit-QSUEG7CL.js.map → edit-PZJIILQE.js.map} +0 -0
- /package/dist/{fund-JF6A76YS.js.map → fund-EUDH5KPA.js.map} +0 -0
- /package/dist/{inspect-NFNAA4LA.js.map → inspect-QC6WEQPN.js.map} +0 -0
- /package/dist/{outcome-IUSYFJTN.js.map → outcome-KSGWZHUS.js.map} +0 -0
- /package/dist/{publish-O2I6IAEL.js.map → publish-LXWFDIKF.js.map} +0 -0
- /package/dist/{search-JVOHEF3E.js.map → search-TSQAB45E.js.map} +0 -0
- /package/dist/{send-SI254H3R.js.map → send-G746D7PQ.js.map} +0 -0
- /package/dist/{wallet-NS7TYWNN.js.map → skill-placement-RIU4AMC2.js.map} +0 -0
- /package/dist/{wallet-TZVD2M4I.js.map → wallet-TQ7D5EQ7.js.map} +0 -0
|
@@ -1,20 +1,18 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
package_default
|
|
4
|
-
} from "./chunk-CA3JV7FX.js";
|
|
5
2
|
import {
|
|
6
3
|
emitNotice
|
|
7
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-OLWTRUTS.js";
|
|
8
5
|
import {
|
|
9
6
|
loadConfig
|
|
10
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-U6VPKMGC.js";
|
|
11
8
|
import {
|
|
12
|
-
|
|
13
|
-
} from "./chunk-
|
|
9
|
+
package_default
|
|
10
|
+
} from "./chunk-JBIKAAT3.js";
|
|
14
11
|
import {
|
|
15
12
|
external_exports,
|
|
13
|
+
updateCheckPath,
|
|
16
14
|
writeFileAtomic
|
|
17
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-ZFJJ3EXC.js";
|
|
18
16
|
|
|
19
17
|
// src/lib/update-check.ts
|
|
20
18
|
import { readFile } from "fs/promises";
|
|
@@ -23,7 +21,8 @@ var FETCH_TIMEOUT_MS = 1500;
|
|
|
23
21
|
var DIST_TAGS_URL = "https://registry.npmjs.org/-/package/tenjin-cli/dist-tags";
|
|
24
22
|
var TagEntrySchema = external_exports.object({
|
|
25
23
|
checkedAtMs: external_exports.number(),
|
|
26
|
-
|
|
24
|
+
/** The version the tag named. Absent when the answer was unusable. */
|
|
25
|
+
latest: external_exports.string().optional(),
|
|
27
26
|
/** When the nudge was last PRINTED for this tag. Absent until one has been. */
|
|
28
27
|
notifiedAtMs: external_exports.number().optional()
|
|
29
28
|
});
|
|
@@ -57,14 +56,20 @@ async function maybeUpdate(deps) {
|
|
|
57
56
|
const cached = await readCache(path);
|
|
58
57
|
const entry = cached?.tags[tag];
|
|
59
58
|
const fresh = entry !== void 0 && nowMs - entry.checkedAtMs < CHECK_INTERVAL_MS;
|
|
60
|
-
|
|
61
|
-
if (
|
|
62
|
-
|
|
59
|
+
let latest;
|
|
60
|
+
if (fresh) {
|
|
61
|
+
latest = entry.latest ?? null;
|
|
62
|
+
} else {
|
|
63
|
+
const answer = await resolveLatest(current, deps);
|
|
64
|
+
if (answer === null) return;
|
|
65
|
+
latest = answer.latest;
|
|
66
|
+
}
|
|
67
|
+
const upgradeable = latest !== null && isNewer(latest, current);
|
|
63
68
|
const human = deps.io.isTTY && !deps.json;
|
|
64
69
|
const notifiedAtMs = entry?.notifiedAtMs;
|
|
65
70
|
const due = human && upgradeable && (notifiedAtMs === void 0 || nowMs - notifiedAtMs >= CHECK_INTERVAL_MS);
|
|
66
71
|
const nudgedAtMs = due ? nowMs : notifiedAtMs;
|
|
67
|
-
const signal = upgradeable ? { current, latest } : void 0;
|
|
72
|
+
const signal = upgradeable && latest !== null ? { current, latest } : void 0;
|
|
68
73
|
const signalChanged = cached?.signal?.current !== signal?.current || cached?.signal?.latest !== signal?.latest;
|
|
69
74
|
if (!fresh || due || signalChanged) {
|
|
70
75
|
await writeCache(path, {
|
|
@@ -76,18 +81,19 @@ async function maybeUpdate(deps) {
|
|
|
76
81
|
...cached?.tags,
|
|
77
82
|
[tag]: {
|
|
78
83
|
checkedAtMs: fresh ? entry.checkedAtMs : nowMs,
|
|
79
|
-
latest,
|
|
84
|
+
...latest !== null ? { latest } : {},
|
|
80
85
|
...nudgedAtMs !== void 0 ? { notifiedAtMs: nudgedAtMs } : {}
|
|
81
86
|
}
|
|
82
87
|
}
|
|
83
88
|
});
|
|
84
89
|
}
|
|
85
|
-
if (
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
90
|
+
if (due && latest !== null) {
|
|
91
|
+
emitNotice(
|
|
92
|
+
deps.io,
|
|
93
|
+
`tenjin-cli ${latest} is available (you have ${current}). Update: run tenjin update`,
|
|
94
|
+
{ json: deps.json }
|
|
95
|
+
);
|
|
96
|
+
}
|
|
91
97
|
} catch {
|
|
92
98
|
}
|
|
93
99
|
}
|
|
@@ -106,20 +112,14 @@ async function readUpdateSignal(dir, currentVersion) {
|
|
|
106
112
|
}
|
|
107
113
|
}
|
|
108
114
|
function channelTag(version) {
|
|
109
|
-
|
|
110
|
-
if (parsed === null) return null;
|
|
111
|
-
return parsed.alpha !== null ? "alpha" : "latest";
|
|
115
|
+
return parseVersion(version) === null ? null : "latest";
|
|
112
116
|
}
|
|
113
117
|
function resolveTarget(current, tags) {
|
|
114
118
|
const channel = channelTag(current);
|
|
115
119
|
if (channel === null) return null;
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
if (candidate === void 0 || parseVersion(candidate) === null) continue;
|
|
120
|
-
if (best === null || isNewer(candidate, best)) best = candidate;
|
|
121
|
-
}
|
|
122
|
-
return best;
|
|
120
|
+
const candidate = tags[channel];
|
|
121
|
+
if (candidate === void 0 || parseVersion(candidate) === null) return null;
|
|
122
|
+
return candidate;
|
|
123
123
|
}
|
|
124
124
|
async function fetchDistTags(opts) {
|
|
125
125
|
const doFetch = opts.fetchImpl ?? fetch;
|
|
@@ -136,7 +136,7 @@ async function fetchDistTags(opts) {
|
|
|
136
136
|
}
|
|
137
137
|
async function resolveLatest(current, deps) {
|
|
138
138
|
const tags = await fetchDistTags({ fetchImpl: deps.fetchImpl, timeoutMs: FETCH_TIMEOUT_MS });
|
|
139
|
-
return tags === null ? null : resolveTarget(current, tags);
|
|
139
|
+
return tags === null ? null : { latest: resolveTarget(current, tags) };
|
|
140
140
|
}
|
|
141
141
|
async function writeCache(path, cache) {
|
|
142
142
|
await writeFileAtomic(path, `${JSON.stringify(cache, null, 2)}
|
|
@@ -186,4 +186,4 @@ export {
|
|
|
186
186
|
fetchDistTags,
|
|
187
187
|
isNewer
|
|
188
188
|
};
|
|
189
|
-
//# sourceMappingURL=chunk-
|
|
189
|
+
//# sourceMappingURL=chunk-HPJGOLTN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/update-check.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { z } from 'zod';\nimport pkg from '../../package.json';\nimport { writeFileAtomic } from './atomic-json';\nimport { loadConfig } from './config';\nimport type { UpdateMode } from './config';\nimport { emitNotice } from './output';\nimport type { Io } from './output';\nimport type { UpdateAvailable } from '../schemas';\nimport { updateCheckPath } from './paths';\n\n/**\n * \"A newer tenjin-cli exists\", asked of npm at most once a day and reported\n * three ways: one dim stderr line for a human at a terminal, `updateAvailable`\n * on the JSON envelope, and a line on the generated hook scripts' output.\n *\n * It REPORTS and never installs. A CLI that starts a fresh process per\n * invocation has no deferred-activation window to hide a binary swap in — \"next\n * start\" is \"mid-session\" for whatever is driving it — so the decision to run\n * `tenjin update` belongs to the agent or the human, not to this check.\n *\n * Everything here is subordinate to the command that ran: the fetch happens\n * AFTER the envelope is written, it never touches stdout, it never changes an\n * exit code, and every failure it can have (offline, slow registry, junk JSON, a\n * tag that does not exist) is swallowed. CI skips the whole thing: a build log\n * can act on none of it. `update.mode off` is the opt-out and silences all three\n * surfaces, including the request to npm.\n */\n\nconst CHECK_INTERVAL_MS = 86_400_000; // 24h\nconst FETCH_TIMEOUT_MS = 1500;\nconst DIST_TAGS_URL = 'https://registry.npmjs.org/-/package/tenjin-cli/dist-tags';\n\n/** What is known about ONE dist-tag: when it was asked, and what it said. */\nconst TagEntrySchema = z.object({\n checkedAtMs: z.number(),\n /** The version the tag named. Absent when the answer was unusable. */\n latest: z.string().optional(),\n /** When the nudge was last PRINTED for this tag. Absent until one has been. */\n notifiedAtMs: z.number().optional(),\n});\n\n/**\n * The cache is a pure optimization, so a bad one is re-fetched, never repaired.\n * Keyed by dist-tag: an entry this build did not ask about is carried forward\n * untouched rather than evicted.\n */\nconst CacheSchema = z.object({\n schemaVersion: z.literal(1),\n tags: z.record(z.string(), TagEntrySchema),\n /**\n * The resolved \"you could upgrade\" fact, written whenever it changes and\n * cleared when it stops being true.\n *\n * Denormalized from `tags` on purpose: the generated hook scripts are\n * standalone .mjs that cannot import this module and do not know which\n * version is running, so a per-tag entry would leave them unable to tell an\n * upgrade from a match. Storing the comparison's ANSWER is what lets a hook\n * report it without reimplementing any of it.\n */\n signal: z.object({ current: z.string(), latest: z.string() }).optional(),\n});\ntype Cache = z.infer<typeof CacheSchema>;\n\n/** `{\"latest\":\"1.2.3\",\"alpha\":\"1.3.0-alpha.1\"}` — tag names are not fixed. */\nconst DistTagsSchema = z.record(z.string(), z.string());\n\nexport interface UpdateCheckDeps {\n dir: string;\n io: Io;\n /** The global --json flag; ANDed with io.isTTY exactly as the emit path does. */\n json: boolean;\n env?: NodeJS.ProcessEnv;\n /** Clock seam (ms since epoch) for deterministic TTL tests. */\n now?: () => number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** The running version; defaults to this build's. Injectable for tests. */\n currentVersion?: string;\n /** Resolved update.mode; defaults to reading the config file. */\n mode?: UpdateMode;\n}\n\n/**\n * Print the update nudge if one is due. NEVER rejects — the caller awaits it\n * between a command's output and its exit, so a throw here would replace a\n * finished command's result with an internal error.\n */\nexport async function maybeUpdate(deps: UpdateCheckDeps): Promise<void> {\n try {\n const env = deps.env ?? process.env;\n // Never in CI, in either mode: a build log cannot act on a nudge, and a\n // build machine must not silently acquire a different binary mid-pipeline.\n if (env.CI !== undefined && env.CI.length > 0) return;\n\n const mode = deps.mode ?? (await loadConfig(deps.dir)).update.mode;\n if (mode === 'off') return;\n\n const nowMs = (deps.now ?? Date.now)();\n const current = deps.currentVersion ?? pkg.version;\n const path = updateCheckPath(deps.dir);\n const tag = channelTag(current);\n if (tag === null) return; // a version this build cannot parse follows no channel\n\n // Only this tag's entry answers this binary's question; the other channel's\n // is neither used nor disturbed.\n const cached = await readCache(path);\n const entry = cached?.tags[tag];\n const fresh = entry !== undefined && nowMs - entry.checkedAtMs < CHECK_INTERVAL_MS;\n\n // Resolved through the same function `tenjin update` uses, so the nudge can\n // never advertise a version the command would decline to install, nor stay\n // quiet about one it would.\n //\n // Only a registry that could not be ASKED returns without caching; an answer\n // this build cannot use has still been answered, and moves the clock below.\n let latest: string | null;\n if (fresh) {\n latest = entry.latest ?? null;\n } else {\n const answer = await resolveLatest(current, deps);\n if (answer === null) return;\n latest = answer.latest;\n }\n\n const upgradeable = latest !== null && isNewer(latest, current);\n\n // Once a day means once a day, not once per FETCH: a fresh cache would\n // otherwise repeat the same line on every command for 24h. The two clocks are\n // separate because they answer separate questions — when we last asked npm,\n // and when we last interrupted the human.\n //\n // `human` is part of `due` for the second of those: this code now runs on\n // every surface, to feed the envelope signal, so without it an agent run\n // would stamp the nudge clock having printed nothing and leave a shared\n // machine's terminal quiet for 24h.\n const human = deps.io.isTTY && !deps.json;\n const notifiedAtMs = entry?.notifiedAtMs;\n const due =\n human &&\n upgradeable &&\n (notifiedAtMs === undefined || nowMs - notifiedAtMs >= CHECK_INTERVAL_MS);\n\n // Carried forward when nothing is printed: the day since the last nudge does\n // not restart just because the registry was asked again.\n const nudgedAtMs = due ? nowMs : notifiedAtMs;\n\n // Carries the agent-visible half of the answer, so a hook or an envelope can\n // report it without knowing which version is running.\n const signal = upgradeable && latest !== null ? { current, latest } : undefined;\n const signalChanged =\n cached?.signal?.current !== signal?.current || cached?.signal?.latest !== signal?.latest;\n\n // Nothing learned and nothing said means nothing to write. Deliberately NOT\n // locked: two concurrent CLI processes can both nudge, and one duplicated\n // line is cheaper than a lock on the exit path of every command.\n if (!fresh || due || signalChanged) {\n await writeCache(path, {\n schemaVersion: 1,\n ...(signal !== undefined ? { signal } : {}),\n // Read-modify-write: the tag this run did not ask about keeps whatever it\n // knew, including its own nudge clock.\n tags: {\n ...cached?.tags,\n [tag]: {\n checkedAtMs: fresh ? entry.checkedAtMs : nowMs,\n ...(latest !== null ? { latest } : {}),\n ...(nudgedAtMs !== undefined ? { notifiedAtMs: nudgedAtMs } : {}),\n },\n },\n });\n }\n\n // Named as the command, not the npm invocation it wraps: `update` prints the\n // right instructions itself for an install it cannot perform (a source\n // checkout, a yarn global), so this line is correct everywhere.\n if (due && latest !== null) {\n emitNotice(\n deps.io,\n `tenjin-cli ${latest} is available (you have ${current}). Update: run tenjin update`,\n { json: deps.json },\n );\n }\n } catch {\n // Unreachable by construction (every step below is already guarded); here so\n // that staying invisible does not depend on that remaining true.\n }\n}\n\n/**\n * What the last check learned, for the envelope. Cache only: this runs before\n * every command's output, so it may not fetch, may not block, and may not throw.\n * Null when nothing newer is known, when the cache is absent or stale-shaped, or\n * when `update.mode` is `off` — off silences BOTH surfaces, not just the line a\n * human sees.\n *\n * Reporting rather than installing is the whole design. A CLI that starts a\n * fresh process per invocation has no deferred-activation moment to hide a\n * binary swap in, so the agent is told and decides for itself.\n */\nexport async function readUpdateSignal(\n dir: string,\n currentVersion?: string,\n): Promise<UpdateAvailable | null> {\n try {\n const current = currentVersion ?? pkg.version;\n const tag = channelTag(current);\n if (tag === null) return null;\n if ((await loadConfig(dir)).update.mode === 'off') return null;\n const cached = await readCache(updateCheckPath(dir));\n const latest = cached?.tags[tag]?.latest;\n if (latest === undefined || !isNewer(latest, current)) return null;\n return { current, latest };\n } catch {\n return null; // never the command's business\n }\n}\n\n/**\n * Which dist-tag this build follows, or null for a version string this package\n * has no channel for. Null rather than a default, because every caller's right\n * answer differs: the nudge goes quiet, and `tenjin update` refuses instead of\n * silently reporting a foreign build \"up to date\" against a tag it never\n * belonged to.\n *\n * Every build follows `latest`; see RELEASING.md, which changes with this.\n */\nexport function channelTag(version: string): 'latest' | null {\n return parseVersion(version) === null ? null : 'latest';\n}\n\n/**\n * The version this build can move to: whatever sits on the tag it follows.\n * Consulting a second tag added no reachable version and one way to be wrong: a\n * tag sitting ahead of `latest` could redirect the self-update to a build the\n * release line never promoted. Null both when that tag is absent and when it\n * names a version VERSION_RE rejects; `runUpdate` separates those, and neither\n * means the registry was unreachable.\n */\nexport function resolveTarget(current: string, tags: Record<string, string>): string | null {\n const channel = channelTag(current);\n if (channel === null) return null;\n const candidate = tags[channel];\n // Unparseable counts as absent: isNewer loses every comparison against junk,\n // so admitting one would read as \"up to date\" forever.\n if (candidate === undefined || parseVersion(candidate) === null) return null;\n return candidate;\n}\n\n/**\n * Ask the registry for tenjin-cli's whole dist-tag map. Returns null for every\n * failure there is, INCLUDING a response that arrives too late — the AbortSignal\n * is what bounds the delay a finished command can suffer. Nothing is written\n * here: a failed check caches nothing, so the next command retries rather than\n * going quiet for 24h over one dropped packet. The nudge passes its own short\n * budget; `tenjin update` passes the run's request timeout, because there the\n * fetch IS the command rather than a stowaway on someone else's exit path.\n *\n * The whole map rather than one tag, so a caller can tell an unreachable\n * registry (null) from one that answered without the tag it asked for (a map\n * that lacks the key) — two failures with two different fixes.\n */\nexport async function fetchDistTags(opts: {\n fetchImpl?: typeof fetch;\n timeoutMs: number;\n}): Promise<Record<string, string> | null> {\n const doFetch = opts.fetchImpl ?? fetch;\n let json: unknown;\n try {\n const res = await doFetch(DIST_TAGS_URL, { signal: AbortSignal.timeout(opts.timeoutMs) });\n if (!res.ok) return null;\n json = await res.json();\n } catch {\n return null;\n }\n const parsed = DistTagsSchema.safeParse(json);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * The nudge's one-shot: fetch, then resolve. Null when the registry could not be\n * asked; `{ latest: null }` when it answered with nothing usable.\n */\nasync function resolveLatest(\n current: string,\n deps: UpdateCheckDeps,\n): Promise<{ latest: string | null } | null> {\n const tags = await fetchDistTags({ fetchImpl: deps.fetchImpl, timeoutMs: FETCH_TIMEOUT_MS });\n return tags === null ? null : { latest: resolveTarget(current, tags) };\n}\n\nasync function writeCache(path: string, cache: Cache): Promise<void> {\n await writeFileAtomic(path, `${JSON.stringify(cache, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\nasync function readCache(path: string): Promise<Cache | null> {\n try {\n const parsed = CacheSchema.safeParse(JSON.parse(await readFile(path, 'utf8')));\n return parsed.success ? parsed.data : null;\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Version comparison: this package's shape only, no semver dependency.\n// ---------------------------------------------------------------------------\n\n/** `major.minor.patch` with an optional `-alpha.N` — every version tenjin-cli\n * has ever published. Anything else is unparseable ON PURPOSE (see isNewer). */\nconst VERSION_RE = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-alpha\\.(\\d+))?$/;\n\ninterface Version {\n major: number;\n minor: number;\n patch: number;\n /** null = a release; a number = that prerelease counter. */\n alpha: number | null;\n}\n\nfunction parseVersion(raw: string): Version | null {\n const m = VERSION_RE.exec(raw);\n if (m === null) return null;\n const [, major, minor, patch, alpha] = m;\n if (major === undefined || minor === undefined || patch === undefined) return null;\n return {\n major: Number(major),\n minor: Number(minor),\n patch: Number(patch),\n alpha: alpha !== undefined ? Number(alpha) : null,\n };\n}\n\n/**\n * Is `candidate` newer than `current`? An unparseable version on EITHER side is\n * \"not newer\": the registry is untrusted input, and the failure mode of guessing\n * is nagging every single command with a line the user cannot act on. A true\n * return therefore also certifies that BOTH sides parse, which is what lets\n * `tenjin update` splice the candidate into an npm argv without re-validating.\n */\nexport function isNewer(candidate: string, current: string): boolean {\n const a = parseVersion(candidate);\n const b = parseVersion(current);\n if (a === null || b === null) return false;\n if (a.major !== b.major) return a.major > b.major;\n if (a.minor !== b.minor) return a.minor > b.minor;\n if (a.patch !== b.patch) return a.patch > b.patch;\n // Same release triple: semver says a prerelease precedes its own release, so\n // 0.1.0 beats 0.1.0-alpha.9 and never the other way around.\n if (a.alpha === null) return b.alpha !== null;\n if (b.alpha === null) return false;\n return a.alpha > b.alpha;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AA6BzB,IAAM,oBAAoB;AAC1B,IAAM,mBAAmB;AACzB,IAAM,gBAAgB;AAGtB,IAAM,iBAAiB,iBAAE,OAAO;AAAA,EAC9B,aAAa,iBAAE,OAAO;AAAA;AAAA,EAEtB,QAAQ,iBAAE,OAAO,EAAE,SAA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AAO;AAAA,EACT;AACF;AAQA,IAAM,aAAa;AAUnB,SAAS,aAAa,KAA6B;AACjD,QAAM,IAAI,WAAW,KAAK,GAAG;AAC7B,MAAI,MAAM,KAAM,QAAO;AACvB,QAAM,CAAC,EAAE,OAAO,OAAO,OAAO,KAAK,IAAI;AACvC,MAAI,UAAU,UAAa,UAAU,UAAa,UAAU,OAAW,QAAO;AAC9E,SAAO;AAAA,IACL,OAAO,OAAO,KAAK;AAAA,IACnB,OAAO,OAAO,KAAK;AAAA,IACnB,OAAO,OAAO,KAAK;AAAA,IACnB,OAAO,UAAU,SAAY,OAAO,KAAK,IAAI;AAAA,EAC/C;AACF;AASO,SAAS,QAAQ,WAAmB,SAA0B;AACnE,QAAM,IAAI,aAAa,SAAS;AAChC,QAAM,IAAI,aAAa,OAAO;AAC9B,MAAI,MAAM,QAAQ,MAAM,KAAM,QAAO;AACrC,MAAI,EAAE,UAAU,EAAE,MAAO,QAAO,EAAE,QAAQ,EAAE;AAC5C,MAAI,EAAE,UAAU,EAAE,MAAO,QAAO,EAAE,QAAQ,EAAE;AAC5C,MAAI,EAAE,UAAU,EAAE,MAAO,QAAO,EAAE,QAAQ,EAAE;AAG5C,MAAI,EAAE,UAAU,KAAM,QAAO,EAAE,UAAU;AACzC,MAAI,EAAE,UAAU,KAAM,QAAO;AAC7B,SAAO,EAAE,QAAQ,EAAE;AACrB;","names":[]}
|
|
@@ -1,12 +1,10 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
sessionPath
|
|
4
|
-
} from "./chunk-ZQIQ55KK.js";
|
|
5
2
|
import {
|
|
6
3
|
CliError,
|
|
7
4
|
external_exports,
|
|
8
|
-
hasCode
|
|
9
|
-
|
|
5
|
+
hasCode,
|
|
6
|
+
sessionPath
|
|
7
|
+
} from "./chunk-ZFJJ3EXC.js";
|
|
10
8
|
|
|
11
9
|
// src/lib/session-present.ts
|
|
12
10
|
import { createHash, randomBytes, webcrypto } from "crypto";
|
|
@@ -202,4 +200,4 @@ export {
|
|
|
202
200
|
isSessionPresentable,
|
|
203
201
|
isSessionUsable
|
|
204
202
|
};
|
|
205
|
-
//# sourceMappingURL=chunk-
|
|
203
|
+
//# sourceMappingURL=chunk-HRGBS2PA.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/session-present.ts"],"sourcesContent":["import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split exists so `tenjin read` can present an owner's session key on a cold\n * 402 while its import graph stays test-pinned clear of the wallet. What that\n * pin establishes is exactly two things: read cannot mint a session, and read\n * cannot pay (a P-256 key cannot produce the secp256k1/EIP-712 signature an\n * EIP-3009 transfer authorization needs). It says nothing about what an\n * already-minted delegation is worth to whoever holds it — see `origin` below,\n * and the tier note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET has no body to cover at all,\n * so content-digest drops out of the covered set. As a union, \"GET with a body\"\n * and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache and run `tenjin session start --scope read`; a write command re-establishes on its own.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends.\n const digest = req.method === 'GET' ? undefined : contentDigest(req.body);\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n /** An OLDER CLI's file, missing a field the shape has since required. Unusable\n * and re-mintable like an absent one, so NOT the tamper signal `corrupt` is. */\n | { kind: 'outdated'; field: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\n/**\n * Fields an OLDER CLI's file can legitimately lack. An allowlist, not \"any missing\n * key\": a file with no `privateKeyJwk.d` cannot sign and is broken whoever wrote\n * it. Add a name when the schema grows a required field, never to quiet a test.\n */\nconst LATER_ADDED_FIELDS: readonly string[] = ['origin'];\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const legacy = (i: (typeof issues)[number]): boolean =>\n LATER_ADDED_FIELDS.includes(i.path.join('.')) && !hasPath(json, i.path);\n // Report the first NON-legacy issue when there is one: a file missing both\n // `origin` and its private scalar is corrupt because of the scalar, and naming\n // the benign field points the operator at the wrong thing.\n const issue = issues.find((i) => !legacy(i)) ?? issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // EVERY failure must be an allowlisted later field the file genuinely lacks.\n // One legacy omission cannot vouch for the rest of the file, and zod reports in\n // schema order, so the first issue alone would let a broken key ride in.\n const legacyOnly = issues.length > 0 && issues.every(legacy);\n if (legacyOnly && field !== undefined) return { kind: 'outdated', field };\n // Field-qualified: the message alone names none. zod never echoes the received\n // VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** Does `value` actually carry the key at `path`, whatever it holds there? */\nfunction hasPath(value: unknown, path: readonly PropertyKey[]): boolean {\n let cur: unknown = value;\n for (const key of path) {\n if (typeof cur !== 'object' || cur === null) return false;\n if (!Object.hasOwn(cur, key)) return false;\n cur = (cur as Record<PropertyKey, unknown>)[key];\n }\n return true;\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,YAAY,aAAa,iBAAiB;AACnD,SAAS,UAAU,YAAY;AAgCxB,SAAS,eAAe,QAAgB,UAAiC;AAC9E,MAAI,WAAW,SAAU,QAAO;AAChC,SAAO,aAAa,UAAU,WAAW;AAC3C;AAGA,IAAM,cAAc;AAcpB,IAAM,gBAAgB,iBACnB,OAAO;AAAA,EACN,KAAK,iBAAE,QAAQ,IAAI;AAAA,EACnB,KAAK,iBAAE,QAAQ,OAAO;AAAA,EACtB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AACrB,CAAC,EACA,YAAY;AAGf,IAAM,oBAAoB,iBAAE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EAAG,QAAO;AACnD,SAAO,qBAAqB,MAAM,KAAK,UAAU,MAAM;AACzD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/lib/session-present.ts"],"sourcesContent":["import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split exists so `tenjin read` can present an owner's session key on a cold\n * 402 while its import graph stays test-pinned clear of the wallet. What that\n * pin establishes is exactly two things: read cannot mint a session, and read\n * cannot pay (a P-256 key cannot produce the secp256k1/EIP-712 signature an\n * EIP-3009 transfer authorization needs). It says nothing about what an\n * already-minted delegation is worth to whoever holds it — see `origin` below,\n * and the tier note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET has no body to cover at all,\n * so content-digest drops out of the covered set. As a union, \"GET with a body\"\n * and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache and run `tenjin session start --scope read`; a write command re-establishes on its own.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends.\n const digest = req.method === 'GET' ? undefined : contentDigest(req.body);\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n /** An OLDER CLI's file, missing a field the shape has since required. Unusable\n * and re-mintable like an absent one, so NOT the tamper signal `corrupt` is. */\n | { kind: 'outdated'; field: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\n/**\n * Fields an OLDER CLI's file can legitimately lack. An allowlist, not \"any missing\n * key\": a file with no `privateKeyJwk.d` cannot sign and is broken whoever wrote\n * it. Add a name when the schema grows a required field, never to quiet a test.\n */\nconst LATER_ADDED_FIELDS: readonly string[] = ['origin'];\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const legacy = (i: (typeof issues)[number]): boolean =>\n LATER_ADDED_FIELDS.includes(i.path.join('.')) && !hasPath(json, i.path);\n // Report the first NON-legacy issue when there is one: a file missing both\n // `origin` and its private scalar is corrupt because of the scalar, and naming\n // the benign field points the operator at the wrong thing.\n const issue = issues.find((i) => !legacy(i)) ?? issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // EVERY failure must be an allowlisted later field the file genuinely lacks.\n // One legacy omission cannot vouch for the rest of the file, and zod reports in\n // schema order, so the first issue alone would let a broken key ride in.\n const legacyOnly = issues.length > 0 && issues.every(legacy);\n if (legacyOnly && field !== undefined) return { kind: 'outdated', field };\n // Field-qualified: the message alone names none. zod never echoes the received\n // VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** Does `value` actually carry the key at `path`, whatever it holds there? */\nfunction hasPath(value: unknown, path: readonly PropertyKey[]): boolean {\n let cur: unknown = value;\n for (const key of path) {\n if (typeof cur !== 'object' || cur === null) return false;\n if (!Object.hasOwn(cur, key)) return false;\n cur = (cur as Record<PropertyKey, unknown>)[key];\n }\n return true;\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,YAAY,aAAa,iBAAiB;AACnD,SAAS,UAAU,YAAY;AAgCxB,SAAS,eAAe,QAAgB,UAAiC;AAC9E,MAAI,WAAW,SAAU,QAAO;AAChC,SAAO,aAAa,UAAU,WAAW;AAC3C;AAGA,IAAM,cAAc;AAcpB,IAAM,gBAAgB,iBACnB,OAAO;AAAA,EACN,KAAK,iBAAE,QAAQ,IAAI;AAAA,EACnB,KAAK,iBAAE,QAAQ,OAAO;AAAA,EACtB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AACrB,CAAC,EACA,YAAY;AAGf,IAAM,oBAAoB,iBAAE,OAAO;AAAA;AAAA,EAEjC,SAAS,iBAAE,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAalB,QAAQ,iBAAE,OAAO;AAAA;AAAA,EAE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AAG,KAAK,KAAK,OAAO,KAAK;AAAA,IAC7E;AAAA,EACF;AACA,SAAO,EAAE,MAAM,MAAM,MAAM,OAAO,KAAK;AACzC;AAGA,SAAS,QAAQ,OAAgB,MAAuC;AACtE,MAAI,MAAe;AACnB,aAAW,OAAO,MAAM;AACtB,QAAI,OAAO,QAAQ,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAI,CAAC,OAAO,OAAO,KAAK,GAAG,EAAG,QAAO;AACrC,UAAO,IAAqC,GAAG;AAAA,EACjD;AACA,SAAO;AACT;AAGA,eAAsB,gBAAgB,KAA0C;AAC9E,QAAM,QAAQ,MAAM,gBAAgB,GAAG;AACvC,MAAI,MAAM,SAAS,KAAM,QAAO,MAAM;AAItC,MAAI,MAAM,SAAS,cAAc;AAC/B,UAAM,IAAI,SAAS,YAAY,uCAAuC,YAAY,GAAG,CAAC,IAAI;AAAA,MACxF,KAAK,6BAA6B,YAAY,GAAG,CAAC;AAAA,MAClD,OAAO,MAAM;AAAA,IACf,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEA,SAAS,UAAU,KAAsB;AACvC,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;AASO,SAAS,qBACd,MACA,KACA,UACA,QACS;AACT,MAAI,KAAK,WAAW,OAAQ,QAAO;AACnC,MAAI,CAAC,eAAe,KAAK,OAAO,QAAQ,EAAG,QAAO;AAClD,QAAM,QAAQ,KAAK,MAAM,KAAK,GAAG;AACjC,MAAI,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACpC,SAAO,MAAM,QAAQ;AACvB;AAGO,SAAS,gBACd,MACA,SACA,KACA,UACA,QACS;AACT,MAAI,KAAK,YAAY,QAAQ,YAAY,EAAG,QAAO;AACnD,SAAO,qBAAqB,MAAM,KAAK,UAAU,MAAM;AACzD;","names":[]}
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
httpRequest
|
|
4
|
-
} from "./chunk-SPUORKD7.js";
|
|
5
2
|
import {
|
|
6
3
|
trimSlash
|
|
7
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-EDZSNPE5.js";
|
|
5
|
+
import {
|
|
6
|
+
httpRequest
|
|
7
|
+
} from "./chunk-5QQTYWEU.js";
|
|
8
8
|
import {
|
|
9
9
|
ATOMIC_RE,
|
|
10
10
|
UUID_RE
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-EFWZPUTC.js";
|
|
12
12
|
import {
|
|
13
13
|
CliError,
|
|
14
14
|
external_exports
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-ZFJJ3EXC.js";
|
|
16
16
|
|
|
17
17
|
// src/lib/agent-api.ts
|
|
18
18
|
var FRESH_WITHIN_RE = /^P(\d+)[DWMY]$/;
|
|
@@ -73,12 +73,19 @@ function buildSearchRequest(input) {
|
|
|
73
73
|
}
|
|
74
74
|
}
|
|
75
75
|
}
|
|
76
|
-
|
|
77
|
-
schemaVersion: 2,
|
|
78
|
-
question,
|
|
76
|
+
const filters = {
|
|
79
77
|
...input.freshWithin !== void 0 ? { freshWithin: input.freshWithin } : {},
|
|
80
78
|
...input.maxPrice !== void 0 ? { maxPrice: input.maxPrice } : {},
|
|
81
|
-
...input.appliesTo !== void 0 ? { appliesTo: input.appliesTo } : {}
|
|
79
|
+
...input.appliesTo !== void 0 ? { appliesTo: input.appliesTo } : {}
|
|
80
|
+
};
|
|
81
|
+
return {
|
|
82
|
+
schemaVersion: 3,
|
|
83
|
+
view: "decision",
|
|
84
|
+
query: question,
|
|
85
|
+
// Omitted entirely when nothing narrows, rather than sent as `{}`: an empty
|
|
86
|
+
// object is a filter set that filters nothing, and saying so on the wire only
|
|
87
|
+
// invites a server to read meaning into it.
|
|
88
|
+
...Object.keys(filters).length > 0 ? { filters } : {},
|
|
82
89
|
limit
|
|
83
90
|
};
|
|
84
91
|
}
|
|
@@ -95,31 +102,22 @@ var searchCandidateSchema = external_exports.object({
|
|
|
95
102
|
estimatedTokens: external_exports.number(),
|
|
96
103
|
creator: external_exports.object({ handle: external_exports.string() }).passthrough()
|
|
97
104
|
}).passthrough();
|
|
98
|
-
var
|
|
99
|
-
|
|
100
|
-
resourceId: external_exports.string().regex(UUID_RE, "resourceId must be a uuid"),
|
|
101
|
-
url: external_exports.string().max(BROWSE_BOUNDS.url, `url must be at most ${BROWSE_BOUNDS.url} characters`),
|
|
102
|
-
title: external_exports.string(),
|
|
103
|
-
price: external_exports.string().regex(ATOMIC_RE, "price must be an atomic integer string"),
|
|
104
|
-
creator: external_exports.object({ handle: external_exports.string() }).passthrough()
|
|
105
|
-
}).passthrough();
|
|
106
|
-
var searchResponseSchema = external_exports.object({
|
|
107
|
-
schemaVersion: external_exports.literal(2),
|
|
105
|
+
var searchResultSchema = external_exports.object({
|
|
106
|
+
schemaVersion: external_exports.literal(3),
|
|
108
107
|
searchId: external_exports.string().regex(UUID_RE, "searchId must be a uuid"),
|
|
109
|
-
decision: external_exports.enum(["CANDIDATES", "MISS"]),
|
|
110
108
|
calibration: external_exports.string(),
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
//
|
|
114
|
-
//
|
|
115
|
-
|
|
116
|
-
//
|
|
117
|
-
//
|
|
118
|
-
|
|
119
|
-
//
|
|
120
|
-
//
|
|
121
|
-
//
|
|
122
|
-
|
|
109
|
+
items: external_exports.array(searchCandidateSchema),
|
|
110
|
+
matched: external_exports.number().int().nonnegative(),
|
|
111
|
+
// Present only when `matched` is 0. Server-authored display text, so it rides
|
|
112
|
+
// the same per-field cap as every other free-form string below.
|
|
113
|
+
hint: external_exports.string().optional(),
|
|
114
|
+
// Set only when the server's size backstop dropped trailing items the requested
|
|
115
|
+
// limit had room for; omitted entirely otherwise. There is no cursor, so a retry
|
|
116
|
+
// at a SMALLER limit returns strictly fewer rows; the ceiling scales with the
|
|
117
|
+
// items returned, so a LARGER limit (up to MAX_LIMIT) is what recovers the tail,
|
|
118
|
+
// and at MAX_LIMIT the tail is unrecoverable and narrowing the question is the
|
|
119
|
+
// remedy. `runSearch` picks the half that applies.
|
|
120
|
+
truncated: external_exports.literal(true).optional()
|
|
123
121
|
});
|
|
124
122
|
function apiFailure(url, result) {
|
|
125
123
|
const code = result.kind === "network" || result.kind === "timeout" ? "NETWORK_ERROR" : "API_UNREACHABLE";
|
|
@@ -151,7 +149,7 @@ function serverErrorMessage(json) {
|
|
|
151
149
|
return void 0;
|
|
152
150
|
}
|
|
153
151
|
async function postSearch(body, opts) {
|
|
154
|
-
const url = `${trimSlash(opts.baseUrl)}/api/
|
|
152
|
+
const url = `${trimSlash(opts.baseUrl)}/api/search`;
|
|
155
153
|
const res = await httpRequest(url, {
|
|
156
154
|
method: "POST",
|
|
157
155
|
timeoutMs: opts.timeoutMs,
|
|
@@ -162,8 +160,18 @@ async function postSearch(body, opts) {
|
|
|
162
160
|
if (!res.ok) throw apiFailure(url, res);
|
|
163
161
|
if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));
|
|
164
162
|
if (res.status !== 200) {
|
|
163
|
+
if (res.status === 404) {
|
|
164
|
+
throw new CliError(
|
|
165
|
+
"CONTRACT_MISMATCH",
|
|
166
|
+
`${url} answered 404: either this server predates search v3, or the configured base URL does not route POST /api/search.`,
|
|
167
|
+
{
|
|
168
|
+
fix: "Check the base URL (`tenjin config get baseUrl`; `tenjin doctor` probes it), then point it at an updated deployment or install an older tenjin-cli.",
|
|
169
|
+
details: res.json
|
|
170
|
+
}
|
|
171
|
+
);
|
|
172
|
+
}
|
|
165
173
|
if (res.status === 400 && rejectedSchemaVersion(res.json)) {
|
|
166
|
-
throw outdatedServerError("The server rejected schemaVersion
|
|
174
|
+
throw outdatedServerError("The server rejected schemaVersion 3: it predates search v3.", {
|
|
167
175
|
details: res.json
|
|
168
176
|
});
|
|
169
177
|
}
|
|
@@ -176,12 +184,12 @@ async function postSearch(body, opts) {
|
|
|
176
184
|
}
|
|
177
185
|
);
|
|
178
186
|
}
|
|
179
|
-
const parsed =
|
|
187
|
+
const parsed = searchResultSchema.safeParse(res.json);
|
|
180
188
|
if (!parsed.success) {
|
|
181
189
|
const served = serverSchemaVersion(res.json);
|
|
182
|
-
if (served !== void 0 && served !==
|
|
190
|
+
if (served !== void 0 && served !== 3) {
|
|
183
191
|
throw outdatedServerError(
|
|
184
|
-
`Search response is schemaVersion ${served}; this CLI requires
|
|
192
|
+
`Search response is schemaVersion ${served}; this CLI requires 3 (search v3).`,
|
|
185
193
|
{ details: parsed.error.issues }
|
|
186
194
|
);
|
|
187
195
|
}
|
|
@@ -194,14 +202,16 @@ async function postSearch(body, opts) {
|
|
|
194
202
|
}
|
|
195
203
|
function outdatedServerError(message, opts) {
|
|
196
204
|
return new CliError("CONTRACT_MISMATCH", message, {
|
|
197
|
-
fix: "The server predates search
|
|
205
|
+
fix: "The server predates search v3. Point the configured base URL (`tenjin config set baseUrl`) at an updated deployment, or install an older tenjin-cli.",
|
|
198
206
|
details: opts.details
|
|
199
207
|
});
|
|
200
208
|
}
|
|
201
209
|
function rejectedSchemaVersion(json) {
|
|
202
210
|
const record = (v) => typeof v === "object" && v !== null ? v : void 0;
|
|
203
|
-
const
|
|
204
|
-
|
|
211
|
+
const details = record(record(record(json)?.error)?.details);
|
|
212
|
+
if (Array.isArray(record(details?.fieldErrors)?.schemaVersion)) return true;
|
|
213
|
+
const problems = details?.problems;
|
|
214
|
+
return Array.isArray(problems) && problems.some((p) => typeof p === "string" && p.startsWith("schemaVersion"));
|
|
205
215
|
}
|
|
206
216
|
function serverSchemaVersion(json) {
|
|
207
217
|
if (typeof json !== "object" || json === null) return void 0;
|
|
@@ -213,26 +223,13 @@ var CAND_BOUNDS = {
|
|
|
213
223
|
matchReasons: 3,
|
|
214
224
|
matchReasonChars: 80
|
|
215
225
|
};
|
|
226
|
+
var HINT_MAX = 200;
|
|
216
227
|
var cap = (s, n) => s.length > n ? s.slice(0, n) : s;
|
|
217
228
|
function truncateResponse(res) {
|
|
218
|
-
const out = { ...res };
|
|
219
|
-
if (res.
|
|
220
|
-
if (res.browse !== void 0 && res.decision === "MISS") {
|
|
221
|
-
out.browse = res.browse.slice(0, BROWSE_MAX).map((b) => ({
|
|
222
|
-
resourceId: b.resourceId,
|
|
223
|
-
// Not capped: the schema already refused anything over BROWSE_BOUNDS.url,
|
|
224
|
-
// so this is the url the server sent, verbatim and payable.
|
|
225
|
-
url: b.url,
|
|
226
|
-
title: cap(b.title, BROWSE_BOUNDS.title),
|
|
227
|
-
price: b.price,
|
|
228
|
-
creator: { handle: cap(b.creator.handle, BROWSE_BOUNDS.handle) }
|
|
229
|
-
}));
|
|
230
|
-
} else {
|
|
231
|
-
delete out.browse;
|
|
232
|
-
}
|
|
229
|
+
const out = { ...res, items: res.items.map(truncateCandidate) };
|
|
230
|
+
if (res.hint !== void 0) out.hint = cap(res.hint, HINT_MAX);
|
|
233
231
|
return out;
|
|
234
232
|
}
|
|
235
|
-
var BROWSE_MAX = 3;
|
|
236
233
|
function truncateCandidate(c) {
|
|
237
234
|
return {
|
|
238
235
|
...c,
|
|
@@ -314,4 +311,4 @@ export {
|
|
|
314
311
|
buildOutcomeItem,
|
|
315
312
|
postOutcomes
|
|
316
313
|
};
|
|
317
|
-
//# sourceMappingURL=chunk-
|
|
314
|
+
//# sourceMappingURL=chunk-ITUXPJIS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/agent-api.ts"],"sourcesContent":["import { z } from 'zod';\nimport { CliError } from './errors';\nimport { httpRequest, type HttpResult } from './http';\nimport { ATOMIC_RE, UUID_RE } from './ids';\nimport { trimSlash } from './url';\n\n/**\n * The search + outcome HTTP contract. Request building and response validation\n * live here; the wire shape is validated defensively, an unknown `schemaVersion`\n * degrades to a parse refusal rather than a guess, and unrecognized candidate\n * fields are ignored (forward-compatible), per spec 10.\n *\n * Search speaks schemaVersion 3 to POST /api/search with `view: \"decision\"`\n * (tenjin#137). The old POST /api/agent/search is a deprecated alias that the\n * server serves for one release and then answers 410, so nothing here still\n * calls it. v3 also reshaped the envelope: `decision` + `candidates[]` became\n * `matched` + `items[]`, the filters moved under a nested `filters` object, and\n * the MISS `browse[]` tail is gone entirely — a miss is an empty result plus a\n * `hint` pointing at GET /api/articles, not a different kind of answer.\n *\n * These endpoints are anonymous: no wallet, no SIWX. The shared transport's\n * User-Agent is what attributes a later purchase back to the search flow.\n */\n\nconst FRESH_WITHIN_RE = /^P(\\d+)[DWMY]$/;\nconst CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;\n\n/** The DECISION view's `limit` ceiling. The v3 schema admits `limit` up to 100\n * across views and the server clamps per view (tenjin lib/search/understand.ts\n * VIEW_LIMITS: decision 10, display 100, suggest 10); the CLI only ever sends\n * `view: \"decision\"`, so 10 is the real bound and asking for more would be\n * silently clamped back to it. Exported because the truncation advice in\n * `search` has to name it: the response budget scales with the items returned,\n * so a truncated page is recovered by asking for MORE, and this is the value\n * to ask for. One definition, so the cap the CLI enforces and the number it\n * tells the operator to retry with cannot drift apart. */\nexport const MAX_LIMIT = 10;\n\n/** Client-side search request (mirrors the server lookupRequestSchema bounds\n * so a malformed flag fails locally as USAGE, before a round trip). */\nexport interface SearchInput {\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit?: number;\n}\n\n/** The nested v3 filter object. Freshness, price and applicability are no longer\n * top-level request fields: v3 groups every narrowing under `filters`, and the\n * server's `filters` schema is a strictObject, so a stray top-level spelling is\n * stripped into `warnings` and the search runs UNFILTERED. Building it in one\n * place is what keeps a `--max-price` from silently going nowhere. */\nexport interface SearchFilters {\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n}\n\nexport interface SearchRequestBody {\n schemaVersion: 3;\n /** Pinned rather than defaulted. The server defaults `view` to `decision`, but\n * a default is the server's to change and this client parses exactly one\n * projection, so it names the one it can read. */\n view: 'decision';\n /** The DOCUMENTED spelling. `question` and `q` are undocumented compatibility\n * aliases the server still resolves (precedence question, query, q), and it\n * echoes the losers in `warnings`; a client written today sends the spelling\n * the contract publishes. */\n query: string;\n filters?: SearchFilters;\n limit: number;\n}\n\nexport function buildSearchRequest(input: SearchInput): SearchRequestBody {\n const question = input.question.trim();\n if (question.length === 0 || question.length > 512) {\n throw new CliError('USAGE', 'question must be 1 to 512 characters', {\n fix: 'Pass a non-empty question under 512 characters.',\n });\n }\n if (input.freshWithin !== undefined) {\n // The server rejects ANY zero-valued duration (P0D, P0W, P00M, ...), so a\n // zero window fails here as USAGE instead of a remote 400.\n const digits = FRESH_WITHIN_RE.exec(input.freshWithin)?.[1];\n if (digits === undefined || Number(digits) === 0) {\n throw new CliError('USAGE', `Invalid --fresh-within: ${JSON.stringify(input.freshWithin)}`, {\n fix: 'Use a nonzero ISO-like window P<n>[DWMY], e.g. P30D, P2W, P1Y.',\n });\n }\n }\n if (input.maxPrice !== undefined && !ATOMIC_RE.test(input.maxPrice)) {\n throw new CliError('USAGE', `Invalid --max-price: ${JSON.stringify(input.maxPrice)}`, {\n fix: 'Pass an atomic USDC integer, e.g. 100000 for $0.10.',\n });\n }\n const limit = input.limit ?? 5;\n if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(input.limit)}`, {\n fix: `Pass an integer between 1 and ${MAX_LIMIT}.`,\n });\n }\n if (input.appliesTo !== undefined) {\n // Mirror the server's strictObject bounds (<=8 keys, <=20 values/key,\n // 1..120 chars/value) so a bad filter fails locally, never as a remote 400.\n const keys = Object.keys(input.appliesTo);\n if (keys.length > 8) {\n throw new CliError('USAGE', 'Too many --applies-to keys (max 8).');\n }\n for (const [key, values] of Object.entries(input.appliesTo)) {\n if (!CANONICAL_KEY_RE.test(key)) {\n throw new CliError('USAGE', `Invalid appliesTo key: ${JSON.stringify(key)}`, {\n fix: 'Keys must be canonical lowercase identifiers, e.g. products=Vercel.',\n });\n }\n if (values.length === 0) {\n throw new CliError('USAGE', `appliesTo key ${JSON.stringify(key)} has no values`, {\n fix: 'Give each --applies-to key at least one value.',\n });\n }\n if (values.length > 20) {\n throw new CliError('USAGE', `Too many --applies-to values for ${key} (max 20).`);\n }\n for (const value of values) {\n if (value.length === 0 || value.length > 120) {\n throw new CliError(\n 'USAGE',\n `Invalid --applies-to value for ${key}: must be 1 to 120 characters.`,\n );\n }\n }\n }\n }\n const filters: SearchFilters = {\n ...(input.freshWithin !== undefined ? { freshWithin: input.freshWithin } : {}),\n ...(input.maxPrice !== undefined ? { maxPrice: input.maxPrice } : {}),\n ...(input.appliesTo !== undefined ? { appliesTo: input.appliesTo } : {}),\n };\n return {\n schemaVersion: 3,\n view: 'decision',\n query: question,\n // Omitted entirely when nothing narrows, rather than sent as `{}`: an empty\n // object is a filter set that filters nothing, and saying so on the wire only\n // invites a server to read meaning into it.\n ...(Object.keys(filters).length > 0 ? { filters } : {}),\n limit,\n };\n}\n\n// Response schemas. `.passthrough()` on the candidate keeps unknown future fields\n// instead of stripping them (forward-compatible), while still requiring the\n// contract fields this CLI reads.\n//\n// A candidate is a LEAN hit (search v2): identity, price, freshness and why it\n// matched, and nothing more. The full answer card is one free unpaid GET of `url`\n// away, which is what `tenjin inspect` does, so breadth here costs no depth there.\nexport const searchCandidateSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string(),\n slug: z.string(),\n title: z.string(),\n artifactType: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n asOf: z.string().nullable(),\n validUntil: z.string().nullable(),\n matchReasons: z.array(z.string()),\n estimatedTokens: z.number(),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchCandidate = z.infer<typeof searchCandidateSchema>;\n\n/** The v3 decision-view result envelope (lib/search/project.ts\n * SearchResultEnvelope). `items` is the same lean candidate projection v2 put in\n * `candidates`; what changed is the frame around it.\n *\n * There is no `decision` field any more, and that is the point of v3: a miss is\n * an EMPTY result, not a second kind of answer to branch on. `matched` is 0,\n * `items` is empty, and `hint` says where to browse instead. `browse[]` is gone\n * with it — the decision view never draws a fallback tail, so this client no\n * longer has one to render or to record.\n *\n * Unknown keys are STRIPPED (plain `z.object`), which is why `inspect` and\n * `warnings` are absent here: they are real contract fields this CLI does not\n * read, and declaring them would put unbounded server text into `--json` and\n * into an agent transcript with nothing rendering it. */\nexport const searchResultSchema = z.object({\n schemaVersion: z.literal(3),\n searchId: z.string().regex(UUID_RE, 'searchId must be a uuid'),\n calibration: z.string(),\n items: z.array(searchCandidateSchema),\n matched: z.number().int().nonnegative(),\n // Present only when `matched` is 0. Server-authored display text, so it rides\n // the same per-field cap as every other free-form string below.\n hint: z.string().optional(),\n // Set only when the server's size backstop dropped trailing items the requested\n // limit had room for; omitted entirely otherwise. There is no cursor, so a retry\n // at a SMALLER limit returns strictly fewer rows; the ceiling scales with the\n // items returned, so a LARGER limit (up to MAX_LIMIT) is what recovers the tail,\n // and at MAX_LIMIT the tail is unrecoverable and narrowing the question is the\n // remedy. `runSearch` picks the half that applies.\n truncated: z.literal(true).optional(),\n});\n\nexport type SearchResult = z.infer<typeof searchResultSchema>;\n\nexport interface AgentApiOptions {\n baseUrl: string;\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n /** Spec 09 §3 evaluation-cohort opt-in: sends X-Tenjin-Eval-Cohort: 1. */\n evalCohort?: boolean;\n}\n\n/** Turn a non-2xx / transport HttpResult into the CLI error contract. */\nfunction apiFailure(url: string, result: Exclude<HttpResult, { ok: true }>): CliError {\n const code =\n result.kind === 'network' || result.kind === 'timeout' ? 'NETWORK_ERROR' : 'API_UNREACHABLE';\n return new CliError(code, `${url}: ${result.message}`, {\n fix: 'Check your network and the configured base URL (`tenjin config get baseUrl`), then retry.',\n });\n}\n\n/** 429 with Retry-After: a recoverable pause, not an outage; agents branch on it. */\nexport function rateLimitError(\n url: string,\n header: (name: string) => string | undefined,\n): CliError {\n const retryAfter = header('retry-after');\n const seconds = retryAfter !== undefined ? Number(retryAfter) : undefined;\n return new CliError('RATE_LIMITED', `${url}: rate limited by the server.`, {\n fix:\n seconds !== undefined && Number.isFinite(seconds)\n ? `Retry after ${seconds}s.`\n : 'Back off and retry shortly.',\n details: {\n ...(seconds !== undefined && Number.isFinite(seconds) ? { retryAfterSeconds: seconds } : {}),\n },\n });\n}\n\nfunction serverErrorMessage(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const rec = json as Record<string, unknown>;\n const err = rec.error;\n if (typeof err === 'string') return err;\n if (typeof err === 'object' && err !== null) {\n const m = (err as Record<string, unknown>).message;\n if (typeof m === 'string') return m;\n }\n if (typeof rec.message === 'string') return rec.message;\n }\n return undefined;\n}\n\nexport async function postSearch(\n body: SearchRequestBody,\n opts: AgentApiOptions,\n): Promise<SearchResult> {\n const url = `${trimSlash(opts.baseUrl)}/api/search`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: opts.evalCohort === true ? { 'x-tenjin-eval-cohort': '1' } : {},\n jsonBody: body,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n if (res.status !== 200) {\n // A deployment that predates v3 has no route here AT ALL, so it answers 404\n // from the Next router rather than anything contract-shaped. That is the arm\n // that fires in practice against a stale server, and without it the operator\n // is told to \"retry\" a path that will never exist on that deploy. A 404 is\n // equally what a wrong base URL path or a gateway that does not route\n // POST /api/search answers, so the remedy names both causes rather than\n // asserting the server's age.\n if (res.status === 404) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `${url} answered 404: either this server predates search v3, or the configured base URL does not route POST /api/search.`,\n {\n fix: 'Check the base URL (`tenjin config get baseUrl`; `tenjin doctor` probes it), then point it at an updated deployment or install an older tenjin-cli.',\n details: res.json,\n },\n );\n }\n // The REQUEST gate: a server that HAS the route but pins an older\n // `schemaVersion` refuses the body before the handler runs. The v2 alias\n // answers with a zod flatten under `error.details.fieldErrors`; the v3 route\n // drops `fieldErrors` and states the same thing as sentences in\n // `error.details.problems`. Both spellings are read, keyed on the FIELD name\n // rather than on any message text.\n if (res.status === 400 && rejectedSchemaVersion(res.json)) {\n throw outdatedServerError('The server rejected schemaVersion 3: it predates search v3.', {\n details: res.json,\n });\n }\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Search failed (${res.status})`,\n {\n fix: 'Retry; if it persists the search endpoint may be unavailable.',\n details: res.json,\n },\n );\n }\n const parsed = searchResultSchema.safeParse(res.json);\n if (!parsed.success) {\n // The other way a stale server surfaces: it accepted the request and answered\n // 200 with an older envelope. The v2 alias does exactly this if a base URL\n // ever points at it, so the version it served is named rather than reported\n // as an anonymous shape mismatch.\n const served = serverSchemaVersion(res.json);\n if (served !== undefined && served !== 3) {\n throw outdatedServerError(\n `Search response is schemaVersion ${served}; this CLI requires 3 (search v3).`,\n { details: parsed.error.issues },\n );\n }\n throw new CliError('CONTRACT_MISMATCH', 'Search response did not match the expected contract', {\n fix: 'Update tenjin-cli; the server contract may have changed.',\n details: parsed.error.issues,\n });\n }\n return truncateResponse(parsed.data);\n}\n\n/** One wording for all three ways a pre-v3 server refuses this CLI (no route, a\n * request-gate 400, a v2 envelope in a 200), so the arms can never drift apart. */\nfunction outdatedServerError(message: string, opts: { details: unknown }): CliError {\n return new CliError('CONTRACT_MISMATCH', message, {\n fix: 'The server predates search v3. Point the configured base URL (`tenjin config set baseUrl`) at an updated deployment, or install an older tenjin-cli.',\n details: opts.details,\n });\n}\n\n/** True when a 400 body is an older server's request-gate refusal of our\n * `schemaVersion`. Two shapes, because the two surfaces report differently: the\n * v2 alias carries a zod `flatten()` under `error.details.fieldErrors`, while\n * the v3 route drops that map and lists sentences under `error.details.problems`\n * instead. Both are keyed on the FIELD NAME appearing where the server puts its\n * per-field complaints, never on message wording. */\nfunction rejectedSchemaVersion(json: unknown): boolean {\n const record = (v: unknown): Record<string, unknown> | undefined =>\n typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : undefined;\n const details = record(record(record(json)?.error)?.details);\n if (Array.isArray(record(details?.fieldErrors)?.schemaVersion)) return true;\n const problems = details?.problems;\n return (\n Array.isArray(problems) &&\n problems.some((p) => typeof p === 'string' && p.startsWith('schemaVersion'))\n );\n}\n\n/** The `schemaVersion` an unparsed body claims, when it claims a number at all. */\nfunction serverSchemaVersion(json: unknown): number | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const v = (json as { schemaVersion?: unknown }).schemaVersion;\n return typeof v === 'number' ? v : undefined;\n}\n\n/**\n * The server bounds every free-form candidate string (spec 09); re-apply the same\n * caps defensively so a misbehaving server cannot blow up an agent transcript\n * through the CLI (spec 10 response-size discipline).\n *\n * `slug` is deliberately absent: it is an identifier, not display text, so\n * clipping it would not shorten it but change it into a slug that resolves to\n * nothing while still looking usable in `--json`. The server tolerates an\n * uncapped slug for the same reason (that is the one case its `truncated` flag\n * exists for), so capping here would fail on a response the server calls valid.\n */\nconst CAND_BOUNDS = {\n title: 200,\n matchReasons: 3,\n matchReasonChars: 80,\n} as const;\n\n/** The miss `hint` is one fixed server sentence today, but it is server-authored\n * display text like any other, so it is bounded rather than trusted. */\nconst HINT_MAX = 200;\n\nconst cap = (s: string, n: number): string => (s.length > n ? s.slice(0, n) : s);\n\nfunction truncateResponse(res: SearchResult): SearchResult {\n const out: SearchResult = { ...res, items: res.items.map(truncateCandidate) };\n if (res.hint !== undefined) out.hint = cap(res.hint, HINT_MAX);\n return out;\n}\n\nfunction truncateCandidate(c: SearchCandidate): SearchCandidate {\n return {\n ...c,\n title: cap(c.title, CAND_BOUNDS.title),\n matchReasons: c.matchReasons\n .slice(0, CAND_BOUNDS.matchReasons)\n .map((r) => cap(r, CAND_BOUNDS.matchReasonChars)),\n };\n}\n\nconst OUTCOME_STATUSES = [\n 'used',\n 'partially_used',\n 'rejected',\n 'regenerated',\n 'purchase_declined',\n] as const;\nexport type OutcomeStatus = (typeof OUTCOME_STATUSES)[number];\nexport const OUTCOME_STATUS_VALUES: readonly string[] = OUTCOME_STATUSES;\n\nconst CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;\n\nexport interface OutcomeInput {\n status: string;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport interface OutcomeBodyItem {\n status: OutcomeStatus;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport function buildOutcomeItem(input: OutcomeInput): OutcomeBodyItem {\n if (!OUTCOME_STATUS_VALUES.includes(input.status)) {\n throw new CliError('USAGE', `Invalid outcome status: ${JSON.stringify(input.status)}`, {\n fix: `Use one of: ${OUTCOME_STATUSES.join(', ')}.`,\n });\n }\n if (input.resourceId !== undefined && !UUID_RE.test(input.resourceId)) {\n throw new CliError('USAGE', `Invalid --resource id: ${JSON.stringify(input.resourceId)}`, {\n fix: 'Pass the resourceId (a uuid) from a search candidate.',\n });\n }\n if (input.contentHash !== undefined && !CONTENT_HASH_RE.test(input.contentHash)) {\n throw new CliError('USAGE', `Invalid content hash: ${JSON.stringify(input.contentHash)}`, {\n fix: 'A content hash is \"sha256:<64 hex>\".',\n });\n }\n return {\n status: input.status as OutcomeStatus,\n ...(input.resourceId !== undefined ? { resourceId: input.resourceId } : {}),\n ...(input.contentHash !== undefined ? { contentHash: input.contentHash } : {}),\n };\n}\n\nconst SEARCH_ID_RE = UUID_RE;\n\nexport async function postOutcomes(\n searchId: string,\n items: OutcomeBodyItem[],\n opts: AgentApiOptions,\n): Promise<{ accepted: number }> {\n if (!SEARCH_ID_RE.test(searchId)) {\n throw new CliError('USAGE', `Invalid search id: ${JSON.stringify(searchId)}`, {\n fix: 'Pass the searchId from a prior search (or use --last).',\n });\n }\n if (items.length === 0 || items.length > 10) {\n throw new CliError('USAGE', 'An outcome report carries 1 to 10 items', {\n fix: 'Report between 1 and 10 outcomes per call.',\n });\n }\n const url = `${trimSlash(opts.baseUrl)}/api/searches/${searchId}/outcomes`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n jsonBody: items.length === 1 ? items[0] : items,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n // 202 is the only success; the body is a uniform { accepted } regardless of\n // whether the searchId existed (no existence oracle, by design).\n if (res.status !== 202) {\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Outcome report failed (${res.status})`,\n {\n fix: 'Check the status vocabulary and search id, then retry.',\n details: res.json,\n },\n );\n }\n const accepted =\n typeof res.json === 'object' && res.json !== null && 'accepted' in res.json\n ? Number((res.json as { accepted: unknown }).accepted)\n : items.length;\n return { accepted: Number.isFinite(accepted) ? accepted : items.length };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAWlB,IAAM,YAAY;AAsClB,SAAS,mBAAmB,OAAuC;AACxE,QAAM,WAAW,MAAM,SAAS,KAAK;AACrC,MAAI,SAAS,WAAW,KAAK,SAAS,SAAS,KAAK;AAClD,UAAM,IAAI,SAAS,SAAS,wCAAwC;AAAA,MAClE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,MAAI,MAAM,gBAAgB,QAAW;AAGnC,UAAM,SAAS,gBAAgB,KAAK,MAAM,WAAW,IAAI,CAAC;AAC1D,QAAI,WAAW,UAAa,OAAO,MAAM,MAAM,GAAG;AAChD,YAAM,IAAI,SAAS,SAAS,2BAA2B,KAAK,UAAU,MAAM,WAAW,CAAC,IAAI;AAAA,QAC1F,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AAAA,EACF;AACA,MAAI,MAAM,aAAa,UAAa,CAAC,UAAU,KAAK,MAAM,QAAQ,GAAG;AACnE,UAAM,IAAI,SAAS,SAAS,wBAAwB,KAAK,UAAU,MAAM,QAAQ,CAAC,IAAI;AAAA,MACpF,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,Q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IAAI,MAAM,CAAC,IAAI;AAAA,IAC1C,WAAW,KAAK;AAAA,EAClB,CAAC;AACD,MAAI,CAAC,IAAI,GAAI,OAAM,WAAW,KAAK,GAAG;AACtC,MAAI,IAAI,WAAW,IAAK,OAAM,eAAe,KAAK,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC;AAGtE,MAAI,IAAI,WAAW,KAAK;AACtB,UAAM,IAAI;AAAA,MACR;AAAA,MACA,mBAAmB,IAAI,IAAI,KAAK,0BAA0B,IAAI,MAAM;AAAA,MACpE;AAAA,QACE,KAAK;AAAA,QACL,SAAS,IAAI;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACA,QAAM,WACJ,OAAO,IAAI,SAAS,YAAY,IAAI,SAAS,QAAQ,cAAc,IAAI,OACnE,OAAQ,IAAI,KAA+B,QAAQ,IACnD,MAAM;AACZ,SAAO,EAAE,UAAU,OAAO,SAAS,QAAQ,IAAI,WAAW,MAAM,OAAO;AACzE;","names":[]}
|
|
@@ -3,7 +3,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
|
|
|
3
3
|
// package.json
|
|
4
4
|
var package_default = {
|
|
5
5
|
name: "tenjin-cli",
|
|
6
|
-
version: "0.1.0-alpha.
|
|
6
|
+
version: "0.1.0-alpha.15",
|
|
7
7
|
mcpName: "blog.tenjin/tenjin",
|
|
8
8
|
type: "module",
|
|
9
9
|
description: "Tenjin agent CLI for the x402 knowledge marketplace.",
|
|
@@ -80,4 +80,4 @@ var package_default = {
|
|
|
80
80
|
export {
|
|
81
81
|
package_default
|
|
82
82
|
};
|
|
83
|
-
//# sourceMappingURL=chunk-
|
|
83
|
+
//# sourceMappingURL=chunk-JBIKAAT3.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"tenjin-cli\",\n \"version\": \"0.1.0-alpha.
|
|
1
|
+
{"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"tenjin-cli\",\n \"version\": \"0.1.0-alpha.15\",\n \"mcpName\": \"blog.tenjin/tenjin\",\n \"type\": \"module\",\n \"description\": \"Tenjin agent CLI for the x402 knowledge marketplace.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/BackTrackCo/tenjin-agent.git\"\n },\n \"homepage\": \"https://tenjin.blog/agents\",\n \"bugs\": \"https://github.com/BackTrackCo/tenjin-agent/issues\",\n \"keywords\": [\n \"x402\",\n \"usdc\",\n \"base\",\n \"ai-agents\",\n \"agent-payments\",\n \"mcp\",\n \"knowledge-marketplace\",\n \"micropayments\",\n \"claude\",\n \"codex\",\n \"cli\"\n ],\n \"bin\": {\n \"tenjin\": \"dist/index.js\"\n },\n \"engines\": {\n \"node\": \">=22\"\n },\n \"files\": [\n \"dist\",\n \"docs\",\n \"skills\",\n \"NOTICE.md\"\n ],\n \"packageManager\": \"pnpm@11.11.0\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format\": \"prettier --write .\",\n \"format:check\": \"prettier --check .\",\n \"check\": \"pnpm run build && pnpm run test\",\n \"sync:skill\": \"node scripts/sync-skill.mjs\",\n \"pack-smoke\": \"bash scripts/pack-smoke.sh\",\n \"changeset\": \"changeset\",\n \"prepublishOnly\": \"pnpm run build\",\n \"prepare\": \"git config core.hooksPath .githooks || true\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.31.1\",\n \"@clack/prompts\": \"^1.7.0\",\n \"@eslint/js\": \"^10\",\n \"@modelcontextprotocol/sdk\": \"1.29.0\",\n \"@types/node\": \"^25\",\n \"@x402/core\": \"2.17.0\",\n \"@x402/evm\": \"2.17.0\",\n \"@x402/extensions\": \"2.17.0\",\n \"commander\": \"^14.0.1\",\n \"eslint\": \"^10\",\n \"eslint-config-prettier\": \"^10\",\n \"ox\": \"0.14.30\",\n \"prettier\": \"^3\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^6\",\n \"typescript-eslint\": \"^8\",\n \"viem\": \"^2.53.1\",\n \"vitest\": \"^4.1.9\",\n \"zod\": \"^4.4.3\"\n }\n}\n"],"mappings":";;;AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,SAAW;AAAA,EACX,MAAQ;AAAA,EACR,aAAe;AAAA,EACf,SAAW;AAAA,EACX,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,EACR,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,KAAO;AAAA,IACL,QAAU;AAAA,EACZ;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,gBAAkB;AAAA,EAClB,SAAW;AAAA,IACT,OAAS;AAAA,IACT,MAAQ;AAAA,IACR,WAAa;AAAA,IACb,MAAQ;AAAA,IACR,QAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,OAAS;AAAA,IACT,cAAc;AAAA,IACd,cAAc;AAAA,IACd,WAAa;AAAA,IACb,gBAAkB;AAAA,IAClB,SAAW;AAAA,EACb;AAAA,EACA,iBAAmB;AAAA,IACjB,mBAAmB;AAAA,IACnB,kBAAkB;AAAA,IAClB,cAAc;AAAA,IACd,6BAA6B;AAAA,IAC7B,eAAe;AAAA,IACf,cAAc;AAAA,IACd,aAAa;AAAA,IACb,oBAAoB;AAAA,IACpB,WAAa;AAAA,IACb,QAAU;AAAA,IACV,0BAA0B;AAAA,IAC1B,IAAM;AAAA,IACN,UAAY;AAAA,IACZ,MAAQ;AAAA,IACR,YAAc;AAAA,IACd,qB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