tenjin-cli 0.1.0-alpha.14 → 0.1.0-alpha.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE.md +54 -7
- package/README.md +41 -295
- package/dist/{_esm-N4KAVXQR.js → _esm-CE7KNONL.js} +9 -10
- package/dist/{ccip-ZGGWQN4X.js → ccip-7RMRLAGV.js} +4 -4
- package/dist/{ccip-RPPPKTJR.js → ccip-NLCSCHKI.js} +5 -5
- package/dist/chunk-25TJPVBF.js +353 -0
- package/dist/chunk-25TJPVBF.js.map +1 -0
- package/dist/chunk-2BKS2FVE.js +93 -0
- package/dist/chunk-2BKS2FVE.js.map +1 -0
- package/dist/chunk-2QYORQBF.js +55 -0
- package/dist/chunk-2QYORQBF.js.map +1 -0
- package/dist/{chunk-ACBEHJAH.js → chunk-2U5ZVEV3.js} +14 -16
- package/dist/chunk-2U5ZVEV3.js.map +1 -0
- package/dist/{chunk-MJSXP4LW.js → chunk-3AJS6LLN.js} +11 -8
- package/dist/chunk-3AJS6LLN.js.map +1 -0
- package/dist/{chunk-OWVVI4VQ.js → chunk-3AUDA53C.js} +7650 -7361
- package/dist/chunk-3AUDA53C.js.map +1 -0
- package/dist/{chunk-MJZZTKCC.js → chunk-56MOAIP5.js} +5 -10
- package/dist/chunk-56MOAIP5.js.map +1 -0
- package/dist/{chunk-U5S527PP.js → chunk-5IEP5EGE.js} +3 -3
- package/dist/chunk-5X4SZ5BF.js +227 -0
- package/dist/chunk-5X4SZ5BF.js.map +1 -0
- package/dist/chunk-7WEQQJLG.js +68 -0
- package/dist/chunk-7WEQQJLG.js.map +1 -0
- package/dist/{chunk-7FK2UN2T.js → chunk-AWQPGIR6.js} +65 -67
- package/dist/{chunk-7FK2UN2T.js.map → chunk-AWQPGIR6.js.map} +1 -1
- package/dist/{chunk-PAOVPSP6.js → chunk-BBVUVBUO.js} +517 -138
- package/dist/chunk-BBVUVBUO.js.map +1 -0
- package/dist/{chunk-ETKZWJ4B.js → chunk-BFFM2WFK.js} +8 -8
- package/dist/chunk-BFFM2WFK.js.map +1 -0
- package/dist/{chunk-KYQVEKP5.js → chunk-BPMWXTFX.js} +8 -8
- package/dist/chunk-DMZZLPZN.js +205 -0
- package/dist/chunk-DMZZLPZN.js.map +1 -0
- package/dist/{chunk-47PP7TAG.js → chunk-EGELTSPU.js} +1356 -1356
- package/dist/chunk-EGELTSPU.js.map +1 -0
- package/dist/chunk-GULLJQXA.js +698 -0
- package/dist/chunk-GULLJQXA.js.map +1 -0
- package/dist/{chunk-S5RYMCV6.js → chunk-HPWO4O6S.js} +3 -3
- package/dist/chunk-HVRC33OL.js +174 -0
- package/dist/chunk-HVRC33OL.js.map +1 -0
- package/dist/{chunk-W6R3HAAG.js → chunk-JRGFKVAZ.js} +2 -2
- package/dist/{chunk-XJN5WUKL.js → chunk-KG3D7FIF.js} +2 -2
- package/dist/chunk-L3PVMIYQ.js +10328 -0
- package/dist/chunk-L3PVMIYQ.js.map +1 -0
- package/dist/{chunk-QW2Q2KAH.js → chunk-LHHMV4GU.js} +2 -2
- package/dist/{chunk-ZOBNS7CX.js → chunk-MEFB5KHA.js} +4 -18
- package/dist/chunk-MEFB5KHA.js.map +1 -0
- package/dist/{chunk-M2O56UK7.js → chunk-N35E6CM2.js} +293 -163
- package/dist/chunk-N35E6CM2.js.map +1 -0
- package/dist/chunk-OCBHUHWB.js +69 -0
- package/dist/chunk-OCBHUHWB.js.map +1 -0
- package/dist/chunk-OIM4HLN6.js +1405 -0
- package/dist/chunk-OIM4HLN6.js.map +1 -0
- package/dist/{chunk-PKW3H26Z.js → chunk-OJLYNM4Z.js} +56 -33
- package/dist/chunk-OJLYNM4Z.js.map +1 -0
- package/dist/{chunk-POJRB2AE.js → chunk-POUWHWID.js} +2 -2
- package/dist/chunk-PZEN5PHN.js +285 -0
- package/dist/chunk-PZEN5PHN.js.map +1 -0
- package/dist/chunk-SKAHDQH7.js +1785 -0
- package/dist/chunk-SKAHDQH7.js.map +1 -0
- package/dist/{chunk-KZAAWQNP.js → chunk-TTNESUPQ.js} +3 -3
- package/dist/{chunk-QWBUKIP2.js → chunk-U5DXNFJC.js} +23 -94
- package/dist/chunk-U5DXNFJC.js.map +1 -0
- package/dist/chunk-USS336NF.js +165 -0
- package/dist/chunk-USS336NF.js.map +1 -0
- package/dist/{chunk-UO22YNY4.js → chunk-WH7OWT6G.js} +49 -1
- package/dist/chunk-WH7OWT6G.js.map +1 -0
- package/dist/chunk-WXC57XGG.js +29 -0
- package/dist/chunk-WXC57XGG.js.map +1 -0
- package/dist/{chunk-YLYINX2H.js → chunk-XZKD7DIF.js} +3 -3
- package/dist/{chunk-7GJQ5RGA.js → chunk-YEETV6IW.js} +1077 -1039
- package/dist/chunk-YEETV6IW.js.map +1 -0
- package/dist/{chunk-B676GPS2.js → chunk-YJHHCWM3.js} +39 -16
- package/dist/chunk-YJHHCWM3.js.map +1 -0
- package/dist/{cli-U2BEUA55.js → cli-M3XCSOU6.js} +295 -349
- package/dist/cli-M3XCSOU6.js.map +1 -0
- package/dist/config-MXOX7XDR.js +41 -0
- package/dist/{dist-U4M6QCKE.js → dist-3LOO6M4U.js} +10 -10
- package/dist/doctor-LU4YIZWM.js +349 -0
- package/dist/doctor-LU4YIZWM.js.map +1 -0
- package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
- package/dist/{chunk-3ZW7HPY5.js → fund-A54P2QFK.js} +81 -22
- package/dist/fund-A54P2QFK.js.map +1 -0
- package/dist/hook-command-U6KWPEDQ.js +377 -0
- package/dist/hook-command-U6KWPEDQ.js.map +1 -0
- package/dist/index.js +8 -3
- package/dist/index.js.map +1 -1
- package/dist/install-XUM2XSHW.js +53 -0
- package/dist/install-wallet-QIOFORTX.js +105 -0
- package/dist/install-wallet-QIOFORTX.js.map +1 -0
- package/dist/{run-CJWPGMIQ.js → mcp-HJC2PLRV.js} +3725 -10661
- package/dist/mcp-HJC2PLRV.js.map +1 -0
- package/dist/paths-P2N4JTDZ.js +49 -0
- package/dist/pay-SBXZEPEP.js +37 -0
- package/dist/redact-46ZHF2NH.js +17 -0
- package/dist/{secp256k1-XRPVBC6V.js → secp256k1-ZZZT2CAX.js} +3 -3
- package/dist/{send-C5EOKXOU.js → send-ASD2ZXJD.js} +28 -30
- package/dist/send-ASD2ZXJD.js.map +1 -0
- package/dist/{chunk-NAAMHWSI.js → skill-placement-NFVHY6A3.js} +159 -12
- package/dist/skill-placement-NFVHY6A3.js.map +1 -0
- package/dist/status-T2SDB57A.js +63 -0
- package/dist/status-T2SDB57A.js.map +1 -0
- package/dist/status-line-CGPUSDMC.js +71 -0
- package/dist/status-line-CGPUSDMC.js.map +1 -0
- package/dist/status-line-wiring-BYPHTYZE.js +30 -0
- package/dist/tenjin-daemon.mjs +20060 -0
- package/dist/tenjin-shim.mjs +251 -0
- package/dist/tenjin-vitest-reporter.mjs +49 -0
- package/dist/uninstall-FKYZHAM3.js +144 -0
- package/dist/uninstall-FKYZHAM3.js.map +1 -0
- package/dist/{update-24Y2CQTT.js → update-ANJ2AOTN.js} +133 -17
- package/dist/update-ANJ2AOTN.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-TUQJBMHM.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
- package/dist/wallet-PWAHVKWW.js +31 -0
- package/dist/wallet-kdf-worker.mjs +980 -0
- package/docs/agent-permissions.md +68 -342
- package/docs/safety-model.md +25 -6
- package/package.json +8 -7
- package/LICENSE +0 -21
- package/dist/buy-2JBYPHAI.js +0 -46
- package/dist/chunk-3P3ES4XU.js +0 -144
- package/dist/chunk-3P3ES4XU.js.map +0 -1
- package/dist/chunk-3ZW7HPY5.js.map +0 -1
- package/dist/chunk-47PP7TAG.js.map +0 -1
- package/dist/chunk-4UHNXY6B.js +0 -786
- package/dist/chunk-4UHNXY6B.js.map +0 -1
- package/dist/chunk-4Y53PDH6.js +0 -213
- package/dist/chunk-4Y53PDH6.js.map +0 -1
- package/dist/chunk-54AJIO3E.js +0 -198
- package/dist/chunk-54AJIO3E.js.map +0 -1
- package/dist/chunk-736DW4V3.js +0 -65
- package/dist/chunk-736DW4V3.js.map +0 -1
- package/dist/chunk-7GJQ5RGA.js.map +0 -1
- package/dist/chunk-7NADDA2V.js +0 -161
- package/dist/chunk-7NADDA2V.js.map +0 -1
- package/dist/chunk-ACBEHJAH.js.map +0 -1
- package/dist/chunk-B676GPS2.js.map +0 -1
- package/dist/chunk-DAZAXFSF.js +0 -1357
- package/dist/chunk-DAZAXFSF.js.map +0 -1
- package/dist/chunk-DTCXO7HS.js +0 -791
- package/dist/chunk-DTCXO7HS.js.map +0 -1
- package/dist/chunk-ETKZWJ4B.js.map +0 -1
- package/dist/chunk-FDUD3W5V.js +0 -317
- package/dist/chunk-FDUD3W5V.js.map +0 -1
- package/dist/chunk-GEHL43VE.js +0 -711
- package/dist/chunk-GEHL43VE.js.map +0 -1
- package/dist/chunk-IU2HVT3Y.js +0 -313
- package/dist/chunk-IU2HVT3Y.js.map +0 -1
- package/dist/chunk-IUQZ4Z7M.js +0 -162
- package/dist/chunk-IUQZ4Z7M.js.map +0 -1
- package/dist/chunk-IXZJ3JOO.js +0 -614
- package/dist/chunk-IXZJ3JOO.js.map +0 -1
- package/dist/chunk-J6FUAIRR.js +0 -205
- package/dist/chunk-J6FUAIRR.js.map +0 -1
- package/dist/chunk-L6G35FU5.js +0 -105
- package/dist/chunk-L6G35FU5.js.map +0 -1
- package/dist/chunk-LSWP7MU2.js +0 -290
- package/dist/chunk-LSWP7MU2.js.map +0 -1
- package/dist/chunk-M2O56UK7.js.map +0 -1
- package/dist/chunk-MJSXP4LW.js.map +0 -1
- package/dist/chunk-MJZZTKCC.js.map +0 -1
- package/dist/chunk-NAAMHWSI.js.map +0 -1
- package/dist/chunk-O75FOHXS.js +0 -372
- package/dist/chunk-O75FOHXS.js.map +0 -1
- package/dist/chunk-OWVVI4VQ.js.map +0 -1
- package/dist/chunk-PAOVPSP6.js.map +0 -1
- package/dist/chunk-PCX2JQ2J.js +0 -233
- package/dist/chunk-PCX2JQ2J.js.map +0 -1
- package/dist/chunk-PKW3H26Z.js.map +0 -1
- package/dist/chunk-PQZVDCCA.js +0 -125
- package/dist/chunk-PQZVDCCA.js.map +0 -1
- package/dist/chunk-QWBUKIP2.js.map +0 -1
- package/dist/chunk-SGK2B724.js +0 -67
- package/dist/chunk-SGK2B724.js.map +0 -1
- package/dist/chunk-UHTVXQ2O.js +0 -140
- package/dist/chunk-UHTVXQ2O.js.map +0 -1
- package/dist/chunk-UO22YNY4.js.map +0 -1
- package/dist/chunk-VEAERJVJ.js +0 -43
- package/dist/chunk-VEAERJVJ.js.map +0 -1
- package/dist/chunk-VRPLZERE.js +0 -1421
- package/dist/chunk-VRPLZERE.js.map +0 -1
- package/dist/chunk-W4VW5XYB.js +0 -149
- package/dist/chunk-W4VW5XYB.js.map +0 -1
- package/dist/chunk-WU5CZPLD.js +0 -145
- package/dist/chunk-WU5CZPLD.js.map +0 -1
- package/dist/chunk-WYLMJQVH.js +0 -240
- package/dist/chunk-WYLMJQVH.js.map +0 -1
- package/dist/chunk-XGZ5EVMB.js +0 -35
- package/dist/chunk-XGZ5EVMB.js.map +0 -1
- package/dist/chunk-XVPQGCH4.js +0 -176
- package/dist/chunk-XVPQGCH4.js.map +0 -1
- package/dist/chunk-ZOBNS7CX.js.map +0 -1
- package/dist/chunk-ZQIQ55KK.js +0 -51
- package/dist/chunk-ZQIQ55KK.js.map +0 -1
- package/dist/cli-U2BEUA55.js.map +0 -1
- package/dist/config-CNUIX23Q.js +0 -32
- package/dist/doctor-QJJXRWTO.js +0 -31
- package/dist/edit-HJ44P44P.js +0 -40
- package/dist/fund-Y5IAHZ5D.js +0 -40
- package/dist/inspect-NFQ6SQQQ.js +0 -37
- package/dist/install-DXX7PVUP.js +0 -854
- package/dist/install-DXX7PVUP.js.map +0 -1
- package/dist/outcome-ANV4QIED.js +0 -24
- package/dist/publish-PCBTCXCZ.js +0 -42
- package/dist/read-W7QVRBVD.js +0 -160
- package/dist/read-W7QVRBVD.js.map +0 -1
- package/dist/run-CJWPGMIQ.js.map +0 -1
- package/dist/search-JGAVKTYJ.js +0 -25
- package/dist/secp256k1-XRPVBC6V.js.map +0 -1
- package/dist/send-C5EOKXOU.js.map +0 -1
- package/dist/session-OBCUUIFX.js +0 -89
- package/dist/session-OBCUUIFX.js.map +0 -1
- package/dist/skill-heal-D6EPLPS6.js +0 -84
- package/dist/skill-heal-D6EPLPS6.js.map +0 -1
- package/dist/uninstall-OWJNJ5LI.js +0 -73
- package/dist/uninstall-OWJNJ5LI.js.map +0 -1
- package/dist/update-24Y2CQTT.js.map +0 -1
- package/dist/usdc-4VCDHFWX.js +0 -38
- package/dist/usdc-4VCDHFWX.js.map +0 -1
- package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +0 -1
- package/dist/wallet-OFXDIIGP.js +0 -33
- package/dist/wallet-OFXDIIGP.js.map +0 -1
- package/dist/wallet-SLRIYJ2U.js +0 -42
- package/dist/wallet-SLRIYJ2U.js.map +0 -1
- package/docs/command-reference.md +0 -261
- package/skills/tenjin/SKILL.md +0 -364
- package/skills/tenjin-publish/SKILL.md +0 -224
- package/skills/tenjin-publish/references/maintain.md +0 -39
- package/skills/tenjin-search/SKILL.md +0 -149
- package/skills/tenjin-search/references/permissions.md +0 -106
- /package/dist/{_esm-N4KAVXQR.js.map → _esm-CE7KNONL.js.map} +0 -0
- /package/dist/{buy-2JBYPHAI.js.map → ccip-7RMRLAGV.js.map} +0 -0
- /package/dist/{ccip-RPPPKTJR.js.map → ccip-NLCSCHKI.js.map} +0 -0
- /package/dist/{chunk-U5S527PP.js.map → chunk-5IEP5EGE.js.map} +0 -0
- /package/dist/{chunk-KYQVEKP5.js.map → chunk-BPMWXTFX.js.map} +0 -0
- /package/dist/{chunk-S5RYMCV6.js.map → chunk-HPWO4O6S.js.map} +0 -0
- /package/dist/{chunk-W6R3HAAG.js.map → chunk-JRGFKVAZ.js.map} +0 -0
- /package/dist/{chunk-XJN5WUKL.js.map → chunk-KG3D7FIF.js.map} +0 -0
- /package/dist/{chunk-QW2Q2KAH.js.map → chunk-LHHMV4GU.js.map} +0 -0
- /package/dist/{chunk-POJRB2AE.js.map → chunk-POUWHWID.js.map} +0 -0
- /package/dist/{chunk-KZAAWQNP.js.map → chunk-TTNESUPQ.js.map} +0 -0
- /package/dist/{chunk-YLYINX2H.js.map → chunk-XZKD7DIF.js.map} +0 -0
- /package/dist/{ccip-ZGGWQN4X.js.map → config-MXOX7XDR.js.map} +0 -0
- /package/dist/{dist-U4M6QCKE.js.map → dist-3LOO6M4U.js.map} +0 -0
- /package/dist/{config-CNUIX23Q.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
- /package/dist/{doctor-QJJXRWTO.js.map → install-XUM2XSHW.js.map} +0 -0
- /package/dist/{edit-HJ44P44P.js.map → paths-P2N4JTDZ.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js.map → pay-SBXZEPEP.js.map} +0 -0
- /package/dist/{fund-Y5IAHZ5D.js.map → redact-46ZHF2NH.js.map} +0 -0
- /package/dist/{inspect-NFQ6SQQQ.js.map → secp256k1-ZZZT2CAX.js.map} +0 -0
- /package/dist/{outcome-ANV4QIED.js.map → status-line-wiring-BYPHTYZE.js.map} +0 -0
- /package/dist/{publish-PCBTCXCZ.js.map → viemAdapter-By13KInL-X2VY6CY3.js.map} +0 -0
- /package/dist/{search-JGAVKTYJ.js.map → wallet-PWAHVKWW.js.map} +0 -0
|
@@ -0,0 +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.blog/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.blog/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET 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';\n\n/**\n * Open a URL in the platform's 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 * 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}\n\nconst OPEN_TIMEOUT_MS = 5000;\n\nexport function openerFor(platform: NodeJS.Platform): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: 'open', args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n return { cmd: 'xdg-open', args: [] };\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const { cmd, args } = openerFor(opts.platform ?? process.platform);\n const run = opts.execFileImpl ?? execFile;\n return await new Promise((resolve) => {\n run(cmd, [...args, url], { timeout: OPEN_TIMEOUT_MS, windowsHide: true }, (err) =>\n resolve(err === null),\n );\n });\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 { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin wallet fund`: card-fund THIS wallet via Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend to mint a\n * Coinbase-hosted checkout URL for that same address (the server refuses any\n * other address, per Coinbase's onboarding-verified auth model). The money\n * moves entirely on Coinbase's side; the minted session grants no spending\n * power over the wallet. Two Coinbase properties shape the UX here: the URL is\n * single-use and expires in ~5 minutes (mint fresh per run, open immediately,\n * never persist), and it is bound to this machine's public IP at mint time, so\n * it must be opened in a browser on this machine/network.\n */\n\n/** The only host a minted checkout URL may point at; anything else is refused unopened. */\nconst 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/** Matches the server's presetAmount bound (app/api/cdp/session bodySchema). */\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 /** 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 mode: 'onramp',\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/cdp/session`, 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 emitWriteNotice(ctx.io, `Coinbase Onramp checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\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 );\n\n let opened = false;\n if (opts.open !== false && ctx.io.isTTY) {\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 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 Coinbase's\n * checkout host before anything else sees it: a compromised or misconfigured\n * server must not be able to steer the 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 (parsed !== undefined && parsed.protocol === 'https:' && parsed.host === CHECKOUT_HOST) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https://${CHECKOUT_HOST}; 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;AAoD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AAA,EACH;AACA,MAAI,WAAW,KAAK;AAClB,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,QACE,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACA,QAAM,IAAI;AAAA,IACR;AAAA,IACA,iCAAiC,MAAM,GAAG,SAAS,SAAY,KAAK,IAAI,MAAM,EAAE;AAAA,IAChF,EAAE,KAAK,mDAAmD;AAAA,EAC5D;AACF;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,377 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
ROUTER_PATH,
|
|
4
|
+
requestDecision
|
|
5
|
+
} from "./chunk-USS336NF.js";
|
|
6
|
+
import "./chunk-5X4SZ5BF.js";
|
|
7
|
+
import {
|
|
8
|
+
mask
|
|
9
|
+
} from "./chunk-OIM4HLN6.js";
|
|
10
|
+
import {
|
|
11
|
+
bindDecision,
|
|
12
|
+
newCallId,
|
|
13
|
+
noteSession,
|
|
14
|
+
pruneProgress,
|
|
15
|
+
pruneSessions,
|
|
16
|
+
sessionDir,
|
|
17
|
+
writeProgress
|
|
18
|
+
} from "./chunk-PZEN5PHN.js";
|
|
19
|
+
import {
|
|
20
|
+
external_exports,
|
|
21
|
+
loadRawConfig,
|
|
22
|
+
resolveSettings
|
|
23
|
+
} from "./chunk-BBVUVBUO.js";
|
|
24
|
+
import "./chunk-BFFM2WFK.js";
|
|
25
|
+
import "./chunk-OCBHUHWB.js";
|
|
26
|
+
import "./chunk-2BKS2FVE.js";
|
|
27
|
+
import "./chunk-7WEQQJLG.js";
|
|
28
|
+
import "./chunk-ZXTAQYNA.js";
|
|
29
|
+
|
|
30
|
+
// src/router/context.ts
|
|
31
|
+
import { open } from "node:fs/promises";
|
|
32
|
+
var MAX_HISTORY = 6;
|
|
33
|
+
var MAX_PACKET_BYTES = 16 * 1024;
|
|
34
|
+
var MAX_MESSAGE_CHARS = 16e3;
|
|
35
|
+
var MAX_TRANSCRIPT_BYTES = 4e6;
|
|
36
|
+
var MAX_LITERAL_URLS = 8;
|
|
37
|
+
var MAX_LITERAL_URL_CHARS = 2e3;
|
|
38
|
+
var URL_RE = /\bhttps?:\/\/[^\s<>"'`)\]]+/gi;
|
|
39
|
+
function literalUrlsIn(text) {
|
|
40
|
+
const found = /* @__PURE__ */ new Set();
|
|
41
|
+
for (const match of text.matchAll(URL_RE)) {
|
|
42
|
+
const candidate = match[0].replace(/[.,;:!?]+$/, "");
|
|
43
|
+
try {
|
|
44
|
+
const normalized = new URL(candidate).toString();
|
|
45
|
+
if (normalized.length <= MAX_LITERAL_URL_CHARS) found.add(normalized);
|
|
46
|
+
} catch {
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (found.size >= MAX_LITERAL_URLS) break;
|
|
50
|
+
}
|
|
51
|
+
return [...found];
|
|
52
|
+
}
|
|
53
|
+
function fit(packet) {
|
|
54
|
+
const size = (value) => Buffer.byteLength(JSON.stringify(value));
|
|
55
|
+
const next = { ...packet, history: packet.history.slice(-MAX_HISTORY) };
|
|
56
|
+
while (next.history.length > 0 && size(next) > MAX_PACKET_BYTES) {
|
|
57
|
+
next.history = next.history.slice(1);
|
|
58
|
+
}
|
|
59
|
+
while (next.literalUrls.length > 0 && size(next) > MAX_PACKET_BYTES) {
|
|
60
|
+
next.literalUrls = next.literalUrls.slice(0, -1);
|
|
61
|
+
}
|
|
62
|
+
while (size(next) > MAX_PACKET_BYTES && next.current.text.length > 1) {
|
|
63
|
+
const over = size(next) - MAX_PACKET_BYTES;
|
|
64
|
+
const keep = Math.max(1, next.current.text.length - Math.max(over, 1));
|
|
65
|
+
next.current = { ...next.current, text: next.current.text.slice(0, keep) };
|
|
66
|
+
}
|
|
67
|
+
return next;
|
|
68
|
+
}
|
|
69
|
+
async function buildPromptPacket(transcriptPath, sessionId, prompt) {
|
|
70
|
+
const masked = mask(prompt.trim()).slice(0, MAX_MESSAGE_CHARS);
|
|
71
|
+
const text = masked.length > 0 ? masked : "(empty prompt)";
|
|
72
|
+
const read = await readHistory(transcriptPath, sessionId);
|
|
73
|
+
return fit({
|
|
74
|
+
current: { role: "user", text },
|
|
75
|
+
history: read ?? [],
|
|
76
|
+
literalUrls: literalUrlsIn(text),
|
|
77
|
+
historyStatus: read === null ? "unavailable" : "ok"
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
async function buildNativePacket(transcriptPath, sessionId, pending) {
|
|
81
|
+
const subject = "query" in pending ? pending.query : pending.url;
|
|
82
|
+
const read = await readHistory(transcriptPath, sessionId);
|
|
83
|
+
const messages = read ?? [];
|
|
84
|
+
const lastUser = messages.map((message, index) => ({ message, index })).filter((entry) => entry.message.role === "user");
|
|
85
|
+
const current = lastUser.at(-1);
|
|
86
|
+
const bounded = mask(subject).slice(0, MAX_MESSAGE_CHARS);
|
|
87
|
+
return fit({
|
|
88
|
+
current: current?.message ?? { role: "user", text: bounded },
|
|
89
|
+
history: current === void 0 ? messages : messages.slice(0, current.index),
|
|
90
|
+
literalUrls: literalUrlsIn(`${current?.message.text ?? ""}
|
|
91
|
+
${bounded}`),
|
|
92
|
+
historyStatus: read === null ? "unavailable" : "ok",
|
|
93
|
+
pendingCall: pending
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
async function readHistory(path, sessionId) {
|
|
97
|
+
if (path === void 0 || path.length === 0) return null;
|
|
98
|
+
let raw;
|
|
99
|
+
let file;
|
|
100
|
+
try {
|
|
101
|
+
file = await open(path, "r");
|
|
102
|
+
} catch {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
const stat = await file.stat();
|
|
107
|
+
if (!stat.isFile() || stat.size > MAX_TRANSCRIPT_BYTES) return null;
|
|
108
|
+
const buffer = Buffer.alloc(MAX_TRANSCRIPT_BYTES + 1);
|
|
109
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
110
|
+
if (bytesRead > MAX_TRANSCRIPT_BYTES) return null;
|
|
111
|
+
raw = buffer.subarray(0, bytesRead).toString("utf8");
|
|
112
|
+
} catch {
|
|
113
|
+
return null;
|
|
114
|
+
} finally {
|
|
115
|
+
await file.close();
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
return parseRows(raw, sessionId);
|
|
119
|
+
} catch {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function parseRows(raw, sessionId) {
|
|
124
|
+
let messages = [];
|
|
125
|
+
for (const line of raw.split("\n")) {
|
|
126
|
+
if (line.trim().length === 0) continue;
|
|
127
|
+
let row;
|
|
128
|
+
try {
|
|
129
|
+
row = JSON.parse(line);
|
|
130
|
+
} catch {
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (row === null || typeof row !== "object" || Array.isArray(row)) continue;
|
|
134
|
+
if (row.type === "system" && row.subtype === "compact_boundary") {
|
|
135
|
+
messages = [];
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (typeof row.sessionId === "string" && row.sessionId !== sessionId) continue;
|
|
139
|
+
if (row.isSidechain === true) continue;
|
|
140
|
+
if (row.type !== "user" && row.type !== "assistant") continue;
|
|
141
|
+
if (row.sessionId !== sessionId) continue;
|
|
142
|
+
let text;
|
|
143
|
+
try {
|
|
144
|
+
text = textOf(row.message);
|
|
145
|
+
} catch {
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const bounded = mask(text).slice(0, MAX_MESSAGE_CHARS);
|
|
149
|
+
if (bounded.length > 0) messages.push({ role: row.type, text: bounded });
|
|
150
|
+
}
|
|
151
|
+
return messages;
|
|
152
|
+
}
|
|
153
|
+
function textOf(message) {
|
|
154
|
+
if (message === null || typeof message !== "object" || Array.isArray(message)) {
|
|
155
|
+
throw new Error("malformed message");
|
|
156
|
+
}
|
|
157
|
+
const content = message.content;
|
|
158
|
+
if (typeof content === "string") return content;
|
|
159
|
+
if (!Array.isArray(content)) throw new Error("malformed content");
|
|
160
|
+
const parts = [];
|
|
161
|
+
for (const part of content) {
|
|
162
|
+
if (part === null || typeof part !== "object" || typeof part.type !== "string") {
|
|
163
|
+
throw new Error("malformed block");
|
|
164
|
+
}
|
|
165
|
+
const block = part;
|
|
166
|
+
if (block.type !== "text") continue;
|
|
167
|
+
if (typeof block.text !== "string") throw new Error("malformed text block");
|
|
168
|
+
parts.push(block.text);
|
|
169
|
+
}
|
|
170
|
+
return parts.join("\n");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// src/router/gate.ts
|
|
174
|
+
var GATE_TIMEOUT_MS = 3500;
|
|
175
|
+
|
|
176
|
+
// src/router/hooks.ts
|
|
177
|
+
var PromptEventSchema = external_exports.object({
|
|
178
|
+
session_id: external_exports.string().min(1).max(200),
|
|
179
|
+
transcript_path: external_exports.string().optional(),
|
|
180
|
+
prompt: external_exports.string()
|
|
181
|
+
});
|
|
182
|
+
var NativeEventSchema = external_exports.object({
|
|
183
|
+
session_id: external_exports.string().min(1).max(200),
|
|
184
|
+
/** The harness's own path for THIS session: the native decision reads the
|
|
185
|
+
* same bounded history the prompt one does, so a restriction the user gave
|
|
186
|
+
* reaches both gates. */
|
|
187
|
+
transcript_path: external_exports.string().optional(),
|
|
188
|
+
tool_name: external_exports.enum(["WebSearch", "WebFetch"]),
|
|
189
|
+
tool_input: external_exports.record(external_exports.string(), external_exports.unknown())
|
|
190
|
+
});
|
|
191
|
+
var ACKNOWLEDGEMENTS = /* @__PURE__ */ new Set(["y", "yes", "ok", "okay", "continue", "go", "sure", "thanks"]);
|
|
192
|
+
function promptSkipReason(prompt) {
|
|
193
|
+
const trimmed = prompt.trim();
|
|
194
|
+
if (trimmed.startsWith("/")) return "slash";
|
|
195
|
+
const normalized = trimmed.toLowerCase().replace(/[.!,]+$/, "");
|
|
196
|
+
return ACKNOWLEDGEMENTS.has(normalized) ? "acknowledgement" : null;
|
|
197
|
+
}
|
|
198
|
+
async function resolveBaseUrl(deps) {
|
|
199
|
+
if (deps.baseUrl !== void 0) return deps.baseUrl;
|
|
200
|
+
const config = await loadRawConfig(deps.dataDir).catch(() => ({}));
|
|
201
|
+
return resolveSettings({ config, flags: {}, env: deps.env ?? process.env }).baseUrl.value;
|
|
202
|
+
}
|
|
203
|
+
async function runPromptHook(raw, deps) {
|
|
204
|
+
const parsed = PromptEventSchema.safeParse(raw);
|
|
205
|
+
if (!parsed.success) return { response: null };
|
|
206
|
+
const event = parsed.data;
|
|
207
|
+
const skipped = promptSkipReason(event.prompt);
|
|
208
|
+
if (skipped !== null) return { response: null, skipped };
|
|
209
|
+
const packet = await buildPromptPacket(event.transcript_path, event.session_id, event.prompt);
|
|
210
|
+
const footer = await openFooter(deps, event.session_id, "prompt");
|
|
211
|
+
const outcome = await decide(packet, deps);
|
|
212
|
+
await footer.close(outcome);
|
|
213
|
+
if (outcome === null) return { response: null };
|
|
214
|
+
if (outcome.action !== "execute") return { response: null, action: outcome.action };
|
|
215
|
+
return { action: "execute", id: outcome.id, ...injection(outcome.hint) };
|
|
216
|
+
}
|
|
217
|
+
function injection(line) {
|
|
218
|
+
return {
|
|
219
|
+
response: {
|
|
220
|
+
hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: line }
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
async function runNativeHook(raw, deps) {
|
|
225
|
+
const parsed = NativeEventSchema.safeParse(raw);
|
|
226
|
+
if (!parsed.success) return { response: null, decision: "allow" };
|
|
227
|
+
const event = parsed.data;
|
|
228
|
+
const pending = pendingCallOf(event.tool_name, event.tool_input);
|
|
229
|
+
if (pending === null) return { response: null, decision: "allow" };
|
|
230
|
+
const packet = await buildNativePacket(event.transcript_path, event.session_id, pending);
|
|
231
|
+
if (packet.historyStatus !== "ok") {
|
|
232
|
+
(deps.warn ?? ((line) => process.stderr.write(`${line}
|
|
233
|
+
`)))(
|
|
234
|
+
"tenjin hook: this session's transcript could not be read, so the native call runs unrouted"
|
|
235
|
+
);
|
|
236
|
+
return { response: null, decision: "allow" };
|
|
237
|
+
}
|
|
238
|
+
const footer = await openFooter(deps, event.session_id, "search");
|
|
239
|
+
const outcome = await decide(packet, deps);
|
|
240
|
+
await footer.close(outcome);
|
|
241
|
+
if (outcome === null || outcome.action !== "execute") {
|
|
242
|
+
return {
|
|
243
|
+
response: null,
|
|
244
|
+
decision: "allow",
|
|
245
|
+
...outcome !== null ? { action: outcome.action } : {}
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
response: {
|
|
250
|
+
hookSpecificOutput: {
|
|
251
|
+
hookEventName: "PreToolUse",
|
|
252
|
+
permissionDecision: "deny",
|
|
253
|
+
// THE SERVER'S LINE, VERBATIM. It already carries the id and, on a
|
|
254
|
+
// native call, the exact search or URL that was denied, so there is
|
|
255
|
+
// nothing left here to compose and nothing to trim.
|
|
256
|
+
permissionDecisionReason: outcome.hint
|
|
257
|
+
}
|
|
258
|
+
},
|
|
259
|
+
decision: "deny",
|
|
260
|
+
action: "execute",
|
|
261
|
+
id: outcome.id
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
async function openFooter(deps, sessionId, operation) {
|
|
265
|
+
const now = () => deps.now?.() ?? Date.now();
|
|
266
|
+
const directory = sessionDir(deps.dataDir, sessionId);
|
|
267
|
+
const callId = newCallId();
|
|
268
|
+
await noteSession(deps.dataDir, sessionId, now());
|
|
269
|
+
await writeProgress(
|
|
270
|
+
directory,
|
|
271
|
+
callId,
|
|
272
|
+
{ phase: "routing", operation, outcome: "selecting service" },
|
|
273
|
+
now()
|
|
274
|
+
);
|
|
275
|
+
await pruneProgress(directory, now());
|
|
276
|
+
await pruneSessions(deps.dataDir, now());
|
|
277
|
+
return {
|
|
278
|
+
close: async (decision) => {
|
|
279
|
+
await writeProgress(
|
|
280
|
+
directory,
|
|
281
|
+
callId,
|
|
282
|
+
{ phase: "done", operation, outcome: hookOutcome(decision) },
|
|
283
|
+
now()
|
|
284
|
+
);
|
|
285
|
+
if (decision !== null && decision.action === "execute") {
|
|
286
|
+
await bindDecision(deps.dataDir, sessionId, decision.id, now());
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
function hookOutcome(decision) {
|
|
292
|
+
if (decision === null) return "native tools (router unavailable)";
|
|
293
|
+
if (decision.action === "execute") return `paid lookup offered (${decision.provider})`;
|
|
294
|
+
if (decision.action === "native") return "native tools (no x402 payment)";
|
|
295
|
+
return "needs input";
|
|
296
|
+
}
|
|
297
|
+
async function decide(packet, deps) {
|
|
298
|
+
const baseUrl = await resolveBaseUrl(deps);
|
|
299
|
+
const warn = deps.warn ?? ((line) => process.stderr.write(`${line}
|
|
300
|
+
`));
|
|
301
|
+
const outcome = await requestDecision(
|
|
302
|
+
"hook",
|
|
303
|
+
{ packet },
|
|
304
|
+
{
|
|
305
|
+
ctx: {
|
|
306
|
+
flags: { json: true, timeout: deps.timeoutMs ?? GATE_TIMEOUT_MS },
|
|
307
|
+
dataDir: deps.dataDir,
|
|
308
|
+
io: { stdout: nullStream(), stderr: nullStream(), isTTY: false }
|
|
309
|
+
},
|
|
310
|
+
baseUrl,
|
|
311
|
+
timeoutMs: deps.timeoutMs ?? GATE_TIMEOUT_MS,
|
|
312
|
+
...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
|
|
313
|
+
}
|
|
314
|
+
);
|
|
315
|
+
if (outcome.status === "failed") {
|
|
316
|
+
warn(`tenjin hook: ${baseUrl}${ROUTER_PATH} ${outcome.reason}`);
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
return outcome.decision.decision;
|
|
320
|
+
}
|
|
321
|
+
function nullStream() {
|
|
322
|
+
return { write: () => true };
|
|
323
|
+
}
|
|
324
|
+
function pendingCallOf(tool, input) {
|
|
325
|
+
const value = tool === "WebSearch" ? input.query : input.url;
|
|
326
|
+
if (typeof value !== "string") return null;
|
|
327
|
+
const bounded = value.trim().slice(0, 4e3);
|
|
328
|
+
if (bounded.length === 0) return null;
|
|
329
|
+
return tool === "WebSearch" ? { tool, query: bounded } : { tool, url: bounded };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// src/router/hook-command.ts
|
|
333
|
+
var MAX_EVENT_BYTES = 1e6;
|
|
334
|
+
var STDIN_TIMEOUT_MS = 1e3;
|
|
335
|
+
async function runHookCommand(kind, io, deps) {
|
|
336
|
+
let response;
|
|
337
|
+
try {
|
|
338
|
+
const raw = await (deps.readEvent ?? readStdin)();
|
|
339
|
+
const event = JSON.parse(raw);
|
|
340
|
+
const outcome = kind === "prompt" ? await runPromptHook(event, deps) : await runNativeHook(event, deps);
|
|
341
|
+
response = outcome.response;
|
|
342
|
+
} catch {
|
|
343
|
+
response = null;
|
|
344
|
+
}
|
|
345
|
+
if (response !== null) io.stdout.write(`${JSON.stringify(response)}
|
|
346
|
+
`);
|
|
347
|
+
}
|
|
348
|
+
async function readStdin() {
|
|
349
|
+
return new Promise((resolve, reject) => {
|
|
350
|
+
const chunks = [];
|
|
351
|
+
let size = 0;
|
|
352
|
+
const timer = setTimeout(() => reject(new Error("no harness event")), STDIN_TIMEOUT_MS);
|
|
353
|
+
const done = (value) => {
|
|
354
|
+
clearTimeout(timer);
|
|
355
|
+
resolve(value);
|
|
356
|
+
};
|
|
357
|
+
process.stdin.on("data", (chunk) => {
|
|
358
|
+
size += chunk.length;
|
|
359
|
+
if (size > MAX_EVENT_BYTES) {
|
|
360
|
+
clearTimeout(timer);
|
|
361
|
+
reject(new Error("harness event too large"));
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
chunks.push(chunk);
|
|
365
|
+
});
|
|
366
|
+
process.stdin.once("end", () => done(Buffer.concat(chunks).toString("utf8")));
|
|
367
|
+
process.stdin.once("error", () => {
|
|
368
|
+
clearTimeout(timer);
|
|
369
|
+
reject(new Error("harness event unreadable"));
|
|
370
|
+
});
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
export {
|
|
374
|
+
STDIN_TIMEOUT_MS,
|
|
375
|
+
runHookCommand
|
|
376
|
+
};
|
|
377
|
+
//# sourceMappingURL=hook-command-U6KWPEDQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/context.ts","../src/router/gate.ts","../src/router/hooks.ts","../src/router/hook-command.ts"],"sourcesContent":["import { open } from 'node:fs/promises';\nimport { mask } from '../lib/redact';\n\n/**\n * The bounded conversation packet the router's gate and paid decision read.\n *\n * WHAT GOES IN IT: ordinary user and assistant text from the CURRENT session\n * only, redacted, at most {@link MAX_HISTORY} prior messages and at most\n * {@link MAX_PACKET_BYTES} in total, oldest dropped first. Tool results are\n * excluded: a tool result is other people's content, and a packet that carried\n * it would be a channel from a fetched page into a routing decision.\n *\n * WHAT NEVER HAPPENS: a transcript this reader cannot vouch for (another\n * session, a subagent sidechain, a compaction boundary, malformed rows, an\n * oversized file) is reported as `unavailable` rather than partially believed,\n * and the user's turn is never blocked by any of that. Adapted from the draft\n * auto-mode experiment (PR #369 `context.ts`), whose 48,000-character reader\n * this tightens.\n */\n\nexport const MAX_HISTORY = 6;\nexport const MAX_PACKET_BYTES = 16 * 1024;\n/** Every bound here is the server's own (tenjin `lib/x402-router/wire.ts`). A\n * packet this side lets through and that side refuses is a paid 400. */\nexport const MAX_MESSAGE_CHARS = 16_000;\nconst MAX_TRANSCRIPT_BYTES = 4_000_000;\nconst MAX_LITERAL_URLS = 8;\nconst MAX_LITERAL_URL_CHARS = 2_000;\n\nexport type PacketRole = 'user' | 'assistant';\nexport interface PacketMessage {\n role: PacketRole;\n text: string;\n}\n\nexport type HistoryStatus = 'ok' | 'unavailable';\n\nexport interface Packet {\n current: PacketMessage;\n history: PacketMessage[];\n /** Absolute http(s) URLs written literally in the current message. */\n literalUrls: string[];\n historyStatus: HistoryStatus;\n pendingCall?: PendingCall;\n}\n\n/** The pending native call, INSIDE the packet: the gate request is a strict\n * object with exactly `schemaVersion`, `source` and `packet`. */\nexport type PendingCall = { tool: 'WebSearch'; query: string } | { tool: 'WebFetch'; url: string };\n\nconst URL_RE = /\\bhttps?:\\/\\/[^\\s<>\"'`)\\]]+/gi;\n\nexport function literalUrlsIn(text: string): string[] {\n const found = new Set<string>();\n for (const match of text.matchAll(URL_RE)) {\n const candidate = match[0].replace(/[.,;:!?]+$/, '');\n try {\n const normalized = new URL(candidate).toString();\n if (normalized.length <= MAX_LITERAL_URL_CHARS) found.add(normalized);\n } catch {\n continue;\n }\n if (found.size >= MAX_LITERAL_URLS) break;\n }\n return [...found];\n}\n\n/**\n * Bring the packet inside the server's caps: oldest history first, then the\n * current message itself, measured on the WHOLE packet rather than on the two\n * message lists, because `literalUrls` and a pending call are bytes too.\n *\n * EXPORTED BECAUSE ATTACHING ANYTHING RE-OPENS THE QUESTION. A packet this\n * returned at exactly the cap is over it the moment a caller adds a field, and\n * the server refuses rather than truncates, so every caller that adds one runs\n * this again on what it is actually going to send.\n */\nexport function fit(packet: Packet): Packet {\n const size = (value: Packet): number => Buffer.byteLength(JSON.stringify(value));\n const next: Packet = { ...packet, history: packet.history.slice(-MAX_HISTORY) };\n // In order of what is cheapest to lose. History first: a prior turn is\n // context. Then the literal URLs, which are a convenience the server can\n // re-derive from the text. The current message LAST, because it is the task\n // itself, and only down to one character, so a packet is never empty.\n while (next.history.length > 0 && size(next) > MAX_PACKET_BYTES) {\n next.history = next.history.slice(1);\n }\n while (next.literalUrls.length > 0 && size(next) > MAX_PACKET_BYTES) {\n next.literalUrls = next.literalUrls.slice(0, -1);\n }\n while (size(next) > MAX_PACKET_BYTES && next.current.text.length > 1) {\n const over = size(next) - MAX_PACKET_BYTES;\n const keep = Math.max(1, next.current.text.length - Math.max(over, 1));\n next.current = { ...next.current, text: next.current.text.slice(0, keep) };\n }\n return next;\n}\n\n/**\n * A packet for a caller that has no conversation to send: the query itself is\n * the current message, because the server's message text is `min(1)` and an\n * empty one is a 400 after the routing fee has already settled.\n */\nexport function packetForText(text: string): Packet {\n const bounded = text.trim().slice(0, MAX_MESSAGE_CHARS);\n return fit({\n current: { role: 'user', text: bounded.length > 0 ? bounded : '(no task text)' },\n history: [],\n literalUrls: literalUrlsIn(bounded),\n historyStatus: 'unavailable',\n });\n}\n\n/**\n * Build the packet for one user prompt. `transcriptPath` is the harness's own\n * path for this session; an absent or unusable one yields `unavailable`.\n */\nexport async function buildPromptPacket(\n transcriptPath: string | undefined,\n sessionId: string,\n prompt: string,\n): Promise<Packet> {\n const masked = mask(prompt.trim()).slice(0, MAX_MESSAGE_CHARS);\n const text = masked.length > 0 ? masked : '(empty prompt)';\n const read = await readHistory(transcriptPath, sessionId);\n return fit({\n current: { role: 'user', text },\n history: read ?? [],\n literalUrls: literalUrlsIn(text),\n historyStatus: read === null ? 'unavailable' : 'ok',\n });\n}\n\n/**\n * Build the packet for a native call the host is about to make. SAME BOUNDS as\n * a prompt packet, and the same reader: the six most recent messages, 16 KiB,\n * masked, with tool results excluded.\n *\n * THE USER'S WORDS ARE WHAT CARRY THEIR AUTHORITY. Building this packet from\n * the tool argument alone made the search string the entire conversation, so a\n * turn that said \"native tools only, no paid services\" reached the prompt gate\n * and never reached this one: the same session could then be redirected to a\n * paid provider on a bare URL. Reading the transcript at the hook event is not\n * session guessing; the harness hands this hook the path to its own session.\n *\n * The pending call rides INSIDE the packet as the proposed operation, which is\n * the shape the route takes and the one `wire-gate-request.json` pins.\n */\nexport async function buildNativePacket(\n transcriptPath: string | undefined,\n sessionId: string,\n pending: PendingCall,\n): Promise<Packet> {\n const subject = 'query' in pending ? pending.query : pending.url;\n const read = await readHistory(transcriptPath, sessionId);\n const messages = read ?? [];\n // The most recent user message is the turn this call belongs to; everything\n // before it is context. With no transcript the call speaks for itself, which\n // is what this hook did before it could read one.\n const lastUser = messages\n .map((message, index) => ({ message, index }))\n .filter((entry) => entry.message.role === 'user');\n const current = lastUser.at(-1);\n const bounded = mask(subject).slice(0, MAX_MESSAGE_CHARS);\n return fit({\n current: current?.message ?? { role: 'user', text: bounded },\n history: current === undefined ? messages : messages.slice(0, current.index),\n literalUrls: literalUrlsIn(`${current?.message.text ?? ''}\\n${bounded}`),\n historyStatus: read === null ? 'unavailable' : 'ok',\n pendingCall: pending,\n });\n}\n\n/** `null` means \"cannot be vouched for\"; an empty array is a genuinely fresh session. */\nasync function readHistory(\n path: string | undefined,\n sessionId: string,\n): Promise<PacketMessage[] | null> {\n if (path === undefined || path.length === 0) return null;\n let raw: string;\n let file;\n try {\n file = await open(path, 'r');\n } catch {\n return null;\n }\n try {\n const stat = await file.stat();\n if (!stat.isFile() || stat.size > MAX_TRANSCRIPT_BYTES) return null;\n const buffer = Buffer.alloc(MAX_TRANSCRIPT_BYTES + 1);\n const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);\n if (bytesRead > MAX_TRANSCRIPT_BYTES) return null;\n raw = buffer.subarray(0, bytesRead).toString('utf8');\n } catch {\n return null;\n } finally {\n await file.close();\n }\n try {\n return parseRows(raw, sessionId);\n } catch {\n return null;\n }\n}\n\n/**\n * TOLERANT BY ROW, STRICT BY CONTENT. Every rule below still holds about what\n * may enter a packet: no other session's text, no subagent's, no tool results.\n * What changed is the blast radius of one bad row. Rejecting the whole\n * transcript over a compaction boundary or a sidechain line meant the native\n * hook routed on the tool argument alone, which is exactly how a current-turn\n * \"native tools only\" instruction went missing from the decision it was about.\n *\n * A compaction boundary is not a reason to read nothing: the rows after it are\n * the live context, so the collected messages start again there.\n */\nfunction parseRows(raw: string, sessionId: string): PacketMessage[] {\n let messages: PacketMessage[] = [];\n for (const line of raw.split('\\n')) {\n if (line.trim().length === 0) continue;\n let row: Record<string, unknown>;\n try {\n row = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue; // One unreadable line is one line, not the conversation.\n }\n if (row === null || typeof row !== 'object' || Array.isArray(row)) continue;\n // Everything before the boundary belongs to a context that was summarized\n // away; what follows is the turn in play.\n if (row.type === 'system' && row.subtype === 'compact_boundary') {\n messages = [];\n continue;\n }\n // Never ours to read: another window's rows and a subagent's are skipped\n // rather than allowed to void the file.\n if (typeof row.sessionId === 'string' && row.sessionId !== sessionId) continue;\n if (row.isSidechain === true) continue;\n if (row.type !== 'user' && row.type !== 'assistant') continue;\n if (row.sessionId !== sessionId) continue;\n let text: string;\n try {\n text = textOf(row.message);\n } catch {\n continue; // A row this build cannot read contributes nothing, and no more.\n }\n const bounded = mask(text).slice(0, MAX_MESSAGE_CHARS);\n if (bounded.length > 0) messages.push({ role: row.type, text: bounded });\n }\n return messages;\n}\n\n/** Ordinary text blocks only; a tool result contributes nothing. */\nfunction textOf(message: unknown): string {\n if (message === null || typeof message !== 'object' || Array.isArray(message)) {\n throw new Error('malformed message');\n }\n const content = (message as { content?: unknown }).content;\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) throw new Error('malformed content');\n const parts: string[] = [];\n for (const part of content) {\n if (\n part === null ||\n typeof part !== 'object' ||\n typeof (part as { type?: unknown }).type !== 'string'\n ) {\n throw new Error('malformed block');\n }\n const block = part as { type: string; text?: unknown };\n if (block.type !== 'text') continue;\n if (typeof block.text !== 'string') throw new Error('malformed text block');\n parts.push(block.text);\n }\n return parts.join('\\n');\n}\n","/**\n * THE HOOK'S TIME BUDGET, which is the only thing this module still owns.\n *\n * There is no separate gate call any more: the hook asks `POST\n * /api/x402-router` for the one free decision, and the backend answers as soon\n * as the native-versus-paid question is settled, binding whatever it chose in\n * the background. What used to live here, the `/prepare` client and the\n * category-shaped hint validator, went with that second round trip.\n */\n\n/**\n * The hook's whole budget is 5 s (the timeout `install` writes). Stdin waits up\n * to 1 s of it, so the decision gets 3.5 s and the two together still leave\n * 500 ms for node's boot and the transcript read; `wire.test.ts` pins the sum.\n * The expected wait is about 1 s: the backend answers on the gate question and\n * binds afterwards.\n *\n * AN ABORT HERE IS A LOST HINT, not a lost turn. The hook falls back to one\n * line telling the model to call `request` with its own query, and the tool\n * makes the decision instead. One of four live prompts was swallowed at a 1.5 s\n * abort against a backend measured at 0.4 to 0.5 s, so this holds the slack the\n * harness budget was already leaving unused.\n */\nexport const GATE_TIMEOUT_MS = 3_500;\n","import { z } from 'zod';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport type { PartialConfig } from '../lib/config';\nimport { buildNativePacket, buildPromptPacket, type Packet, type PendingCall } from './context';\nimport { requestDecision, ROUTER_PATH, type HookDecision } from './decision';\nimport { GATE_TIMEOUT_MS } from './gate';\nimport {\n bindDecision,\n newCallId,\n noteSession,\n pruneProgress,\n pruneSessions,\n sessionDir,\n writeProgress,\n} from './progress';\n\n/**\n * The two hook handlers. Between them they do exactly three things: build the\n * bounded packet, ask for one free decision, and say one thing back to the\n * harness.\n *\n * NOTHING ELSE IS IN REACH FROM HERE. No wallet, no signer, no payment SDK, no\n * MCP server: a dist test asserts the chunk graph, because the hooks run on\n * every prompt and every native search, and their cost is the product's floor.\n * The decision is free, so nothing on this path can spend anything either.\n *\n * EVERY FAILURE IS SILENT. A backend that is down, slow or answering nonsense\n * leaves the native call allowed and the prompt unchanged; the cause goes to\n * stderr. The user's turn is never blocked by this.\n */\n\nconst PromptEventSchema = z.object({\n session_id: z.string().min(1).max(200),\n transcript_path: z.string().optional(),\n prompt: z.string(),\n});\n\nconst NativeEventSchema = z.object({\n session_id: z.string().min(1).max(200),\n /** The harness's own path for THIS session: the native decision reads the\n * same bounded history the prompt one does, so a restriction the user gave\n * reaches both gates. */\n transcript_path: z.string().optional(),\n tool_name: z.enum(['WebSearch', 'WebFetch']),\n tool_input: z.record(z.string(), z.unknown()),\n});\n\n/** Acknowledgements that cannot be a lookup; `install` never gates them. */\nconst ACKNOWLEDGEMENTS = new Set(['y', 'yes', 'ok', 'okay', 'continue', 'go', 'sure', 'thanks']);\n\nexport type PromptSkip = 'slash' | 'acknowledgement';\n\n/**\n * Prompts that cannot need a lookup, decided locally with no network call. Any\n * OTHER short prompt still goes to the backend: `2^1000`, a bare URL and a task\n * typed without spaces can all need one, and a computation has no later\n * WebSearch or WebFetch hook to recover a skipped classification.\n */\nexport function promptSkipReason(prompt: string): PromptSkip | null {\n const trimmed = prompt.trim();\n if (trimmed.startsWith('/')) return 'slash';\n const normalized = trimmed.toLowerCase().replace(/[.!,]+$/, '');\n return ACKNOWLEDGEMENTS.has(normalized) ? 'acknowledgement' : null;\n}\n\nexport interface HookDeps {\n dataDir: string;\n /** Overrides the resolved base URL entirely; tests point it at a local stub. */\n baseUrl?: string;\n /** The environment the base URL precedence reads `TENJIN_BASE_URL` from. */\n env?: NodeJS.ProcessEnv;\n fetchImpl?: typeof fetch;\n timeoutMs?: number;\n now?: () => number;\n /**\n * Where a silent failure says why. The harness keeps hook stderr in its log,\n * so one line there is the difference between \"the feature is off\" and \"the\n * router answered 401 at this URL\". Never stdout: that is the harness's\n * protocol channel.\n */\n warn?: (line: string) => void;\n}\n\n/**\n * The CLI's ONE precedence, not a second copy of it: flag, then\n * `TENJIN_BASE_URL`, then the config file, then the production default. The\n * hook read the file alone, so a session pointed somewhere by the environment\n * had its prompts routed against whatever the file said instead; on a machine\n * whose file named a protected deployment that was a 401, and a 401 is silence.\n */\nasync function resolveBaseUrl(deps: HookDeps): Promise<string> {\n if (deps.baseUrl !== undefined) return deps.baseUrl;\n const config: PartialConfig = await loadRawConfig(deps.dataDir).catch(() => ({}));\n return resolveSettings({ config, flags: {}, env: deps.env ?? process.env }).baseUrl.value;\n}\n\nexport interface PromptHookOutcome {\n /** What the harness is told, or null for \"nothing to say\". */\n response: unknown | null;\n skipped?: PromptSkip;\n action?: HookDecision['action'];\n /** The turn id, for the smoke to correlate against. */\n id?: string;\n}\n\n/**\n * `tenjin hook prompt` (UserPromptSubmit). One free decision from the user's\n * own words. Only an `execute` gets a line, the server's hint verbatim.\n * `native`, `needs_input` and a decision that failed or timed out are silence:\n * a turn with no lookup carries nothing extra, and `decide` has already written\n * any failure cause to stderr.\n */\nexport async function runPromptHook(raw: unknown, deps: HookDeps): Promise<PromptHookOutcome> {\n const parsed = PromptEventSchema.safeParse(raw);\n if (!parsed.success) return { response: null };\n const event = parsed.data;\n const skipped = promptSkipReason(event.prompt);\n if (skipped !== null) return { response: null, skipped };\n\n const packet = await buildPromptPacket(event.transcript_path, event.session_id, event.prompt);\n const footer = await openFooter(deps, event.session_id, 'prompt');\n const outcome = await decide(packet, deps);\n await footer.close(outcome);\n if (outcome === null) return { response: null };\n if (outcome.action !== 'execute') return { response: null, action: outcome.action };\n return { action: 'execute', id: outcome.id, ...injection(outcome.hint) };\n}\n\nfunction injection(line: string): { response: unknown } {\n return {\n response: {\n hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: line },\n },\n };\n}\n\nexport interface NativeHookOutcome {\n response: unknown | null;\n decision: 'allow' | 'deny';\n action?: HookDecision['action'];\n id?: string;\n}\n\n/**\n * `tenjin hook native` (PreToolUse on `WebSearch|WebFetch`). ALLOW IS THE\n * DEFAULT and a redirect is the exception: it fires only on a clear `execute`,\n * and it carries the id so the redirected call runs the decision that was just\n * made rather than paying for a second one. Anything else, including silence,\n * a slow backend and a `needs_input`, lets the native call run.\n */\nexport async function runNativeHook(raw: unknown, deps: HookDeps): Promise<NativeHookOutcome> {\n const parsed = NativeEventSchema.safeParse(raw);\n if (!parsed.success) return { response: null, decision: 'allow' };\n const event = parsed.data;\n const pending = pendingCallOf(event.tool_name, event.tool_input);\n if (pending === null) return { response: null, decision: 'allow' };\n // THE USER'S WORDS COME WITH IT. Building this from the tool argument alone\n // made the search string the whole conversation, so \"native tools only, no\n // paid services\" never reached this gate.\n const packet = await buildNativePacket(event.transcript_path, event.session_id, pending);\n // AND WHEN THEY CANNOT BE READ, THE CALL RUNS. Routing a redirect on the tool\n // argument alone is how an instruction the user gave this turn gets\n // overruled by a decision that never saw it. A native call the user's own\n // assistant chose is the safe default; the only cost is a lookup this turn\n // does not route.\n if (packet.historyStatus !== 'ok') {\n (deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`)))(\n \"tenjin hook: this session's transcript could not be read, so the native call runs unrouted\",\n );\n return { response: null, decision: 'allow' };\n }\n const footer = await openFooter(deps, event.session_id, 'search');\n const outcome = await decide(packet, deps);\n await footer.close(outcome);\n if (outcome === null || outcome.action !== 'execute') {\n return {\n response: null,\n decision: 'allow',\n ...(outcome !== null ? { action: outcome.action } : {}),\n };\n }\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: 'PreToolUse',\n permissionDecision: 'deny',\n // THE SERVER'S LINE, VERBATIM. It already carries the id and, on a\n // native call, the exact search or URL that was denied, so there is\n // nothing left here to compose and nothing to trim.\n permissionDecisionReason: outcome.hint,\n },\n },\n decision: 'deny',\n action: 'execute',\n id: outcome.id,\n };\n}\n\n/**\n * THE HOOK STAGE, WHICH IS THE ONE THE DEMO OPENS WITH. The decision is in\n * flight for about a second, and at a one-second refresh a state that is\n * written and then erased inside that second is a state nobody ever sees. So\n * the record is not cleared: `selecting service` is REPLACED by what the\n * decision turned out to be, and that outcome holds the line until the next\n * state arrives or its hold runs out.\n *\n * Display only. Every write inside swallows its own failure, and an `execute`\n * also leaves the id-to-session binding the tool resolves its progress through.\n */\nasync function openFooter(\n deps: HookDeps,\n sessionId: string,\n operation: 'prompt' | 'search',\n): Promise<{ close: (decision: HookDecision | null) => Promise<void> }> {\n const now = (): number => deps.now?.() ?? Date.now();\n const directory = sessionDir(deps.dataDir, sessionId);\n const callId = newCallId();\n await noteSession(deps.dataDir, sessionId, now());\n await writeProgress(\n directory,\n callId,\n { phase: 'routing', operation, outcome: 'selecting service' },\n now(),\n );\n await pruneProgress(directory, now());\n // The root, not just this session: a directory per session ever opened would\n // eventually be more than the resolver can scan.\n await pruneSessions(deps.dataDir, now());\n return {\n close: async (decision) => {\n await writeProgress(\n directory,\n callId,\n { phase: 'done', operation, outcome: hookOutcome(decision) },\n now(),\n );\n if (decision !== null && decision.action === 'execute') {\n await bindDecision(deps.dataDir, sessionId, decision.id, now());\n }\n },\n };\n}\n\n/** What the gate decided, in the footer's own words. A silent backend is not a\n * blank line: the turn runs on native tools and the footer says which. */\nfunction hookOutcome(decision: HookDecision | null): string {\n if (decision === null) return 'native tools (router unavailable)';\n if (decision.action === 'execute') return `paid lookup offered (${decision.provider})`;\n if (decision.action === 'native') return 'native tools (no x402 payment)';\n return 'needs input';\n}\n\n/** One free decision, with the hook's own deadline and its own silence. */\nasync function decide(packet: Packet, deps: HookDeps): Promise<HookDecision | null> {\n const baseUrl = await resolveBaseUrl(deps);\n const warn = deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`));\n const outcome = await requestDecision(\n 'hook',\n { packet },\n {\n ctx: {\n flags: { json: true, timeout: deps.timeoutMs ?? GATE_TIMEOUT_MS },\n dataDir: deps.dataDir,\n io: { stdout: nullStream(), stderr: nullStream(), isTTY: false },\n },\n baseUrl,\n timeoutMs: deps.timeoutMs ?? GATE_TIMEOUT_MS,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n },\n );\n if (outcome.status === 'failed') {\n warn(`tenjin hook: ${baseUrl}${ROUTER_PATH} ${outcome.reason}`);\n return null;\n }\n return outcome.decision.decision;\n}\n\n/** The hooks write their own protocol answer on stdout and nothing else. */\nfunction nullStream(): NodeJS.WritableStream {\n return { write: () => true } as unknown as NodeJS.WritableStream;\n}\n\nfunction pendingCallOf(\n tool: 'WebSearch' | 'WebFetch',\n input: Record<string, unknown>,\n): PendingCall | null {\n const value = tool === 'WebSearch' ? input.query : input.url;\n if (typeof value !== 'string') return null;\n const bounded = value.trim().slice(0, 4_000);\n if (bounded.length === 0) return null;\n return tool === 'WebSearch' ? { tool, query: bounded } : { tool, url: bounded };\n}\n","import { runNativeHook, runPromptHook, type HookDeps } from './hooks';\nimport type { Io } from '../lib/output';\n\n/**\n * `tenjin hook prompt` and `tenjin hook native`. The harness writes its event on\n * stdin and reads a JSON object (or nothing) from stdout, so these two commands\n * bypass the CLI's envelope entirely. They never fail the turn: a stdin that\n * never arrives, an unreadable event or a handler that throws all exit 0 with\n * an empty stdout, which the harness reads as \"no opinion\".\n */\n\nconst MAX_EVENT_BYTES = 1_000_000;\n/** One fifth of the hook's 5 s budget, leaving the gate its 3.5 s; `wire.test.ts`\n * pins the sum against the timeout `install` writes. The harness writes its\n * event immediately, so this wait is a liveness check rather than a budget to\n * spend: every second it holds is a second the gate does not get. */\nexport const STDIN_TIMEOUT_MS = 1_000;\n\nexport type HookKind = 'prompt' | 'native';\n\nexport interface HookCommandDeps extends HookDeps {\n /** Test seam for the harness event; production reads stdin. */\n readEvent?: () => Promise<string>;\n}\n\nexport async function runHookCommand(kind: HookKind, io: Io, deps: HookCommandDeps): Promise<void> {\n let response: unknown;\n try {\n const raw = await (deps.readEvent ?? readStdin)();\n const event: unknown = JSON.parse(raw);\n const outcome =\n kind === 'prompt' ? await runPromptHook(event, deps) : await runNativeHook(event, deps);\n response = outcome.response;\n } catch {\n response = null;\n }\n if (response !== null) io.stdout.write(`${JSON.stringify(response)}\\n`);\n}\n\nasync function readStdin(): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n const timer = setTimeout(() => reject(new Error('no harness event')), STDIN_TIMEOUT_MS);\n const done = (value: string): void => {\n clearTimeout(timer);\n resolve(value);\n };\n process.stdin.on('data', (chunk: Buffer) => {\n size += chunk.length;\n if (size > MAX_EVENT_BYTES) {\n clearTimeout(timer);\n reject(new Error('harness event too large'));\n return;\n }\n chunks.push(chunk);\n });\n process.stdin.once('end', () => done(Buffer.concat(chunks).toString('utf8')));\n process.stdin.once('error', () => {\n clearTimeout(timer);\n reject(new Error('harness event unreadable'));\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY;AAoBd,IAAM,cAAc;AACpB,IAAM,mBAAmB,KAAK;AAG9B,IAAM,oBAAoB;AACjC,IAAM,uBAAuB;AAC7B,IAAM,mBAAmB;AACzB,IAAM,wBAAwB;AAuB9B,IAAM,SAAS;AAER,SAAS,cAAc,MAAwB;AACpD,QAAM,QAAQ,oBAAI,IAAY;AAC9B,aAAW,SAAS,KAAK,SAAS,MAAM,GAAG;AACzC,UAAM,YAAY,MAAM,CAAC,EAAE,QAAQ,cAAc,EAAE;AACnD,QAAI;AACF,YAAM,aAAa,IAAI,IAAI,SAAS,EAAE,SAAS;AAC/C,UAAI,WAAW,UAAU,sBAAuB,OAAM,IAAI,UAAU;AAAA,IACtE,QAAQ;AACN;AAAA,IACF;AACA,QAAI,MAAM,QAAQ,iBAAkB;AAAA,EACtC;AACA,SAAO,CAAC,GAAG,KAAK;AAClB;AAYO,SAAS,IAAI,QAAwB;AAC1C,QAAM,OAAO,CAAC,UAA0B,OAAO,WAAW,KAAK,UAAU,KAAK,CAAC;AA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]}
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
3
3
|
|
|
4
4
|
// src/index.ts
|
|
5
|
-
var MIN_NODE_MAJOR =
|
|
5
|
+
var MIN_NODE_MAJOR = 24;
|
|
6
6
|
var nodeMajor = Number.parseInt(process.versions.node.split(".")[0] ?? "", 10);
|
|
7
7
|
if (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {
|
|
8
8
|
const envelope = {
|
|
@@ -12,7 +12,7 @@ if (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {
|
|
|
12
12
|
error: {
|
|
13
13
|
code: "NODE_UNSUPPORTED",
|
|
14
14
|
message: `Tenjin CLI requires Node ${MIN_NODE_MAJOR} or newer (found ${process.versions.node}).`,
|
|
15
|
-
fix: "Install Node
|
|
15
|
+
fix: "Install Node 24 or newer"
|
|
16
16
|
}
|
|
17
17
|
};
|
|
18
18
|
process.stdout.write(`${JSON.stringify(envelope, null, 2)}
|
|
@@ -21,6 +21,11 @@ if (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {
|
|
|
21
21
|
`);
|
|
22
22
|
process.exit(1);
|
|
23
23
|
}
|
|
24
|
-
|
|
24
|
+
if (process.argv.length === 3 && process.argv[2] === "status-line") {
|
|
25
|
+
const { statusLineMain } = await import("./status-line-CGPUSDMC.js");
|
|
26
|
+
await statusLineMain();
|
|
27
|
+
process.exit(0);
|
|
28
|
+
}
|
|
29
|
+
var { main } = await import("./cli-M3XCSOU6.js");
|
|
25
30
|
process.exit(await main(process.argv.slice(2)));
|
|
26
31
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n// Bin entry. The Node version guard runs BEFORE importing anything else — no\n// static imports above it — so an out-of-support runtime gets one JSON error\n// envelope plus a human stderr line instead of a syntax/parse crash from a\n// lazily-loaded module written in newer syntax. Kept in conservative syntax.\nconst MIN_NODE_MAJOR =
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n// Bin entry. The Node version guard runs BEFORE importing anything else — no\n// static imports above it — so an out-of-support runtime gets one JSON error\n// envelope plus a human stderr line instead of a syntax/parse crash from a\n// lazily-loaded module written in newer syntax. Kept in conservative syntax.\nconst MIN_NODE_MAJOR = 24;\n\nconst nodeMajor = Number.parseInt(process.versions.node.split('.')[0] ?? '', 10);\n\nif (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {\n const envelope = {\n schemaVersion: 1,\n command: 'preflight',\n ok: false,\n error: {\n code: 'NODE_UNSUPPORTED',\n message: `Tenjin CLI requires Node ${MIN_NODE_MAJOR} or newer (found ${process.versions.node}).`,\n fix: 'Install Node 24 or newer',\n },\n };\n process.stdout.write(`${JSON.stringify(envelope, null, 2)}\\n`);\n process.stderr.write(`error: Node ${MIN_NODE_MAJOR}+ required, found ${process.versions.node}\\n`);\n process.exit(1);\n}\n\n// THE STATUS LINE NEVER LOADS THE CLI. Claude Code runs it once a second for as\n// long as a session is open, and commander, zod and the command tree are parse\n// cost it has no use for. Only the bare invocation is diverted; `--help` and\n// every flag fall through to the command tree, which registers it like any verb.\nif (process.argv.length === 3 && process.argv[2] === 'status-line') {\n const { statusLineMain } = await import('./router/status-line');\n await statusLineMain();\n process.exit(0);\n}\n\nconst { main } = await import('./cli');\nprocess.exit(await main(process.argv.slice(2)));\n\n// Marks this file a module so top-level await is legal; emits nothing.\nexport {};\n"],"mappings":";;;;AAKA,IAAM,iBAAiB;AAEvB,IAAM,YAAY,OAAO,SAAS,QAAQ,SAAS,KAAK,MAAM,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE;AAE/E,IAAI,OAAO,MAAM,SAAS,KAAK,YAAY,gBAAgB;AACzD,QAAM,WAAW;AAAA,IACf,eAAe;AAAA,IACf,SAAS;AAAA,IACT,IAAI;AAAA,IACJ,OAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS,4BAA4B,cAAc,oBAAoB,QAAQ,SAAS,IAAI;AAAA,MAC5F,KAAK;AAAA,IACP;AAAA,EACF;AACA,UAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,CAAC;AAAA,CAAI;AAC7D,UAAQ,OAAO,MAAM,eAAe,cAAc,qBAAqB,QAAQ,SAAS,IAAI;AAAA,CAAI;AAChG,UAAQ,KAAK,CAAC;AAChB;AAMA,IAAI,QAAQ,KAAK,WAAW,KAAK,QAAQ,KAAK,CAAC,MAAM,eAAe;AAClE,QAAM,EAAE,eAAe,IAAI,MAAM,OAAO,2BAAsB;AAC9D,QAAM,eAAe;AACrB,UAAQ,KAAK,CAAC;AAChB;AAEA,IAAM,EAAE,KAAK,IAAI,MAAM,OAAO,mBAAO;AACrC,QAAQ,KAAK,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC;","names":[]}
|