tenjin-cli 0.1.0-alpha.32 → 0.1.0-alpha.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -23
- package/dist/{_esm-RLLC72MS.js → _esm-BIN7VY2L.js} +2 -2
- package/dist/{alive-MROUMFH3.js → alive-GSOWKUOY.js} +4 -4
- package/dist/{auto-update-OPWMRZLS.js → auto-update-Y24UL56V.js} +5 -3
- package/dist/{chunk-2GNOFONN.js → chunk-2M2VPI2E.js} +2 -2
- package/dist/chunk-2M2VPI2E.js.map +1 -0
- package/dist/{chunk-VUGQTZ2L.js → chunk-2RWB7RKE.js} +89 -33
- package/dist/chunk-2RWB7RKE.js.map +1 -0
- package/dist/{chunk-OTWLERSW.js → chunk-36RVGZNY.js} +2 -2
- package/dist/{chunk-B7EM4GGF.js → chunk-3GNJXKIT.js} +2 -2
- package/dist/{chunk-DRDUIZIA.js → chunk-4K7TQHNP.js} +4 -4
- package/dist/{chunk-SYOS5CAC.js → chunk-4YOZGGTZ.js} +73 -2
- package/dist/chunk-4YOZGGTZ.js.map +1 -0
- package/dist/{chunk-AD226HDR.js → chunk-A5GKIG5O.js} +5 -5
- package/dist/{chunk-JEVQ5LKO.js → chunk-AGMVASXZ.js} +3 -3
- package/dist/{chunk-ADV4LDTB.js → chunk-BF4XHEQK.js} +12 -2
- package/dist/chunk-BF4XHEQK.js.map +1 -0
- package/dist/{chunk-IDTRSAHE.js → chunk-C2Q76BVM.js} +48 -49
- package/dist/chunk-C2Q76BVM.js.map +1 -0
- package/dist/{chunk-VJUVFZ2D.js → chunk-FVIGCDSV.js} +1 -1
- package/dist/chunk-FVIGCDSV.js.map +1 -0
- package/dist/{chunk-QF3LSMGS.js → chunk-GTTUCOPD.js} +2 -2
- package/dist/{chunk-3DIL66VX.js → chunk-HGGWCP7W.js} +2 -2
- package/dist/{chunk-D5TOQSO4.js → chunk-HMWYAUA6.js} +10 -6
- package/dist/{chunk-D5TOQSO4.js.map → chunk-HMWYAUA6.js.map} +1 -1
- package/dist/{chunk-445VQTVM.js → chunk-IE7P2BZE.js} +2 -2
- package/dist/{chunk-VOZA6O7K.js → chunk-ILNIZ5I2.js} +190 -96
- package/dist/chunk-ILNIZ5I2.js.map +1 -0
- package/dist/{chunk-TF5HCP33.js → chunk-INTFHMU4.js} +4 -4
- package/dist/{chunk-HREHWL32.js → chunk-J57UC3DD.js} +2 -2
- package/dist/{chunk-AV5NZMYO.js → chunk-KM7RY2ZS.js} +2 -2
- package/dist/{chunk-TAW4UFFF.js → chunk-L6JEXB3E.js} +132 -132
- package/dist/chunk-L6JEXB3E.js.map +1 -0
- package/dist/{chunk-E7LGOMH6.js → chunk-LRW6S53P.js} +4 -3
- package/dist/chunk-LRW6S53P.js.map +1 -0
- package/dist/{chunk-PKHI276N.js → chunk-LXAYUOXI.js} +18 -9
- package/dist/chunk-LXAYUOXI.js.map +1 -0
- package/dist/{chunk-WOM257PW.js → chunk-NDGZDTSJ.js} +3 -3
- package/dist/{chunk-SFASB5FL.js → chunk-P3LFTKE7.js} +3 -14
- package/dist/chunk-P3LFTKE7.js.map +1 -0
- package/dist/{chunk-YUY4SAGM.js → chunk-RVPYTUP4.js} +5 -5
- package/dist/chunk-RVPYTUP4.js.map +1 -0
- package/dist/{chunk-GAKUQHKA.js → chunk-TC2WZLSC.js} +3 -3
- package/dist/{chunk-D3ZURCG7.js → chunk-TKPF35W6.js} +2 -2
- package/dist/{chunk-I5TDIUKM.js → chunk-U3IKUGRP.js} +23 -5
- package/dist/chunk-U3IKUGRP.js.map +1 -0
- package/dist/{chunk-BI673VEJ.js → chunk-UXZONNEQ.js} +3 -3
- package/dist/{chunk-PJNENX2A.js → chunk-WFSPCCVW.js} +2 -2
- package/dist/{chunk-PJNENX2A.js.map → chunk-WFSPCCVW.js.map} +1 -1
- package/dist/{chunk-DW4YTVR3.js → chunk-WXA2BWTE.js} +6 -2
- package/dist/chunk-WXA2BWTE.js.map +1 -0
- package/dist/{chunk-JRZBBPO6.js → chunk-ZDZERB6L.js} +56 -228
- package/dist/chunk-ZDZERB6L.js.map +1 -0
- package/dist/{chunk-G75OPGAK.js → chunk-ZNNXRNFD.js} +5 -3
- package/dist/chunk-ZNNXRNFD.js.map +1 -0
- package/dist/{chunk-CISYM4EO.js → chunk-ZURZHELF.js} +2 -2
- package/dist/{cli-FB4LOA5A.js → cli-E36SPKBW.js} +44 -44
- package/dist/{cli-FB4LOA5A.js.map → cli-E36SPKBW.js.map} +1 -1
- package/dist/{codex-event-TYVES3UX.js → codex-event-ZO2GEFE6.js} +2 -2
- package/dist/{codex-host-WW4H2SKT.js → codex-host-KECJVTA2.js} +3 -3
- package/dist/{codex-install-2C623HPW.js → codex-install-HQZDGFXW.js} +90 -47
- package/dist/codex-install-HQZDGFXW.js.map +1 -0
- package/dist/{config-HOVJFEKD.js → config-HY2E4GGW.js} +8 -8
- package/dist/{doctor-NKU4V5OV.js → doctor-I6XQEKWD.js} +42 -31
- package/dist/doctor-I6XQEKWD.js.map +1 -0
- package/dist/{fund-WEBHTZGN.js → fund-2QRO7OJL.js} +16 -11
- package/dist/{fund-WEBHTZGN.js.map → fund-2QRO7OJL.js.map} +1 -1
- package/dist/{hook-command-ZA2PNKS6.js → hook-command-2UBCSZG6.js} +12 -13
- package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
- package/dist/hosts/claude/tenjin/hooks/register.tsx +51 -11
- package/dist/hosts/claude/tenjin/types/index.d.ts +2 -1
- package/dist/{hosts-AV5MHBAU.js → hosts-DVQJ32QC.js} +2 -2
- package/dist/index.js +16 -15
- package/dist/index.js.map +1 -1
- package/dist/{install-PT4EZS4R.js → install-ILUX5C4A.js} +24 -17
- package/dist/{install-identity-5A4OE6YC.js → install-identity-TZKGY6LQ.js} +7 -7
- package/dist/{install-wallet-SAAPKB73.js → install-wallet-5M4OTYLX.js} +13 -13
- package/dist/isows-native-Q2UDIVPT.js +9 -0
- package/dist/isows-native-Q2UDIVPT.js.map +1 -0
- package/dist/{mcp-HAWKCTPQ.js → mcp-LE4DUS22.js} +23 -24
- package/dist/{mcp-HAWKCTPQ.js.map → mcp-LE4DUS22.js.map} +1 -1
- package/dist/{package-SR2WB6MK.js → package-IJFGMWEV.js} +2 -2
- package/dist/{pay-OXC3WKYV.js → pay-WCG3IH4R.js} +13 -13
- package/dist/{payments-3KHMP2MG.js → payments-HFPPWHTV.js} +6 -6
- package/dist/{plugin-registration-N3GRIZVM.js → plugin-registration-PZFI5GZW.js} +18 -17
- package/dist/{runtime-UVNUA3AS.js → runtime-UZOKSUZX.js} +145 -27
- package/dist/runtime-UZOKSUZX.js.map +1 -0
- package/dist/{runtime-fetch-EKFRNR6Z.js → runtime-fetch-ZSSSK72Y.js} +5 -2
- package/dist/{runtime-layout-BDWZG2TQ.js → runtime-layout-WIDILZ6K.js} +2 -2
- package/dist/{send-HMKJLT34.js → send-GCVEAQKL.js} +8 -8
- package/dist/{status-RWXIIWYS.js → status-HCVAOCN7.js} +10 -10
- package/dist/{status-line-77XYZP7E.js → status-line-OPCXDHL2.js} +6 -6
- package/dist/{uninstall-D5G67UJH.js → uninstall-BAWRBXXQ.js} +19 -18
- package/dist/{uninstall-D5G67UJH.js.map → uninstall-BAWRBXXQ.js.map} +1 -1
- package/dist/{update-LRNOEGSB.js → update-CACXLQLR.js} +20 -17
- package/dist/{usdc-D6X7EIQ2.js → usdc-VG4CIOUK.js} +4 -4
- package/dist/{viemAdapter-By13KInL-RL742ETX.js → viemAdapter-By13KInL-DOFTEIJV.js} +2 -2
- package/dist/{wallet-XFYC27BR.js → wallet-QL4UUXEZ.js} +11 -11
- package/docs/agent-permissions.md +16 -12
- package/docs/troubleshooting.md +5 -5
- package/package.json +4 -4
- package/scripts/installers/install.ps1 +67 -0
- package/scripts/installers/install.sh +68 -0
- package/dist/_esm-C5CRWCYU.js +0 -3737
- package/dist/_esm-C5CRWCYU.js.map +0 -1
- package/dist/chunk-2GNOFONN.js.map +0 -1
- package/dist/chunk-ADV4LDTB.js.map +0 -1
- package/dist/chunk-DW4YTVR3.js.map +0 -1
- package/dist/chunk-E7LGOMH6.js.map +0 -1
- package/dist/chunk-G75OPGAK.js.map +0 -1
- package/dist/chunk-I5TDIUKM.js.map +0 -1
- package/dist/chunk-IDTRSAHE.js.map +0 -1
- package/dist/chunk-JRZBBPO6.js.map +0 -1
- package/dist/chunk-PKHI276N.js.map +0 -1
- package/dist/chunk-SFASB5FL.js.map +0 -1
- package/dist/chunk-SYOS5CAC.js.map +0 -1
- package/dist/chunk-TAW4UFFF.js.map +0 -1
- package/dist/chunk-VJUVFZ2D.js.map +0 -1
- package/dist/chunk-VOZA6O7K.js.map +0 -1
- package/dist/chunk-VUGQTZ2L.js.map +0 -1
- package/dist/chunk-YUY4SAGM.js.map +0 -1
- package/dist/codex-install-2C623HPW.js.map +0 -1
- package/dist/doctor-NKU4V5OV.js.map +0 -1
- package/dist/runtime-UVNUA3AS.js.map +0 -1
- /package/dist/{_esm-RLLC72MS.js.map → _esm-BIN7VY2L.js.map} +0 -0
- /package/dist/{alive-MROUMFH3.js.map → alive-GSOWKUOY.js.map} +0 -0
- /package/dist/{auto-update-OPWMRZLS.js.map → auto-update-Y24UL56V.js.map} +0 -0
- /package/dist/{chunk-OTWLERSW.js.map → chunk-36RVGZNY.js.map} +0 -0
- /package/dist/{chunk-B7EM4GGF.js.map → chunk-3GNJXKIT.js.map} +0 -0
- /package/dist/{chunk-DRDUIZIA.js.map → chunk-4K7TQHNP.js.map} +0 -0
- /package/dist/{chunk-AD226HDR.js.map → chunk-A5GKIG5O.js.map} +0 -0
- /package/dist/{chunk-JEVQ5LKO.js.map → chunk-AGMVASXZ.js.map} +0 -0
- /package/dist/{chunk-QF3LSMGS.js.map → chunk-GTTUCOPD.js.map} +0 -0
- /package/dist/{chunk-3DIL66VX.js.map → chunk-HGGWCP7W.js.map} +0 -0
- /package/dist/{chunk-445VQTVM.js.map → chunk-IE7P2BZE.js.map} +0 -0
- /package/dist/{chunk-TF5HCP33.js.map → chunk-INTFHMU4.js.map} +0 -0
- /package/dist/{chunk-HREHWL32.js.map → chunk-J57UC3DD.js.map} +0 -0
- /package/dist/{chunk-AV5NZMYO.js.map → chunk-KM7RY2ZS.js.map} +0 -0
- /package/dist/{chunk-WOM257PW.js.map → chunk-NDGZDTSJ.js.map} +0 -0
- /package/dist/{chunk-GAKUQHKA.js.map → chunk-TC2WZLSC.js.map} +0 -0
- /package/dist/{chunk-D3ZURCG7.js.map → chunk-TKPF35W6.js.map} +0 -0
- /package/dist/{chunk-BI673VEJ.js.map → chunk-UXZONNEQ.js.map} +0 -0
- /package/dist/{chunk-CISYM4EO.js.map → chunk-ZURZHELF.js.map} +0 -0
- /package/dist/{codex-event-TYVES3UX.js.map → codex-event-ZO2GEFE6.js.map} +0 -0
- /package/dist/{codex-host-WW4H2SKT.js.map → codex-host-KECJVTA2.js.map} +0 -0
- /package/dist/{config-HOVJFEKD.js.map → config-HY2E4GGW.js.map} +0 -0
- /package/dist/{hook-command-ZA2PNKS6.js.map → hook-command-2UBCSZG6.js.map} +0 -0
- /package/dist/{hosts-AV5MHBAU.js.map → hosts-DVQJ32QC.js.map} +0 -0
- /package/dist/{install-PT4EZS4R.js.map → install-ILUX5C4A.js.map} +0 -0
- /package/dist/{install-identity-5A4OE6YC.js.map → install-identity-TZKGY6LQ.js.map} +0 -0
- /package/dist/{install-wallet-SAAPKB73.js.map → install-wallet-5M4OTYLX.js.map} +0 -0
- /package/dist/{package-SR2WB6MK.js.map → package-IJFGMWEV.js.map} +0 -0
- /package/dist/{pay-OXC3WKYV.js.map → pay-WCG3IH4R.js.map} +0 -0
- /package/dist/{payments-3KHMP2MG.js.map → payments-HFPPWHTV.js.map} +0 -0
- /package/dist/{plugin-registration-N3GRIZVM.js.map → plugin-registration-PZFI5GZW.js.map} +0 -0
- /package/dist/{runtime-fetch-EKFRNR6Z.js.map → runtime-fetch-ZSSSK72Y.js.map} +0 -0
- /package/dist/{runtime-layout-BDWZG2TQ.js.map → runtime-layout-WIDILZ6K.js.map} +0 -0
- /package/dist/{send-HMKJLT34.js.map → send-GCVEAQKL.js.map} +0 -0
- /package/dist/{status-RWXIIWYS.js.map → status-HCVAOCN7.js.map} +0 -0
- /package/dist/{status-line-77XYZP7E.js.map → status-line-OPCXDHL2.js.map} +0 -0
- /package/dist/{update-LRNOEGSB.js.map → update-CACXLQLR.js.map} +0 -0
- /package/dist/{usdc-D6X7EIQ2.js.map → usdc-VG4CIOUK.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-RL742ETX.js.map → viemAdapter-By13KInL-DOFTEIJV.js.map} +0 -0
- /package/dist/{wallet-XFYC27BR.js.map → wallet-QL4UUXEZ.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/session-key.ts","../src/lib/session-present.ts","../src/lib/open-url.ts","../src/commands/fund.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport { sessionPath } from './paths';\nimport { writeFileAtomic } from './atomic-json';\nimport { buildSiwxHeader } from './siwx';\nimport { originOf } from './url';\nimport {\n isSessionUsable,\n loadSessionFile,\n signWithSession,\n type SessionFile,\n type SessionKeyDeps,\n type SessionScope,\n type SignableRequest,\n} from './session-present';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * Session-key delegation (RFC 9421 signed HTTP, RFC 9530-shaped Content-Digest),\n * verified byte-for-byte against the live \"Auth — session keys\" contract in\n * https://tenjin.sh/llms-full.txt (D35).\n *\n * The point: a plain SIWX write burns a single-use nonce, so every write needs a\n * fresh WALLET signature. A session key trades that for ONE wallet signature per\n * session: generate a P-256 keypair, wallet-sign a SIWX message binding its\n * pubkey/exp/scope, then sign each subsequent write with the P-256 key (no wallet\n * popup) until the delegation expires. The delegated key is short-lived (≤24h,\n * server-clamped) and cached 0600, address-bound so a wallet change invalidates it.\n *\n * This module is the MINT half — everything that needs a wallet signer, i.e.\n * `establishSession`, the cache writer, and the two `WriteAuth` implementations.\n * The present-only half (load a file, sign one request with it) lives in\n * `session-present.ts` and is re-exported below, so `posts-api`/`publish`/`edit`\n * keep importing one module while a caller that only wants to present a live\n * delegation — `read`, on the reuse path — imports that half alone and touches\n * no keystore. Do not move a signer-touching function down into\n * `session-present.ts`: that free reuse path is what it buys.\n *\n * A minted delegation is a wallet-derived credential, so it is bound to the\n * ORIGIN it was minted against and every presenter re-checks that binding.\n *\n * Never hand-rolls crypto: P-256 keygen is node:crypto webcrypto (subtle) and the\n * wallet delegation reuses the siwx.ts seam.\n */\n\nexport {\n contentDigest,\n isSessionPresentable,\n readSessionFile,\n isSessionUsable,\n keyidFor,\n loadSessionFile,\n scopeSatisfies,\n signatureBase,\n signatureParams,\n signWithSession,\n targetUri,\n} from './session-present';\nexport type {\n SessionFile,\n SessionFileState,\n SessionKeyDeps,\n SessionScope,\n SignableRequest,\n SignatureParamsInput,\n} from './session-present';\n\n/**\n * The chain a session delegation is signed over. Writes require Base mainnet per\n * the server's SIWX chain constraint, and a session covers reads and writes\n * alike, so there is exactly ONE session chain id rather than a per-caller\n * choice: the read path and the write path must mint against the same chain or\n * the file they share would flip between two delegations.\n */\nexport const SESSION_CHAIN_ID = 'eip155:8453';\n\nconst SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h; the server clamps to ≤24h.\n\n/**\n * The write-auth seam a posts client signs through. `headersFor` attaches the\n * signature headers (establishing the session lazily on first use); `recover`\n * reacts to a 401 by returning whether a retry is worthwhile.\n */\nexport interface WriteAuth {\n headersFor(req: SignableRequest): Promise<Record<string, string>>;\n /** React to a write's 401 `code`; true ⇒ the next headersFor retry may succeed. */\n recover(code: string | undefined): Promise<boolean>;\n}\n\nexport interface SessionKeyConfig {\n signer: TenjinSigner;\n baseUrl: string;\n chainId: string;\n dataDir: string;\n /**\n * The scope this session is minted at, and the scope a cached session must\n * cover to be reused. Required, not defaulted: over-granting silently is the\n * failure mode worth making impossible, so every caller states what it needs.\n */\n scope: SessionScope;\n}\n\nconst subtle = webcrypto.subtle;\n\nfunction generateP256KeyPair(): Promise<webcrypto.CryptoKeyPair> {\n return subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]) as Promise<webcrypto.CryptoKeyPair>;\n}\n\n/** base64url (no padding) of raw bytes — the pubkey/keyid encoding. */\nfunction toBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** The three URNs bound into the delegation's SIWX `resources` array (D35). */\nexport function delegationResources(\n publicKeyRaw: string,\n expIso: string,\n scope: SessionScope,\n): string[] {\n return [\n `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,\n `urn:tenjin:session:exp:${expIso}`,\n `urn:tenjin:session:scope:${scope}`,\n ];\n}\n\n/**\n * Establish a session with ONE wallet signature: generate a P-256 keypair, bind\n * its pubkey/exp/scope into a SIWX message, wallet-sign it, and cache the result\n * 0600 address-bound. The returned file's `delegation` is the constant\n * `Tenjin-Session-Delegation` header for the session's life.\n */\nexport async function establishSession(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): Promise<SessionFile> {\n const now = deps.now ?? Date.now;\n const pair = await generateP256KeyPair();\n const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));\n const publicKeyRaw = toBase64Url(rawPub);\n const jwk = (await subtle.exportKey('jwk', pair.privateKey)) as SessionFile['privateKeyJwk'];\n\n const expIso = new Date(now() + SESSION_TTL_MS).toISOString();\n const delegation = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n ttlMs: SESSION_TTL_MS,\n statement: 'Delegate a Tenjin session key.',\n resources: delegationResources(publicKeyRaw, expIso, config.scope),\n });\n\n const file: SessionFile = {\n address: config.signer.address.toLowerCase(),\n origin: originOf(config.baseUrl),\n delegation,\n exp: expIso,\n scope: config.scope,\n publicKeyRaw,\n privateKeyJwk: jwk,\n };\n await saveSessionFile(config.dataDir, file);\n return file;\n}\n\n// ---------------------------------------------------------------------------\n// Cache writes (0600, address-bound). The reader lives in session-present.\n// ---------------------------------------------------------------------------\n\nexport async function saveSessionFile(dir: string, file: SessionFile): Promise<void> {\n await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n// ---------------------------------------------------------------------------\n// The WriteAuth implementation: lazy establish, cache reuse, 401 recovery.\n// ---------------------------------------------------------------------------\n\n/** How each 401 `code` maps to recovery (per the llms-full.txt policy section). */\ntype Recovery = 'resign' | 'reestablish' | 'fatal';\n\nexport function recoveryFor(code: string | undefined): Recovery {\n switch (code) {\n case 'proof_expired':\n // The per-request signature is too old; just re-sign (no wallet).\n return 'resign';\n case 'session_expired':\n case 'proof_revoked':\n case 'insufficient_scope':\n // The delegation itself is gone/insufficient; re-establish (one wallet sig).\n return 'reestablish';\n case 'session_key_unbound':\n // keyid ≠ the delegation-bound key: retrying cannot fix it.\n return 'fatal';\n default:\n return 'fatal';\n }\n}\n\n/**\n * A session-key WriteAuth: mints (or loads) the delegation on first use and signs\n * every write with the P-256 key — so a returning agent never wallet-signs again\n * until the session expires. On a 401 it re-signs or re-establishes per the code.\n */\nexport function createSessionKeyAuth(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): WriteAuth {\n const now = deps.now ?? Date.now;\n let cached: SessionFile | null = null;\n let forceReestablish = false;\n\n const ensure = async (): Promise<SessionFile> => {\n if (\n !forceReestablish &&\n cached !== null &&\n isSessionUsable(cached, config.signer.address, now(), config.scope, originOf(config.baseUrl))\n ) {\n return cached;\n }\n if (!forceReestablish) {\n const onDisk = await loadSessionFile(config.dataDir);\n const origin = originOf(config.baseUrl);\n if (\n onDisk !== null &&\n isSessionUsable(onDisk, config.signer.address, now(), config.scope, origin)\n ) {\n cached = onDisk;\n return cached;\n }\n }\n cached = await establishSession(config, deps);\n forceReestablish = false;\n return cached;\n };\n\n return {\n async headersFor(req) {\n const file = await ensure();\n return signWithSession(file, req, deps);\n },\n async recover(code) {\n const recovery = recoveryFor(code);\n if (recovery === 'fatal') return false;\n if (recovery === 'reestablish') {\n cached = null;\n forceReestablish = true;\n }\n // 'resign' needs no state change: the next headersFor mints a fresh\n // created/nonce over the same (still-valid) delegation.\n return true;\n },\n };\n}\n\n/**\n * The plain-SIWX fallback (no session): every write carries its own fresh\n * wallet-signed `SIGN-IN-WITH-X` header. Used when session establishment is\n * disabled; a burned/stale nonce (401) is recovered by re-signing.\n */\nexport function createSiwxAuth(config: SessionKeyConfig): WriteAuth {\n return {\n async headersFor() {\n const header = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n });\n return { 'SIGN-IN-WITH-X': header };\n },\n async recover(code) {\n // A single-use nonce burns on every write; a stale/burned nonce (or an\n // expired proof) is recovered by re-signing with a fresh nonce + issuedAt.\n return code === 'nonce_already_used' || code === 'invalid_proof' || code === 'proof_expired';\n },\n };\n}\n","import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split earns its keep on the reuse path: presenting a live delegation costs\n * no keystore decryption, so `tenjin read` reaches this half alone whenever one\n * is cached and only falls through to the mint half (and one passphrase) when\n * there is none. Neither half says anything about what an already-minted\n * delegation is worth to whoever holds it — see `origin` below, and the tier\n * note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.sh/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET or DELETE has no body to\n * cover at all, so content-digest drops out of the covered set. As a union,\n * \"GET with a body\" and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET' | 'DELETE'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache (`~/.tenjin/session.json`); the next read or write mints a fresh one.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends. Keyed on\n // the presence of a body rather than on the method list, so a bodiless method\n // added to the union above needs no second edit here to stay bodiless.\n const digest = 'body' in req ? contentDigest(req.body) : undefined;\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n /** An OLDER CLI's file, missing a field the shape has since required. Unusable\n * and re-mintable like an absent one, so NOT the tamper signal `corrupt` is. */\n | { kind: 'outdated'; field: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\n/**\n * Fields an OLDER CLI's file can legitimately lack. An allowlist, not \"any missing\n * key\": a file with no `privateKeyJwk.d` cannot sign and is broken whoever wrote\n * it. Add a name when the schema grows a required field, never to quiet a test.\n */\nconst LATER_ADDED_FIELDS: readonly string[] = ['origin'];\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const legacy = (i: (typeof issues)[number]): boolean =>\n LATER_ADDED_FIELDS.includes(i.path.join('.')) && !hasPath(json, i.path);\n // Report the first NON-legacy issue when there is one: a file missing both\n // `origin` and its private scalar is corrupt because of the scalar, and naming\n // the benign field points the operator at the wrong thing.\n const issue = issues.find((i) => !legacy(i)) ?? issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // EVERY failure must be an allowlisted later field the file genuinely lacks.\n // One legacy omission cannot vouch for the rest of the file, and zod reports in\n // schema order, so the first issue alone would let a broken key ride in.\n const legacyOnly = issues.length > 0 && issues.every(legacy);\n if (legacyOnly && field !== undefined) return { kind: 'outdated', field };\n // Field-qualified: the message alone names none. zod never echoes the received\n // VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** Does `value` actually carry the key at `path`, whatever it holds there? */\nfunction hasPath(value: unknown, path: readonly PropertyKey[]): boolean {\n let cur: unknown = value;\n for (const key of path) {\n if (typeof cur !== 'object' || cur === null) return false;\n if (!Object.hasOwn(cur, key)) return false;\n cur = (cur as Record<PropertyKey, unknown>)[key];\n }\n return true;\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n","import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * Open a URL in the user's real default browser, best-effort. Follows the\n * passphrase.ts subprocess rules: an argv array (never a shell), a hard\n * timeout, and failure as a return value rather than a throw — callers print\n * the URL first, so a machine without an opener degrades to copy/paste.\n *\n * The opener is an absolute system path, never a bare name looked up on PATH,\n * and the BROWSER variable and other host-provided hints are dropped from the\n * child's environment. An agent host (Claude Desktop, an IDE) can put a shim on\n * PATH or set BROWSER to route the link into its own embedded view, where Apple\n * Pay and Google Pay cannot complete. On macOS the system's default https\n * handler is looked up and named explicitly with `open -b`. If the default\n * browser is itself an embedded view there is nothing more this can do, and the\n * caller's printed link and QR remain the way out.\n *\n * Windows uses rundll32's FileProtocolHandler because `start` exists only\n * inside cmd.exe, and spawning a shell around an attacker-influenced string is\n * the injection shape this module exists to avoid.\n */\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n execFileImpl?: typeof execFile;\n /** Test seam for the Linux opener search. */\n existsImpl?: (path: string) => boolean;\n /** Test seam for the macOS LaunchServices preferences location. */\n homeDir?: string;\n /** Test seam for the environment handed to the child. */\n env?: NodeJS.ProcessEnv;\n}\n\nconst OPEN_TIMEOUT_MS = 5000;\nconst MAC_OPEN = '/usr/bin/open';\nconst XDG_OPEN_CANDIDATES = [\n '/usr/bin/xdg-open',\n '/bin/xdg-open',\n '/usr/local/bin/xdg-open',\n] as const;\n/** What a bundle id may look like; keeps a hostile preference value from becoming a flag. */\nconst BUNDLE_ID = /^[A-Za-z0-9][A-Za-z0-9.-]*$/;\n\nexport function openerFor(\n platform: NodeJS.Platform,\n existsImpl: (path: string) => boolean = existsSync,\n): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: MAC_OPEN, args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n const found = XDG_OPEN_CANDIDATES.find((p) => existsImpl(p));\n return { cmd: found ?? XDG_OPEN_CANDIDATES[0], args: [] };\n}\n\n/** The child's environment without BROWSER, which xdg-open and others honor over the system default. */\nfunction openerEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const env = { ...base };\n delete env.BROWSER;\n return env;\n}\n\n/**\n * The bundle id of the default https handler, read from the user's LaunchServices\n * preferences, or undefined when none is recorded (the OS default then applies)\n * or anything about the read fails.\n */\nasync function macDefaultBrowserBundleId(\n run: typeof execFile,\n homeDir: string,\n env: NodeJS.ProcessEnv,\n): Promise<string | undefined> {\n const plist = join(\n homeDir,\n 'Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist',\n );\n const out = await new Promise<string | undefined>((resolve) => {\n run(\n '/usr/bin/plutil',\n ['-convert', 'json', '-o', '-', plist],\n { timeout: OPEN_TIMEOUT_MS, env },\n (err, stdout) => resolve(err === null ? String(stdout) : undefined),\n );\n });\n if (out === undefined) return undefined;\n try {\n const parsed = JSON.parse(out) as { LSHandlers?: unknown };\n if (!Array.isArray(parsed.LSHandlers)) return undefined;\n for (const entry of parsed.LSHandlers as Record<string, unknown>[]) {\n const scheme = entry.LSHandlerURLScheme;\n if (typeof scheme !== 'string' || scheme.toLowerCase() !== 'https') continue;\n const id = entry.LSHandlerRoleAll ?? entry.LSHandlerRoleViewer;\n if (typeof id === 'string' && BUNDLE_ID.test(id)) return id;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const platform = opts.platform ?? process.platform;\n const run = opts.execFileImpl ?? execFile;\n const env = openerEnv(opts.env ?? process.env);\n const { cmd, args } = openerFor(platform, opts.existsImpl);\n const launch = (extra: string[]): Promise<boolean> =>\n new Promise((resolve) => {\n run(\n cmd,\n [...args, ...extra, url],\n { timeout: OPEN_TIMEOUT_MS, windowsHide: true, env },\n (err) => resolve(err === null),\n );\n });\n\n if (platform === 'darwin') {\n const bundleId = await macDefaultBrowserBundleId(run, opts.homeDir ?? homedir(), env);\n if (bundleId !== undefined && (await launch(['-b', bundleId]))) return true;\n }\n return await launch([]);\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { buildSiwxHeader, SIWX_HEADER } from '../lib/siwx';\nimport { SESSION_CHAIN_ID } from '../lib/session-key';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { toMoney } from '../lib/money';\nimport { emitNotice, emitWriteNotice } from '../lib/output';\nimport { addressQrLines } from '../lib/qr';\nimport { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { underAgentHarness } from '../lib/session';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin wallet fund`: fund THIS wallet through Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend for a checkout\n * link for that same address (the server refuses any other address). The link is\n * either the Tenjin /fund page (US callers once headless onramp is live, with a\n * short-lived token in the URL fragment) or a Coinbase-hosted checkout. The money\n * moves entirely on Coinbase's side and the link grants no spending power over\n * the wallet. A hosted link is single-use, expires in ~5 minutes and is bound to\n * this machine's public IP at mint time, so it must be opened in a browser on this\n * machine/network.\n */\n\n/** The hosted Coinbase checkout host, one of the two hosts a returned link may use. */\nconst COINBASE_CHECKOUT_HOST = 'pay.coinbase.com';\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = PRODUCTION_ORIGIN;\n/**\n * The only hosts a returned link may point at; anything else is refused unopened.\n * The first is the host of the pinned origin (the Tenjin /fund page), so it\n * follows the origin if that is ever re-pointed.\n */\nconst ALLOWED_CHECKOUT_HOSTS: readonly string[] = [\n new URL(FUND_ORIGIN).host,\n COINBASE_CHECKOUT_HOST,\n];\n/** Matches the server's presetAmount bound (the fund link route's body schema). */\nconst MAX_PRESET_USD = 100_000;\nconst POLL_INTERVAL_MS = 5_000;\nconst POLL_TIMEOUT_MS = 600_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline won. Only `timed-out` says anything about the purchase.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to Coinbase (clamped upward to its own floor there). */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** The environment the agent-harness check reads; defaults to the process's. */\n env?: NodeJS.ProcessEnv;\n /** `--no-qr`: skip the QR block a TTY otherwise gets for sending USDC from a phone. */\n qr?: boolean;\n /** Poll the balance after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n pollIntervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n const signer = await provider.getSigner();\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const baseUrl = FUND_ORIGIN;\n const rpcUrl = settings.rpcUrl.value;\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting, because\n // the envelope carrying the link is written only after runFund returns, and a\n // link that expires in ~5 minutes is worthless after a 10-minute poll.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n\n // Read the balance BEFORE minting so the poll has a baseline; an RPC flake\n // here only disables the wait, it never blocks funding.\n const startBalance = shouldWait ? await balanceOrUndefined(desc, rpcUrl) : undefined;\n\n const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: SESSION_CHAIN_ID });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n jsonBody: {\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/fund/link`, request);\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n const url = checkoutUrlFrom(res.status, res.json);\n\n // The link goes out on EVERY surface and before any waiting: it is single-use\n // with a ~5 minute expiry, and the stdout envelope that also carries it is\n // written only after this function returns. A piped or agent-driven run is\n // exactly the case that must not get the link after it has died, so these\n // three lines are write-notices (stderr, no TTY gate, no --json gate) rather\n // than human-mode notices. stdout stays exactly one JSON object.\n //\n // A Tenjin /fund link carries a token in its fragment, and it prints whole on\n // every path: a user who copies it into another browser needs the token. It is\n // not worth hiding, since it can only fund this wallet and expires in ~10 minutes.\n // An agent's shell has no terminal, but an agent runs this only on the\n // person's yes to \"open the funding page\" (`tenjin install` hands it that\n // question), so under a harness the page opens too.\n const willOpen =\n opts.open !== false && (ctx.io.isTTY || underAgentHarness(opts.env ?? process.env));\n const hosted = new URL(url).host === COINBASE_CHECKOUT_HOST;\n emitWriteNotice(ctx.io, `Checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\n hosted\n ? 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required.'\n : 'The link expires in ~10 minutes. In the US, pay with Apple Pay or Google Pay, no Coinbase account needed.',\n );\n\n let opened = false;\n // The opener is resolved by absolute path and ignores BROWSER (lib/open-url.ts), so an\n // agent host cannot route the link into its embedded view. If the user's default browser\n // is itself an embedded view there is nothing more to do here: the link and QR are printed.\n if (willOpen) {\n opened = await (opts.openUrl ?? openInBrowser)(url);\n emitNotice(\n ctx.io,\n opened ? 'Opened in your default browser.' : 'Could not open a browser; use the link above.',\n { json: ctx.flags.json },\n );\n }\n\n // Human mode only, and before the wait: the poll below also sees USDC sent\n // straight to the address, so a phone wallet is a second way to finish.\n const qrLines =\n opts.qr !== false && ctx.io.isTTY && !ctx.flags.json\n ? addressQrLines(address, ctx.io.stderr)\n : [];\n if (qrLines.length > 0) {\n ctx.io.stderr.write(\n [`Or send USDC from a phone wallet to ${address}:`, ...qrLines].join('\\n') + '\\n',\n );\n }\n\n const funded =\n shouldWait && startBalance !== undefined\n ? await pollForFunds(ctx, desc, rpcUrl, startBalance, opts)\n : undefined;\n if (funded !== undefined) {\n emitWriteNotice(ctx.io, 'USDC arrived - you can close the checkout tab.');\n }\n const pollStatus: FundPollStatus = !shouldWait\n ? 'skipped'\n : startBalance === undefined\n ? 'unavailable'\n : funded !== undefined\n ? 'arrived'\n : 'timed-out';\n\n const balanceAtomic = funded ?? startBalance;\n return {\n data: {\n address,\n checkoutUrl: url,\n opened,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n funded: funded !== undefined,\n pollStatus,\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n },\n humanLines:\n funded !== undefined\n ? [`Funded: balance is now ${toMoney(funded.toString()).usd} USDC on Base.`]\n : [\n 'Checkout link issued (printed above).',\n ...(pollStatus === 'unavailable'\n ? ['Could not read the balance to wait on it; the link is unaffected.']\n : []),\n 'Confirm arrival later with `tenjin wallet balance`.',\n ],\n };\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin wallet fund 5',\n });\n }\n return n;\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on one of the two\n * allowed hosts (the Tenjin origin or Coinbase's checkout) before anything else\n * sees it: a compromised or misconfigured server must not be able to steer the\n * user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (\n parsed !== undefined &&\n parsed.protocol === 'https:' &&\n ALLOWED_CHECKOUT_HOSTS.includes(parsed.host)\n ) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https on ${ALLOWED_CHECKOUT_HOSTS.join(' or ')}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Coinbase Onramp is not available in your region.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', 'The funding endpoint rejected the signed proof.', {\n fix: 'Check this machine’s clock, then retry.',\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'The funding endpoint is rate limited right now.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError(\n 'API_UNREACHABLE',\n 'Production has no Coinbase Onramp configured right now.',\n {\n fix: 'Retry later.',\n },\n );\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(\n desc: { address: string },\n rpcUrl: string,\n): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(desc.address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wait for the purchased USDC to land: any balance above the pre-mint baseline\n * counts (Coinbase clamps presets, so an exact-amount check would be wrong).\n * RPC flakes mid-poll are tolerated; the deadline is the only exit besides\n * arrival, and timing out is a normal outcome (the human may still be paying),\n * not an error.\n */\nasync function pollForFunds(\n ctx: CommandContext,\n desc: { address: string },\n rpcUrl: string,\n startBalance: bigint,\n opts: FundOptions,\n): Promise<bigint | undefined> {\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;\n const deadline = Date.now() + (opts.pollTimeoutMs ?? POLL_TIMEOUT_MS);\n emitNotice(ctx.io, 'Waiting for the USDC to arrive (Ctrl-C is safe; the purchase is not).', {\n json: ctx.flags.json,\n });\n while (Date.now() < deadline) {\n await sleep(interval);\n const balance = await balanceOrUndefined(desc, rpcUrl);\n if (balance !== undefined && balance > startBalance) return balance;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,kBAAiB;;;ACA1B,SAAS,YAAY,aAAa,iBAAiB;AAoDnD,IAAM,gBAAgB,iBACnB,OAAO;AAAA,EACN,KAAK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AACN,WAAO;AAAA,EACT;AACF;AASA,eAAe,aACb,KACA,MACA,QACA,cACA,MAC6B;AAC7B,QAAM,QACJ,KAAK,UAAU,CAAC,OAAe,IAAI,QAAc,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACvF,QAAM,WAAW,KAAK,kBAAkB;AACxC,QAAM,WAAW,KAAK,IAAI,KAAK,KAAK,iBAAiB;AACrD,aAAW,IAAI,IAAI,yEAAyE;AAAA,IAC1F,MAAM,IAAI,MAAM;AAAA,EAClB,CAAC;AACD,SAAO,KAAK,IAAI,IAAI,UAAU;AAC5B,UAAM,MAAM,QAAQ;AACpB,UAAM,UAAU,MAAM,mBAAmB,MAAM,MAAM;AACrD,QAAI,YAAY,UAAa,UAAU,aAAc,QAAO;AAAA,EAC9D;AACA,SAAO;AACT;","names":["webcrypto","subtle","webcrypto"]}
|
|
1
|
+
{"version":3,"sources":["../src/lib/session-key.ts","../src/lib/session-present.ts","../src/lib/open-url.ts","../src/commands/fund.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport { sessionPath } from './paths';\nimport { writeFileAtomic } from './atomic-json';\nimport { buildSiwxHeader } from './siwx';\nimport { originOf } from './url';\nimport {\n isSessionUsable,\n loadSessionFile,\n signWithSession,\n type SessionFile,\n type SessionKeyDeps,\n type SessionScope,\n type SignableRequest,\n} from './session-present';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * Session-key delegation (RFC 9421 signed HTTP, RFC 9530-shaped Content-Digest),\n * verified byte-for-byte against the live \"Auth — session keys\" contract in\n * https://tenjin.sh/llms-full.txt (D35).\n *\n * The point: a plain SIWX write burns a single-use nonce, so every write needs a\n * fresh WALLET signature. A session key trades that for ONE wallet signature per\n * session: generate a P-256 keypair, wallet-sign a SIWX message binding its\n * pubkey/exp/scope, then sign each subsequent write with the P-256 key (no wallet\n * popup) until the delegation expires. The delegated key is short-lived (≤24h,\n * server-clamped) and cached 0600, address-bound so a wallet change invalidates it.\n *\n * This module is the MINT half — everything that needs a wallet signer, i.e.\n * `establishSession`, the cache writer, and the two `WriteAuth` implementations.\n * The present-only half (load a file, sign one request with it) lives in\n * `session-present.ts` and is re-exported below, so `posts-api`/`publish`/`edit`\n * keep importing one module while a caller that only wants to present a live\n * delegation — `read`, on the reuse path — imports that half alone and touches\n * no keystore. Do not move a signer-touching function down into\n * `session-present.ts`: that free reuse path is what it buys.\n *\n * A minted delegation is a wallet-derived credential, so it is bound to the\n * ORIGIN it was minted against and every presenter re-checks that binding.\n *\n * Never hand-rolls crypto: P-256 keygen is node:crypto webcrypto (subtle) and the\n * wallet delegation reuses the siwx.ts seam.\n */\n\nexport {\n contentDigest,\n isSessionPresentable,\n readSessionFile,\n isSessionUsable,\n keyidFor,\n loadSessionFile,\n scopeSatisfies,\n signatureBase,\n signatureParams,\n signWithSession,\n targetUri,\n} from './session-present';\nexport type {\n SessionFile,\n SessionFileState,\n SessionKeyDeps,\n SessionScope,\n SignableRequest,\n SignatureParamsInput,\n} from './session-present';\n\n/**\n * The chain a session delegation is signed over. Writes require Base mainnet per\n * the server's SIWX chain constraint, and a session covers reads and writes\n * alike, so there is exactly ONE session chain id rather than a per-caller\n * choice: the read path and the write path must mint against the same chain or\n * the file they share would flip between two delegations.\n */\nexport const SESSION_CHAIN_ID = 'eip155:8453';\n\nconst SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h; the server clamps to ≤24h.\n\n/**\n * The write-auth seam a posts client signs through. `headersFor` attaches the\n * signature headers (establishing the session lazily on first use); `recover`\n * reacts to a 401 by returning whether a retry is worthwhile.\n */\nexport interface WriteAuth {\n headersFor(req: SignableRequest): Promise<Record<string, string>>;\n /** React to a write's 401 `code`; true ⇒ the next headersFor retry may succeed. */\n recover(code: string | undefined): Promise<boolean>;\n}\n\nexport interface SessionKeyConfig {\n signer: TenjinSigner;\n baseUrl: string;\n chainId: string;\n dataDir: string;\n /**\n * The scope this session is minted at, and the scope a cached session must\n * cover to be reused. Required, not defaulted: over-granting silently is the\n * failure mode worth making impossible, so every caller states what it needs.\n */\n scope: SessionScope;\n}\n\nconst subtle = webcrypto.subtle;\n\nfunction generateP256KeyPair(): Promise<webcrypto.CryptoKeyPair> {\n return subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]) as Promise<webcrypto.CryptoKeyPair>;\n}\n\n/** base64url (no padding) of raw bytes — the pubkey/keyid encoding. */\nfunction toBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** The three URNs bound into the delegation's SIWX `resources` array (D35). */\nexport function delegationResources(\n publicKeyRaw: string,\n expIso: string,\n scope: SessionScope,\n): string[] {\n return [\n `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,\n `urn:tenjin:session:exp:${expIso}`,\n `urn:tenjin:session:scope:${scope}`,\n ];\n}\n\n/**\n * Establish a session with ONE wallet signature: generate a P-256 keypair, bind\n * its pubkey/exp/scope into a SIWX message, wallet-sign it, and cache the result\n * 0600 address-bound. The returned file's `delegation` is the constant\n * `Tenjin-Session-Delegation` header for the session's life.\n */\nexport async function establishSession(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): Promise<SessionFile> {\n const now = deps.now ?? Date.now;\n const pair = await generateP256KeyPair();\n const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));\n const publicKeyRaw = toBase64Url(rawPub);\n const jwk = (await subtle.exportKey('jwk', pair.privateKey)) as SessionFile['privateKeyJwk'];\n\n const expIso = new Date(now() + SESSION_TTL_MS).toISOString();\n const delegation = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n ttlMs: SESSION_TTL_MS,\n statement: 'Delegate a Tenjin session key.',\n resources: delegationResources(publicKeyRaw, expIso, config.scope),\n });\n\n const file: SessionFile = {\n address: config.signer.address.toLowerCase(),\n origin: originOf(config.baseUrl),\n delegation,\n exp: expIso,\n scope: config.scope,\n publicKeyRaw,\n privateKeyJwk: jwk,\n };\n await saveSessionFile(config.dataDir, file);\n return file;\n}\n\n// ---------------------------------------------------------------------------\n// Cache writes (0600, address-bound). The reader lives in session-present.\n// ---------------------------------------------------------------------------\n\nexport async function saveSessionFile(dir: string, file: SessionFile): Promise<void> {\n await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n// ---------------------------------------------------------------------------\n// The WriteAuth implementation: lazy establish, cache reuse, 401 recovery.\n// ---------------------------------------------------------------------------\n\n/** How each 401 `code` maps to recovery (per the llms-full.txt policy section). */\ntype Recovery = 'resign' | 'reestablish' | 'fatal';\n\nexport function recoveryFor(code: string | undefined): Recovery {\n switch (code) {\n case 'proof_expired':\n // The per-request signature is too old; just re-sign (no wallet).\n return 'resign';\n case 'session_expired':\n case 'proof_revoked':\n case 'insufficient_scope':\n // The delegation itself is gone/insufficient; re-establish (one wallet sig).\n return 'reestablish';\n case 'session_key_unbound':\n // keyid ≠ the delegation-bound key: retrying cannot fix it.\n return 'fatal';\n default:\n return 'fatal';\n }\n}\n\n/**\n * A session-key WriteAuth: mints (or loads) the delegation on first use and signs\n * every write with the P-256 key — so a returning agent never wallet-signs again\n * until the session expires. On a 401 it re-signs or re-establishes per the code.\n */\nexport function createSessionKeyAuth(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): WriteAuth {\n const now = deps.now ?? Date.now;\n let cached: SessionFile | null = null;\n let forceReestablish = false;\n\n const ensure = async (): Promise<SessionFile> => {\n if (\n !forceReestablish &&\n cached !== null &&\n isSessionUsable(cached, config.signer.address, now(), config.scope, originOf(config.baseUrl))\n ) {\n return cached;\n }\n if (!forceReestablish) {\n const onDisk = await loadSessionFile(config.dataDir);\n const origin = originOf(config.baseUrl);\n if (\n onDisk !== null &&\n isSessionUsable(onDisk, config.signer.address, now(), config.scope, origin)\n ) {\n cached = onDisk;\n return cached;\n }\n }\n cached = await establishSession(config, deps);\n forceReestablish = false;\n return cached;\n };\n\n return {\n async headersFor(req) {\n const file = await ensure();\n return signWithSession(file, req, deps);\n },\n async recover(code) {\n const recovery = recoveryFor(code);\n if (recovery === 'fatal') return false;\n if (recovery === 'reestablish') {\n cached = null;\n forceReestablish = true;\n }\n // 'resign' needs no state change: the next headersFor mints a fresh\n // created/nonce over the same (still-valid) delegation.\n return true;\n },\n };\n}\n\n/**\n * The plain-SIWX fallback (no session): every write carries its own fresh\n * wallet-signed `SIGN-IN-WITH-X` header. Used when session establishment is\n * disabled; a burned/stale nonce (401) is recovered by re-signing.\n */\nexport function createSiwxAuth(config: SessionKeyConfig): WriteAuth {\n return {\n async headersFor() {\n const header = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n });\n return { 'SIGN-IN-WITH-X': header };\n },\n async recover(code) {\n // A single-use nonce burns on every write; a stale/burned nonce (or an\n // expired proof) is recovered by re-signing with a fresh nonce + issuedAt.\n return code === 'nonce_already_used' || code === 'invalid_proof' || code === 'proof_expired';\n },\n };\n}\n","import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split earns its keep on the reuse path: presenting a live delegation costs\n * no keystore decryption, so `tenjin read` reaches this half alone whenever one\n * is cached and only falls through to the mint half (and one passphrase) when\n * there is none. Neither half says anything about what an already-minted\n * delegation is worth to whoever holds it — see `origin` below, and the tier\n * note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.sh/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET or DELETE has no body to\n * cover at all, so content-digest drops out of the covered set. As a union,\n * \"GET with a body\" and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET' | 'DELETE'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache (`~/.tenjin/session.json`); the next read or write mints a fresh one.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends. Keyed on\n // the presence of a body rather than on the method list, so a bodiless method\n // added to the union above needs no second edit here to stay bodiless.\n const digest = 'body' in req ? contentDigest(req.body) : undefined;\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n /** An OLDER CLI's file, missing a field the shape has since required. Unusable\n * and re-mintable like an absent one, so NOT the tamper signal `corrupt` is. */\n | { kind: 'outdated'; field: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\n/**\n * Fields an OLDER CLI's file can legitimately lack. An allowlist, not \"any missing\n * key\": a file with no `privateKeyJwk.d` cannot sign and is broken whoever wrote\n * it. Add a name when the schema grows a required field, never to quiet a test.\n */\nconst LATER_ADDED_FIELDS: readonly string[] = ['origin'];\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const legacy = (i: (typeof issues)[number]): boolean =>\n LATER_ADDED_FIELDS.includes(i.path.join('.')) && !hasPath(json, i.path);\n // Report the first NON-legacy issue when there is one: a file missing both\n // `origin` and its private scalar is corrupt because of the scalar, and naming\n // the benign field points the operator at the wrong thing.\n const issue = issues.find((i) => !legacy(i)) ?? issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // EVERY failure must be an allowlisted later field the file genuinely lacks.\n // One legacy omission cannot vouch for the rest of the file, and zod reports in\n // schema order, so the first issue alone would let a broken key ride in.\n const legacyOnly = issues.length > 0 && issues.every(legacy);\n if (legacyOnly && field !== undefined) return { kind: 'outdated', field };\n // Field-qualified: the message alone names none. zod never echoes the received\n // VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** Does `value` actually carry the key at `path`, whatever it holds there? */\nfunction hasPath(value: unknown, path: readonly PropertyKey[]): boolean {\n let cur: unknown = value;\n for (const key of path) {\n if (typeof cur !== 'object' || cur === null) return false;\n if (!Object.hasOwn(cur, key)) return false;\n cur = (cur as Record<PropertyKey, unknown>)[key];\n }\n return true;\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n","import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * Open a URL in the user's real default browser, best-effort. Follows the\n * passphrase.ts subprocess rules: an argv array (never a shell), a hard\n * timeout, and failure as a return value rather than a throw — callers print\n * the URL first, so a machine without an opener degrades to copy/paste.\n *\n * The opener is an absolute system path, never a bare name looked up on PATH,\n * and the BROWSER variable and other host-provided hints are dropped from the\n * child's environment. An agent host (Claude Desktop, an IDE) can put a shim on\n * PATH or set BROWSER to route the link into its own embedded view, where Apple\n * Pay and Google Pay cannot complete. On macOS the system's default https\n * handler is looked up and named explicitly with `open -b`. If the default\n * browser is itself an embedded view there is nothing more this can do, and the\n * caller's printed link and QR remain the way out.\n *\n * Windows uses rundll32's FileProtocolHandler because `start` exists only\n * inside cmd.exe, and spawning a shell around an attacker-influenced string is\n * the injection shape this module exists to avoid.\n */\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n execFileImpl?: typeof execFile;\n /** Test seam for the Linux opener search. */\n existsImpl?: (path: string) => boolean;\n /** Test seam for the macOS LaunchServices preferences location. */\n homeDir?: string;\n /** Test seam for the environment handed to the child. */\n env?: NodeJS.ProcessEnv;\n}\n\nconst OPEN_TIMEOUT_MS = 5000;\nconst MAC_OPEN = '/usr/bin/open';\nconst XDG_OPEN_CANDIDATES = [\n '/usr/bin/xdg-open',\n '/bin/xdg-open',\n '/usr/local/bin/xdg-open',\n] as const;\n/** What a bundle id may look like; keeps a hostile preference value from becoming a flag. */\nconst BUNDLE_ID = /^[A-Za-z0-9][A-Za-z0-9.-]*$/;\n\nexport function openerFor(\n platform: NodeJS.Platform,\n existsImpl: (path: string) => boolean = existsSync,\n): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: MAC_OPEN, args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n const found = XDG_OPEN_CANDIDATES.find((p) => existsImpl(p));\n return { cmd: found ?? XDG_OPEN_CANDIDATES[0], args: [] };\n}\n\n/** The child's environment without BROWSER, which xdg-open and others honor over the system default. */\nfunction openerEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const env = { ...base };\n delete env.BROWSER;\n return env;\n}\n\n/**\n * The bundle id of the default https handler, read from the user's LaunchServices\n * preferences, or undefined when none is recorded (the OS default then applies)\n * or anything about the read fails.\n */\nasync function macDefaultBrowserBundleId(\n run: typeof execFile,\n homeDir: string,\n env: NodeJS.ProcessEnv,\n): Promise<string | undefined> {\n const plist = join(\n homeDir,\n 'Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist',\n );\n const out = await new Promise<string | undefined>((resolve) => {\n run(\n '/usr/bin/plutil',\n ['-convert', 'json', '-o', '-', plist],\n { timeout: OPEN_TIMEOUT_MS, env },\n (err, stdout) => resolve(err === null ? String(stdout) : undefined),\n );\n });\n if (out === undefined) return undefined;\n try {\n const parsed = JSON.parse(out) as { LSHandlers?: unknown };\n if (!Array.isArray(parsed.LSHandlers)) return undefined;\n for (const entry of parsed.LSHandlers as Record<string, unknown>[]) {\n const scheme = entry.LSHandlerURLScheme;\n if (typeof scheme !== 'string' || scheme.toLowerCase() !== 'https') continue;\n const id = entry.LSHandlerRoleAll ?? entry.LSHandlerRoleViewer;\n if (typeof id === 'string' && BUNDLE_ID.test(id)) return id;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const platform = opts.platform ?? process.platform;\n const run = opts.execFileImpl ?? execFile;\n const env = openerEnv(opts.env ?? process.env);\n const { cmd, args } = openerFor(platform, opts.existsImpl);\n const launch = (extra: string[]): Promise<boolean> =>\n new Promise((resolve) => {\n run(\n cmd,\n [...args, ...extra, url],\n { timeout: OPEN_TIMEOUT_MS, windowsHide: true, env },\n (err) => resolve(err === null),\n );\n });\n\n if (platform === 'darwin') {\n const bundleId = await macDefaultBrowserBundleId(run, opts.homeDir ?? homedir(), env);\n if (bundleId !== undefined && (await launch(['-b', bundleId]))) return true;\n }\n return await launch([]);\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { buildSiwxHeader, SIWX_HEADER } from '../lib/siwx';\nimport { SESSION_CHAIN_ID } from '../lib/session-key';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { forgetRememberedBalance } from '../lib/usdc-balance';\nimport { toMoney } from '../lib/money';\nimport { emitNotice, emitWriteNotice } from '../lib/output';\nimport { addressQrLines } from '../lib/qr';\nimport { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { underAgentHarness } from '../lib/session';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin wallet fund`: fund THIS wallet through Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend for a checkout\n * link for that same address (the server refuses any other address). The link is\n * either the Tenjin /fund page (US callers once headless onramp is live, with a\n * short-lived token in the URL fragment) or a Coinbase-hosted checkout. The money\n * moves entirely on Coinbase's side and the link grants no spending power over\n * the wallet. A hosted link is single-use, expires in ~5 minutes and is bound to\n * this machine's public IP at mint time, so it must be opened in a browser on this\n * machine/network.\n */\n\n/** The hosted Coinbase checkout host, one of the two hosts a returned link may use. */\nconst COINBASE_CHECKOUT_HOST = 'pay.coinbase.com';\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = PRODUCTION_ORIGIN;\n/**\n * The only hosts a returned link may point at; anything else is refused unopened.\n * The first is the host of the pinned origin (the Tenjin /fund page), so it\n * follows the origin if that is ever re-pointed.\n */\nconst ALLOWED_CHECKOUT_HOSTS: readonly string[] = [\n new URL(FUND_ORIGIN).host,\n COINBASE_CHECKOUT_HOST,\n];\n/** Matches the server's presetAmount bound (the fund link route's body schema). */\nconst MAX_PRESET_USD = 100_000;\nconst POLL_INTERVAL_MS = 5_000;\nconst POLL_TIMEOUT_MS = 600_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline won. None establishes the checkout's payment status.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to Coinbase (clamped upward to its own floor there). */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** The environment the agent-harness check reads; defaults to the process's. */\n env?: NodeJS.ProcessEnv;\n /** `--no-qr`: skip the QR block a TTY otherwise gets for sending USDC from a phone. */\n qr?: boolean;\n /** Poll the balance after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n pollIntervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n const signer = await provider.getSigner();\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const baseUrl = FUND_ORIGIN;\n const rpcUrl = settings.rpcUrl.value;\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting, because\n // the envelope carrying the link is written only after runFund returns, and a\n // link that expires in ~5 minutes is worthless after a 10-minute poll.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n\n // Read the balance BEFORE minting so the poll has a baseline; an RPC flake\n // here only disables the wait, it never blocks funding.\n const startBalance = shouldWait ? await balanceOrUndefined(desc, rpcUrl) : undefined;\n\n const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: SESSION_CHAIN_ID });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n jsonBody: {\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/fund/link`, request);\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n const url = checkoutUrlFrom(res.status, res.json);\n\n // The link goes out on EVERY surface and before any waiting: it is single-use\n // with a ~5 minute expiry, and the stdout envelope that also carries it is\n // written only after this function returns. A piped or agent-driven run is\n // exactly the case that must not get the link after it has died, so these\n // three lines are write-notices (stderr, no TTY gate, no --json gate) rather\n // than human-mode notices. stdout stays exactly one JSON object.\n //\n // A Tenjin /fund link carries a token in its fragment, and it prints whole on\n // every path: a user who copies it into another browser needs the token. It is\n // not worth hiding, since it can only fund this wallet and expires in ~10 minutes.\n // An agent's shell has no terminal, but an agent runs this only on the\n // person's yes to \"open the funding page\" (`tenjin install` hands it that\n // question), so under a harness the page opens too.\n const willOpen =\n opts.open !== false && (ctx.io.isTTY || underAgentHarness(opts.env ?? process.env));\n const hosted = new URL(url).host === COINBASE_CHECKOUT_HOST;\n emitWriteNotice(ctx.io, `Checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\n hosted\n ? 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required.'\n : 'The link expires in ~10 minutes. In the US, pay with Apple Pay or Google Pay, no Coinbase account needed.',\n );\n\n let opened = false;\n // The opener is resolved by absolute path and ignores BROWSER (lib/open-url.ts), so an\n // agent host cannot route the link into its embedded view. If the user's default browser\n // is itself an embedded view there is nothing more to do here: the link and QR are printed.\n if (willOpen) {\n opened = await (opts.openUrl ?? openInBrowser)(url);\n emitNotice(\n ctx.io,\n opened ? 'Opened in your default browser.' : 'Could not open a browser; use the link above.',\n { json: ctx.flags.json },\n );\n }\n\n // Human mode only, and before the wait: the poll below also sees USDC sent\n // straight to the address, so a phone wallet is a second way to finish.\n const qrLines =\n opts.qr !== false && ctx.io.isTTY && !ctx.flags.json\n ? addressQrLines(address, ctx.io.stderr)\n : [];\n if (qrLines.length > 0) {\n ctx.io.stderr.write(\n [`Or send USDC from a phone wallet to ${address}:`, ...qrLines].join('\\n') + '\\n',\n );\n }\n\n const funded =\n shouldWait && startBalance !== undefined\n ? await pollForFunds(ctx, desc, rpcUrl, startBalance, opts)\n : undefined;\n if (funded !== undefined) {\n await forgetRememberedBalance(ctx.dataDir);\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 nextStep:\n funded !== undefined\n ? 'Funds confirmed. Continue the original task; funding does not require another restart.'\n : 'Ask the person to finish checkout and return to this conversation. When they return, run `wallet balance` with the same Tenjin executable and shell used for this funding command to check funds, then continue their task if sufficient. Until the balance confirms funds, say \"Funds not confirmed\"; if the balance cannot be read, say you could not check it. Do not open another checkout unless they ask for a new link or the current link has expired. Run the check yourself, never ask the person to type a command.',\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 'Finish checkout, then return to your agent to confirm funds and continue your task.',\n 'Funds not confirmed. Check with `tenjin wallet balance` before adding funds again.',\n ],\n };\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin wallet fund 5',\n });\n }\n return n;\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on one of the two\n * allowed hosts (the Tenjin origin or Coinbase's checkout) before anything else\n * sees it: a compromised or misconfigured server must not be able to steer the\n * user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (\n parsed !== undefined &&\n parsed.protocol === 'https:' &&\n ALLOWED_CHECKOUT_HOSTS.includes(parsed.host)\n ) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https on ${ALLOWED_CHECKOUT_HOSTS.join(' or ')}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Coinbase Onramp is not available in your region.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', 'The funding endpoint rejected the signed proof.', {\n fix: 'Check this machine’s clock, then retry.',\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'The funding endpoint is rate limited right now.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError(\n 'API_UNREACHABLE',\n 'Production has no Coinbase Onramp configured right now.',\n {\n fix: 'Retry later.',\n },\n );\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(\n desc: { address: string },\n rpcUrl: string,\n): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(desc.address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wait for the purchased USDC to land: any balance above the pre-mint baseline\n * counts (Coinbase clamps presets, so an exact-amount check would be wrong).\n * RPC flakes mid-poll are tolerated; the deadline is the only exit besides\n * arrival, and timing out is a normal outcome (the human may still be paying),\n * not an error.\n */\nasync function pollForFunds(\n ctx: CommandContext,\n desc: { address: string },\n rpcUrl: string,\n startBalance: bigint,\n opts: FundOptions,\n): Promise<bigint | undefined> {\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;\n const deadline = Date.now() + (opts.pollTimeoutMs ?? POLL_TIMEOUT_MS);\n emitNotice(ctx.io, 'Waiting for the USDC to arrive (Ctrl-C is safe; the purchase is not).', {\n json: ctx.flags.json,\n });\n while (Date.now() < deadline) {\n await sleep(interval);\n const balance = await balanceOrUndefined(desc, rpcUrl);\n if (balance !== undefined && balance > startBalance) return balance;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,kBAAiB;;;ACA1B,SAAS,YAAY,aAAa,iBAAiB;AAoDnD,IAAM,gBAAgB,iBACnB,OAAO;AAAA,EACN,KAAK,iBAAE,QAAQ,IAAI;AAAA,EACnB,KAAK,iBAAE,QAAQ,OAAO;AAAA,EACtB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AACrB,CAAC,EACA,YAAY;AAGf,IAAM,oBAAoB,iBAAE,OAAO;AAAA;AAAA,EAEjC,SAAS,iBAAE,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAalB,QAAQ,iBAAE,OAAO;AAAA;AAAA,EAEjB,YAAY,iBAAE,OAAO;AAAA;AAAA,EAErB,KAAK,iBAAE,OAAO;AAAA,EACd,OAAO,iBAAE,OAAO;AAAA;AAAA,EAEhB,cAAc,iBAAE,OAAO;AAAA,EACvB,eAAe;AACjB,CAAC;AAmBD,IAAM,SAAS,UAAU;;;ADjClB,IAAM,mBAAmB;AAEhC,IAAM,iBAAiB,KAAK,KAAK,KAAK;AA0BtC,IAAMC,UAASC,WAAU;;;AErGzB,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,SAAS,YAAY;AAiCrB,IAAM,kBAAkB;AACxB,IAAM,WAAW;AACjB,IAAM,sBAAsB;AAAA,EAC1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;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"]}
|
|
@@ -3,33 +3,32 @@ import {
|
|
|
3
3
|
STDIN_TIMEOUT_MS,
|
|
4
4
|
runHookCommand,
|
|
5
5
|
runHookKind
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-ZDZERB6L.js";
|
|
7
7
|
import "./chunk-JKKAIPTU.js";
|
|
8
|
-
import "./chunk-
|
|
8
|
+
import "./chunk-P3LFTKE7.js";
|
|
9
9
|
import "./chunk-4USCZ2NI.js";
|
|
10
10
|
import "./chunk-62KNUYWD.js";
|
|
11
11
|
import "./chunk-SO3XRZPX.js";
|
|
12
|
-
import "./chunk-
|
|
12
|
+
import "./chunk-LXAYUOXI.js";
|
|
13
13
|
import "./chunk-3623BLPV.js";
|
|
14
14
|
import "./chunk-XKESD27X.js";
|
|
15
15
|
import "./chunk-HDPUXS3Z.js";
|
|
16
16
|
import "./chunk-2SNUOHAT.js";
|
|
17
17
|
import "./chunk-MPZUYCAP.js";
|
|
18
|
-
import "./chunk-
|
|
19
|
-
import "./chunk-
|
|
20
|
-
import "./chunk-YUY4SAGM.js";
|
|
18
|
+
import "./chunk-36RVGZNY.js";
|
|
19
|
+
import "./chunk-RVPYTUP4.js";
|
|
21
20
|
import "./chunk-IADZOXKN.js";
|
|
22
|
-
import "./chunk-
|
|
23
|
-
import "./chunk-
|
|
24
|
-
import "./chunk-
|
|
21
|
+
import "./chunk-C2Q76BVM.js";
|
|
22
|
+
import "./chunk-AGMVASXZ.js";
|
|
23
|
+
import "./chunk-KM7RY2ZS.js";
|
|
25
24
|
import "./chunk-Y527D4TV.js";
|
|
26
|
-
import "./chunk-
|
|
25
|
+
import "./chunk-NDGZDTSJ.js";
|
|
27
26
|
import "./chunk-BFDQ4WNW.js";
|
|
28
27
|
import "./chunk-3AIHRXKO.js";
|
|
29
28
|
import "./chunk-X5ZBP3IY.js";
|
|
30
29
|
import "./chunk-2I4QTOLB.js";
|
|
31
|
-
import "./chunk-
|
|
32
|
-
import "./chunk-
|
|
30
|
+
import "./chunk-2M2VPI2E.js";
|
|
31
|
+
import "./chunk-WXA2BWTE.js";
|
|
33
32
|
import "./chunk-XQJXNMSB.js";
|
|
34
33
|
import "./chunk-SNNSAGMT.js";
|
|
35
34
|
import "./chunk-7WEQQJLG.js";
|
|
@@ -41,4 +40,4 @@ export {
|
|
|
41
40
|
runHookCommand,
|
|
42
41
|
runHookKind
|
|
43
42
|
};
|
|
44
|
-
//# sourceMappingURL=hook-command-
|
|
43
|
+
//# sourceMappingURL=hook-command-2UBCSZG6.js.map
|
|
@@ -6,14 +6,14 @@
|
|
|
6
6
|
},
|
|
7
7
|
"description": "Tenjin's tool router for Claude Code, installed by `tenjin install`.",
|
|
8
8
|
"metadata": {
|
|
9
|
-
"version": "0.1.0-alpha.
|
|
9
|
+
"version": "0.1.0-alpha.33"
|
|
10
10
|
},
|
|
11
11
|
"plugins": [
|
|
12
12
|
{
|
|
13
13
|
"name": "tenjin",
|
|
14
14
|
"source": "./tenjin",
|
|
15
15
|
"description": "Tenjin picks the right tool when your agent needs one, and one wallet on this machine pays for every call.",
|
|
16
|
-
"version": "0.1.0-alpha.
|
|
16
|
+
"version": "0.1.0-alpha.33"
|
|
17
17
|
}
|
|
18
18
|
]
|
|
19
19
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tenjin",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.33",
|
|
4
4
|
"description": "Tenjin picks the right tool when your agent needs one, and one wallet on this machine pays for every call.",
|
|
5
5
|
"types": "./types/index.d.ts",
|
|
6
6
|
"author": {
|
|
@@ -10,6 +10,6 @@
|
|
|
10
10
|
"homepage": "https://tenjin.sh/agents",
|
|
11
11
|
"repository": "https://github.com/BackTrackCo/tenjin-agent",
|
|
12
12
|
"metadata": {
|
|
13
|
-
"tenjin-cli": "0.1.0-alpha.
|
|
13
|
+
"tenjin-cli": "0.1.0-alpha.33"
|
|
14
14
|
}
|
|
15
15
|
}
|
|
@@ -15,8 +15,9 @@ import type { TenjinHeld, TenjinRow } from '../types';
|
|
|
15
15
|
* place `⏺ Exa search("q") · $0.007`, the dot carrying the state.
|
|
16
16
|
*
|
|
17
17
|
* An over-limit answer draws nothing, and the `approve` call that runs its
|
|
18
|
-
* quote draws as the lookup's own row.
|
|
19
|
-
*
|
|
18
|
+
* quote draws as the lookup's own row. A free lookup the CLI named draws the
|
|
19
|
+
* same row with `free` where the price goes. The router's own calls and
|
|
20
|
+
* `needs_input` answers draw nothing; a charged failure
|
|
20
21
|
* draws the error dot, the amount and the state, never a success.
|
|
21
22
|
*
|
|
22
23
|
* EXPANDED: wherever the view shows rows in full (ctrl+o, --verbose: the
|
|
@@ -25,9 +26,10 @@ import type { TenjinHeld, TenjinRow } from '../types';
|
|
|
25
26
|
* here included. Its title there is the tool's static one. A row of a run
|
|
26
27
|
* this mod unfolded in the normal view stays compact.
|
|
27
28
|
*
|
|
28
|
-
* READ ONLY: the spec file, the choice set and the offer
|
|
29
|
-
* and the request tool's own envelope.
|
|
30
|
-
* dir and decides nothing about routing
|
|
29
|
+
* READ ONLY: the spec file, the choice set, the free label and the offer
|
|
30
|
+
* record (`src/router/mod-state.ts`), and the request tool's own envelope.
|
|
31
|
+
* The mod writes nothing under the data dir and decides nothing about routing
|
|
32
|
+
* or payment.
|
|
31
33
|
*/
|
|
32
34
|
|
|
33
35
|
const REQUEST_TOOL = 'mcp__plugin_tenjin_router__request';
|
|
@@ -65,6 +67,8 @@ const HIDDEN = new Set(['spec', 'discovered', 'native', 'browse', 'needs_input',
|
|
|
65
67
|
/** Endings drawn with no state word. */
|
|
66
68
|
const PLAIN = new Set(['fulfilled', 'running']);
|
|
67
69
|
const ERRORS = new Set(['failed', 'interrupted', 'partial']);
|
|
70
|
+
/** What the price slot says for a lookup that costs nothing. */
|
|
71
|
+
const FREE = 'free';
|
|
68
72
|
|
|
69
73
|
type Dollar = EngineInterface;
|
|
70
74
|
type Json = Record<string, unknown>;
|
|
@@ -244,14 +248,15 @@ export const register: Register = (on) => {
|
|
|
244
248
|
});
|
|
245
249
|
};
|
|
246
250
|
|
|
247
|
-
/** A
|
|
248
|
-
*
|
|
249
|
-
* router's own calls. */
|
|
251
|
+
/** A call before it runs: `{id, input}` with a kept spec, `{id, choice,
|
|
252
|
+
* input}` with the choice set kept beside the line's id, or a free `{id,
|
|
253
|
+
* query}` whose name the CLI kept. Null for the router's own calls. */
|
|
250
254
|
async function describeCall($: Dollar, e: Json): Promise<TenjinRow | null> {
|
|
251
255
|
const id = typeof e.id === 'string' && e.id.length > 0 ? e.id : undefined;
|
|
252
256
|
const input = asRecord(e.input);
|
|
253
257
|
const dataDir = await tenjinDataDir($);
|
|
254
|
-
if (id === undefined ||
|
|
258
|
+
if (id === undefined || dataDir === null) return null;
|
|
259
|
+
if (input === undefined) return describeFree($, dataDir, id, e.query);
|
|
255
260
|
const read = async (key: string) =>
|
|
256
261
|
readJson($, `${dataDir}/progress/specs/${await sha256Hex(key)}.json`);
|
|
257
262
|
const choice = typeof e.choice === 'string' && e.choice.length > 0 ? e.choice : undefined;
|
|
@@ -274,6 +279,29 @@ async function describeCall($: Dollar, e: Json): Promise<TenjinRow | null> {
|
|
|
274
279
|
return { label, offerId: id, ...priced([spec], takes), ...shownOf([spec], input) };
|
|
275
280
|
}
|
|
276
281
|
|
|
282
|
+
/**
|
|
283
|
+
* A free lookup the CLI showed a line for (`{id, query}`): it has no spec, so
|
|
284
|
+
* its name is the label the CLI kept by its id
|
|
285
|
+
* (`progress/specs/<sha256(id)>.label.json`), and its input is its `query`.
|
|
286
|
+
*/
|
|
287
|
+
async function describeFree(
|
|
288
|
+
$: Dollar,
|
|
289
|
+
dataDir: string,
|
|
290
|
+
id: string,
|
|
291
|
+
query: unknown,
|
|
292
|
+
): Promise<TenjinRow | null> {
|
|
293
|
+
const kept = await readJson($, `${dataDir}/progress/specs/${await sha256Hex(id)}.label.json`);
|
|
294
|
+
const label = kept?.id === id ? labelOf(kept.label) : undefined;
|
|
295
|
+
if (label === undefined) return null;
|
|
296
|
+
const argument = typeof query === 'string' ? shortKey(query) : undefined;
|
|
297
|
+
return {
|
|
298
|
+
label,
|
|
299
|
+
offerId: id,
|
|
300
|
+
...priceOf(0n, false),
|
|
301
|
+
...(argument !== undefined ? { argument } : {}),
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
277
305
|
/** What the specs cost together, `takes` times each: `$0.04`, or `up to $0.05`. */
|
|
278
306
|
function priced(specs: (Json | null)[], takes: bigint): { price?: string } {
|
|
279
307
|
let total = 0n;
|
|
@@ -284,6 +312,12 @@ function priced(specs: (Json | null)[], takes: bigint): { price?: string } {
|
|
|
284
312
|
if (each === undefined) return {};
|
|
285
313
|
total += BigInt(each) * takes;
|
|
286
314
|
}
|
|
315
|
+
return priceOf(total, varies);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** The price slot: `$0.04`, `up to $0.05`, or `free`. */
|
|
319
|
+
function priceOf(total: bigint, varies: boolean): { price: string } {
|
|
320
|
+
if (total === 0n && !varies) return { price: FREE };
|
|
287
321
|
return { price: `${varies ? 'up to ' : ''}$${usd(total)}` };
|
|
288
322
|
}
|
|
289
323
|
|
|
@@ -313,7 +347,8 @@ function endOf(envelope: Json | undefined): Partial<TenjinRow> {
|
|
|
313
347
|
}
|
|
314
348
|
|
|
315
349
|
/** A request call's row, or null where it draws nothing: not started, one of
|
|
316
|
-
* the router's own, sent back for input,
|
|
350
|
+
* the router's own, sent back for input, ended with nothing paid and not a
|
|
351
|
+
* free lookup the CLI named, or drawn on a held call's row. */
|
|
317
352
|
async function rowOf(
|
|
318
353
|
$: Dollar,
|
|
319
354
|
id: string,
|
|
@@ -329,7 +364,12 @@ async function rowOf(
|
|
|
329
364
|
if (label === undefined) return null;
|
|
330
365
|
const drawn: TenjinRow = { ...stored, ...ended, label };
|
|
331
366
|
if (drawn.status !== undefined && HIDDEN.has(drawn.status)) return null;
|
|
332
|
-
if (
|
|
367
|
+
if (
|
|
368
|
+
drawn.status !== undefined &&
|
|
369
|
+
PLAIN.has(drawn.status) &&
|
|
370
|
+
drawn.paid === undefined &&
|
|
371
|
+
drawn.price !== FREE
|
|
372
|
+
)
|
|
333
373
|
return null;
|
|
334
374
|
const offer = drawn.offerId;
|
|
335
375
|
if (offer !== undefined && (await link($, `hold:${offer}`)) !== undefined) {
|
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
export type TenjinRow = {
|
|
8
8
|
/** The service's `label`, from its spec or the result envelope. */
|
|
9
9
|
label: string;
|
|
10
|
-
/** `$0.007`, `$0.09` for three takes,
|
|
10
|
+
/** `$0.007`, `$0.09` for three takes, `up to $0.05` when it varies, or
|
|
11
|
+
* `free` for a free lookup the CLI named. */
|
|
11
12
|
price?: string;
|
|
12
13
|
/** The one input the CLI says identifies the lookup, bounded. */
|
|
13
14
|
argument?: string;
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
runEach,
|
|
15
15
|
uninstallEach,
|
|
16
16
|
withNote
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-INTFHMU4.js";
|
|
18
18
|
import "./chunk-MPZUYCAP.js";
|
|
19
19
|
import "./chunk-7WEQQJLG.js";
|
|
20
20
|
import "./chunk-3UCIG4TG.js";
|
|
@@ -35,4 +35,4 @@ export {
|
|
|
35
35
|
uninstallEach,
|
|
36
36
|
withNote
|
|
37
37
|
};
|
|
38
|
-
//# sourceMappingURL=hosts-
|
|
38
|
+
//# sourceMappingURL=hosts-DVQJ32QC.js.map
|
package/dist/index.js
CHANGED
|
@@ -24,8 +24,8 @@ if (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {
|
|
|
24
24
|
var verb = process.argv[2];
|
|
25
25
|
if (verb !== "status-line" && verb !== "hook" && verb !== "mcp" && process.env.TENJIN_HANDOFF !== "1") {
|
|
26
26
|
const [{ handoffTarget }, { default: pkg }] = await Promise.all([
|
|
27
|
-
import("./runtime-layout-
|
|
28
|
-
import("./package-
|
|
27
|
+
import("./runtime-layout-WIDILZ6K.js"),
|
|
28
|
+
import("./package-IJFGMWEV.js")
|
|
29
29
|
]);
|
|
30
30
|
const target = handoffTarget(import.meta.url, pkg.version, process.env);
|
|
31
31
|
if (target !== null) {
|
|
@@ -38,27 +38,28 @@ if (verb !== "status-line" && verb !== "hook" && verb !== "mcp" && process.env.T
|
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
40
|
if (process.argv.length === 3 && process.argv[2] === "status-line") {
|
|
41
|
-
const { statusLineMain } = await import("./status-line-
|
|
41
|
+
const { statusLineMain } = await import("./status-line-OPCXDHL2.js");
|
|
42
42
|
await statusLineMain();
|
|
43
43
|
process.exit(0);
|
|
44
44
|
}
|
|
45
45
|
if (process.argv.length === 4 && process.argv[2] === "hook" && process.argv[3] === "alive") {
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
dataDir:
|
|
54
|
-
|
|
55
|
-
|
|
46
|
+
const { dataDir: dataDir2 } = await import("./paths-XCSAKISU.js");
|
|
47
|
+
const dir = dataDir2(process.env);
|
|
48
|
+
try {
|
|
49
|
+
const [{ aliveMain }, { default: pkg }] = await Promise.all([
|
|
50
|
+
import("./alive-GSOWKUOY.js"),
|
|
51
|
+
import("./package-IJFGMWEV.js")
|
|
52
|
+
]);
|
|
53
|
+
await aliveMain({ dataDir: dir, version: pkg.version });
|
|
54
|
+
} finally {
|
|
55
|
+
(await import("./auto-update-Y24UL56V.js")).maybeAutoUpdate({ dataDir: dir, env: process.env });
|
|
56
|
+
}
|
|
56
57
|
process.exit(0);
|
|
57
58
|
}
|
|
58
59
|
var { useEnvProxy } = await import("./env-proxy-R6ZMLQTT.js");
|
|
59
60
|
useEnvProxy(process.env);
|
|
60
|
-
var { main } = await import("./cli-
|
|
61
|
-
var { enableCliIdentity } = await import("./install-identity-
|
|
61
|
+
var { main } = await import("./cli-E36SPKBW.js");
|
|
62
|
+
var { enableCliIdentity } = await import("./install-identity-TZKGY6LQ.js");
|
|
62
63
|
var { dataDir } = await import("./paths-XCSAKISU.js");
|
|
63
64
|
enableCliIdentity(dataDir(process.env));
|
|
64
65
|
process.exit(await main(process.argv.slice(2)));
|
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 = 22;\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 ${MIN_NODE_MAJOR} 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// A STALE COPY HANDS OFF TO TENJIN'S RUNTIME. npm's global bin folder can come\n// before `~/.local/bin` on PATH, so a `tenjin` typed in a terminal may be an\n// npm copy older than the runtime the plugin runs; it must not answer for it.\n// When the runtime's current version is strictly newer, this build runs that\n// one instead, `install` included, so an old copy never sets up anything older\n// than what is already running. The status line, the hooks and `tenjin mcp` pay\n// nothing for this check; any failure falls through and this build runs.\nconst verb = process.argv[2];\nif (\n verb !== 'status-line' &&\n verb !== 'hook' &&\n verb !== 'mcp' &&\n process.env.TENJIN_HANDOFF !== '1'\n) {\n const [{ handoffTarget }, { default: pkg }] = await Promise.all([\n import('./lib/runtime-layout'),\n import('../package.json'),\n ]);\n const target = handoffTarget(import.meta.url, pkg.version, process.env);\n if (target !== null) {\n const { spawnSync } = await import('node:child_process');\n const run = spawnSync(target.node, [target.entry, ...process.argv.slice(2)], {\n stdio: 'inherit',\n env: { ...process.env, TENJIN_HANDOFF: '1' },\n });\n if (run.error === undefined) process.exit(run.status ?? 1);\n }\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\n// THE PLUGIN'S SessionStart LEG NEVER LOADS THE CLI EITHER. It runs before\n// every session starts, writes two small files and prints one JSON line only\n// when the wallet file or its saved passphrase file is unusable, so it takes\n// the same shortcut. A flag falls through to the command tree. Once its answer\n// is out, it starts the daily background update, detached (lib/auto-update).\nif (process.argv.length === 4 && process.argv[2] === 'hook' && process.argv[3] === 'alive') {\n const
|
|
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 = 22;\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 ${MIN_NODE_MAJOR} 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// A STALE COPY HANDS OFF TO TENJIN'S RUNTIME. npm's global bin folder can come\n// before `~/.local/bin` on PATH, so a `tenjin` typed in a terminal may be an\n// npm copy older than the runtime the plugin runs; it must not answer for it.\n// When the runtime's current version is strictly newer, this build runs that\n// one instead, `install` included, so an old copy never sets up anything older\n// than what is already running. The status line, the hooks and `tenjin mcp` pay\n// nothing for this check; any failure falls through and this build runs.\nconst verb = process.argv[2];\nif (\n verb !== 'status-line' &&\n verb !== 'hook' &&\n verb !== 'mcp' &&\n process.env.TENJIN_HANDOFF !== '1'\n) {\n const [{ handoffTarget }, { default: pkg }] = await Promise.all([\n import('./lib/runtime-layout'),\n import('../package.json'),\n ]);\n const target = handoffTarget(import.meta.url, pkg.version, process.env);\n if (target !== null) {\n const { spawnSync } = await import('node:child_process');\n const run = spawnSync(target.node, [target.entry, ...process.argv.slice(2)], {\n stdio: 'inherit',\n env: { ...process.env, TENJIN_HANDOFF: '1' },\n });\n if (run.error === undefined) process.exit(run.status ?? 1);\n }\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\n// THE PLUGIN'S SessionStart LEG NEVER LOADS THE CLI EITHER. It runs before\n// every session starts, writes two small files and prints one JSON line only\n// when the wallet file or its saved passphrase file is unusable, so it takes\n// the same shortcut. A flag falls through to the command tree. Once its answer\n// is out, it starts the daily background update, detached (lib/auto-update):\n// after the answer, so the session waits on nothing new, and in a `finally`,\n// so a leg that throws, or a module that will not load, still starts the\n// update that may replace the build at fault. Starting it never throws and\n// never waits.\nif (process.argv.length === 4 && process.argv[2] === 'hook' && process.argv[3] === 'alive') {\n const { dataDir } = await import('./lib/paths');\n const dir = dataDir(process.env);\n try {\n const [{ aliveMain }, { default: pkg }] = await Promise.all([\n import('./router/alive'),\n import('../package.json'),\n ]);\n await aliveMain({ dataDir: dir, version: pkg.version });\n } finally {\n (await import('./lib/auto-update')).maybeAutoUpdate({ dataDir: dir, env: process.env });\n }\n process.exit(0);\n}\n\n// After the status line, which sends no request: every other process from this\n// bin (the CLI, the hooks, `tenjin mcp`) honours HTTPS_PROXY and NO_PROXY.\nconst { useEnvProxy } = await import('./lib/env-proxy');\nuseEnvProxy(process.env);\n\nconst { main } = await import('./cli');\n// Here and not in `main`, so an in-process test of the command tree sends no\n// telemetry and mints no install id; see lib/install-identity.\nconst { enableCliIdentity } = await import('./lib/install-identity');\nconst { dataDir } = await import('./lib/paths');\nenableCliIdentity(dataDir(process.env));\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,gBAAgB,cAAc;AAAA,IACrC;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;AASA,IAAM,OAAO,QAAQ,KAAK,CAAC;AAC3B,IACE,SAAS,iBACT,SAAS,UACT,SAAS,SACT,QAAQ,IAAI,mBAAmB,KAC/B;AACA,QAAM,CAAC,EAAE,cAAc,GAAG,EAAE,SAAS,IAAI,CAAC,IAAI,MAAM,QAAQ,IAAI;AAAA,IAC9D,OAAO,8BAAsB;AAAA,IAC7B,OAAO,uBAAiB;AAAA,EAC1B,CAAC;AACD,QAAM,S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