tenjin-cli 0.1.0-alpha.30 → 0.1.0-alpha.31
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 +65 -116
- package/dist/{_esm-CE7KNONL.js → _esm-MEXZI5DL.js} +4 -4
- package/dist/{alive-3J3CHOQP.js → alive-J64H46HI.js} +14 -4
- package/dist/{chunk-O2FRQ2L2.js → chunk-27EPWVOY.js} +4 -64
- package/dist/chunk-27EPWVOY.js.map +1 -0
- package/dist/{chunk-OSYTBCUC.js → chunk-2XLC3AEX.js} +16 -14
- package/dist/{chunk-OSYTBCUC.js.map → chunk-2XLC3AEX.js.map} +1 -1
- package/dist/chunk-3623BLPV.js +184 -0
- package/dist/chunk-3623BLPV.js.map +1 -0
- package/dist/chunk-3UCIG4TG.js +65 -0
- package/dist/chunk-3UCIG4TG.js.map +1 -0
- package/dist/{chunk-PAYV4XUA.js → chunk-4ZZO6ULA.js} +2 -2
- package/dist/{chunk-VUFAK2LW.js → chunk-5C32RLTA.js} +2 -2
- package/dist/{chunk-VUFAK2LW.js.map → chunk-5C32RLTA.js.map} +1 -1
- package/dist/{chunk-YHKXNYTB.js → chunk-5K5W4S66.js} +2 -2
- package/dist/{chunk-3O2BQIF6.js → chunk-5MARFNSB.js} +273 -482
- package/dist/chunk-5MARFNSB.js.map +1 -0
- package/dist/{chunk-HPWO4O6S.js → chunk-6E5R45ZO.js} +2 -2
- package/dist/{chunk-JMM6YE7J.js → chunk-77TCKDEC.js} +125 -312
- package/dist/chunk-77TCKDEC.js.map +1 -0
- package/dist/{chunk-LFZJM56J.js → chunk-7Q5FDF65.js} +2 -2
- package/dist/chunk-7WEQQJLG.js +68 -0
- package/dist/chunk-7WEQQJLG.js.map +1 -0
- package/dist/{chunk-AWFUPKTM.js → chunk-7WU4OPLP.js} +12 -6
- package/dist/{chunk-AWFUPKTM.js.map → chunk-7WU4OPLP.js.map} +1 -1
- package/dist/{chunk-AEG2PXBP.js → chunk-7ZRL2LBQ.js} +3 -3
- package/dist/{chunk-IOODYAXL.js → chunk-AGZ7PJKY.js} +6 -4
- package/dist/{chunk-IOODYAXL.js.map → chunk-AGZ7PJKY.js.map} +1 -1
- package/dist/{chunk-VFMQTSXG.js → chunk-B7HUUJOK.js} +3 -3
- package/dist/{chunk-EL56RW2J.js → chunk-BL3332HQ.js} +7 -7
- package/dist/{chunk-5LJCEMFD.js → chunk-D65GNPS3.js} +35 -27
- package/dist/{chunk-5LJCEMFD.js.map → chunk-D65GNPS3.js.map} +1 -1
- package/dist/{chunk-P7LABKCW.js → chunk-DOQGNFHM.js} +33 -2
- package/dist/{chunk-P7LABKCW.js.map → chunk-DOQGNFHM.js.map} +1 -1
- package/dist/{chunk-OK2TDZQU.js → chunk-FW75G2W4.js} +7 -5
- package/dist/chunk-FW75G2W4.js.map +1 -0
- package/dist/chunk-GA7JETVM.js +150 -0
- package/dist/chunk-GA7JETVM.js.map +1 -0
- package/dist/{chunk-6W5GYG3W.js → chunk-I3EQFHCD.js} +48 -1
- package/dist/chunk-I3EQFHCD.js.map +1 -0
- package/dist/{chunk-EBVIKMCH.js → chunk-JKKAIPTU.js} +2 -2
- package/dist/{chunk-N35E6CM2.js → chunk-K3I7C2MO.js} +6 -6
- package/dist/{chunk-KYFZTGMC.js → chunk-K72RURN3.js} +5 -3
- package/dist/{chunk-KYFZTGMC.js.map → chunk-K72RURN3.js.map} +1 -1
- package/dist/{chunk-RAULEAZ6.js → chunk-KXQ4UIP7.js} +3 -3
- package/dist/{chunk-VZGAONSJ.js → chunk-KXVP2VKA.js} +5 -5
- package/dist/chunk-LEFIX6RS.js +100 -0
- package/dist/chunk-LEFIX6RS.js.map +1 -0
- package/dist/{chunk-TTBKWWTV.js → chunk-MNXS2U45.js} +246 -83
- package/dist/chunk-MNXS2U45.js.map +1 -0
- package/dist/{chunk-AWQPGIR6.js → chunk-NEFNKLBE.js} +5 -5
- package/dist/chunk-OHRR5OYM.js +63 -0
- package/dist/chunk-OHRR5OYM.js.map +1 -0
- package/dist/{chunk-U6YQ6FRI.js → chunk-P4NH7OUK.js} +31 -11
- package/dist/chunk-P4NH7OUK.js.map +1 -0
- package/dist/chunk-QSCPK4F5.js +145 -0
- package/dist/chunk-QSCPK4F5.js.map +1 -0
- package/dist/chunk-QXP3Z3JN.js +131 -0
- package/dist/chunk-QXP3Z3JN.js.map +1 -0
- package/dist/{chunk-YFQOA5AU.js → chunk-R5LCN54M.js} +4 -4
- package/dist/{chunk-KHE6L6TD.js → chunk-UKY4CHNC.js} +92 -10
- package/dist/chunk-UKY4CHNC.js.map +1 -0
- package/dist/{chunk-QUVVWYJW.js → chunk-UQUOVWBG.js} +8 -6
- package/dist/{chunk-QUVVWYJW.js.map → chunk-UQUOVWBG.js.map} +1 -1
- package/dist/{chunk-HE2MS4QO.js → chunk-V6BSF6OC.js} +17 -13
- package/dist/{chunk-HE2MS4QO.js.map → chunk-V6BSF6OC.js.map} +1 -1
- package/dist/{chunk-WVUSXNIE.js → chunk-WJXLQXJY.js} +6 -2
- package/dist/{chunk-WVUSXNIE.js.map → chunk-WJXLQXJY.js.map} +1 -1
- package/dist/{chunk-NZIP4PA2.js → chunk-WK7F3B2E.js} +2 -2
- package/dist/chunk-XQJXNMSB.js +23 -0
- package/dist/chunk-XQJXNMSB.js.map +1 -0
- package/dist/chunk-Y527D4TV.js +56 -0
- package/dist/chunk-Y527D4TV.js.map +1 -0
- package/dist/{chunk-SPAVAYSW.js → chunk-YFPY4ONH.js} +6 -4
- package/dist/{chunk-SPAVAYSW.js.map → chunk-YFPY4ONH.js.map} +1 -1
- package/dist/{chunk-WO5BJNIB.js → chunk-YVFXE7RR.js} +9 -129
- package/dist/chunk-YVFXE7RR.js.map +1 -0
- package/dist/clack-EZ7TDWQU.js +19 -0
- package/dist/claude-cli-2YKABJJZ.js +31 -0
- package/dist/{cli-O5SN7ZJ4.js → cli-D5OE3URZ.js} +128 -56
- package/dist/{cli-O5SN7ZJ4.js.map → cli-D5OE3URZ.js.map} +1 -1
- package/dist/codex-event-PPNVRRDH.js +16 -0
- package/dist/codex-host-2RJOJW2B.js +28 -0
- package/dist/codex-install-UUZ6QMBQ.js +221 -0
- package/dist/codex-install-UUZ6QMBQ.js.map +1 -0
- package/dist/{config-OJQI27LT.js → config-ZD4OB2DO.js} +18 -12
- package/dist/{doctor-IQQJHGGM.js → doctor-KBR34Q4B.js} +48 -37
- package/dist/doctor-KBR34Q4B.js.map +1 -0
- package/dist/{fund-WEV6DMTD.js → fund-5ITKQGYF.js} +38 -31
- package/dist/{fund-WEV6DMTD.js.map → fund-5ITKQGYF.js.map} +1 -1
- package/dist/hook-command-4TYCHHRL.js +39 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +3 -2
- package/dist/hosts/claude/tenjin/hooks/hooks.json +4 -1
- package/dist/hosts/claude/tenjin/hooks/register.tsx +589 -0
- package/dist/hosts/claude/tenjin/types/index.d.ts +41 -0
- package/dist/hosts/codex/.agents/plugins/marketplace.json +20 -0
- package/dist/hosts/codex/tenjin/.codex-plugin/plugin.json +16 -0
- package/dist/hosts/codex/tenjin/.mcp.json +12 -0
- package/dist/hosts/codex/tenjin/hooks/hooks.json +52 -0
- package/dist/hosts-FWZOV26H.js +216 -0
- package/dist/hosts-FWZOV26H.js.map +1 -0
- package/dist/index.js +5 -5
- package/dist/{install-TUCRF32I.js → install-XWGE4Q7L.js} +38 -21
- package/dist/{install-identity-WHPNMNMQ.js → install-identity-K7EJIQFP.js} +11 -7
- package/dist/{install-wallet-MA27FTQ5.js → install-wallet-XQ6XFZV4.js} +27 -23
- package/dist/{install-wallet-MA27FTQ5.js.map → install-wallet-XQ6XFZV4.js.map} +1 -1
- package/dist/{mcp-QML7ZMPH.js → mcp-3LIJSSJB.js} +184 -58
- package/dist/mcp-3LIJSSJB.js.map +1 -0
- package/dist/{package-LGKYOEPV.js → package-ZKQFDWLE.js} +2 -2
- package/dist/{pay-2C2UBBXJ.js → pay-WHBERZ3W.js} +27 -23
- package/dist/{payments-C44QUFXU.js → payments-KVICEKD2.js} +14 -10
- package/dist/{payments-C44QUFXU.js.map → payments-KVICEKD2.js.map} +1 -1
- package/dist/plugin-registration-5TIA564H.js +54 -0
- package/dist/plugin-registration-5TIA564H.js.map +1 -0
- package/dist/{send-KVJX4XIR.js → send-7G7Y7DLN.js} +25 -19
- package/dist/{send-KVJX4XIR.js.map → send-7G7Y7DLN.js.map} +1 -1
- package/dist/{status-S7C3WMSH.js → status-OF7RH5HM.js} +26 -21
- package/dist/{status-S7C3WMSH.js.map → status-OF7RH5HM.js.map} +1 -1
- package/dist/{status-line-YR2T5HC4.js → status-line-XOUE6MPL.js} +10 -6
- package/dist/{status-line-YR2T5HC4.js.map → status-line-XOUE6MPL.js.map} +1 -1
- package/dist/{uninstall-HY6LKIIT.js → uninstall-JXUAFNDB.js} +30 -21
- package/dist/{uninstall-HY6LKIIT.js.map → uninstall-JXUAFNDB.js.map} +1 -1
- package/dist/update-ZKUERSO2.js +44 -0
- package/dist/update-ZKUERSO2.js.map +1 -0
- package/dist/{usdc-JK4RRFFQ.js → usdc-OGOGEHV2.js} +7 -6
- package/dist/usdc-OGOGEHV2.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-X2VY6CY3.js → viemAdapter-By13KInL-S3DA7DFW.js} +2 -2
- package/dist/viemAdapter-By13KInL-S3DA7DFW.js.map +1 -0
- package/dist/{wallet-PD2IMZDU.js → wallet-2HA6W4R4.js} +24 -20
- package/dist/wallet-2HA6W4R4.js.map +1 -0
- package/docs/agent-permissions.md +21 -5
- package/package.json +1 -1
- package/dist/chunk-3O2BQIF6.js.map +0 -1
- package/dist/chunk-6W5GYG3W.js.map +0 -1
- package/dist/chunk-JMM6YE7J.js.map +0 -1
- package/dist/chunk-KHE6L6TD.js.map +0 -1
- package/dist/chunk-O2FRQ2L2.js.map +0 -1
- package/dist/chunk-OK2TDZQU.js.map +0 -1
- package/dist/chunk-TTBKWWTV.js.map +0 -1
- package/dist/chunk-U6YQ6FRI.js.map +0 -1
- package/dist/chunk-WO5BJNIB.js.map +0 -1
- package/dist/doctor-IQQJHGGM.js.map +0 -1
- package/dist/hook-command-D2P3ILRV.js +0 -32
- package/dist/mcp-QML7ZMPH.js.map +0 -1
- package/dist/update-OJV22LR3.js +0 -36
- /package/dist/{_esm-CE7KNONL.js.map → _esm-MEXZI5DL.js.map} +0 -0
- /package/dist/{alive-3J3CHOQP.js.map → alive-J64H46HI.js.map} +0 -0
- /package/dist/{chunk-PAYV4XUA.js.map → chunk-4ZZO6ULA.js.map} +0 -0
- /package/dist/{chunk-YHKXNYTB.js.map → chunk-5K5W4S66.js.map} +0 -0
- /package/dist/{chunk-HPWO4O6S.js.map → chunk-6E5R45ZO.js.map} +0 -0
- /package/dist/{chunk-LFZJM56J.js.map → chunk-7Q5FDF65.js.map} +0 -0
- /package/dist/{chunk-AEG2PXBP.js.map → chunk-7ZRL2LBQ.js.map} +0 -0
- /package/dist/{chunk-VFMQTSXG.js.map → chunk-B7HUUJOK.js.map} +0 -0
- /package/dist/{chunk-EL56RW2J.js.map → chunk-BL3332HQ.js.map} +0 -0
- /package/dist/{chunk-EBVIKMCH.js.map → chunk-JKKAIPTU.js.map} +0 -0
- /package/dist/{chunk-N35E6CM2.js.map → chunk-K3I7C2MO.js.map} +0 -0
- /package/dist/{chunk-RAULEAZ6.js.map → chunk-KXQ4UIP7.js.map} +0 -0
- /package/dist/{chunk-VZGAONSJ.js.map → chunk-KXVP2VKA.js.map} +0 -0
- /package/dist/{chunk-AWQPGIR6.js.map → chunk-NEFNKLBE.js.map} +0 -0
- /package/dist/{chunk-YFQOA5AU.js.map → chunk-R5LCN54M.js.map} +0 -0
- /package/dist/{chunk-NZIP4PA2.js.map → chunk-WK7F3B2E.js.map} +0 -0
- /package/dist/{config-OJQI27LT.js.map → clack-EZ7TDWQU.js.map} +0 -0
- /package/dist/{hook-command-D2P3ILRV.js.map → claude-cli-2YKABJJZ.js.map} +0 -0
- /package/dist/{install-TUCRF32I.js.map → codex-event-PPNVRRDH.js.map} +0 -0
- /package/dist/{install-identity-WHPNMNMQ.js.map → codex-host-2RJOJW2B.js.map} +0 -0
- /package/dist/{package-LGKYOEPV.js.map → config-ZD4OB2DO.js.map} +0 -0
- /package/dist/{pay-2C2UBBXJ.js.map → hook-command-4TYCHHRL.js.map} +0 -0
- /package/dist/{update-OJV22LR3.js.map → install-XWGE4Q7L.js.map} +0 -0
- /package/dist/{usdc-JK4RRFFQ.js.map → install-identity-K7EJIQFP.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-X2VY6CY3.js.map → package-ZKQFDWLE.js.map} +0 -0
- /package/dist/{wallet-PD2IMZDU.js.map → pay-WHBERZ3W.js.map} +0 -0
|
@@ -3,60 +3,67 @@ import {
|
|
|
3
3
|
SIWX_HEADER,
|
|
4
4
|
buildSiwxHeader
|
|
5
5
|
} from "./chunk-7EKYXMUO.js";
|
|
6
|
+
import "./chunk-6E5R45ZO.js";
|
|
6
7
|
import "./chunk-POUWHWID.js";
|
|
8
|
+
import "./chunk-XZKD7DIF.js";
|
|
7
9
|
import {
|
|
8
10
|
addressQrLines
|
|
9
11
|
} from "./chunk-ORWL5BSN.js";
|
|
10
|
-
import
|
|
11
|
-
getUsdcBalance
|
|
12
|
-
} from "./chunk-YFQOA5AU.js";
|
|
13
|
-
import "./chunk-EL56RW2J.js";
|
|
12
|
+
import "./chunk-BL3332HQ.js";
|
|
14
13
|
import {
|
|
15
14
|
describeWallet,
|
|
16
15
|
resolveWalletProvider
|
|
17
|
-
} from "./chunk-
|
|
18
|
-
import "./chunk-
|
|
19
|
-
import "./chunk-
|
|
20
|
-
import "./chunk-TTNESUPQ.js";
|
|
21
|
-
import "./chunk-HPWO4O6S.js";
|
|
22
|
-
import "./chunk-XZKD7DIF.js";
|
|
23
|
-
import {
|
|
24
|
-
underAgentHarness
|
|
25
|
-
} from "./chunk-KOGZDMHO.js";
|
|
26
|
-
import "./chunk-XKESD27X.js";
|
|
27
|
-
import "./chunk-MEFB5KHA.js";
|
|
16
|
+
} from "./chunk-2XLC3AEX.js";
|
|
17
|
+
import "./chunk-7ZRL2LBQ.js";
|
|
18
|
+
import "./chunk-WK7F3B2E.js";
|
|
28
19
|
import {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
import "./chunk-
|
|
33
|
-
import "./chunk-AWQPGIR6.js";
|
|
34
|
-
import "./chunk-N35E6CM2.js";
|
|
35
|
-
import "./chunk-JRGFKVAZ.js";
|
|
20
|
+
getUsdcBalance
|
|
21
|
+
} from "./chunk-R5LCN54M.js";
|
|
22
|
+
import "./chunk-NEFNKLBE.js";
|
|
23
|
+
import "./chunk-K3I7C2MO.js";
|
|
36
24
|
import "./chunk-5IEP5EGE.js";
|
|
37
25
|
import {
|
|
38
26
|
getAddress,
|
|
39
27
|
isAddress
|
|
40
28
|
} from "./chunk-EGELTSPU.js";
|
|
29
|
+
import "./chunk-JRGFKVAZ.js";
|
|
30
|
+
import "./chunk-TTNESUPQ.js";
|
|
41
31
|
import "./chunk-KG3D7FIF.js";
|
|
42
32
|
import "./chunk-RBJPAZFI.js";
|
|
43
33
|
import "./chunk-BPMWXTFX.js";
|
|
34
|
+
import {
|
|
35
|
+
underAgentHarness
|
|
36
|
+
} from "./chunk-KOGZDMHO.js";
|
|
37
|
+
import "./chunk-XKESD27X.js";
|
|
38
|
+
import "./chunk-MEFB5KHA.js";
|
|
39
|
+
import "./chunk-2SNUOHAT.js";
|
|
40
|
+
import {
|
|
41
|
+
emitNotice,
|
|
42
|
+
emitWriteNotice
|
|
43
|
+
} from "./chunk-K72RURN3.js";
|
|
44
44
|
import {
|
|
45
45
|
fetchFailureToCliError,
|
|
46
46
|
httpRequest
|
|
47
|
-
} from "./chunk-
|
|
47
|
+
} from "./chunk-AGZ7PJKY.js";
|
|
48
48
|
import "./chunk-2I4QTOLB.js";
|
|
49
49
|
import {
|
|
50
|
-
|
|
51
|
-
|
|
50
|
+
toMoney
|
|
51
|
+
} from "./chunk-Y527D4TV.js";
|
|
52
|
+
import {
|
|
52
53
|
external_exports,
|
|
53
54
|
loadRawConfig,
|
|
54
|
-
resolveSettings
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
55
|
+
resolveSettings
|
|
56
|
+
} from "./chunk-YVFXE7RR.js";
|
|
57
|
+
import {
|
|
58
|
+
PRODUCTION_ORIGIN
|
|
59
|
+
} from "./chunk-XQJXNMSB.js";
|
|
60
|
+
import {
|
|
61
|
+
CliError
|
|
62
|
+
} from "./chunk-3UCIG4TG.js";
|
|
63
|
+
import "./chunk-27EPWVOY.js";
|
|
64
|
+
import "./chunk-7WEQQJLG.js";
|
|
58
65
|
import "./chunk-SJLTEINJ.js";
|
|
59
|
-
import "./chunk-
|
|
66
|
+
import "./chunk-5C32RLTA.js";
|
|
60
67
|
import "./chunk-ZXTAQYNA.js";
|
|
61
68
|
|
|
62
69
|
// src/lib/session-key.ts
|
|
@@ -362,4 +369,4 @@ async function pollForFunds(ctx, desc, rpcUrl, startBalance, opts) {
|
|
|
362
369
|
export {
|
|
363
370
|
runFund
|
|
364
371
|
};
|
|
365
|
-
//# sourceMappingURL=fund-
|
|
372
|
+
//# sourceMappingURL=fund-5ITKQGYF.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/session-key.ts","../src/lib/session-present.ts","../src/lib/open-url.ts","../src/commands/fund.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport { sessionPath } from './paths';\nimport { writeFileAtomic } from './atomic-json';\nimport { buildSiwxHeader } from './siwx';\nimport { originOf } from './url';\nimport {\n isSessionUsable,\n loadSessionFile,\n signWithSession,\n type SessionFile,\n type SessionKeyDeps,\n type SessionScope,\n type SignableRequest,\n} from './session-present';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * Session-key delegation (RFC 9421 signed HTTP, RFC 9530-shaped Content-Digest),\n * verified byte-for-byte against the live \"Auth — session keys\" contract in\n * https://tenjin.sh/llms-full.txt (D35).\n *\n * The point: a plain SIWX write burns a single-use nonce, so every write needs a\n * fresh WALLET signature. A session key trades that for ONE wallet signature per\n * session: generate a P-256 keypair, wallet-sign a SIWX message binding its\n * pubkey/exp/scope, then sign each subsequent write with the P-256 key (no wallet\n * popup) until the delegation expires. The delegated key is short-lived (≤24h,\n * server-clamped) and cached 0600, address-bound so a wallet change invalidates it.\n *\n * This module is the MINT half — everything that needs a wallet signer, i.e.\n * `establishSession`, the cache writer, and the two `WriteAuth` implementations.\n * The present-only half (load a file, sign one request with it) lives in\n * `session-present.ts` and is re-exported below, so `posts-api`/`publish`/`edit`\n * keep importing one module while a caller that only wants to present a live\n * delegation — `read`, on the reuse path — imports that half alone and touches\n * no keystore. Do not move a signer-touching function down into\n * `session-present.ts`: that free reuse path is what it buys.\n *\n * A minted delegation is a wallet-derived credential, so it is bound to the\n * ORIGIN it was minted against and every presenter re-checks that binding.\n *\n * Never hand-rolls crypto: P-256 keygen is node:crypto webcrypto (subtle) and the\n * wallet delegation reuses the siwx.ts seam.\n */\n\nexport {\n contentDigest,\n isSessionPresentable,\n readSessionFile,\n isSessionUsable,\n keyidFor,\n loadSessionFile,\n scopeSatisfies,\n signatureBase,\n signatureParams,\n signWithSession,\n targetUri,\n} from './session-present';\nexport type {\n SessionFile,\n SessionFileState,\n SessionKeyDeps,\n SessionScope,\n SignableRequest,\n SignatureParamsInput,\n} from './session-present';\n\n/**\n * The chain a session delegation is signed over. Writes require Base mainnet per\n * the server's SIWX chain constraint, and a session covers reads and writes\n * alike, so there is exactly ONE session chain id rather than a per-caller\n * choice: the read path and the write path must mint against the same chain or\n * the file they share would flip between two delegations.\n */\nexport const SESSION_CHAIN_ID = 'eip155:8453';\n\nconst SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h; the server clamps to ≤24h.\n\n/**\n * The write-auth seam a posts client signs through. `headersFor` attaches the\n * signature headers (establishing the session lazily on first use); `recover`\n * reacts to a 401 by returning whether a retry is worthwhile.\n */\nexport interface WriteAuth {\n headersFor(req: SignableRequest): Promise<Record<string, string>>;\n /** React to a write's 401 `code`; true ⇒ the next headersFor retry may succeed. */\n recover(code: string | undefined): Promise<boolean>;\n}\n\nexport interface SessionKeyConfig {\n signer: TenjinSigner;\n baseUrl: string;\n chainId: string;\n dataDir: string;\n /**\n * The scope this session is minted at, and the scope a cached session must\n * cover to be reused. Required, not defaulted: over-granting silently is the\n * failure mode worth making impossible, so every caller states what it needs.\n */\n scope: SessionScope;\n}\n\nconst subtle = webcrypto.subtle;\n\nfunction generateP256KeyPair(): Promise<webcrypto.CryptoKeyPair> {\n return subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]) as Promise<webcrypto.CryptoKeyPair>;\n}\n\n/** base64url (no padding) of raw bytes — the pubkey/keyid encoding. */\nfunction toBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** The three URNs bound into the delegation's SIWX `resources` array (D35). */\nexport function delegationResources(\n publicKeyRaw: string,\n expIso: string,\n scope: SessionScope,\n): string[] {\n return [\n `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,\n `urn:tenjin:session:exp:${expIso}`,\n `urn:tenjin:session:scope:${scope}`,\n ];\n}\n\n/**\n * Establish a session with ONE wallet signature: generate a P-256 keypair, bind\n * its pubkey/exp/scope into a SIWX message, wallet-sign it, and cache the result\n * 0600 address-bound. The returned file's `delegation` is the constant\n * `Tenjin-Session-Delegation` header for the session's life.\n */\nexport async function establishSession(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): Promise<SessionFile> {\n const now = deps.now ?? Date.now;\n const pair = await generateP256KeyPair();\n const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));\n const publicKeyRaw = toBase64Url(rawPub);\n const jwk = (await subtle.exportKey('jwk', pair.privateKey)) as SessionFile['privateKeyJwk'];\n\n const expIso = new Date(now() + SESSION_TTL_MS).toISOString();\n const delegation = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n ttlMs: SESSION_TTL_MS,\n statement: 'Delegate a Tenjin session key.',\n resources: delegationResources(publicKeyRaw, expIso, config.scope),\n });\n\n const file: SessionFile = {\n address: config.signer.address.toLowerCase(),\n origin: originOf(config.baseUrl),\n delegation,\n exp: expIso,\n scope: config.scope,\n publicKeyRaw,\n privateKeyJwk: jwk,\n };\n await saveSessionFile(config.dataDir, file);\n return file;\n}\n\n// ---------------------------------------------------------------------------\n// Cache writes (0600, address-bound). The reader lives in session-present.\n// ---------------------------------------------------------------------------\n\nexport async function saveSessionFile(dir: string, file: SessionFile): Promise<void> {\n await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n// ---------------------------------------------------------------------------\n// The WriteAuth implementation: lazy establish, cache reuse, 401 recovery.\n// ---------------------------------------------------------------------------\n\n/** How each 401 `code` maps to recovery (per the llms-full.txt policy section). */\ntype Recovery = 'resign' | 'reestablish' | 'fatal';\n\nexport function recoveryFor(code: string | undefined): Recovery {\n switch (code) {\n case 'proof_expired':\n // The per-request signature is too old; just re-sign (no wallet).\n return 'resign';\n case 'session_expired':\n case 'proof_revoked':\n case 'insufficient_scope':\n // The delegation itself is gone/insufficient; re-establish (one wallet sig).\n return 'reestablish';\n case 'session_key_unbound':\n // keyid ≠ the delegation-bound key: retrying cannot fix it.\n return 'fatal';\n default:\n return 'fatal';\n }\n}\n\n/**\n * A session-key WriteAuth: mints (or loads) the delegation on first use and signs\n * every write with the P-256 key — so a returning agent never wallet-signs again\n * until the session expires. On a 401 it re-signs or re-establishes per the code.\n */\nexport function createSessionKeyAuth(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): WriteAuth {\n const now = deps.now ?? Date.now;\n let cached: SessionFile | null = null;\n let forceReestablish = false;\n\n const ensure = async (): Promise<SessionFile> => {\n if (\n !forceReestablish &&\n cached !== null &&\n isSessionUsable(cached, config.signer.address, now(), config.scope, originOf(config.baseUrl))\n ) {\n return cached;\n }\n if (!forceReestablish) {\n const onDisk = await loadSessionFile(config.dataDir);\n const origin = originOf(config.baseUrl);\n if (\n onDisk !== null &&\n isSessionUsable(onDisk, config.signer.address, now(), config.scope, origin)\n ) {\n cached = onDisk;\n return cached;\n }\n }\n cached = await establishSession(config, deps);\n forceReestablish = false;\n return cached;\n };\n\n return {\n async headersFor(req) {\n const file = await ensure();\n return signWithSession(file, req, deps);\n },\n async recover(code) {\n const recovery = recoveryFor(code);\n if (recovery === 'fatal') return false;\n if (recovery === 'reestablish') {\n cached = null;\n forceReestablish = true;\n }\n // 'resign' needs no state change: the next headersFor mints a fresh\n // created/nonce over the same (still-valid) delegation.\n return true;\n },\n };\n}\n\n/**\n * The plain-SIWX fallback (no session): every write carries its own fresh\n * wallet-signed `SIGN-IN-WITH-X` header. Used when session establishment is\n * disabled; a burned/stale nonce (401) is recovered by re-signing.\n */\nexport function createSiwxAuth(config: SessionKeyConfig): WriteAuth {\n return {\n async headersFor() {\n const header = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n });\n return { 'SIGN-IN-WITH-X': header };\n },\n async recover(code) {\n // A single-use nonce burns on every write; a stale/burned nonce (or an\n // expired proof) is recovered by re-signing with a fresh nonce + issuedAt.\n return code === 'nonce_already_used' || code === 'invalid_proof' || code === 'proof_expired';\n },\n };\n}\n","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 earns its keep on the reuse path: presenting a live delegation costs\n * no keystore decryption, so `tenjin read` reaches this half alone whenever one\n * is cached and only falls through to the mint half (and one passphrase) when\n * there is none. Neither half says anything about what an already-minted\n * delegation is worth to whoever holds it — see `origin` below, and the tier\n * note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.sh/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 or DELETE has no body to\n * cover at all, so content-digest drops out of the covered set. As a union,\n * \"GET with a body\" and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET' | 'DELETE'; 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 (`~/.tenjin/session.json`); the next read or write mints a fresh one.',\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. Keyed on\n // the presence of a body rather than on the method list, so a bodiless method\n // added to the union above needs no second edit here to stay bodiless.\n const digest = 'body' in req ? contentDigest(req.body) : undefined;\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","import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * Open a URL in the user's real default browser, best-effort. Follows the\n * passphrase.ts subprocess rules: an argv array (never a shell), a hard\n * timeout, and failure as a return value rather than a throw — callers print\n * the URL first, so a machine without an opener degrades to copy/paste.\n *\n * The opener is an absolute system path, never a bare name looked up on PATH,\n * and the BROWSER variable and other host-provided hints are dropped from the\n * child's environment. An agent host (Claude Desktop, an IDE) can put a shim on\n * PATH or set BROWSER to route the link into its own embedded view, where Apple\n * Pay and Google Pay cannot complete. On macOS the system's default https\n * handler is looked up and named explicitly with `open -b`. If the default\n * browser is itself an embedded view there is nothing more this can do, and the\n * caller's printed link and QR remain the way out.\n *\n * Windows uses rundll32's FileProtocolHandler because `start` exists only\n * inside cmd.exe, and spawning a shell around an attacker-influenced string is\n * the injection shape this module exists to avoid.\n */\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n execFileImpl?: typeof execFile;\n /** Test seam for the Linux opener search. */\n existsImpl?: (path: string) => boolean;\n /** Test seam for the macOS LaunchServices preferences location. */\n homeDir?: string;\n /** Test seam for the environment handed to the child. */\n env?: NodeJS.ProcessEnv;\n}\n\nconst OPEN_TIMEOUT_MS = 5000;\nconst MAC_OPEN = '/usr/bin/open';\nconst XDG_OPEN_CANDIDATES = [\n '/usr/bin/xdg-open',\n '/bin/xdg-open',\n '/usr/local/bin/xdg-open',\n] as const;\n/** What a bundle id may look like; keeps a hostile preference value from becoming a flag. */\nconst BUNDLE_ID = /^[A-Za-z0-9][A-Za-z0-9.-]*$/;\n\nexport function openerFor(\n platform: NodeJS.Platform,\n existsImpl: (path: string) => boolean = existsSync,\n): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: MAC_OPEN, args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n const found = XDG_OPEN_CANDIDATES.find((p) => existsImpl(p));\n return { cmd: found ?? XDG_OPEN_CANDIDATES[0], args: [] };\n}\n\n/** The child's environment without BROWSER, which xdg-open and others honor over the system default. */\nfunction openerEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const env = { ...base };\n delete env.BROWSER;\n return env;\n}\n\n/**\n * The bundle id of the default https handler, read from the user's LaunchServices\n * preferences, or undefined when none is recorded (the OS default then applies)\n * or anything about the read fails.\n */\nasync function macDefaultBrowserBundleId(\n run: typeof execFile,\n homeDir: string,\n env: NodeJS.ProcessEnv,\n): Promise<string | undefined> {\n const plist = join(\n homeDir,\n 'Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist',\n );\n const out = await new Promise<string | undefined>((resolve) => {\n run(\n '/usr/bin/plutil',\n ['-convert', 'json', '-o', '-', plist],\n { timeout: OPEN_TIMEOUT_MS, env },\n (err, stdout) => resolve(err === null ? String(stdout) : undefined),\n );\n });\n if (out === undefined) return undefined;\n try {\n const parsed = JSON.parse(out) as { LSHandlers?: unknown };\n if (!Array.isArray(parsed.LSHandlers)) return undefined;\n for (const entry of parsed.LSHandlers as Record<string, unknown>[]) {\n const scheme = entry.LSHandlerURLScheme;\n if (typeof scheme !== 'string' || scheme.toLowerCase() !== 'https') continue;\n const id = entry.LSHandlerRoleAll ?? entry.LSHandlerRoleViewer;\n if (typeof id === 'string' && BUNDLE_ID.test(id)) return id;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const platform = opts.platform ?? process.platform;\n const run = opts.execFileImpl ?? execFile;\n const env = openerEnv(opts.env ?? process.env);\n const { cmd, args } = openerFor(platform, opts.existsImpl);\n const launch = (extra: string[]): Promise<boolean> =>\n new Promise((resolve) => {\n run(\n cmd,\n [...args, ...extra, url],\n { timeout: OPEN_TIMEOUT_MS, windowsHide: true, env },\n (err) => resolve(err === null),\n );\n });\n\n if (platform === 'darwin') {\n const bundleId = await macDefaultBrowserBundleId(run, opts.homeDir ?? homedir(), env);\n if (bundleId !== undefined && (await launch(['-b', bundleId]))) return true;\n }\n return await launch([]);\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { buildSiwxHeader, SIWX_HEADER } from '../lib/siwx';\nimport { SESSION_CHAIN_ID } from '../lib/session-key';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { toMoney } from '../lib/money';\nimport { emitNotice, emitWriteNotice } from '../lib/output';\nimport { addressQrLines } from '../lib/qr';\nimport { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { underAgentHarness } from '../lib/session';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin wallet fund`: fund THIS wallet through Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend for a checkout\n * link for that same address (the server refuses any other address). The link is\n * either the Tenjin /fund page (US callers once headless onramp is live, with a\n * short-lived token in the URL fragment) or a Coinbase-hosted checkout. The money\n * moves entirely on Coinbase's side and the link grants no spending power over\n * the wallet. A hosted link is single-use, expires in ~5 minutes and is bound to\n * this machine's public IP at mint time, so it must be opened in a browser on this\n * machine/network.\n */\n\n/** The hosted Coinbase checkout host, one of the two hosts a returned link may use. */\nconst COINBASE_CHECKOUT_HOST = 'pay.coinbase.com';\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = PRODUCTION_ORIGIN;\n/**\n * The only hosts a returned link may point at; anything else is refused unopened.\n * The first is the host of the pinned origin (the Tenjin /fund page), so it\n * follows the origin if that is ever re-pointed.\n */\nconst ALLOWED_CHECKOUT_HOSTS: readonly string[] = [\n new URL(FUND_ORIGIN).host,\n COINBASE_CHECKOUT_HOST,\n];\n/** Matches the server's presetAmount bound (the fund link route's body schema). */\nconst MAX_PRESET_USD = 100_000;\nconst POLL_INTERVAL_MS = 5_000;\nconst POLL_TIMEOUT_MS = 600_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline won. Only `timed-out` says anything about the purchase.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to Coinbase (clamped upward to its own floor there). */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** The environment the agent-harness check reads; defaults to the process's. */\n env?: NodeJS.ProcessEnv;\n /** `--no-qr`: skip the QR block a TTY otherwise gets for sending USDC from a phone. */\n qr?: boolean;\n /** Poll the balance after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n pollIntervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n const signer = await provider.getSigner();\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const baseUrl = FUND_ORIGIN;\n const rpcUrl = settings.rpcUrl.value;\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting, because\n // the envelope carrying the link is written only after runFund returns, and a\n // link that expires in ~5 minutes is worthless after a 10-minute poll.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n\n // Read the balance BEFORE minting so the poll has a baseline; an RPC flake\n // here only disables the wait, it never blocks funding.\n const startBalance = shouldWait ? await balanceOrUndefined(desc, rpcUrl) : undefined;\n\n const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: SESSION_CHAIN_ID });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n jsonBody: {\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/fund/link`, request);\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n const url = checkoutUrlFrom(res.status, res.json);\n\n // The link goes out on EVERY surface and before any waiting: it is single-use\n // with a ~5 minute expiry, and the stdout envelope that also carries it is\n // written only after this function returns. A piped or agent-driven run is\n // exactly the case that must not get the link after it has died, so these\n // three lines are write-notices (stderr, no TTY gate, no --json gate) rather\n // than human-mode notices. stdout stays exactly one JSON object.\n //\n // A Tenjin /fund link carries a token in its fragment, and it prints whole on\n // every path: a user who copies it into another browser needs the token. It is\n // not worth hiding, since it can only fund this wallet and expires in ~10 minutes.\n // An agent's shell has no terminal, but an agent runs this only on the\n // person's yes to \"open the funding page\" (`tenjin install` hands it that\n // question), so under a harness the page opens too.\n const willOpen =\n opts.open !== false && (ctx.io.isTTY || underAgentHarness(opts.env ?? process.env));\n const hosted = new URL(url).host === COINBASE_CHECKOUT_HOST;\n emitWriteNotice(ctx.io, `Checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\n hosted\n ? 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required.'\n : 'The link expires in ~10 minutes. In the US, pay with Apple Pay or Google Pay, no Coinbase account needed.',\n );\n\n let opened = false;\n // The opener is resolved by absolute path and ignores BROWSER (lib/open-url.ts), so an\n // agent host cannot route the link into its embedded view. If the user's default browser\n // is itself an embedded view there is nothing more to do here: the link and QR are printed.\n if (willOpen) {\n opened = await (opts.openUrl ?? openInBrowser)(url);\n emitNotice(\n ctx.io,\n opened ? 'Opened in your default browser.' : 'Could not open a browser; use the link above.',\n { json: ctx.flags.json },\n );\n }\n\n // Human mode only, and before the wait: the poll below also sees USDC sent\n // straight to the address, so a phone wallet is a second way to finish.\n const qrLines =\n opts.qr !== false && ctx.io.isTTY && !ctx.flags.json\n ? addressQrLines(address, ctx.io.stderr)\n : [];\n if (qrLines.length > 0) {\n ctx.io.stderr.write(\n [`Or send USDC from a phone wallet to ${address}:`, ...qrLines].join('\\n') + '\\n',\n );\n }\n\n const funded =\n shouldWait && startBalance !== undefined\n ? await pollForFunds(ctx, desc, rpcUrl, startBalance, opts)\n : undefined;\n if (funded !== undefined) {\n emitWriteNotice(ctx.io, 'USDC arrived - you can close the checkout tab.');\n }\n const pollStatus: FundPollStatus = !shouldWait\n ? 'skipped'\n : startBalance === undefined\n ? 'unavailable'\n : funded !== undefined\n ? 'arrived'\n : 'timed-out';\n\n const balanceAtomic = funded ?? startBalance;\n return {\n data: {\n address,\n checkoutUrl: url,\n opened,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n funded: funded !== undefined,\n pollStatus,\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n },\n humanLines:\n funded !== undefined\n ? [`Funded: balance is now ${toMoney(funded.toString()).usd} USDC on Base.`]\n : [\n 'Checkout link issued (printed above).',\n ...(pollStatus === 'unavailable'\n ? ['Could not read the balance to wait on it; the link is unaffected.']\n : []),\n 'Confirm arrival later with `tenjin wallet balance`.',\n ],\n };\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin wallet fund 5',\n });\n }\n return n;\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on one of the two\n * allowed hosts (the Tenjin origin or Coinbase's checkout) before anything else\n * sees it: a compromised or misconfigured server must not be able to steer the\n * user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (\n parsed !== undefined &&\n parsed.protocol === 'https:' &&\n ALLOWED_CHECKOUT_HOSTS.includes(parsed.host)\n ) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https on ${ALLOWED_CHECKOUT_HOSTS.join(' or ')}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Coinbase Onramp is not available in your region.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', 'The funding endpoint rejected the signed proof.', {\n fix: 'Check this machine’s clock, then retry.',\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'The funding endpoint is rate limited right now.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError(\n 'API_UNREACHABLE',\n 'Production has no Coinbase Onramp configured right now.',\n {\n fix: 'Retry later.',\n },\n );\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(\n desc: { address: string },\n rpcUrl: string,\n): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(desc.address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wait for the purchased USDC to land: any balance above the pre-mint baseline\n * counts (Coinbase clamps presets, so an exact-amount check would be wrong).\n * RPC flakes mid-poll are tolerated; the deadline is the only exit besides\n * arrival, and timing out is a normal outcome (the human may still be paying),\n * not an error.\n */\nasync function pollForFunds(\n ctx: CommandContext,\n desc: { address: string },\n rpcUrl: string,\n startBalance: bigint,\n opts: FundOptions,\n): Promise<bigint | undefined> {\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;\n const deadline = Date.now() + (opts.pollTimeoutMs ?? POLL_TIMEOUT_MS);\n emitNotice(ctx.io, 'Waiting for the USDC to arrive (Ctrl-C is safe; the purchase is not).', {\n json: ctx.flags.json,\n });\n while (Date.now() < deadline) {\n await sleep(interval);\n const balance = await balanceOrUndefined(desc, rpcUrl);\n if (balance !== undefined && balance > startBalance) return balance;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,kBAAiB;;;ACA1B,SAAS,YAAY,aAAa,iBAAiB;AAoDnD,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,EAEjB,YAAY,iBAAE,OAAO;AAAA;AAAA,EAErB,KAAK,iBAAE,OAAO;AAAA,EACd,OAAO,iBAAE,OAAO;AAAA;AAAA,EAEhB,cAAc,iBAAE,OAAO;AAAA,EACvB,eAAe;AACjB,CAAC;AAmBD,IAAM,SAAS,UAAU;;;ADjClB,IAAM,mBAAmB;AAEhC,IAAM,iBAAiB,KAAK,KAAK,KAAK;AA0BtC,IAAMC,UAASC,WAAU;;;AErGzB,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,SAAS,YAAY;AAiCrB,IAAM,kBAAkB;AACxB,IAAM,WAAW;AACjB,IAAM,sBAAsB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,YAAY;AAEX,SAAS,UACd,UACA,aAAwC,YACP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AACpD,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,MAAO,KAA6B;AAC1C,MAAI,OAAO,QAAQ,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAM,OAAQ,IAA2B;AACzC,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;AAEA,eAAe,mBACb,MACA,QAC6B;AAC7B,MAAI;AACF,WAAO,MAAM,eAAe,KAAK,SAA0B,MAAM;AAAA,EACnE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASA,eAAe,aACb,KACA,MACA,QACA,cACA,MAC6B;AAC7B,QAAM,QACJ,KAAK,UAAU,CAAC,OAAe,IAAI,QAAc,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACvF,QAAM,WAAW,KAAK,kBAAkB;AACxC,QAAM,WAAW,KAAK,IAAI,KAAK,KAAK,iBAAiB;AACrD,aAAW,IAAI,IAAI,yEAAyE;AAAA,IAC1F,MAAM,IAAI,MAAM;AAAA,EAClB,CAAC;AACD,SAAO,KAAK,IAAI,IAAI,UAAU;AAC5B,UAAM,MAAM,QAAQ;AACpB,UAAM,UAAU,MAAM,mBAAmB,MAAM,MAAM;AACrD,QAAI,YAAY,UAAa,UAAU,aAAc,QAAO;AAAA,EAC9D;AACA,SAAO;AACT;","names":["webcrypto","subtle","webcrypto"]}
|
|
1
|
+
{"version":3,"sources":["../src/lib/session-key.ts","../src/lib/session-present.ts","../src/lib/open-url.ts","../src/commands/fund.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport { sessionPath } from './paths';\nimport { writeFileAtomic } from './atomic-json';\nimport { buildSiwxHeader } from './siwx';\nimport { originOf } from './url';\nimport {\n isSessionUsable,\n loadSessionFile,\n signWithSession,\n type SessionFile,\n type SessionKeyDeps,\n type SessionScope,\n type SignableRequest,\n} from './session-present';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * Session-key delegation (RFC 9421 signed HTTP, RFC 9530-shaped Content-Digest),\n * verified byte-for-byte against the live \"Auth — session keys\" contract in\n * https://tenjin.sh/llms-full.txt (D35).\n *\n * The point: a plain SIWX write burns a single-use nonce, so every write needs a\n * fresh WALLET signature. A session key trades that for ONE wallet signature per\n * session: generate a P-256 keypair, wallet-sign a SIWX message binding its\n * pubkey/exp/scope, then sign each subsequent write with the P-256 key (no wallet\n * popup) until the delegation expires. The delegated key is short-lived (≤24h,\n * server-clamped) and cached 0600, address-bound so a wallet change invalidates it.\n *\n * This module is the MINT half — everything that needs a wallet signer, i.e.\n * `establishSession`, the cache writer, and the two `WriteAuth` implementations.\n * The present-only half (load a file, sign one request with it) lives in\n * `session-present.ts` and is re-exported below, so `posts-api`/`publish`/`edit`\n * keep importing one module while a caller that only wants to present a live\n * delegation — `read`, on the reuse path — imports that half alone and touches\n * no keystore. Do not move a signer-touching function down into\n * `session-present.ts`: that free reuse path is what it buys.\n *\n * A minted delegation is a wallet-derived credential, so it is bound to the\n * ORIGIN it was minted against and every presenter re-checks that binding.\n *\n * Never hand-rolls crypto: P-256 keygen is node:crypto webcrypto (subtle) and the\n * wallet delegation reuses the siwx.ts seam.\n */\n\nexport {\n contentDigest,\n isSessionPresentable,\n readSessionFile,\n isSessionUsable,\n keyidFor,\n loadSessionFile,\n scopeSatisfies,\n signatureBase,\n signatureParams,\n signWithSession,\n targetUri,\n} from './session-present';\nexport type {\n SessionFile,\n SessionFileState,\n SessionKeyDeps,\n SessionScope,\n SignableRequest,\n SignatureParamsInput,\n} from './session-present';\n\n/**\n * The chain a session delegation is signed over. Writes require Base mainnet per\n * the server's SIWX chain constraint, and a session covers reads and writes\n * alike, so there is exactly ONE session chain id rather than a per-caller\n * choice: the read path and the write path must mint against the same chain or\n * the file they share would flip between two delegations.\n */\nexport const SESSION_CHAIN_ID = 'eip155:8453';\n\nconst SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h; the server clamps to ≤24h.\n\n/**\n * The write-auth seam a posts client signs through. `headersFor` attaches the\n * signature headers (establishing the session lazily on first use); `recover`\n * reacts to a 401 by returning whether a retry is worthwhile.\n */\nexport interface WriteAuth {\n headersFor(req: SignableRequest): Promise<Record<string, string>>;\n /** React to a write's 401 `code`; true ⇒ the next headersFor retry may succeed. */\n recover(code: string | undefined): Promise<boolean>;\n}\n\nexport interface SessionKeyConfig {\n signer: TenjinSigner;\n baseUrl: string;\n chainId: string;\n dataDir: string;\n /**\n * The scope this session is minted at, and the scope a cached session must\n * cover to be reused. Required, not defaulted: over-granting silently is the\n * failure mode worth making impossible, so every caller states what it needs.\n */\n scope: SessionScope;\n}\n\nconst subtle = webcrypto.subtle;\n\nfunction generateP256KeyPair(): Promise<webcrypto.CryptoKeyPair> {\n return subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]) as Promise<webcrypto.CryptoKeyPair>;\n}\n\n/** base64url (no padding) of raw bytes — the pubkey/keyid encoding. */\nfunction toBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** The three URNs bound into the delegation's SIWX `resources` array (D35). */\nexport function delegationResources(\n publicKeyRaw: string,\n expIso: string,\n scope: SessionScope,\n): string[] {\n return [\n `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,\n `urn:tenjin:session:exp:${expIso}`,\n `urn:tenjin:session:scope:${scope}`,\n ];\n}\n\n/**\n * Establish a session with ONE wallet signature: generate a P-256 keypair, bind\n * its pubkey/exp/scope into a SIWX message, wallet-sign it, and cache the result\n * 0600 address-bound. The returned file's `delegation` is the constant\n * `Tenjin-Session-Delegation` header for the session's life.\n */\nexport async function establishSession(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): Promise<SessionFile> {\n const now = deps.now ?? Date.now;\n const pair = await generateP256KeyPair();\n const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));\n const publicKeyRaw = toBase64Url(rawPub);\n const jwk = (await subtle.exportKey('jwk', pair.privateKey)) as SessionFile['privateKeyJwk'];\n\n const expIso = new Date(now() + SESSION_TTL_MS).toISOString();\n const delegation = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n ttlMs: SESSION_TTL_MS,\n statement: 'Delegate a Tenjin session key.',\n resources: delegationResources(publicKeyRaw, expIso, config.scope),\n });\n\n const file: SessionFile = {\n address: config.signer.address.toLowerCase(),\n origin: originOf(config.baseUrl),\n delegation,\n exp: expIso,\n scope: config.scope,\n publicKeyRaw,\n privateKeyJwk: jwk,\n };\n await saveSessionFile(config.dataDir, file);\n return file;\n}\n\n// ---------------------------------------------------------------------------\n// Cache writes (0600, address-bound). The reader lives in session-present.\n// ---------------------------------------------------------------------------\n\nexport async function saveSessionFile(dir: string, file: SessionFile): Promise<void> {\n await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n// ---------------------------------------------------------------------------\n// The WriteAuth implementation: lazy establish, cache reuse, 401 recovery.\n// ---------------------------------------------------------------------------\n\n/** How each 401 `code` maps to recovery (per the llms-full.txt policy section). */\ntype Recovery = 'resign' | 'reestablish' | 'fatal';\n\nexport function recoveryFor(code: string | undefined): Recovery {\n switch (code) {\n case 'proof_expired':\n // The per-request signature is too old; just re-sign (no wallet).\n return 'resign';\n case 'session_expired':\n case 'proof_revoked':\n case 'insufficient_scope':\n // The delegation itself is gone/insufficient; re-establish (one wallet sig).\n return 'reestablish';\n case 'session_key_unbound':\n // keyid ≠ the delegation-bound key: retrying cannot fix it.\n return 'fatal';\n default:\n return 'fatal';\n }\n}\n\n/**\n * A session-key WriteAuth: mints (or loads) the delegation on first use and signs\n * every write with the P-256 key — so a returning agent never wallet-signs again\n * until the session expires. On a 401 it re-signs or re-establishes per the code.\n */\nexport function createSessionKeyAuth(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): WriteAuth {\n const now = deps.now ?? Date.now;\n let cached: SessionFile | null = null;\n let forceReestablish = false;\n\n const ensure = async (): Promise<SessionFile> => {\n if (\n !forceReestablish &&\n cached !== null &&\n isSessionUsable(cached, config.signer.address, now(), config.scope, originOf(config.baseUrl))\n ) {\n return cached;\n }\n if (!forceReestablish) {\n const onDisk = await loadSessionFile(config.dataDir);\n const origin = originOf(config.baseUrl);\n if (\n onDisk !== null &&\n isSessionUsable(onDisk, config.signer.address, now(), config.scope, origin)\n ) {\n cached = onDisk;\n return cached;\n }\n }\n cached = await establishSession(config, deps);\n forceReestablish = false;\n return cached;\n };\n\n return {\n async headersFor(req) {\n const file = await ensure();\n return signWithSession(file, req, deps);\n },\n async recover(code) {\n const recovery = recoveryFor(code);\n if (recovery === 'fatal') return false;\n if (recovery === 'reestablish') {\n cached = null;\n forceReestablish = true;\n }\n // 'resign' needs no state change: the next headersFor mints a fresh\n // created/nonce over the same (still-valid) delegation.\n return true;\n },\n };\n}\n\n/**\n * The plain-SIWX fallback (no session): every write carries its own fresh\n * wallet-signed `SIGN-IN-WITH-X` header. Used when session establishment is\n * disabled; a burned/stale nonce (401) is recovered by re-signing.\n */\nexport function createSiwxAuth(config: SessionKeyConfig): WriteAuth {\n return {\n async headersFor() {\n const header = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n });\n return { 'SIGN-IN-WITH-X': header };\n },\n async recover(code) {\n // A single-use nonce burns on every write; a stale/burned nonce (or an\n // expired proof) is recovered by re-signing with a fresh nonce + issuedAt.\n return code === 'nonce_already_used' || code === 'invalid_proof' || code === 'proof_expired';\n },\n };\n}\n","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 earns its keep on the reuse path: presenting a live delegation costs\n * no keystore decryption, so `tenjin read` reaches this half alone whenever one\n * is cached and only falls through to the mint half (and one passphrase) when\n * there is none. Neither half says anything about what an already-minted\n * delegation is worth to whoever holds it — see `origin` below, and the tier\n * note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.sh/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 or DELETE has no body to\n * cover at all, so content-digest drops out of the covered set. As a union,\n * \"GET with a body\" and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET' | 'DELETE'; 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 (`~/.tenjin/session.json`); the next read or write mints a fresh one.',\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. Keyed on\n // the presence of a body rather than on the method list, so a bodiless method\n // added to the union above needs no second edit here to stay bodiless.\n const digest = 'body' in req ? contentDigest(req.body) : undefined;\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","import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * Open a URL in the user's real default browser, best-effort. Follows the\n * passphrase.ts subprocess rules: an argv array (never a shell), a hard\n * timeout, and failure as a return value rather than a throw — callers print\n * the URL first, so a machine without an opener degrades to copy/paste.\n *\n * The opener is an absolute system path, never a bare name looked up on PATH,\n * and the BROWSER variable and other host-provided hints are dropped from the\n * child's environment. An agent host (Claude Desktop, an IDE) can put a shim on\n * PATH or set BROWSER to route the link into its own embedded view, where Apple\n * Pay and Google Pay cannot complete. On macOS the system's default https\n * handler is looked up and named explicitly with `open -b`. If the default\n * browser is itself an embedded view there is nothing more this can do, and the\n * caller's printed link and QR remain the way out.\n *\n * Windows uses rundll32's FileProtocolHandler because `start` exists only\n * inside cmd.exe, and spawning a shell around an attacker-influenced string is\n * the injection shape this module exists to avoid.\n */\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n execFileImpl?: typeof execFile;\n /** Test seam for the Linux opener search. */\n existsImpl?: (path: string) => boolean;\n /** Test seam for the macOS LaunchServices preferences location. */\n homeDir?: string;\n /** Test seam for the environment handed to the child. */\n env?: NodeJS.ProcessEnv;\n}\n\nconst OPEN_TIMEOUT_MS = 5000;\nconst MAC_OPEN = '/usr/bin/open';\nconst XDG_OPEN_CANDIDATES = [\n '/usr/bin/xdg-open',\n '/bin/xdg-open',\n '/usr/local/bin/xdg-open',\n] as const;\n/** What a bundle id may look like; keeps a hostile preference value from becoming a flag. */\nconst BUNDLE_ID = /^[A-Za-z0-9][A-Za-z0-9.-]*$/;\n\nexport function openerFor(\n platform: NodeJS.Platform,\n existsImpl: (path: string) => boolean = existsSync,\n): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: MAC_OPEN, args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n const found = XDG_OPEN_CANDIDATES.find((p) => existsImpl(p));\n return { cmd: found ?? XDG_OPEN_CANDIDATES[0], args: [] };\n}\n\n/** The child's environment without BROWSER, which xdg-open and others honor over the system default. */\nfunction openerEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const env = { ...base };\n delete env.BROWSER;\n return env;\n}\n\n/**\n * The bundle id of the default https handler, read from the user's LaunchServices\n * preferences, or undefined when none is recorded (the OS default then applies)\n * or anything about the read fails.\n */\nasync function macDefaultBrowserBundleId(\n run: typeof execFile,\n homeDir: string,\n env: NodeJS.ProcessEnv,\n): Promise<string | undefined> {\n const plist = join(\n homeDir,\n 'Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist',\n );\n const out = await new Promise<string | undefined>((resolve) => {\n run(\n '/usr/bin/plutil',\n ['-convert', 'json', '-o', '-', plist],\n { timeout: OPEN_TIMEOUT_MS, env },\n (err, stdout) => resolve(err === null ? String(stdout) : undefined),\n );\n });\n if (out === undefined) return undefined;\n try {\n const parsed = JSON.parse(out) as { LSHandlers?: unknown };\n if (!Array.isArray(parsed.LSHandlers)) return undefined;\n for (const entry of parsed.LSHandlers as Record<string, unknown>[]) {\n const scheme = entry.LSHandlerURLScheme;\n if (typeof scheme !== 'string' || scheme.toLowerCase() !== 'https') continue;\n const id = entry.LSHandlerRoleAll ?? entry.LSHandlerRoleViewer;\n if (typeof id === 'string' && BUNDLE_ID.test(id)) return id;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const platform = opts.platform ?? process.platform;\n const run = opts.execFileImpl ?? execFile;\n const env = openerEnv(opts.env ?? process.env);\n const { cmd, args } = openerFor(platform, opts.existsImpl);\n const launch = (extra: string[]): Promise<boolean> =>\n new Promise((resolve) => {\n run(\n cmd,\n [...args, ...extra, url],\n { timeout: OPEN_TIMEOUT_MS, windowsHide: true, env },\n (err) => resolve(err === null),\n );\n });\n\n if (platform === 'darwin') {\n const bundleId = await macDefaultBrowserBundleId(run, opts.homeDir ?? homedir(), env);\n if (bundleId !== undefined && (await launch(['-b', bundleId]))) return true;\n }\n return await launch([]);\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { buildSiwxHeader, SIWX_HEADER } from '../lib/siwx';\nimport { SESSION_CHAIN_ID } from '../lib/session-key';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { toMoney } from '../lib/money';\nimport { emitNotice, emitWriteNotice } from '../lib/output';\nimport { addressQrLines } from '../lib/qr';\nimport { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { underAgentHarness } from '../lib/session';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin wallet fund`: fund THIS wallet through Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend for a checkout\n * link for that same address (the server refuses any other address). The link is\n * either the Tenjin /fund page (US callers once headless onramp is live, with a\n * short-lived token in the URL fragment) or a Coinbase-hosted checkout. The money\n * moves entirely on Coinbase's side and the link grants no spending power over\n * the wallet. A hosted link is single-use, expires in ~5 minutes and is bound to\n * this machine's public IP at mint time, so it must be opened in a browser on this\n * machine/network.\n */\n\n/** The hosted Coinbase checkout host, one of the two hosts a returned link may use. */\nconst COINBASE_CHECKOUT_HOST = 'pay.coinbase.com';\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = PRODUCTION_ORIGIN;\n/**\n * The only hosts a returned link may point at; anything else is refused unopened.\n * The first is the host of the pinned origin (the Tenjin /fund page), so it\n * follows the origin if that is ever re-pointed.\n */\nconst ALLOWED_CHECKOUT_HOSTS: readonly string[] = [\n new URL(FUND_ORIGIN).host,\n COINBASE_CHECKOUT_HOST,\n];\n/** Matches the server's presetAmount bound (the fund link route's body schema). */\nconst MAX_PRESET_USD = 100_000;\nconst POLL_INTERVAL_MS = 5_000;\nconst POLL_TIMEOUT_MS = 600_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline won. Only `timed-out` says anything about the purchase.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to Coinbase (clamped upward to its own floor there). */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** The environment the agent-harness check reads; defaults to the process's. */\n env?: NodeJS.ProcessEnv;\n /** `--no-qr`: skip the QR block a TTY otherwise gets for sending USDC from a phone. */\n qr?: boolean;\n /** Poll the balance after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n pollIntervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n const signer = await provider.getSigner();\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const baseUrl = FUND_ORIGIN;\n const rpcUrl = settings.rpcUrl.value;\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting, because\n // the envelope carrying the link is written only after runFund returns, and a\n // link that expires in ~5 minutes is worthless after a 10-minute poll.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n\n // Read the balance BEFORE minting so the poll has a baseline; an RPC flake\n // here only disables the wait, it never blocks funding.\n const startBalance = shouldWait ? await balanceOrUndefined(desc, rpcUrl) : undefined;\n\n const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: SESSION_CHAIN_ID });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n jsonBody: {\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/fund/link`, request);\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n const url = checkoutUrlFrom(res.status, res.json);\n\n // The link goes out on EVERY surface and before any waiting: it is single-use\n // with a ~5 minute expiry, and the stdout envelope that also carries it is\n // written only after this function returns. A piped or agent-driven run is\n // exactly the case that must not get the link after it has died, so these\n // three lines are write-notices (stderr, no TTY gate, no --json gate) rather\n // than human-mode notices. stdout stays exactly one JSON object.\n //\n // A Tenjin /fund link carries a token in its fragment, and it prints whole on\n // every path: a user who copies it into another browser needs the token. It is\n // not worth hiding, since it can only fund this wallet and expires in ~10 minutes.\n // An agent's shell has no terminal, but an agent runs this only on the\n // person's yes to \"open the funding page\" (`tenjin install` hands it that\n // question), so under a harness the page opens too.\n const willOpen =\n opts.open !== false && (ctx.io.isTTY || underAgentHarness(opts.env ?? process.env));\n const hosted = new URL(url).host === COINBASE_CHECKOUT_HOST;\n emitWriteNotice(ctx.io, `Checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\n hosted\n ? 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required.'\n : 'The link expires in ~10 minutes. In the US, pay with Apple Pay or Google Pay, no Coinbase account needed.',\n );\n\n let opened = false;\n // The opener is resolved by absolute path and ignores BROWSER (lib/open-url.ts), so an\n // agent host cannot route the link into its embedded view. If the user's default browser\n // is itself an embedded view there is nothing more to do here: the link and QR are printed.\n if (willOpen) {\n opened = await (opts.openUrl ?? openInBrowser)(url);\n emitNotice(\n ctx.io,\n opened ? 'Opened in your default browser.' : 'Could not open a browser; use the link above.',\n { json: ctx.flags.json },\n );\n }\n\n // Human mode only, and before the wait: the poll below also sees USDC sent\n // straight to the address, so a phone wallet is a second way to finish.\n const qrLines =\n opts.qr !== false && ctx.io.isTTY && !ctx.flags.json\n ? addressQrLines(address, ctx.io.stderr)\n : [];\n if (qrLines.length > 0) {\n ctx.io.stderr.write(\n [`Or send USDC from a phone wallet to ${address}:`, ...qrLines].join('\\n') + '\\n',\n );\n }\n\n const funded =\n shouldWait && startBalance !== undefined\n ? await pollForFunds(ctx, desc, rpcUrl, startBalance, opts)\n : undefined;\n if (funded !== undefined) {\n emitWriteNotice(ctx.io, 'USDC arrived - you can close the checkout tab.');\n }\n const pollStatus: FundPollStatus = !shouldWait\n ? 'skipped'\n : startBalance === undefined\n ? 'unavailable'\n : funded !== undefined\n ? 'arrived'\n : 'timed-out';\n\n const balanceAtomic = funded ?? startBalance;\n return {\n data: {\n address,\n checkoutUrl: url,\n opened,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n funded: funded !== undefined,\n pollStatus,\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n },\n humanLines:\n funded !== undefined\n ? [`Funded: balance is now ${toMoney(funded.toString()).usd} USDC on Base.`]\n : [\n 'Checkout link issued (printed above).',\n ...(pollStatus === 'unavailable'\n ? ['Could not read the balance to wait on it; the link is unaffected.']\n : []),\n 'Confirm arrival later with `tenjin wallet balance`.',\n ],\n };\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin wallet fund 5',\n });\n }\n return n;\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on one of the two\n * allowed hosts (the Tenjin origin or Coinbase's checkout) before anything else\n * sees it: a compromised or misconfigured server must not be able to steer the\n * user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (\n parsed !== undefined &&\n parsed.protocol === 'https:' &&\n ALLOWED_CHECKOUT_HOSTS.includes(parsed.host)\n ) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https on ${ALLOWED_CHECKOUT_HOSTS.join(' or ')}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Coinbase Onramp is not available in your region.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', 'The funding endpoint rejected the signed proof.', {\n fix: 'Check this machine’s clock, then retry.',\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'The funding endpoint is rate limited right now.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError(\n 'API_UNREACHABLE',\n 'Production has no Coinbase Onramp configured right now.',\n {\n fix: 'Retry later.',\n },\n );\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(\n desc: { address: string },\n rpcUrl: string,\n): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(desc.address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wait for the purchased USDC to land: any balance above the pre-mint baseline\n * counts (Coinbase clamps presets, so an exact-amount check would be wrong).\n * RPC flakes mid-poll are tolerated; the deadline is the only exit besides\n * arrival, and timing out is a normal outcome (the human may still be paying),\n * not an error.\n */\nasync function pollForFunds(\n ctx: CommandContext,\n desc: { address: string },\n rpcUrl: string,\n startBalance: bigint,\n opts: FundOptions,\n): Promise<bigint | undefined> {\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;\n const deadline = Date.now() + (opts.pollTimeoutMs ?? POLL_TIMEOUT_MS);\n emitNotice(ctx.io, 'Waiting for the USDC to arrive (Ctrl-C is safe; the purchase is not).', {\n json: ctx.flags.json,\n });\n while (Date.now() < deadline) {\n await sleep(interval);\n const balance = await balanceOrUndefined(desc, rpcUrl);\n if (balance !== undefined && balance > startBalance) return balance;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,kBAAiB;;;ACA1B,SAAS,YAAY,aAAa,iBAAiB;AAoDnD,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,EAEjB,YAAY,iBAAE,OAAO;AAAA;AAAA,EAErB,KAAK,iBAAE,OAAO;AAAA,EACd,OAAO,iBAAE,OAAO;AAAA;AAAA,EAEhB,cAAc,iBAAE,OAAO;AAAA,EACvB,eAAe;AACjB,CAAC;AAmBD,IAAM,SAAS,UAAU;;;ADjClB,IAAM,mBAAmB;AAEhC,IAAM,iBAAiB,KAAK,KAAK,KAAK;AA0BtC,IAAMC,UAASC,WAAU;;;AErGzB,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,SAAS,YAAY;AAiCrB,IAAM,kBAAkB;AACxB,IAAM,WAAW;AACjB,IAAM,sBAAsB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,YAAY;AAEX,S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AAGA,SAAS,UAAU,MAAmC;AACpD,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,MAAO,KAA6B;AAC1C,MAAI,OAAO,QAAQ,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAM,OAAQ,IAA2B;AACzC,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;AAEA,eAAe,mBACb,MACA,QAC6B;AAC7B,MAAI;AACF,WAAO,MAAM,eAAe,KAAK,SAA0B,MAAM;AAAA,EACnE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASA,eAAe,aACb,KACA,MACA,QACA,cACA,MAC6B;AAC7B,QAAM,QACJ,KAAK,UAAU,CAAC,OAAe,IAAI,QAAc,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACvF,QAAM,WAAW,KAAK,kBAAkB;AACxC,QAAM,WAAW,KAAK,IAAI,KAAK,KAAK,iBAAiB;AACrD,aAAW,IAAI,IAAI,yEAAyE;AAAA,IAC1F,MAAM,IAAI,MAAM;AAAA,EAClB,CAAC;AACD,SAAO,KAAK,IAAI,IAAI,UAAU;AAC5B,UAAM,MAAM,QAAQ;AACpB,UAAM,UAAU,MAAM,mBAAmB,MAAM,MAAM;AACrD,QAAI,YAAY,UAAa,UAAU,aAAc,QAAO;AAAA,EAC9D;AACA,SAAO;AACT;","names":["webcrypto","subtle","webcrypto"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
STDIN_TIMEOUT_MS,
|
|
4
|
+
runHookCommand,
|
|
5
|
+
runHookKind
|
|
6
|
+
} from "./chunk-MNXS2U45.js";
|
|
7
|
+
import "./chunk-OHRR5OYM.js";
|
|
8
|
+
import "./chunk-JKKAIPTU.js";
|
|
9
|
+
import "./chunk-KXQ4UIP7.js";
|
|
10
|
+
import "./chunk-WK7F3B2E.js";
|
|
11
|
+
import "./chunk-UKY4CHNC.js";
|
|
12
|
+
import "./chunk-3623BLPV.js";
|
|
13
|
+
import "./chunk-WJXLQXJY.js";
|
|
14
|
+
import "./chunk-XKESD27X.js";
|
|
15
|
+
import "./chunk-4ZZO6ULA.js";
|
|
16
|
+
import "./chunk-2SNUOHAT.js";
|
|
17
|
+
import "./chunk-7QKHZQKW.js";
|
|
18
|
+
import "./chunk-P4NH7OUK.js";
|
|
19
|
+
import "./chunk-YFPY4ONH.js";
|
|
20
|
+
import "./chunk-I3EQFHCD.js";
|
|
21
|
+
import "./chunk-S4SAZ7OD.js";
|
|
22
|
+
import "./chunk-AGZ7PJKY.js";
|
|
23
|
+
import "./chunk-2I4QTOLB.js";
|
|
24
|
+
import "./chunk-7WU4OPLP.js";
|
|
25
|
+
import "./chunk-Y527D4TV.js";
|
|
26
|
+
import "./chunk-YVFXE7RR.js";
|
|
27
|
+
import "./chunk-XQJXNMSB.js";
|
|
28
|
+
import "./chunk-3UCIG4TG.js";
|
|
29
|
+
import "./chunk-27EPWVOY.js";
|
|
30
|
+
import "./chunk-7WEQQJLG.js";
|
|
31
|
+
import "./chunk-SJLTEINJ.js";
|
|
32
|
+
import "./chunk-5C32RLTA.js";
|
|
33
|
+
import "./chunk-ZXTAQYNA.js";
|
|
34
|
+
export {
|
|
35
|
+
STDIN_TIMEOUT_MS,
|
|
36
|
+
runHookCommand,
|
|
37
|
+
runHookKind
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=hook-command-4TYCHHRL.js.map
|
|
@@ -6,14 +6,14 @@
|
|
|
6
6
|
},
|
|
7
7
|
"description": "Tenjin's tool router for Claude Code, installed by `tenjin install`.",
|
|
8
8
|
"metadata": {
|
|
9
|
-
"version": "0.1.0-alpha.
|
|
9
|
+
"version": "0.1.0-alpha.31"
|
|
10
10
|
},
|
|
11
11
|
"plugins": [
|
|
12
12
|
{
|
|
13
13
|
"name": "tenjin",
|
|
14
14
|
"source": "./tenjin",
|
|
15
15
|
"description": "Tenjin picks the right tool when your agent needs one, and one wallet on this machine pays for every call.",
|
|
16
|
-
"version": "0.1.0-alpha.
|
|
16
|
+
"version": "0.1.0-alpha.31"
|
|
17
17
|
}
|
|
18
18
|
]
|
|
19
19
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tenjin",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.31",
|
|
4
4
|
"description": "Tenjin picks the right tool when your agent needs one, and one wallet on this machine pays for every call.",
|
|
5
|
+
"types": "./types/index.d.ts",
|
|
5
6
|
"author": {
|
|
6
7
|
"name": "Tenjin",
|
|
7
8
|
"url": "https://tenjin.sh"
|
|
@@ -9,6 +10,6 @@
|
|
|
9
10
|
"homepage": "https://tenjin.sh/agents",
|
|
10
11
|
"repository": "https://github.com/BackTrackCo/tenjin-agent",
|
|
11
12
|
"metadata": {
|
|
12
|
-
"tenjin-cli": "0.1.0-alpha.
|
|
13
|
+
"tenjin-cli": "0.1.0-alpha.31"
|
|
13
14
|
}
|
|
14
15
|
}
|