tenjin-cli 0.1.0-alpha.14 → 0.1.0-alpha.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE.md +54 -7
- package/README.md +41 -295
- package/dist/{_esm-N4KAVXQR.js → _esm-CE7KNONL.js} +9 -10
- package/dist/{ccip-ZGGWQN4X.js → ccip-7RMRLAGV.js} +4 -4
- package/dist/{ccip-RPPPKTJR.js → ccip-NLCSCHKI.js} +5 -5
- package/dist/chunk-25TJPVBF.js +353 -0
- package/dist/chunk-25TJPVBF.js.map +1 -0
- package/dist/chunk-2BKS2FVE.js +93 -0
- package/dist/chunk-2BKS2FVE.js.map +1 -0
- package/dist/chunk-2QYORQBF.js +55 -0
- package/dist/chunk-2QYORQBF.js.map +1 -0
- package/dist/{chunk-ACBEHJAH.js → chunk-2U5ZVEV3.js} +14 -16
- package/dist/chunk-2U5ZVEV3.js.map +1 -0
- package/dist/{chunk-MJSXP4LW.js → chunk-3AJS6LLN.js} +11 -8
- package/dist/chunk-3AJS6LLN.js.map +1 -0
- package/dist/{chunk-OWVVI4VQ.js → chunk-3AUDA53C.js} +7650 -7361
- package/dist/chunk-3AUDA53C.js.map +1 -0
- package/dist/{chunk-MJZZTKCC.js → chunk-56MOAIP5.js} +5 -10
- package/dist/chunk-56MOAIP5.js.map +1 -0
- package/dist/{chunk-U5S527PP.js → chunk-5IEP5EGE.js} +3 -3
- package/dist/chunk-5X4SZ5BF.js +227 -0
- package/dist/chunk-5X4SZ5BF.js.map +1 -0
- package/dist/chunk-7WEQQJLG.js +68 -0
- package/dist/chunk-7WEQQJLG.js.map +1 -0
- package/dist/{chunk-7FK2UN2T.js → chunk-AWQPGIR6.js} +65 -67
- package/dist/{chunk-7FK2UN2T.js.map → chunk-AWQPGIR6.js.map} +1 -1
- package/dist/{chunk-PAOVPSP6.js → chunk-BBVUVBUO.js} +517 -138
- package/dist/chunk-BBVUVBUO.js.map +1 -0
- package/dist/{chunk-ETKZWJ4B.js → chunk-BFFM2WFK.js} +8 -8
- package/dist/chunk-BFFM2WFK.js.map +1 -0
- package/dist/{chunk-KYQVEKP5.js → chunk-BPMWXTFX.js} +8 -8
- package/dist/chunk-DMZZLPZN.js +205 -0
- package/dist/chunk-DMZZLPZN.js.map +1 -0
- package/dist/{chunk-47PP7TAG.js → chunk-EGELTSPU.js} +1356 -1356
- package/dist/chunk-EGELTSPU.js.map +1 -0
- package/dist/chunk-GULLJQXA.js +698 -0
- package/dist/chunk-GULLJQXA.js.map +1 -0
- package/dist/{chunk-S5RYMCV6.js → chunk-HPWO4O6S.js} +3 -3
- package/dist/chunk-HVRC33OL.js +174 -0
- package/dist/chunk-HVRC33OL.js.map +1 -0
- package/dist/{chunk-W6R3HAAG.js → chunk-JRGFKVAZ.js} +2 -2
- package/dist/{chunk-XJN5WUKL.js → chunk-KG3D7FIF.js} +2 -2
- package/dist/chunk-L3PVMIYQ.js +10328 -0
- package/dist/chunk-L3PVMIYQ.js.map +1 -0
- package/dist/{chunk-QW2Q2KAH.js → chunk-LHHMV4GU.js} +2 -2
- package/dist/{chunk-ZOBNS7CX.js → chunk-MEFB5KHA.js} +4 -18
- package/dist/chunk-MEFB5KHA.js.map +1 -0
- package/dist/{chunk-M2O56UK7.js → chunk-N35E6CM2.js} +293 -163
- package/dist/chunk-N35E6CM2.js.map +1 -0
- package/dist/chunk-OCBHUHWB.js +69 -0
- package/dist/chunk-OCBHUHWB.js.map +1 -0
- package/dist/chunk-OIM4HLN6.js +1405 -0
- package/dist/chunk-OIM4HLN6.js.map +1 -0
- package/dist/{chunk-PKW3H26Z.js → chunk-OJLYNM4Z.js} +56 -33
- package/dist/chunk-OJLYNM4Z.js.map +1 -0
- package/dist/{chunk-POJRB2AE.js → chunk-POUWHWID.js} +2 -2
- package/dist/chunk-PZEN5PHN.js +285 -0
- package/dist/chunk-PZEN5PHN.js.map +1 -0
- package/dist/chunk-SKAHDQH7.js +1785 -0
- package/dist/chunk-SKAHDQH7.js.map +1 -0
- package/dist/{chunk-KZAAWQNP.js → chunk-TTNESUPQ.js} +3 -3
- package/dist/{chunk-QWBUKIP2.js → chunk-U5DXNFJC.js} +23 -94
- package/dist/chunk-U5DXNFJC.js.map +1 -0
- package/dist/chunk-USS336NF.js +165 -0
- package/dist/chunk-USS336NF.js.map +1 -0
- package/dist/{chunk-UO22YNY4.js → chunk-WH7OWT6G.js} +49 -1
- package/dist/chunk-WH7OWT6G.js.map +1 -0
- package/dist/chunk-WXC57XGG.js +29 -0
- package/dist/chunk-WXC57XGG.js.map +1 -0
- package/dist/{chunk-YLYINX2H.js → chunk-XZKD7DIF.js} +3 -3
- package/dist/{chunk-7GJQ5RGA.js → chunk-YEETV6IW.js} +1077 -1039
- package/dist/chunk-YEETV6IW.js.map +1 -0
- package/dist/{chunk-B676GPS2.js → chunk-YJHHCWM3.js} +39 -16
- package/dist/chunk-YJHHCWM3.js.map +1 -0
- package/dist/{cli-U2BEUA55.js → cli-M3XCSOU6.js} +295 -349
- package/dist/cli-M3XCSOU6.js.map +1 -0
- package/dist/config-MXOX7XDR.js +41 -0
- package/dist/{dist-U4M6QCKE.js → dist-3LOO6M4U.js} +10 -10
- package/dist/doctor-LU4YIZWM.js +349 -0
- package/dist/doctor-LU4YIZWM.js.map +1 -0
- package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
- package/dist/{chunk-3ZW7HPY5.js → fund-A54P2QFK.js} +81 -22
- package/dist/fund-A54P2QFK.js.map +1 -0
- package/dist/hook-command-U6KWPEDQ.js +377 -0
- package/dist/hook-command-U6KWPEDQ.js.map +1 -0
- package/dist/index.js +8 -3
- package/dist/index.js.map +1 -1
- package/dist/install-XUM2XSHW.js +53 -0
- package/dist/install-wallet-QIOFORTX.js +105 -0
- package/dist/install-wallet-QIOFORTX.js.map +1 -0
- package/dist/{run-CJWPGMIQ.js → mcp-HJC2PLRV.js} +3725 -10661
- package/dist/mcp-HJC2PLRV.js.map +1 -0
- package/dist/paths-P2N4JTDZ.js +49 -0
- package/dist/pay-SBXZEPEP.js +37 -0
- package/dist/redact-46ZHF2NH.js +17 -0
- package/dist/{secp256k1-XRPVBC6V.js → secp256k1-ZZZT2CAX.js} +3 -3
- package/dist/{send-C5EOKXOU.js → send-ASD2ZXJD.js} +28 -30
- package/dist/send-ASD2ZXJD.js.map +1 -0
- package/dist/{chunk-NAAMHWSI.js → skill-placement-NFVHY6A3.js} +159 -12
- package/dist/skill-placement-NFVHY6A3.js.map +1 -0
- package/dist/status-T2SDB57A.js +63 -0
- package/dist/status-T2SDB57A.js.map +1 -0
- package/dist/status-line-CGPUSDMC.js +71 -0
- package/dist/status-line-CGPUSDMC.js.map +1 -0
- package/dist/status-line-wiring-BYPHTYZE.js +30 -0
- package/dist/tenjin-daemon.mjs +20060 -0
- package/dist/tenjin-shim.mjs +251 -0
- package/dist/tenjin-vitest-reporter.mjs +49 -0
- package/dist/uninstall-FKYZHAM3.js +144 -0
- package/dist/uninstall-FKYZHAM3.js.map +1 -0
- package/dist/{update-24Y2CQTT.js → update-ANJ2AOTN.js} +133 -17
- package/dist/update-ANJ2AOTN.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-TUQJBMHM.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
- package/dist/wallet-PWAHVKWW.js +31 -0
- package/dist/wallet-kdf-worker.mjs +980 -0
- package/docs/agent-permissions.md +68 -342
- package/docs/safety-model.md +25 -6
- package/package.json +8 -7
- package/LICENSE +0 -21
- package/dist/buy-2JBYPHAI.js +0 -46
- package/dist/chunk-3P3ES4XU.js +0 -144
- package/dist/chunk-3P3ES4XU.js.map +0 -1
- package/dist/chunk-3ZW7HPY5.js.map +0 -1
- package/dist/chunk-47PP7TAG.js.map +0 -1
- package/dist/chunk-4UHNXY6B.js +0 -786
- package/dist/chunk-4UHNXY6B.js.map +0 -1
- package/dist/chunk-4Y53PDH6.js +0 -213
- package/dist/chunk-4Y53PDH6.js.map +0 -1
- package/dist/chunk-54AJIO3E.js +0 -198
- package/dist/chunk-54AJIO3E.js.map +0 -1
- package/dist/chunk-736DW4V3.js +0 -65
- package/dist/chunk-736DW4V3.js.map +0 -1
- package/dist/chunk-7GJQ5RGA.js.map +0 -1
- package/dist/chunk-7NADDA2V.js +0 -161
- package/dist/chunk-7NADDA2V.js.map +0 -1
- package/dist/chunk-ACBEHJAH.js.map +0 -1
- package/dist/chunk-B676GPS2.js.map +0 -1
- package/dist/chunk-DAZAXFSF.js +0 -1357
- package/dist/chunk-DAZAXFSF.js.map +0 -1
- package/dist/chunk-DTCXO7HS.js +0 -791
- package/dist/chunk-DTCXO7HS.js.map +0 -1
- package/dist/chunk-ETKZWJ4B.js.map +0 -1
- package/dist/chunk-FDUD3W5V.js +0 -317
- package/dist/chunk-FDUD3W5V.js.map +0 -1
- package/dist/chunk-GEHL43VE.js +0 -711
- package/dist/chunk-GEHL43VE.js.map +0 -1
- package/dist/chunk-IU2HVT3Y.js +0 -313
- package/dist/chunk-IU2HVT3Y.js.map +0 -1
- package/dist/chunk-IUQZ4Z7M.js +0 -162
- package/dist/chunk-IUQZ4Z7M.js.map +0 -1
- package/dist/chunk-IXZJ3JOO.js +0 -614
- package/dist/chunk-IXZJ3JOO.js.map +0 -1
- package/dist/chunk-J6FUAIRR.js +0 -205
- package/dist/chunk-J6FUAIRR.js.map +0 -1
- package/dist/chunk-L6G35FU5.js +0 -105
- package/dist/chunk-L6G35FU5.js.map +0 -1
- package/dist/chunk-LSWP7MU2.js +0 -290
- package/dist/chunk-LSWP7MU2.js.map +0 -1
- package/dist/chunk-M2O56UK7.js.map +0 -1
- package/dist/chunk-MJSXP4LW.js.map +0 -1
- package/dist/chunk-MJZZTKCC.js.map +0 -1
- package/dist/chunk-NAAMHWSI.js.map +0 -1
- package/dist/chunk-O75FOHXS.js +0 -372
- package/dist/chunk-O75FOHXS.js.map +0 -1
- package/dist/chunk-OWVVI4VQ.js.map +0 -1
- package/dist/chunk-PAOVPSP6.js.map +0 -1
- package/dist/chunk-PCX2JQ2J.js +0 -233
- package/dist/chunk-PCX2JQ2J.js.map +0 -1
- package/dist/chunk-PKW3H26Z.js.map +0 -1
- package/dist/chunk-PQZVDCCA.js +0 -125
- package/dist/chunk-PQZVDCCA.js.map +0 -1
- package/dist/chunk-QWBUKIP2.js.map +0 -1
- package/dist/chunk-SGK2B724.js +0 -67
- package/dist/chunk-SGK2B724.js.map +0 -1
- package/dist/chunk-UHTVXQ2O.js +0 -140
- package/dist/chunk-UHTVXQ2O.js.map +0 -1
- package/dist/chunk-UO22YNY4.js.map +0 -1
- package/dist/chunk-VEAERJVJ.js +0 -43
- package/dist/chunk-VEAERJVJ.js.map +0 -1
- package/dist/chunk-VRPLZERE.js +0 -1421
- package/dist/chunk-VRPLZERE.js.map +0 -1
- package/dist/chunk-W4VW5XYB.js +0 -149
- package/dist/chunk-W4VW5XYB.js.map +0 -1
- package/dist/chunk-WU5CZPLD.js +0 -145
- package/dist/chunk-WU5CZPLD.js.map +0 -1
- package/dist/chunk-WYLMJQVH.js +0 -240
- package/dist/chunk-WYLMJQVH.js.map +0 -1
- package/dist/chunk-XGZ5EVMB.js +0 -35
- package/dist/chunk-XGZ5EVMB.js.map +0 -1
- package/dist/chunk-XVPQGCH4.js +0 -176
- package/dist/chunk-XVPQGCH4.js.map +0 -1
- package/dist/chunk-ZOBNS7CX.js.map +0 -1
- package/dist/chunk-ZQIQ55KK.js +0 -51
- package/dist/chunk-ZQIQ55KK.js.map +0 -1
- package/dist/cli-U2BEUA55.js.map +0 -1
- package/dist/config-CNUIX23Q.js +0 -32
- package/dist/doctor-QJJXRWTO.js +0 -31
- package/dist/edit-HJ44P44P.js +0 -40
- package/dist/fund-Y5IAHZ5D.js +0 -40
- package/dist/inspect-NFQ6SQQQ.js +0 -37
- package/dist/install-DXX7PVUP.js +0 -854
- package/dist/install-DXX7PVUP.js.map +0 -1
- package/dist/outcome-ANV4QIED.js +0 -24
- package/dist/publish-PCBTCXCZ.js +0 -42
- package/dist/read-W7QVRBVD.js +0 -160
- package/dist/read-W7QVRBVD.js.map +0 -1
- package/dist/run-CJWPGMIQ.js.map +0 -1
- package/dist/search-JGAVKTYJ.js +0 -25
- package/dist/secp256k1-XRPVBC6V.js.map +0 -1
- package/dist/send-C5EOKXOU.js.map +0 -1
- package/dist/session-OBCUUIFX.js +0 -89
- package/dist/session-OBCUUIFX.js.map +0 -1
- package/dist/skill-heal-D6EPLPS6.js +0 -84
- package/dist/skill-heal-D6EPLPS6.js.map +0 -1
- package/dist/uninstall-OWJNJ5LI.js +0 -73
- package/dist/uninstall-OWJNJ5LI.js.map +0 -1
- package/dist/update-24Y2CQTT.js.map +0 -1
- package/dist/usdc-4VCDHFWX.js +0 -38
- package/dist/usdc-4VCDHFWX.js.map +0 -1
- package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +0 -1
- package/dist/wallet-OFXDIIGP.js +0 -33
- package/dist/wallet-OFXDIIGP.js.map +0 -1
- package/dist/wallet-SLRIYJ2U.js +0 -42
- package/dist/wallet-SLRIYJ2U.js.map +0 -1
- package/docs/command-reference.md +0 -261
- package/skills/tenjin/SKILL.md +0 -364
- package/skills/tenjin-publish/SKILL.md +0 -224
- package/skills/tenjin-publish/references/maintain.md +0 -39
- package/skills/tenjin-search/SKILL.md +0 -149
- package/skills/tenjin-search/references/permissions.md +0 -106
- /package/dist/{_esm-N4KAVXQR.js.map → _esm-CE7KNONL.js.map} +0 -0
- /package/dist/{buy-2JBYPHAI.js.map → ccip-7RMRLAGV.js.map} +0 -0
- /package/dist/{ccip-RPPPKTJR.js.map → ccip-NLCSCHKI.js.map} +0 -0
- /package/dist/{chunk-U5S527PP.js.map → chunk-5IEP5EGE.js.map} +0 -0
- /package/dist/{chunk-KYQVEKP5.js.map → chunk-BPMWXTFX.js.map} +0 -0
- /package/dist/{chunk-S5RYMCV6.js.map → chunk-HPWO4O6S.js.map} +0 -0
- /package/dist/{chunk-W6R3HAAG.js.map → chunk-JRGFKVAZ.js.map} +0 -0
- /package/dist/{chunk-XJN5WUKL.js.map → chunk-KG3D7FIF.js.map} +0 -0
- /package/dist/{chunk-QW2Q2KAH.js.map → chunk-LHHMV4GU.js.map} +0 -0
- /package/dist/{chunk-POJRB2AE.js.map → chunk-POUWHWID.js.map} +0 -0
- /package/dist/{chunk-KZAAWQNP.js.map → chunk-TTNESUPQ.js.map} +0 -0
- /package/dist/{chunk-YLYINX2H.js.map → chunk-XZKD7DIF.js.map} +0 -0
- /package/dist/{ccip-ZGGWQN4X.js.map → config-MXOX7XDR.js.map} +0 -0
- /package/dist/{dist-U4M6QCKE.js.map → dist-3LOO6M4U.js.map} +0 -0
- /package/dist/{config-CNUIX23Q.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
- /package/dist/{doctor-QJJXRWTO.js.map → install-XUM2XSHW.js.map} +0 -0
- /package/dist/{edit-HJ44P44P.js.map → paths-P2N4JTDZ.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js.map → pay-SBXZEPEP.js.map} +0 -0
- /package/dist/{fund-Y5IAHZ5D.js.map → redact-46ZHF2NH.js.map} +0 -0
- /package/dist/{inspect-NFQ6SQQQ.js.map → secp256k1-ZZZT2CAX.js.map} +0 -0
- /package/dist/{outcome-ANV4QIED.js.map → status-line-wiring-BYPHTYZE.js.map} +0 -0
- /package/dist/{publish-PCBTCXCZ.js.map → viemAdapter-By13KInL-X2VY6CY3.js.map} +0 -0
- /package/dist/{search-JGAVKTYJ.js.map → wallet-PWAHVKWW.js.map} +0 -0
package/dist/chunk-PCX2JQ2J.js
DELETED
|
@@ -1,233 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
SIWX_HEADER,
|
|
4
|
-
decodePaymentRequiredHeader,
|
|
5
|
-
decodePaymentResponseHeader
|
|
6
|
-
} from "./chunk-OWVVI4VQ.js";
|
|
7
|
-
import {
|
|
8
|
-
rateLimitError
|
|
9
|
-
} from "./chunk-FDUD3W5V.js";
|
|
10
|
-
import {
|
|
11
|
-
httpRequest
|
|
12
|
-
} from "./chunk-54AJIO3E.js";
|
|
13
|
-
import {
|
|
14
|
-
SLUG_RE,
|
|
15
|
-
UUID_RE
|
|
16
|
-
} from "./chunk-736DW4V3.js";
|
|
17
|
-
import {
|
|
18
|
-
CliError,
|
|
19
|
-
external_exports
|
|
20
|
-
} from "./chunk-PAOVPSP6.js";
|
|
21
|
-
|
|
22
|
-
// src/lib/read-client.ts
|
|
23
|
-
var PAYMENT_REQUIRED_HEADER = "PAYMENT-REQUIRED";
|
|
24
|
-
var PAYMENT_RESPONSE_HEADER = "PAYMENT-RESPONSE";
|
|
25
|
-
var readBodySchema = external_exports.object({
|
|
26
|
-
id: external_exports.string().regex(UUID_RE, "resource id must be a uuid"),
|
|
27
|
-
slug: external_exports.string().regex(SLUG_RE, "unsafe slug").max(80),
|
|
28
|
-
title: external_exports.string(),
|
|
29
|
-
bodyMd: external_exports.string(),
|
|
30
|
-
price: external_exports.string(),
|
|
31
|
-
creator: external_exports.object({
|
|
32
|
-
handle: external_exports.string().nullish(),
|
|
33
|
-
walletAddress: external_exports.string().nullish()
|
|
34
|
-
}).passthrough()
|
|
35
|
-
}).passthrough();
|
|
36
|
-
var previewCardSchema = external_exports.object({
|
|
37
|
-
artifactType: external_exports.string(),
|
|
38
|
-
temporalMode: external_exports.string(),
|
|
39
|
-
asOf: external_exports.string().nullable(),
|
|
40
|
-
validUntil: external_exports.string().nullable(),
|
|
41
|
-
questionsAnswered: external_exports.array(external_exports.string()),
|
|
42
|
-
tasksSupported: external_exports.array(external_exports.string()),
|
|
43
|
-
appliesTo: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
|
|
44
|
-
scope: external_exports.string().nullable(),
|
|
45
|
-
exclusions: external_exports.string().nullable(),
|
|
46
|
-
provenanceSummary: external_exports.string().nullable(),
|
|
47
|
-
methodologySummary: external_exports.string().nullable(),
|
|
48
|
-
maintenanceCadence: external_exports.string().nullable()
|
|
49
|
-
}).passthrough();
|
|
50
|
-
var previewSchema = external_exports.object({
|
|
51
|
-
id: external_exports.string().optional(),
|
|
52
|
-
title: external_exports.string().optional(),
|
|
53
|
-
price: external_exports.string().optional(),
|
|
54
|
-
creator: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
|
|
55
|
-
// `.catch` keeps a botched card from taking the rest of the preview with it:
|
|
56
|
-
// every other preview field is optional, so before the card existed a parse
|
|
57
|
-
// failure here was near-impossible, and a server that half-fills the card
|
|
58
|
-
// should still not cost the caller the title and the price it came for.
|
|
59
|
-
// The drop is NOT silent: see `cardError` on the result below.
|
|
60
|
-
card: previewCardSchema.optional().catch(void 0),
|
|
61
|
-
// Set by the SERVER when the piece has a card it could not load, so an absent
|
|
62
|
-
// card is never ambiguous: no flag means uncarded, this flag means temporarily
|
|
63
|
-
// unreadable. Never false and never sent beside `card` (tenjin#500), and the
|
|
64
|
-
// same fail-soft as above so a bogus `false` drops the flag rather than the
|
|
65
|
-
// whole preview.
|
|
66
|
-
cardUnavailable: external_exports.literal(true).optional().catch(void 0)
|
|
67
|
-
}).passthrough();
|
|
68
|
-
var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
69
|
-
var paymentRequiredSchema = external_exports.object({
|
|
70
|
-
x402Version: external_exports.literal(2),
|
|
71
|
-
accepts: external_exports.array(
|
|
72
|
-
external_exports.object({
|
|
73
|
-
scheme: external_exports.string(),
|
|
74
|
-
network: external_exports.string().regex(/^eip155:\d+$/, "network must be CAIP-2 eip155"),
|
|
75
|
-
asset: external_exports.string().regex(ADDRESS_RE, "asset must be a 0x address"),
|
|
76
|
-
amount: external_exports.string().regex(/^\d{1,39}$/, "amount must be an atomic integer string"),
|
|
77
|
-
payTo: external_exports.string().regex(ADDRESS_RE, "payTo must be a 0x address")
|
|
78
|
-
}).passthrough()
|
|
79
|
-
)
|
|
80
|
-
}).passthrough();
|
|
81
|
-
async function fetchRead(url, opts) {
|
|
82
|
-
const headers = { accept: "application/json" };
|
|
83
|
-
if (opts.searchId !== void 0) headers["x-tenjin-search-id"] = opts.searchId;
|
|
84
|
-
if (opts.siwxHeader !== void 0) headers[SIWX_HEADER] = opts.siwxHeader;
|
|
85
|
-
if (opts.sessionHeaders !== void 0) Object.assign(headers, opts.sessionHeaders);
|
|
86
|
-
if (opts.paymentHeaders !== void 0) Object.assign(headers, opts.paymentHeaders);
|
|
87
|
-
const res = await httpRequest(url, {
|
|
88
|
-
method: "GET",
|
|
89
|
-
timeoutMs: opts.timeoutMs,
|
|
90
|
-
headers,
|
|
91
|
-
fetchImpl: opts.fetchImpl,
|
|
92
|
-
// Pinned even when UNSIGNED (the first probe): a 200 from this route is
|
|
93
|
-
// written to the library by `deliverFresh` as an entitlement record under
|
|
94
|
-
// the server-chosen id/slug, and `findDeliveredByUrl` later matches saved
|
|
95
|
-
// receipts by handle+slug alone — so a followed cross-origin redirect
|
|
96
|
-
// would let another host's bytes short-circuit future buys as owned.
|
|
97
|
-
// `assertOnBaseOrigin` cannot catch this; it checks only the URL asked for.
|
|
98
|
-
//
|
|
99
|
-
// Refused for ANY 3xx, same-origin hops included. The transport failing closed
|
|
100
|
-
// on the whole class is the point: an exemption for "benign" redirects is a
|
|
101
|
-
// second origin check living in the one place that already proved it cannot see
|
|
102
|
-
// enough to make one. Keeping a canonical URL is the CALLER's job instead, and
|
|
103
|
-
// `resolveResourceRef` does it for every verb that gets here.
|
|
104
|
-
blockRedirects: true
|
|
105
|
-
});
|
|
106
|
-
if (!res.ok) {
|
|
107
|
-
if (res.kind === "blocked-redirect") {
|
|
108
|
-
throw new CliError("CONTRACT_MISMATCH", `${url}: ${res.message}`, {
|
|
109
|
-
// The origin half of this hint deliberately does NOT name the base-URL
|
|
110
|
-
// flag. `read` is meant to be allowlistable, the skill tells the agent
|
|
111
|
-
// never to pass that flag on an allowlisted verb, and a `fix:` naming it
|
|
112
|
-
// would coach exactly the move the skill forbids. `doctor` is the
|
|
113
|
-
// allowlisted verb that owns the question — its `checkReadPath` probes
|
|
114
|
-
// this route and its own copy names the config command when it should.
|
|
115
|
-
fix: "Ask for the URL in the spelling `tenjin search` or `tenjin inspect` reports. If every read hops, `tenjin doctor` checks the configured origin."
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
const code = res.kind === "network" || res.kind === "timeout" ? "NETWORK_ERROR" : "API_UNREACHABLE";
|
|
119
|
-
throw new CliError(code, `${url}: ${res.message}`, {
|
|
120
|
-
fix: "Check the resource URL and your network, then retry."
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
if (res.status === 200) {
|
|
124
|
-
const parsed = readBodySchema.safeParse(res.json);
|
|
125
|
-
if (!parsed.success) {
|
|
126
|
-
throw new CliError(
|
|
127
|
-
"CONTRACT_MISMATCH",
|
|
128
|
-
"The read response did not match the expected contract",
|
|
129
|
-
{
|
|
130
|
-
fix: "Update tenjin-cli; the read contract may have changed.",
|
|
131
|
-
details: parsed.error.issues
|
|
132
|
-
}
|
|
133
|
-
);
|
|
134
|
-
}
|
|
135
|
-
const settlement = decodeSettlement(res.header(PAYMENT_RESPONSE_HEADER));
|
|
136
|
-
return {
|
|
137
|
-
kind: "entitled",
|
|
138
|
-
body: parsed.data,
|
|
139
|
-
...settlement !== void 0 ? { settlementTxHash: settlement } : {}
|
|
140
|
-
};
|
|
141
|
-
}
|
|
142
|
-
if (res.status === 402) {
|
|
143
|
-
const encoded = res.header(PAYMENT_REQUIRED_HEADER);
|
|
144
|
-
if (encoded === void 0) {
|
|
145
|
-
throw new CliError("CONTRACT_MISMATCH", "The 402 carried no PAYMENT-REQUIRED header", {
|
|
146
|
-
fix: "The server may be misconfigured; try another resource or update tenjin-cli."
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
let decoded;
|
|
150
|
-
try {
|
|
151
|
-
decoded = decodePaymentRequiredHeader(encoded);
|
|
152
|
-
} catch (err) {
|
|
153
|
-
throw new CliError("CONTRACT_MISMATCH", "Could not decode the PAYMENT-REQUIRED header", {
|
|
154
|
-
fix: "Update tenjin-cli; the x402 header format may have changed.",
|
|
155
|
-
cause: err
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
const validated = paymentRequiredSchema.safeParse(decoded);
|
|
159
|
-
if (!validated.success) {
|
|
160
|
-
throw new CliError(
|
|
161
|
-
"CONTRACT_MISMATCH",
|
|
162
|
-
"The 402 challenge is not a valid x402 v2 payment declaration.",
|
|
163
|
-
{
|
|
164
|
-
fix: "Update tenjin-cli, or check the configured base URL (`tenjin config get baseUrl`) points at a Tenjin deployment.",
|
|
165
|
-
details: validated.error.issues
|
|
166
|
-
}
|
|
167
|
-
);
|
|
168
|
-
}
|
|
169
|
-
const paymentRequired = decoded;
|
|
170
|
-
const parsed = previewSchema.safeParse(res.json);
|
|
171
|
-
const preview = parsed.success ? parsed.data : {};
|
|
172
|
-
return {
|
|
173
|
-
kind: "payment_required",
|
|
174
|
-
paymentRequired,
|
|
175
|
-
preview,
|
|
176
|
-
...sentUnparsableCard(res.json, preview) ? { cardError: true } : {}
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
if (res.status === 401 && opts.sessionHeaders !== void 0) {
|
|
180
|
-
const code = readCode(res.json);
|
|
181
|
-
return { kind: "session_rejected", ...code !== void 0 ? { code } : {} };
|
|
182
|
-
}
|
|
183
|
-
if (res.status === 409) {
|
|
184
|
-
return { kind: "already_purchased", message: readMessage(res.json) ?? "Already purchased." };
|
|
185
|
-
}
|
|
186
|
-
if (res.status === 404) {
|
|
187
|
-
throw new CliError("RESOURCE_NOT_FOUND", `No resource at ${url}`, {
|
|
188
|
-
fix: "Check the handle/slug or resource id."
|
|
189
|
-
});
|
|
190
|
-
}
|
|
191
|
-
if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));
|
|
192
|
-
throw new CliError(
|
|
193
|
-
"API_UNREACHABLE",
|
|
194
|
-
readMessage(res.json) ?? `Unexpected status ${res.status} from ${url}`,
|
|
195
|
-
{
|
|
196
|
-
fix: "Retry; if it persists the resource may be unavailable.",
|
|
197
|
-
details: res.json
|
|
198
|
-
}
|
|
199
|
-
);
|
|
200
|
-
}
|
|
201
|
-
function sentUnparsableCard(json, preview) {
|
|
202
|
-
if (typeof json !== "object" || json === null) return false;
|
|
203
|
-
return "card" in json && preview.card === void 0;
|
|
204
|
-
}
|
|
205
|
-
function decodeSettlement(header) {
|
|
206
|
-
if (header === void 0) return void 0;
|
|
207
|
-
try {
|
|
208
|
-
const settle = decodePaymentResponseHeader(header);
|
|
209
|
-
const tx = settle.transaction;
|
|
210
|
-
return typeof tx === "string" ? tx : void 0;
|
|
211
|
-
} catch {
|
|
212
|
-
return void 0;
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
function readCode(json) {
|
|
216
|
-
if (typeof json !== "object" || json === null) return void 0;
|
|
217
|
-
const code = json.code;
|
|
218
|
-
return typeof code === "string" ? code : void 0;
|
|
219
|
-
}
|
|
220
|
-
function readMessage(json) {
|
|
221
|
-
if (typeof json === "object" && json !== null) {
|
|
222
|
-
const rec = json;
|
|
223
|
-
if (typeof rec.message === "string") return rec.message;
|
|
224
|
-
if (typeof rec.error === "string") return rec.error;
|
|
225
|
-
if (typeof rec.code === "string") return rec.code;
|
|
226
|
-
}
|
|
227
|
-
return void 0;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
export {
|
|
231
|
-
fetchRead
|
|
232
|
-
};
|
|
233
|
-
//# sourceMappingURL=chunk-PCX2JQ2J.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/read-client.ts"],"sourcesContent":["import { z } from 'zod';\nimport { decodePaymentRequiredHeader, decodePaymentResponseHeader } from '@x402/core/http';\nimport type { PaymentRequired } from '@x402/core/types';\nimport { CliError } from './errors';\nimport { rateLimitError } from './agent-api';\nimport { httpRequest } from './http';\nimport { SIWX_HEADER } from './siwx';\n\n/**\n * The read-route (`GET /api/read/<handle>/<slug>`) client, always JSON/x402, so\n * it is the robust agent target (llms-full). It surfaces the three outcomes the\n * buy flow branches on: `entitled` (200 with the full body, free post, SIWX\n * re-read, or freshly paid), `payment_required` (402 with the decoded\n * PAYMENT-REQUIRED header + the leak-safe preview body), and `already_purchased`\n * (409 owned-re-pay gate, nothing charged). Purchase attribution rides the\n * shared transport's User-Agent always and `X-Tenjin-Search-Id` when a search\n * preceded the buy.\n */\n\nconst PAYMENT_REQUIRED_HEADER = 'PAYMENT-REQUIRED';\nconst PAYMENT_RESPONSE_HEADER = 'PAYMENT-RESPONSE';\n\n// id/slug become filesystem path segments (the local library), so they are\n// validated as a uuid + the server's slug charset HERE, at the trust boundary, so\n// a hostile id='../../evil' or slug fails as CONTRACT_MISMATCH before delivery.\nimport { SLUG_RE, UUID_RE as RESOURCE_ID_RE } from './ids';\n\n/** The full essay body a 200 returns (loose: require what the CLI reads, keep the rest). */\nconst readBodySchema = z\n .object({\n id: z.string().regex(RESOURCE_ID_RE, 'resource id must be a uuid'),\n slug: z.string().regex(SLUG_RE, 'unsafe slug').max(80),\n title: z.string(),\n bodyMd: z.string(),\n price: z.string(),\n creator: z\n .object({\n handle: z.string().nullish(),\n walletAddress: z.string().nullish(),\n })\n .passthrough(),\n })\n .passthrough();\n\nexport type ReadBody = z.infer<typeof readBodySchema>;\n\n/**\n * The public half of the piece's answer card, carried on the 402 body when the\n * piece has one. The key is ABSENT (never null) on an uncarded piece, so callers\n * branch on presence; the projection emits every field whenever it emits the card\n * at all, so a present card is never partial. Nullable fields carry null.\n *\n * This is the depth half of the search/inspect split: the card left the search\n * candidate in search v2 and lives here, one free unpaid GET away.\n */\nexport const previewCardSchema = z\n .object({\n artifactType: z.string(),\n temporalMode: z.string(),\n asOf: z.string().nullable(),\n validUntil: z.string().nullable(),\n questionsAnswered: z.array(z.string()),\n tasksSupported: z.array(z.string()),\n appliesTo: z.record(z.string(), z.array(z.string())),\n scope: z.string().nullable(),\n exclusions: z.string().nullable(),\n provenanceSummary: z.string().nullable(),\n methodologySummary: z.string().nullable(),\n maintenanceCadence: z.string().nullable(),\n })\n .passthrough();\n\nexport type PreviewCard = z.infer<typeof previewCardSchema>;\n\n/** The leak-safe 402 preview body, never the paid content. */\nconst previewSchema = z\n .object({\n id: z.string().optional(),\n title: z.string().optional(),\n price: z.string().optional(),\n creator: z.record(z.string(), z.unknown()).optional(),\n // `.catch` keeps a botched card from taking the rest of the preview with it:\n // every other preview field is optional, so before the card existed a parse\n // failure here was near-impossible, and a server that half-fills the card\n // should still not cost the caller the title and the price it came for.\n // The drop is NOT silent: see `cardError` on the result below.\n card: previewCardSchema.optional().catch(undefined),\n // Set by the SERVER when the piece has a card it could not load, so an absent\n // card is never ambiguous: no flag means uncarded, this flag means temporarily\n // unreadable. Never false and never sent beside `card` (tenjin#500), and the\n // same fail-soft as above so a bogus `false` drops the flag rather than the\n // whole preview.\n cardUnavailable: z.literal(true).optional().catch(undefined),\n })\n .passthrough();\n\nexport type Preview = z.infer<typeof previewSchema>;\n\n// The decoded PAYMENT-REQUIRED is money-path input: validate the fields the pay\n// path consumes (amount as an atomic integer, CAIP-2 network, 0x asset/payTo)\n// at THIS boundary instead of trusting raw base64 JSON. Loose otherwise so new\n// server fields never break an older CLI.\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\nconst paymentRequiredSchema = z\n .object({\n x402Version: z.literal(2),\n accepts: z.array(\n z\n .object({\n scheme: z.string(),\n network: z.string().regex(/^eip155:\\d+$/, 'network must be CAIP-2 eip155'),\n asset: z.string().regex(ADDRESS_RE, 'asset must be a 0x address'),\n amount: z.string().regex(/^\\d{1,39}$/, 'amount must be an atomic integer string'),\n payTo: z.string().regex(ADDRESS_RE, 'payTo must be a 0x address'),\n })\n .passthrough(),\n ),\n })\n .passthrough();\n\nexport type ReadResult =\n | { kind: 'entitled'; body: ReadBody; settlementTxHash?: string }\n | {\n kind: 'payment_required';\n paymentRequired: PaymentRequired;\n preview: Preview;\n /** The 402 carried a `card` this CLI could not parse, so `preview.card` is\n * absent for a reason that is NOT \"the piece is uncarded\". The two must\n * stay distinguishable: an uncarded piece is a real signal a buyer acts\n * on, and this 402 is the only pre-purchase depth there is. */\n cardError?: true;\n }\n | { kind: 'already_purchased'; message: string };\n\n/**\n * The extra outcome a SESSION-SIGNED read can have: a 401 saying the delegation is\n * expired, revoked, or bound to a key this server will not accept.\n *\n * It is a value rather than a thrown API_UNREACHABLE because the caller has a\n * defined answer for it — `read` falls to its ordinary exit-3 refusal, never a\n * retry loop, because re-establishing needs a wallet it cannot reach. And it is\n * kept OUT of `ReadResult` because an unsigned or SIWX 401 has no such contract:\n * widening the shared union would make `buy` and `inspect` branch on a state they\n * can never produce, and a \"cannot happen\" branch is where wrong handling hides.\n */\nexport type SessionReadResult = ReadResult | { kind: 'session_rejected'; code?: string };\n\nexport interface ReadRequestOptions {\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n /** A `SIGN-IN-WITH-X` header for the entitled free re-read. */\n siwxHeader?: string;\n /** The `PAYMENT-SIGNATURE` header(s) for a paid request. */\n paymentHeaders?: Record<string, string>;\n /**\n * RFC 9421 session-key headers (`Tenjin-Session-Delegation`, `Signature-Input`,\n * `Signature`) proving an entitlement without a wallet and without paying. A\n * bodyless GET carries no `Content-Digest`, so the covered set is method+URI.\n */\n sessionHeaders?: Record<string, string>;\n /** Attribute a following purchase to the search that surfaced it. */\n searchId?: string;\n}\n\n/**\n * One transport, two result types, selected by whether the caller actually\n * presented a session key. The `session_rejected` arm is reachable only when\n * `sessionHeaders` were sent, so the overloads say exactly that instead of\n * leaving every caller to prove it by inspection.\n */\nexport async function fetchRead(\n url: string,\n opts: ReadRequestOptions & { sessionHeaders: Record<string, string> },\n): Promise<SessionReadResult>;\nexport async function fetchRead(url: string, opts: ReadRequestOptions): Promise<ReadResult>;\nexport async function fetchRead(url: string, opts: ReadRequestOptions): Promise<SessionReadResult> {\n const headers: Record<string, string> = { accept: 'application/json' };\n if (opts.searchId !== undefined) headers['x-tenjin-search-id'] = opts.searchId;\n if (opts.siwxHeader !== undefined) headers[SIWX_HEADER] = opts.siwxHeader;\n if (opts.sessionHeaders !== undefined) Object.assign(headers, opts.sessionHeaders);\n if (opts.paymentHeaders !== undefined) Object.assign(headers, opts.paymentHeaders);\n\n const res = await httpRequest(url, {\n method: 'GET',\n timeoutMs: opts.timeoutMs,\n headers,\n fetchImpl: opts.fetchImpl,\n // Pinned even when UNSIGNED (the first probe): a 200 from this route is\n // written to the library by `deliverFresh` as an entitlement record under\n // the server-chosen id/slug, and `findDeliveredByUrl` later matches saved\n // receipts by handle+slug alone — so a followed cross-origin redirect\n // would let another host's bytes short-circuit future buys as owned.\n // `assertOnBaseOrigin` cannot catch this; it checks only the URL asked for.\n //\n // Refused for ANY 3xx, same-origin hops included. The transport failing closed\n // on the whole class is the point: an exemption for \"benign\" redirects is a\n // second origin check living in the one place that already proved it cannot see\n // enough to make one. Keeping a canonical URL is the CALLER's job instead, and\n // `resolveResourceRef` does it for every verb that gets here.\n blockRedirects: true,\n });\n if (!res.ok) {\n // A redirect refused mid-flight is a URL-shape problem, not a flaky network:\n // retrying a signed request re-sends the same signature into the same\n // redirect, and retrying the unsigned probe re-fetches bytes the library must\n // never record as this origin's. The `fix` names the URL, not the route: the\n // route is allowed to redirect (canonicalizing a path is what a redirect is\n // FOR), and pointing an agent at the base URL for a hop the base URL did not\n // cause spends two useless steps and still does not read the piece.\n // `resolveResourceRef` canonicalizes what it can (the trailing slash); what\n // reaches here is a spelling it could not.\n if (res.kind === 'blocked-redirect') {\n throw new CliError('CONTRACT_MISMATCH', `${url}: ${res.message}`, {\n // The origin half of this hint deliberately does NOT name the base-URL\n // flag. `read` is meant to be allowlistable, the skill tells the agent\n // never to pass that flag on an allowlisted verb, and a `fix:` naming it\n // would coach exactly the move the skill forbids. `doctor` is the\n // allowlisted verb that owns the question — its `checkReadPath` probes\n // this route and its own copy names the config command when it should.\n fix:\n 'Ask for the URL in the spelling `tenjin search` or `tenjin inspect` ' +\n 'reports. If every read hops, `tenjin doctor` checks the configured origin.',\n });\n }\n const code =\n res.kind === 'network' || res.kind === 'timeout' ? 'NETWORK_ERROR' : 'API_UNREACHABLE';\n throw new CliError(code, `${url}: ${res.message}`, {\n fix: 'Check the resource URL and your network, then retry.',\n });\n }\n\n if (res.status === 200) {\n const parsed = readBodySchema.safeParse(res.json);\n if (!parsed.success) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n 'The read response did not match the expected contract',\n {\n fix: 'Update tenjin-cli; the read contract may have changed.',\n details: parsed.error.issues,\n },\n );\n }\n const settlement = decodeSettlement(res.header(PAYMENT_RESPONSE_HEADER));\n return {\n kind: 'entitled',\n body: parsed.data,\n ...(settlement !== undefined ? { settlementTxHash: settlement } : {}),\n };\n }\n\n if (res.status === 402) {\n const encoded = res.header(PAYMENT_REQUIRED_HEADER);\n if (encoded === undefined) {\n throw new CliError('CONTRACT_MISMATCH', 'The 402 carried no PAYMENT-REQUIRED header', {\n fix: 'The server may be misconfigured; try another resource or update tenjin-cli.',\n });\n }\n let decoded: PaymentRequired;\n try {\n decoded = decodePaymentRequiredHeader(encoded);\n } catch (err) {\n throw new CliError('CONTRACT_MISMATCH', 'Could not decode the PAYMENT-REQUIRED header', {\n fix: 'Update tenjin-cli; the x402 header format may have changed.',\n cause: err,\n });\n }\n const validated = paymentRequiredSchema.safeParse(decoded);\n if (!validated.success) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n 'The 402 challenge is not a valid x402 v2 payment declaration.',\n {\n fix: 'Update tenjin-cli, or check the configured base URL (`tenjin config get baseUrl`) points at a Tenjin deployment.',\n details: validated.error.issues,\n },\n );\n }\n const paymentRequired = decoded;\n const parsed = previewSchema.safeParse(res.json);\n const preview = parsed.success ? parsed.data : {};\n return {\n kind: 'payment_required',\n paymentRequired,\n preview,\n ...(sentUnparsableCard(res.json, preview) ? { cardError: true as const } : {}),\n };\n }\n\n // Narrow on purpose: only a request that actually presented a session key gets\n // the soft outcome. Widening this to every 401 would quietly turn buy's SIWX\n // re-check failure into a value the caller has to remember to branch on.\n if (res.status === 401 && opts.sessionHeaders !== undefined) {\n const code = readCode(res.json);\n return { kind: 'session_rejected', ...(code !== undefined ? { code } : {}) };\n }\n\n if (res.status === 409) {\n // The owned-re-pay gate: a payment for a post this wallet already bought is\n // refused, nothing charged. The caller falls back to a SIWX free re-read.\n return { kind: 'already_purchased', message: readMessage(res.json) ?? 'Already purchased.' };\n }\n\n if (res.status === 404) {\n throw new CliError('RESOURCE_NOT_FOUND', `No resource at ${url}`, {\n fix: 'Check the handle/slug or resource id.',\n });\n }\n\n // 429 on the paid-read path is a recoverable pause, not an outage: surface\n // RATE_LIMITED + retryAfterSeconds like postSearch/postOutcomes do, so a looping\n // agent (the caller most likely to hit this) can back off instead of treating it\n // as API_UNREACHABLE.\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n\n throw new CliError(\n 'API_UNREACHABLE',\n readMessage(res.json) ?? `Unexpected status ${res.status} from ${url}`,\n {\n fix: 'Retry; if it persists the resource may be unavailable.',\n details: res.json,\n },\n );\n}\n\n/** The server sent a `card` key but nothing survived the parse. Distinguishes a\n * DROPPED card from an absent one, which the `.catch` above otherwise makes\n * look identical. */\nfunction sentUnparsableCard(json: unknown, preview: Preview): boolean {\n if (typeof json !== 'object' || json === null) return false;\n return 'card' in json && preview.card === undefined;\n}\n\nfunction decodeSettlement(header: string | undefined): string | undefined {\n if (header === undefined) return undefined;\n try {\n const settle = decodePaymentResponseHeader(header);\n const tx = (settle as { transaction?: unknown }).transaction;\n return typeof tx === 'string' ? tx : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The server's machine `code` on an auth failure (`session_expired`, …), if any. */\nfunction readCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const code = (json as Record<string, unknown>).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nfunction readMessage(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const rec = json as Record<string, unknown>;\n if (typeof rec.message === 'string') return rec.message;\n if (typeof rec.error === 'string') return rec.error;\n if (typeof rec.code === 'string') return rec.code;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAM,0BAA0B;AAChC,IAAM,0BAA0B;AAQhC,IAAM,iBAAiB,iBACpB,OAAO;AAAA,EACN,IAAI,iBAAE,OAAO,EAAE,MAAM,SAAgB,4BAA4B;AAAA,EACjE,MAAM,iBAAE,OAAO,EAAE,MAAM,SAAS,aAAa,EAAE,IAAI,EAAE;AAAA,EACrD,OAAO,iBAAE,OAAO;AAAA,EAChB,QAAQ,iBAAE,OAAO;AAAA,EACjB,OAAO,iBAAE,OAAO;AAAA,EAChB,SAAS,iBACN,OAAO;AAAA,IACN,QAAQ,iBAAE,OAAO,EAAE,QAAQ;AAAA,IAC3B,eAAe,iBAAE,OAAO,EAAE,QAAQ;AAAA,EACpC,CAAC,EACA,YAAY;AACjB,CAAC,EACA,YAAY;AAaR,IAAM,oBAAoB,iBAC9B,OAAO;AAAA,EACN,cAAc,iBAAE,OAAO;AAAA,EACvB,cAAc,iBAAE,OAAO;AAAA,EACvB,MAAM,iBAAE,OAAO,EAAE,SAAS;AAAA,EAC1B,YAAY,iBAAE,OAAO,EAAE,SAAS;AAAA,EAChC,mBAAmB,iBAAE,MAAM,iBAAE,OAAO,CAAC;AAAA,EACrC,gBAAgB,iBAAE,MAAM,iBAAE,OAAO,CAAC;AAAA,EAClC,WAAW,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,MAAM,iBAAE,OAAO,CAAC,CAAC;AAAA,EACnD,OAAO,iBAAE,OAAO,EAAE,SAAS;AAAA,EAC3B,YAAY,iBAAE,OAAO,EAAE,SAAS;AAAA,EAChC,mBAAmB,iBAAE,OAAO,EAAE,SAAS;AAAA,EACvC,oBAAoB,iBAAE,OAAO,EAAE,SAAS;AAAA,EACxC,oBAAoB,iBAAE,OAAO,EAAE,SAAS;AAC1C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I,MAAM,SAAS,GAAG;AAAA,IACpE;AAAA,MACE,KAAK;AAAA,MACL,SAAS,IAAI;AAAA,IACf;AAAA,EACF;AACF;AAKA,SAAS,mBAAmB,MAAe,SAA2B;AACpE,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,SAAO,UAAU,QAAQ,QAAQ,SAAS;AAC5C;AAEA,SAAS,iBAAiB,QAAgD;AACxE,MAAI,WAAW,OAAW,QAAO;AACjC,MAAI;AACF,UAAM,SAAS,4BAA4B,MAAM;AACjD,UAAM,KAAM,OAAqC;AACjD,WAAO,OAAO,OAAO,WAAW,KAAK;AAAA,EACvC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,SAAS,SAAS,MAAmC;AACnD,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,OAAQ,KAAiC;AAC/C,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;AAEA,SAAS,YAAY,MAAmC;AACtD,MAAI,OAAO,SAAS,YAAY,SAAS,MAAM;AAC7C,UAAM,MAAM;AACZ,QAAI,OAAO,IAAI,YAAY,SAAU,QAAO,IAAI;AAChD,QAAI,OAAO,IAAI,UAAU,SAAU,QAAO,IAAI;AAC9C,QAAI,OAAO,IAAI,SAAS,SAAU,QAAO,IAAI;AAAA,EAC/C;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type { Provenance, ProjectPublishLayer, PublishMode } from './config';\nimport { parseUsdToAtomic } from './money';\nimport { parseConfirmPolicy, type SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /**\n * Hard per-send cap for `tenjin send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n return {\n baseUrl: s.baseUrl.value,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: BigInt(s.sessionBudget.value),\n confirm: parseConfirmPolicy(s.confirm.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const homeDir = deps.homeDir ?? homedir();\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n const candidate = join(dir, PROJECT_CONFIG_FILE);\n if (await pathExists(candidate)) {\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n return candidate;\n }\n }\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). Shared with the candidate command's\n * repo-root walk so the two `.git`/file probes stay one implementation. */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err === null),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,YAAY;AAC/B,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAmC9B,eAAsB,uBAAuB,KAAgD;AAC3F,QAAM,SAAS,MAAM,cAAc,IAAI,OAAO;AAC9C,QAAM,IAAI,gBAAgB,EAAE,QAAQ,OAAO,EAAE,SAAS,IAAI,MAAM,QAAQ,GAAG,KAAK,QAAQ,IAAI,CAAC;AAC7F,SAAO;AAAA,IACL,SAAS,EAAE,QAAQ;AAAA,IACnB,QAAQ,EAAE,OAAO;AAAA,IACjB,YAAY,EAAE,WAAW;AAAA,IACzB,qBACE,EAAE,cAAc,UAAU,iBACtB,iBACA,EAAE,cAAc,UAAU,SACxB,OACA,OAAO,EAAE,cAAc,KAAK;AAAA,IACpC,QAAQ;AAAA,MACN,oBAAoB,OAAO,EAAE,aAAa,KAAK;AAAA,MAC/C,qBAAqB,OAAO,EAAE,cAAc,KAAK;AAAA,MACjD,SAAS,mBAAmB,EAAE,QAAQ,KAAK;AAAA,MAC3C,mBAAmB,EAAE,kBAAkB;AAAA,IACzC;AAAA,EACF;AACF;AAaO,IAAM,sBAAsB;AAUnC,IAAM,sBAAsB,iBACzB,OAAO;AAAA,EACN,SAAS,iBACN,OAAO;AAAA,IACN,MAAM,kBAAkB,SAAS;AAAA,IACjC,cAAc,iBAAE,OAAO,EAAE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AC1B,QAAI,WAAW,IAAK,QAAO;AAC3B,UAAM;AAAA,EACR;AACF;AAOA,eAAe,sBAAsB,UAAoC;AACvE,QAAM,MAAM,QAAQ,SAAS;AAC7B,MAAI,QAAQ,OAAW,QAAO;AAC9B,MAAI;AACF,YAAQ,MAAM,KAAK,QAAQ,GAAG,QAAQ;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAIA,eAAsB,WAAW,MAAgC;AAC/D,MAAI;AACF,UAAM,KAAK,IAAI;AACf,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,oBAAoB,UAAoC;AAC/D,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B;AAAA,MACE;AAAA,MACA,CAAC,gBAAgB,WAAW,MAAM,QAAQ;AAAA,MAC1C,EAAE,KAAK,QAAQ,QAAQ,EAAE;AAAA,MACzB,CAAC,QAAQ,QAAQ,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":[]}
|
package/dist/chunk-PQZVDCCA.js
DELETED
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
latestSearch,
|
|
4
|
-
loadSearches,
|
|
5
|
-
markSearchResolved
|
|
6
|
-
} from "./chunk-7NADDA2V.js";
|
|
7
|
-
import {
|
|
8
|
-
buildOutcomeItem,
|
|
9
|
-
postOutcomes
|
|
10
|
-
} from "./chunk-FDUD3W5V.js";
|
|
11
|
-
import {
|
|
12
|
-
sanitizeForTerminal
|
|
13
|
-
} from "./chunk-B676GPS2.js";
|
|
14
|
-
import {
|
|
15
|
-
resolveContextSettings
|
|
16
|
-
} from "./chunk-PKW3H26Z.js";
|
|
17
|
-
import {
|
|
18
|
-
isPaidPrice
|
|
19
|
-
} from "./chunk-736DW4V3.js";
|
|
20
|
-
import {
|
|
21
|
-
CliError
|
|
22
|
-
} from "./chunk-PAOVPSP6.js";
|
|
23
|
-
|
|
24
|
-
// src/commands/outcome.ts
|
|
25
|
-
async function runOutcome(args, ctx, deps = {}) {
|
|
26
|
-
const target = await resolveTarget(args, ctx);
|
|
27
|
-
const item = buildOutcomeItem({
|
|
28
|
-
status: args.status,
|
|
29
|
-
...args.resource !== void 0 ? { resourceId: args.resource } : {},
|
|
30
|
-
...args.contentHash !== void 0 ? { contentHash: args.contentHash } : {}
|
|
31
|
-
});
|
|
32
|
-
if (target.stored !== null) assertOutcomeCoherent(item.status, target.stored, item.resourceId);
|
|
33
|
-
const { searchId } = target;
|
|
34
|
-
const question = target.stored !== null ? echoQuestion(target.stored.question) : void 0;
|
|
35
|
-
const settings = await resolveContextSettings(ctx);
|
|
36
|
-
const result = await postOutcomes(searchId, [item], {
|
|
37
|
-
baseUrl: settings.baseUrl,
|
|
38
|
-
timeoutMs: ctx.flags.timeout,
|
|
39
|
-
...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
|
|
40
|
-
});
|
|
41
|
-
await markSearchResolved(ctx.dataDir, searchId, "outcome");
|
|
42
|
-
return {
|
|
43
|
-
data: {
|
|
44
|
-
searchId,
|
|
45
|
-
status: item.status,
|
|
46
|
-
accepted: result.accepted,
|
|
47
|
-
...question !== void 0 ? { question } : {}
|
|
48
|
-
},
|
|
49
|
-
humanLines: [
|
|
50
|
-
`Reported ${item.status} for search ${searchId}${question !== void 0 ? ` "${sanitizeForTerminal(question)}"` : ""} (accepted ${result.accepted}).`
|
|
51
|
-
]
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
async function resolveTarget(args, ctx) {
|
|
55
|
-
if (args.searchId !== void 0 && args.last === true) {
|
|
56
|
-
throw new CliError("USAGE", "Pass either --search-id or --last, not both.", {
|
|
57
|
-
fix: "Use --search-id <id> for a specific search, or --last for the most recent."
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
if (args.searchId !== void 0) {
|
|
61
|
-
const searches = await loadSearches(ctx.dataDir);
|
|
62
|
-
return {
|
|
63
|
-
searchId: args.searchId,
|
|
64
|
-
stored: searches.find((s) => s.searchId === args.searchId) ?? null
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
if (args.last === true) {
|
|
68
|
-
const latest = await latestSearch(ctx.dataDir);
|
|
69
|
-
if (latest === null) {
|
|
70
|
-
throw new CliError("SEARCH_NOT_FOUND", "No local search to target with --last.", {
|
|
71
|
-
fix: "Run `tenjin search` first, or pass --search-id <id>."
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
return { searchId: latest.searchId, stored: latest };
|
|
75
|
-
}
|
|
76
|
-
throw new CliError("USAGE", "An outcome needs a search to report against.", {
|
|
77
|
-
fix: "Pass --search-id <id> or --last."
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
var QUESTION_ECHO_MAX = 80;
|
|
81
|
-
function echoQuestion(question) {
|
|
82
|
-
return question.length > QUESTION_ECHO_MAX ? `${question.slice(0, QUESTION_ECHO_MAX - 1)}\u2026` : question;
|
|
83
|
-
}
|
|
84
|
-
function assertOutcomeCoherent(status, stored, resourceId) {
|
|
85
|
-
const named = resourceId !== void 0 ? stored.candidates.find((c) => c.resourceId === resourceId) : void 0;
|
|
86
|
-
if (resourceId !== void 0 && named === void 0 && stored.decision === "CANDIDATES") {
|
|
87
|
-
throw new CliError(
|
|
88
|
-
"USAGE",
|
|
89
|
-
`Search ${stored.searchId} "${echoQuestion(stored.question)}" surfaced no candidate ${resourceId}, so an outcome naming it would not be recorded.`,
|
|
90
|
-
{
|
|
91
|
-
fix: "Pass a resourceId from this search, or drop --resource to report on the search as a whole."
|
|
92
|
-
}
|
|
93
|
-
);
|
|
94
|
-
}
|
|
95
|
-
if (status !== "purchase_declined") return;
|
|
96
|
-
if (named !== void 0) {
|
|
97
|
-
if (isPaidPrice(named.price) !== false) return;
|
|
98
|
-
throw new CliError(
|
|
99
|
-
"USAGE",
|
|
100
|
-
`Search ${stored.searchId} "${echoQuestion(stored.question)}" listed ${resourceId} at no cost, so purchase_declined cannot describe it.`,
|
|
101
|
-
{
|
|
102
|
-
fix: "A free piece is reported as used, partially_used, rejected or regenerated; pass the --resource you actually declined to buy."
|
|
103
|
-
}
|
|
104
|
-
);
|
|
105
|
-
}
|
|
106
|
-
if (offeredSomethingToBuy(stored) !== false) return;
|
|
107
|
-
throw new CliError(
|
|
108
|
-
"USAGE",
|
|
109
|
-
`Search ${stored.searchId} "${echoQuestion(stored.question)}" was a ${stored.decision} that offered nothing to buy, so purchase_declined cannot describe it.`,
|
|
110
|
-
{
|
|
111
|
-
fix: "Report used, partially_used, rejected or regenerated for this search, or pass --search-id <id> for the search you meant to report against."
|
|
112
|
-
}
|
|
113
|
-
);
|
|
114
|
-
}
|
|
115
|
-
function offeredSomethingToBuy(stored) {
|
|
116
|
-
if (stored.candidates.some((c) => isPaidPrice(c.price) === true)) return true;
|
|
117
|
-
if (stored.candidates.some((c) => isPaidPrice(c.price) === null)) return null;
|
|
118
|
-
if (stored.paidBrowseCount === void 0) return null;
|
|
119
|
-
return stored.paidBrowseCount > 0;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
export {
|
|
123
|
-
runOutcome
|
|
124
|
-
};
|
|
125
|
-
//# sourceMappingURL=chunk-PQZVDCCA.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/outcome.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildOutcomeItem, postOutcomes } from '../lib/agent-api';\nimport {\n latestSearch,\n loadSearches,\n markSearchResolved,\n type StoredSearch,\n} from '../lib/search-store';\nimport { isPaidPrice } from '../lib/money';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin outcome --search-id <id> --status <s>`, POST to\n * /api/searches/:id/outcomes, closing the reuse loop (used / partially_used\n * / rejected / regenerated / purchase_declined). The searchId is the capability,\n * so no wallet is needed; `--last` sugar targets the most recent DELIBERATE\n * search — entries the WebSearch hook rode along with are skipped, or every web\n * search in auto mode would silently re-aim the report (a hook entry is reached\n * by explicit --search-id, which is what the Stop hook's reminder names).\n *\n * `--last` binds to whatever search ran most recently, which in a multi-search\n * session is often not the one the agent means (issue #100). Two guards, both\n * local: the targeted search's question is echoed back in the success line and in\n * the machine data, so a misfire is visible in the same breath as the report; and\n * an outcome that could not describe that search, whether by its status or by\n * naming a resource the search never surfaced, is refused before the request.\n */\n\nexport interface OutcomeArgs {\n searchId?: string;\n last?: boolean;\n status: string;\n resource?: string;\n contentHash?: string;\n}\n\nexport interface OutcomeDeps {\n fetchImpl?: typeof fetch;\n}\n\nexport async function runOutcome(\n args: OutcomeArgs,\n ctx: CommandContext,\n deps: OutcomeDeps = {},\n): Promise<CommandResult> {\n const target = await resolveTarget(args, ctx);\n // Status name first, so an unknown status still fails as an unknown status\n // rather than as an incoherent one.\n const item = buildOutcomeItem({\n status: args.status,\n ...(args.resource !== undefined ? { resourceId: args.resource } : {}),\n ...(args.contentHash !== undefined ? { contentHash: args.contentHash } : {}),\n });\n if (target.stored !== null) assertOutcomeCoherent(item.status, target.stored, item.resourceId);\n const { searchId } = target;\n const question = target.stored !== null ? echoQuestion(target.stored.question) : undefined;\n\n const settings = await resolveContextSettings(ctx);\n const result = await postOutcomes(searchId, [item], {\n baseUrl: settings.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n // The loop is closed, so the Stop hook has nothing left to raise about it.\n // AFTER the post, so a refused or failed report leaves the loop open. Local\n // bookkeeping only, and it never throws: see markSearchResolved.\n await markSearchResolved(ctx.dataDir, searchId, 'outcome');\n\n // The question rides both renderings, so the misfire this guards against is\n // visible whether a human is reading the line or an agent is reading the JSON.\n // Sanitized on the human line only: the envelope is machine data and keeps the\n // bytes it was given (see output.ts).\n return {\n data: {\n searchId,\n status: item.status,\n accepted: result.accepted,\n ...(question !== undefined ? { question } : {}),\n },\n humanLines: [\n `Reported ${item.status} for search ${searchId}${\n question !== undefined ? ` \"${sanitizeForTerminal(question)}\"` : ''\n } (accepted ${result.accepted}).`,\n ],\n };\n}\n\n/** The search this report will land on, plus the local record of it when there is\n * one. `stored` is null for a `--search-id` from another machine or an evicted\n * entry: unknown, so neither echoed nor checked. */\ninterface OutcomeTarget {\n searchId: string;\n stored: StoredSearch | null;\n}\n\nasync function resolveTarget(args: OutcomeArgs, ctx: CommandContext): Promise<OutcomeTarget> {\n if (args.searchId !== undefined && args.last === true) {\n throw new CliError('USAGE', 'Pass either --search-id or --last, not both.', {\n fix: 'Use --search-id <id> for a specific search, or --last for the most recent.',\n });\n }\n if (args.searchId !== undefined) {\n const searches = await loadSearches(ctx.dataDir);\n return {\n searchId: args.searchId,\n stored: searches.find((s) => s.searchId === args.searchId) ?? null,\n };\n }\n if (args.last === true) {\n const latest = await latestSearch(ctx.dataDir);\n if (latest === null) {\n throw new CliError('SEARCH_NOT_FOUND', 'No local search to target with --last.', {\n fix: 'Run `tenjin search` first, or pass --search-id <id>.',\n });\n }\n return { searchId: latest.searchId, stored: latest };\n }\n throw new CliError('USAGE', 'An outcome needs a search to report against.', {\n fix: 'Pass --search-id <id> or --last.',\n });\n}\n\n/** Long enough to tell two searches apart on one line, short enough not to bury\n * the searchId next to it. The ellipsis is part of the echo: a question cut with\n * no marker reads as a shorter question that was never asked. */\nconst QUESTION_ECHO_MAX = 80;\n\nfunction echoQuestion(question: string): string {\n return question.length > QUESTION_ECHO_MAX\n ? `${question.slice(0, QUESTION_ECHO_MAX - 1)}…`\n : question;\n}\n\n/**\n * Refuse an outcome that could not describe the search it is aimed at. Two\n * independent checks, because they answer to different rules.\n *\n * MEMBERSHIP, for any status that names a `--resource`: the id has to be one this\n * search surfaced. On a CANDIDATES decision that is provable, since browse\n * pointers are MISS-only by contract AND truncateResponse deletes the array\n * outright on CANDIDATES rather than trust the server, so `candidates` is the\n * entire payable set the agent was shown and `search` records all of it. A uuid\n * outside it is a typo or another search's, and the server drops the item behind\n * its 202 (tenjin#641) whatever the status says, leaving the CLI to report\n * success for an outcome nobody stored. A MISS keeps the fail-open: its browse\n * tail is payable and deliberately unrecorded, so an absent id there is\n * unknowable rather than wrong. So does any other decision value.\n *\n * PAYABILITY, for `purchase_declined` alone. The status matrix is deliberately\n * one-sided: four of the five describe ANY search, so only this one has a\n * precondition.\n *\n * used, partially_used always. A MISS's browse tail is readable, and a free\n * piece is used without any purchase, so \"used\" on a\n * MISS, or on a free candidate, is a real report and not\n * a mistake (issue #100).\n * rejected, regenerated always. \"Nothing here helped, I wrote it myself\" is\n * exactly what a MISS deserves to record.\n * purchase_declined needs the search to have offered something to buy, or,\n * when `--resource` names a candidate the store knows,\n * needs THAT candidate to have cost money. Declining a\n * purchase nobody offered cannot have happened, and that\n * is the shape the dogfooding misfire took: a\n * purchase_declined aimed at a bare MISS.\n *\n * Local knowledge only, and fail-open by construction: an unknown is never a\n * refusal. The server owns the checks this cannot make.\n */\nfunction assertOutcomeCoherent(status: string, stored: StoredSearch, resourceId?: string): void {\n const named =\n resourceId !== undefined\n ? stored.candidates.find((c) => c.resourceId === resourceId)\n : undefined;\n\n if (resourceId !== undefined && named === undefined && stored.decision === 'CANDIDATES') {\n throw new CliError(\n 'USAGE',\n `Search ${stored.searchId} \"${echoQuestion(stored.question)}\" surfaced no candidate ${resourceId}, so an outcome naming it would not be recorded.`,\n {\n fix: 'Pass a resourceId from this search, or drop --resource to report on the search as a whole.',\n },\n );\n }\n\n if (status !== 'purchase_declined') return;\n\n // A named candidate the store knows answers for itself. A piece that was free\n // is not made purchasable by a paid sibling in the same result, so the specific\n // claim is checked against the specific price rather than the search's total.\n if (named !== undefined) {\n if (isPaidPrice(named.price) !== false) return;\n throw new CliError(\n 'USAGE',\n `Search ${stored.searchId} \"${echoQuestion(stored.question)}\" listed ${resourceId} at no cost, so purchase_declined cannot describe it.`,\n {\n fix: 'A free piece is reported as used, partially_used, rejected or regenerated; pass the --resource you actually declined to buy.',\n },\n );\n }\n\n if (offeredSomethingToBuy(stored) !== false) return;\n throw new CliError(\n 'USAGE',\n `Search ${stored.searchId} \"${echoQuestion(stored.question)}\" was a ${stored.decision} that offered nothing to buy, so purchase_declined cannot describe it.`,\n {\n fix: 'Report used, partially_used, rejected or regenerated for this search, or pass --search-id <id> for the search you meant to report against.',\n },\n );\n}\n\n/**\n * Whether the search put anything payable in front of the agent. Priced at zero\n * does not count: `read` delivers a free piece with no payment, so a result that\n * was free end to end offered no purchase to decline, however many rows it had.\n * Null when the stored entry cannot say: it predates `paidBrowseCount`, so an\n * all-free candidate list might still have sat above a payable browse tail.\n */\nfunction offeredSomethingToBuy(stored: StoredSearch): boolean | null {\n if (stored.candidates.some((c) => isPaidPrice(c.price) === true)) return true;\n // A price the store cannot parse is not evidence that the result was free.\n if (stored.candidates.some((c) => isPaidPrice(c.price) === null)) return null;\n if (stored.paidBrowseCount === undefined) return null;\n return stored.paidBrowseCount > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0CA,eAAsB,WACpB,MACA,KACA,OAAoB,CAAC,GACG;AACxB,QAAM,SAAS,MAAM,cAAc,MAAM,GAAG;AAG5C,QAAM,OAAO,iBAAiB;AAAA,IAC5B,QAAQ,KAAK;AAAA,IACb,GAAI,KAAK,aAAa,SAAY,EAAE,YAAY,KAAK,SAAS,IAAI,CAAC;AAAA,IACnE,GAAI,KAAK,gBAAgB,SAAY,EAAE,aAAa,KAAK,YAAY,IAAI,CAAC;AAAA,EAC5E,CAAC;AACD,MAAI,OAAO,WAAW,KAAM,uBAAsB,KAAK,QAAQ,OAAO,QAAQ,KAAK,UAAU;AAC7F,QAAM,EAAE,SAAS,IAAI;AACrB,QAAM,WAAW,OAAO,WAAW,OAAO,aAAa,OAAO,OAAO,QAAQ,IAAI;AAEjF,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,SAAS,MAAM,aAAa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+0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/skills-source.ts","../src/lib/skill-wiring.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * The packaged skills `install` copies into every target harness. All three go to\n * every target: `tenjin` (the zero-install curriculum, works with no CLI),\n * `tenjin-search` and `tenjin-publish` (thin CLI adapters). Order is the install\n * order and the human-render order.\n */\nexport const SKILL_NAMES = ['tenjin-search', 'tenjin-publish', 'tenjin'] as const;\nexport type SkillName = (typeof SKILL_NAMES)[number];\n\n/**\n * Every file a packaged skill ships, per skill, as a path relative to the skill\n * directory.\n *\n * DECLARED rather than discovered, because `uninstall` needs it on a machine\n * where the packaged source may be gone or unreadable, and \"remove exactly the\n * files this package wrote\" is not a question it can answer by listing the\n * operator's directory — everything else in there is theirs. `install` still\n * copies the real tree; a test pins this list against it, so a new reference\n * file that nobody declares fails the build rather than becoming litter no\n * uninstall can reclaim.\n */\nexport const SHIPPED_SKILL_FILES: Record<SkillName, readonly string[]> = {\n 'tenjin-search': ['SKILL.md', 'references/permissions.md'],\n 'tenjin-publish': ['SKILL.md', 'references/maintain.md'],\n tenjin: ['SKILL.md'],\n};\n\n// A `skills/` directory is the real one iff it holds `tenjin/SKILL.md`; a bare\n// `skills/` created for some other reason up the tree can't false-positive.\nconst SENTINEL = join('tenjin', 'SKILL.md');\n\n/**\n * Locate the packaged `skills/` directory by walking up from `startDir`. This has\n * to work in two layouts from one resolver: a global npm install where the module\n * lives in `dist/` with `skills/` a sibling (the `files` array ships it), and a\n * repo/source run where the module is under `src/` and `skills/` sits at the repo\n * root. Walking up until a `skills/` with the sentinel appears covers both without\n * hard-coding either depth. Sync (existsSync) on purpose: this is one-shot path\n * resolution at command start, the same shape as `require.resolve`.\n */\nexport function resolveSkillsSource(startDir: string): string {\n let dir = startDir;\n for (let i = 0; i < 8; i += 1) {\n const candidate = join(dir, 'skills');\n if (existsSync(join(candidate, SENTINEL))) return candidate;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n throw new CliError('INTERNAL', 'Could not locate the packaged Tenjin skills directory', {\n fix: 'Reinstall tenjin-cli; the published package must ship the skills/ directory (files array).',\n details: { startDir },\n });\n}\n","import { existsSync, statSync } from 'node:fs';\nimport { constants, open } from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport { hasCode } from './errno';\nimport { delimiter, join } from 'node:path';\nimport { SKILL_NAMES } from './skills-source';\nimport type { SkillName } from './skills-source';\n\n/**\n * CLI_SKILL_NAMES are the thin adapter skills (roadmap C1), both required for the\n * CLI to be usable from a harness; HOSTED_SKILL_NAME is the zero-install\n * curriculum mirror (roadmap G4), typed as their complement so a rename in\n * skills-source.ts is a compile error here rather than a silently-always-false\n * `cliSkillsWired`.\n */\nexport const CLI_SKILL_NAMES = [\n 'tenjin-search',\n 'tenjin-publish',\n] as const satisfies readonly SkillName[];\nexport type CliSkillName = (typeof CLI_SKILL_NAMES)[number];\nexport type HostedSkillName = Exclude<SkillName, CliSkillName>;\nexport const HOSTED_SKILL_NAME: HostedSkillName = 'tenjin';\n\nexport type NotInvocableReason = 'disabled' | 'unreadable';\n\nexport interface SkillWiring {\n name: string;\n present: boolean;\n /** Undefined when absent. False means on disk yet never surfaced to the model. */\n modelInvocable?: boolean;\n reason?: NotInvocableReason;\n}\n\n/**\n * One directory's verdict. `shadowed` and `partial` are actionable; `hosted-only`\n * is a working zero-install machine, not a defect; `empty` is not a Tenjin dir.\n */\nexport type DirState = 'empty' | 'hosted-only' | 'partial' | 'shadowed' | 'wired';\n\nexport interface HarnessWiring {\n dir: string;\n exists: boolean;\n skills: SkillWiring[];\n state: DirState;\n}\n\nexport function skillsDirsFor(home: string): string[] {\n return [join(home, '.claude', 'skills'), join(home, '.agents', 'skills')];\n}\n\n/**\n * Every value `install --harness` accepts: the two detectable harnesses plus the\n * `shared` fallback. It lives beside the detection probes because `doctor` has to map\n * a PERSISTED choice back to a directory using the same rules `install` targeted it\n * with, and a second copy of that mapping is exactly the drift this module exists to\n * prevent.\n */\nexport const HARNESS_TARGETS = ['claude', 'codex', 'shared'] as const;\nexport type HarnessTarget = (typeof HARNESS_TARGETS)[number];\n\n/** The skills directory a target writes to. `codex` and `shared` share ~/.agents/skills. */\nexport function harnessTargetDir(home: string, harness: HarnessTarget): string {\n return harness === 'claude' ? join(home, '.claude', 'skills') : join(home, '.agents', 'skills');\n}\n\n/**\n * The `--harness` value that targets `dir`. A Claude-only machine never targets\n * ~/.agents/skills by default, so a bare `tenjin install` cannot clear a problem\n * found there.\n */\nexport function harnessFlagFor(home: string, dir: string): string {\n return dir === join(home, '.claude', 'skills') ? 'claude' : 'shared';\n}\n\n/** The harnesses `install` probes for. `shared` is a fallback target, never detected. */\nexport type DetectableHarness = Exclude<HarnessTarget, 'shared'>;\n\n/**\n * Why we think `harness` is on this machine: its home dir (~/.claude, ~/.codex) and\n * its binary on PATH. Single-sourced so `install` picks its targets and `doctor`\n * decides which directories MUST be wired from the same two probes — a directory no\n * harness here reads is a leftover, not a defect.\n */\nexport function harnessDetectedBy(\n home: string,\n harness: DetectableHarness,\n which: (bin: string) => boolean,\n): string[] {\n const reasons: string[] = [];\n if (existsSync(join(home, `.${harness}`))) reasons.push('home-dir');\n if (which(harness)) reasons.push('binary');\n return reasons;\n}\n\nexport interface HarnessPresence {\n claude: boolean;\n codex: boolean;\n}\n\nexport function detectHarnesses(home: string, which: (bin: string) => boolean): HarnessPresence {\n return {\n claude: harnessDetectedBy(home, 'claude', which).length > 0,\n codex: harnessDetectedBy(home, 'codex', which).length > 0,\n };\n}\n\n/**\n * Does a harness ON THIS MACHINE read `dir`? Claude Code reads ~/.claude/skills and\n * Codex reads ~/.agents/skills, so a wired .agents does NOT make Claude Code wired:\n * the question has to be asked per directory. When neither harness is detected the\n * shared directory is still in play, because that is the fallback target `install`\n * writes to, so a half-written fallback install is still reported.\n */\nexport function harnessReads(home: string, dir: string, present: HarnessPresence): boolean {\n return harnessFlagFor(home, dir) === 'claude' ? present.claude : present.codex || !present.claude;\n}\n\n/**\n * Did a past `tenjin install --harness ...` name `dir` on purpose? Detection only sees\n * the harnesses this CLI probes for, and ~/.agents/skills is the cross-harness Agent\n * Skills convention, so \"no Codex here\" is not \"nothing reads it\". `requested` is the\n * user's own answer to that question and outranks the probes.\n */\nexport function harnessRequested(\n home: string,\n dir: string,\n requested: readonly HarnessTarget[],\n): boolean {\n return requested.some((h) => harnessTargetDir(home, h) === dir);\n}\n\n/**\n * Is `dir` this machine's business at all: read by a detected harness, or explicitly\n * requested. The union is kept separate from `harnessReads` so the reported\n * `harnessPresent` stays a detection fact and does not quietly absorb a config value.\n */\nexport function harnessInPlay(\n home: string,\n dir: string,\n present: HarnessPresence,\n requested: readonly HarnessTarget[],\n): boolean {\n return harnessReads(home, dir, present) || harnessRequested(home, dir, requested);\n}\n\n/**\n * Is `bin` a real executable file on PATH? Gates on statSync().isFile() so a\n * same-named DIRECTORY on PATH never false-positives as the binary, and probes the\n * PATHEXT extensions on win32 where the real binary is `claude.cmd`/`claude.exe`\n * rather than a bare `claude`.\n */\nexport function onPath(bin: string, env: NodeJS.ProcessEnv): boolean {\n const raw = env.PATH ?? '';\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of raw.split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (isFile(join(part, bin + ext))) return true;\n }\n }\n return false;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\nexport async function readHarnessWiring(dir: string): Promise<HarnessWiring> {\n const exists = existsSync(dir);\n const skills: SkillWiring[] = [];\n for (const name of SKILL_NAMES) skills.push(await readSkillWiring(dir, name));\n return { dir, exists, skills, state: classify(skills) };\n}\n\nexport async function readAllWiring(home: string): Promise<HarnessWiring[]> {\n const out: HarnessWiring[] = [];\n for (const dir of skillsDirsFor(home)) out.push(await readHarnessWiring(dir));\n return out;\n}\n\nfunction classify(skills: SkillWiring[]): DirState {\n const cli = CLI_SKILL_NAMES.map((n) => skills.find((s) => s.name === n)).filter(\n (s) => s?.present === true,\n );\n if (cli.length === 0) return skills.some((s) => s.present) ? 'hosted-only' : 'empty';\n if (cli.some((s) => s?.modelInvocable === false)) return 'shadowed';\n return cli.length === CLI_SKILL_NAMES.length ? 'wired' : 'partial';\n}\n\n/**\n * What reading a SKILL.md found. A skill path is operator-controlled, so it is not\n * necessarily a file at all.\n */\nexport type SkillFileRead =\n | { kind: 'ok'; bytes: Buffer }\n | { kind: 'absent' }\n | { kind: 'not-regular' }\n | { kind: 'unreadable'; err: unknown };\n\n/**\n * Read a SKILL.md through ONE descriptor, and only when it is a regular file.\n *\n * `readFile` on a FIFO blocks until a writer appears, and on a character device it\n * streams without end; neither call fails, so no error handling reaches them. A\n * pipe at a wired SKILL.md path hung `tenjin doctor` and `tenjin install` past\n * SIGTERM. Opening non-blocking returns immediately whatever the node type is,\n * `fstat` on that descriptor says what it actually is, and only a regular file is\n * read. Checking the pathname and then reading the pathname would let the two\n * answer about different files.\n *\n * O_NONBLOCK does not exist on Windows, where it degrades to 0; FIFOs are not a\n * meaningful case there.\n */\nexport async function readSkillFile(path: string): Promise<SkillFileRead> {\n let handle: FileHandle;\n try {\n handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', err };\n }\n try {\n if (!(await handle.stat()).isFile()) return { kind: 'not-regular' };\n return { kind: 'ok', bytes: await handle.readFile() };\n } catch (err) {\n return { kind: 'unreadable', err };\n } finally {\n await handle.close().catch(() => undefined);\n }\n}\n\nasync function readSkillWiring(dir: string, name: string): Promise<SkillWiring> {\n const read = await readSkillFile(join(dir, name, 'SKILL.md'));\n if (read.kind === 'absent') return { name, present: false };\n // A pipe or a device is there, but it is not a skill and must never be read as\n // one; `unreadable` is the state that already describes \"present, unusable\".\n if (read.kind !== 'ok')\n return { name, present: true, modelInvocable: false, reason: 'unreadable' };\n const text = read.bytes.toString('utf8');\n if (isModelInvocationDisabled(text)) {\n return { name, present: true, modelInvocable: false, reason: 'disabled' };\n }\n return { name, present: true, modelInvocable: true };\n}\n\n/** YAML 1.1 truthy spellings a harness frontmatter parser may accept. */\nconst YAML_TRUE = /^(?:true|yes|on)$/i;\n\n/**\n * Deliberately not a general YAML parse: only the leading `---` block is read,\n * because this repo's own skills discuss the key in prose and a whole-file match\n * would call a working skill disabled.\n */\nexport function isModelInvocationDisabled(skillMd: string): boolean {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return false;\n return frontmatter.some((line) => {\n const m = /^disable-model-invocation:\\s*(.+?)\\s*$/.exec(line.trim());\n if (m === null) return false;\n // Strip an inline `# comment` and optional quotes before testing truthiness.\n const value = (m[1] ?? '').replace(/\\s+#.*$/, '').replace(/^[\"']|[\"']$/g, '');\n return YAML_TRUE.test(value);\n });\n}\n\n/**\n * The `name:` a SKILL.md declares in its leading frontmatter, or null when it\n * declares none. It is what a harness registers the skill AS, so it is also the\n * cheapest evidence that a file at one of our paths is one of ours: the\n * unattended self-heal refuses to overwrite a same-named third-party skill.\n */\nexport function skillFrontmatterName(skillMd: string): string | null {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return null;\n for (const line of frontmatter) {\n const m = /^name:\\s*(.+?)\\s*$/.exec(line);\n if (m !== null) return (m[1] ?? '').replace(/^[\"']|[\"']$/g, '');\n }\n return null;\n}\n\nfunction extractFrontmatter(text: string): string[] | null {\n // Tolerate a UTF-8 BOM, CRLF, and leading blank lines before the opening fence.\n const lines = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const open = lines.findIndex((l) => l.trim().length > 0);\n if (open === -1 || lines[open]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > open && l.trim() === '---');\n if (end === -1) return null;\n return lines.slice(open + 1, end);\n}\n\nexport function cliSkillsWired(wiring: HarnessWiring): boolean {\n return wiring.state === 'wired';\n}\n\nexport function missingCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter(\n (name) => wiring.skills.find((x) => x.name === name)?.present !== true,\n );\n}\n\nexport function shadowedCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter((name) => {\n const s = wiring.skills.find((x) => x.name === name);\n return s?.present === true && s.modelInvocable === false;\n });\n}\n\nexport function anyTenjinSkill(wiring: HarnessWiring): boolean {\n return wiring.state !== 'empty';\n}\n"],"mappings":";;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,SAAS,YAAY;AASvB,IAAM,cAAc,CAAC,iBAAiB,kBAAkB,QAAQ;AAehE,IAAM,sBAA4D;AAAA,EACvE,iBAAiB,CAAC,YAAY,2BAA2B;AAAA,EACzD,kBAAkB,CAAC,YAAY,wBAAwB;AAAA,EACvD,QAAQ,CAAC,UAAU;AACrB;AAIA,IAAM,WAAW,KAAK,UAAU,UAAU;AAWnC,SAAS,oBAAoB,UAA0B;AAC5D,MAAI,MAAM;AACV,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG;AAC7B,UAAM,YAAY,KAAK,KAAK,QAAQ;AACpC,QAAI,WAAW,KAAK,WAAW,QAAQ,CAAC,EAAG,QAAO;AAClD,UAAM,SAAS,QAAQ,GAAG;AAC1B,QAAI,WAAW,IAAK;AACpB,UAAM;AAAA,EACR;AACA,QAAM,IAAI,SAAS,YAAY,yDAAyD;AAAA,IACtF,KAAK;AAAA,IACL,SAAS,EAAE,SAAS;AAAA,EACtB,CAAC;AACH;;;ACzDA,SAAS,cAAAA,aAAY,gBAAgB;AACrC,SAAS,WAAW,YAAY;AAGhC,SAAS,WAAW,QAAAC,aAAY;AAWzB,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AACF;AAGO,IAAM,oBAAqC;AAyB3C,SAAS,cAAc,MAAwB;AACpD,SAAO,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
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
|
|
3
|
-
// src/lib/markdown.ts
|
|
4
|
-
function headingOutline(bodyMd) {
|
|
5
|
-
const headings = [];
|
|
6
|
-
let inFence = false;
|
|
7
|
-
for (const line of bodyMd.split(/\r?\n/)) {
|
|
8
|
-
if (/^\s*(```|~~~)/.test(line)) {
|
|
9
|
-
inFence = !inFence;
|
|
10
|
-
continue;
|
|
11
|
-
}
|
|
12
|
-
if (inFence) continue;
|
|
13
|
-
const m = /^(#{1,6})\s+(.*\S)\s*$/.exec(line);
|
|
14
|
-
if (m && m[1] !== void 0 && m[2] !== void 0) {
|
|
15
|
-
headings.push({ level: m[1].length, text: m[2] });
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
return headings;
|
|
19
|
-
}
|
|
20
|
-
function estimateTokens(text) {
|
|
21
|
-
const words = text.split(/\s+/).filter((w) => w.length > 0).length;
|
|
22
|
-
return Math.ceil(words * 1.33);
|
|
23
|
-
}
|
|
24
|
-
function splitSections(bodyMd) {
|
|
25
|
-
const sections = [];
|
|
26
|
-
let heading = null;
|
|
27
|
-
let level = 0;
|
|
28
|
-
let lines = [];
|
|
29
|
-
let inFence = false;
|
|
30
|
-
const push = () => {
|
|
31
|
-
const body = lines.join("\n").trim();
|
|
32
|
-
if (heading === null && body.length === 0) return;
|
|
33
|
-
sections.push({ heading, level, body, estimatedTokens: estimateTokens(body) });
|
|
34
|
-
};
|
|
35
|
-
for (const line of bodyMd.split(/\r?\n/)) {
|
|
36
|
-
if (/^\s*(```|~~~)/.test(line)) inFence = !inFence;
|
|
37
|
-
const m = inFence ? null : /^(#{1,6})\s+(.*\S)\s*$/.exec(line);
|
|
38
|
-
if (m && m[1] !== void 0 && m[2] !== void 0) {
|
|
39
|
-
push();
|
|
40
|
-
heading = m[2].trim();
|
|
41
|
-
level = m[1].length;
|
|
42
|
-
lines = [];
|
|
43
|
-
} else {
|
|
44
|
-
lines.push(line);
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
push();
|
|
48
|
-
return sections;
|
|
49
|
-
}
|
|
50
|
-
function selectSections(sections, budgetTokens) {
|
|
51
|
-
const selected = [];
|
|
52
|
-
let spent = 0;
|
|
53
|
-
for (const section of sections) {
|
|
54
|
-
if (selected.length > 0 && spent + section.estimatedTokens > budgetTokens) break;
|
|
55
|
-
selected.push(section);
|
|
56
|
-
spent += section.estimatedTokens;
|
|
57
|
-
if (spent >= budgetTokens) break;
|
|
58
|
-
}
|
|
59
|
-
return selected;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export {
|
|
63
|
-
headingOutline,
|
|
64
|
-
splitSections,
|
|
65
|
-
selectSections
|
|
66
|
-
};
|
|
67
|
-
//# sourceMappingURL=chunk-SGK2B724.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/markdown.ts"],"sourcesContent":["/**\n * Deterministic markdown structure helpers for delivery output: the heading\n * outline that replaces the body on stdout, and the `--sections` budgeted\n * selection. No model calls, no scoring; identical input always yields\n * identical output. Split from library.ts so filesystem delivery and text\n * shaping stay separate concerns.\n */\n\nexport interface Heading {\n level: number;\n text: string;\n}\n\n/**\n * Deterministic ATX-heading outline for the stdout summary, never the body, so\n * agent transcripts stay small (spec 10). Skips fenced code blocks so a `#`\n * comment inside a code sample is not mistaken for a heading.\n */\nexport function headingOutline(bodyMd: string): Heading[] {\n const headings: Heading[] = [];\n let inFence = false;\n for (const line of bodyMd.split(/\\r?\\n/)) {\n if (/^\\s*(```|~~~)/.test(line)) {\n inFence = !inFence;\n continue;\n }\n if (inFence) continue;\n const m = /^(#{1,6})\\s+(.*\\S)\\s*$/.exec(line);\n if (m && m[1] !== undefined && m[2] !== undefined) {\n headings.push({ level: m[1].length, text: m[2] });\n }\n }\n return headings;\n}\n\nexport interface MarkdownSection {\n /** Heading text without the leading #s; null for preamble before any heading. */\n heading: string | null;\n level: number;\n body: string;\n estimatedTokens: number;\n}\n\n/** The server's own heuristic: ceil(words x 1.33). A display hint, never a boundary. */\nexport function estimateTokens(text: string): number {\n const words = text.split(/\\s+/).filter((w) => w.length > 0).length;\n return Math.ceil(words * 1.33);\n}\n\n/**\n * Deterministic heading-split of the body for `--sections` delivery: no model\n * calls, no scoring; the same input always splits identically. Fenced code\n * blocks are ignored for heading detection, like headingOutline.\n */\nexport function splitSections(bodyMd: string): MarkdownSection[] {\n const sections: MarkdownSection[] = [];\n let heading: string | null = null;\n let level = 0;\n let lines: string[] = [];\n let inFence = false;\n\n const push = (): void => {\n const body = lines.join('\\n').trim();\n if (heading === null && body.length === 0) return;\n sections.push({ heading, level, body, estimatedTokens: estimateTokens(body) });\n };\n\n for (const line of bodyMd.split(/\\r?\\n/)) {\n if (/^\\s*(```|~~~)/.test(line)) inFence = !inFence;\n const m = inFence ? null : /^(#{1,6})\\s+(.*\\S)\\s*$/.exec(line);\n if (m && m[1] !== undefined && m[2] !== undefined) {\n push();\n heading = m[2].trim();\n level = m[1].length;\n lines = [];\n } else {\n lines.push(line);\n }\n }\n push();\n return sections;\n}\n\n/**\n * Sections in document order until the budget is spent. The first section always\n * ships even when it alone exceeds the budget, so a tiny budget still returns\n * something rather than an empty selection.\n */\nexport function selectSections(\n sections: MarkdownSection[],\n budgetTokens: number,\n): MarkdownSection[] {\n const selected: MarkdownSection[] = [];\n let spent = 0;\n for (const section of sections) {\n if (selected.length > 0 && spent + section.estimatedTokens > budgetTokens) break;\n selected.push(section);\n spent += section.estimatedTokens;\n if (spent >= budgetTokens) break;\n }\n return selected;\n}\n"],"mappings":";;;AAkBO,SAAS,eAAe,QAA2B;AACxD,QAAM,WAAsB,CAAC;AAC7B,MAAI,UAAU;AACd,aAAW,QAAQ,OAAO,MAAM,OAAO,GAAG;AACxC,QAAI,gBAAgB,KAAK,IAAI,GAAG;AAC9B,gBAAU,CAAC;AACX;AAAA,IACF;AACA,QAAI,QAAS;AACb,UAAM,I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